Search Results

Search found 1014 results on 41 pages for 'trim'.

Page 10/41 | < Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >

  • How can I secure my $_GETs in PHP?

    - by ggfan
    My profile.php displays all the user's postings,comments,pictures. If the user wants to delete, it sends the posting's id to the remove.php so it's like remove.php?action=removeposting&posting_id=2. If they want to remove a picture, it's remove.php?action=removepicture&picture_id=1. Using the get data, I do a query to the database to display the info they want to delete and if they want to delete it, they click "yes". So the data is deleted via $POST NOT $GET to prevent cross-site request forgery. My question is how do I make sure the GETs are not some javascript code, sql injection that will mess me up. here is my remove.php //how do I make $action safe? //should I use mysqli_real_escape_string? //use strip_tags()? $action=trim($_GET['action']); if (($action != 'removeposting') && ($action != 'removefriend') && ($action != 'removecomment')) { echo "please don't change the action. go back and refresh"; header("Location: index.php"); exit(); } if ($action == 'removeposting') { //get the info and display it in a form. if user clicks "yes", deletes } if ($action =='removepicture') { //remove pic } I know I can't be 100% safe, but what are some common defenses I can use. EDIT Do this to prevent xss $action=trim($_GET['action']); htmlspecialchars(strip_tags($action)); Then when I am 'recalling' the data back via POST, I would use $posting_id = mysqli_real_escape_string($dbc, trim($_POST['posting_id']));

    Read the article

  • How to limit a user to entering 10 keywords or less using PHP & MySQL?

    - by G4TV
    I'm trying to limit my users to entering at least 10 keywords and was wondering how would I be able to do this using PHP & MySQL with my current Keyword script? Here is the add keywords PHP MySQL code. if (isset($_POST['tag']) && trim($_POST['tag'])!=='') { $tags = explode(",", $_POST['tag']); for ($x = 0; $x < count($tags); $x++){ $mysqli = mysqli_connect("localhost", "root", "", "sitename"); $query1 = "INSERT INTO tags (tag) VALUES ('" . mysqli_real_escape_string($mysqli, strtolower(htmlentities(trim(strip_tags($tags[$x]))))) . "')"; if (!mysqli_query($mysqli, $query1)) { print mysqli_error($mysqli); return; } $mysqli = mysqli_connect("localhost", "root", "", "sitename"); $dbc = mysqli_query($mysqli,"SELECT id FROM tags WHERE tag='" . mysqli_real_escape_string($mysqli, strtolower(htmlentities(trim(strip_tags($tags[$x]))))) . "'"); if (!$dbc) { print mysqli_error($mysqli); } else { while($row = mysqli_fetch_array($dbc)){ $id = $row["id"]; } } $query2 = "INSERT INTO question_tags (tag_id, question_id, user_id, date_created) VALUES ('$id', '$question', '$user', NOW())"; if (!mysqli_query($mysqli, $query2)) { print mysqli_error($mysqli); return; } } }

    Read the article

  • How safe is it to run CHKDSK on an SSD?

    - by Eilon
    I recently saw Windows 7 pop up a warning or two that I should run chkdsk on my laptop. My laptop came with an SSD and I'm not sure if there are any negative implications to running chkdsk on such a drive. Are there any potential issues with reporting "bad sectors" on the drive? I would imagine that the physical concept of sectors is completely different between a platter and a microchip. I don't think my SSD supports TRIM. It's about 14 months old and a quick web search seems to hint that it doesn't (though it's nearly impossible to find out this info for sure!). I'm also not sure if TRIM is even relevant here since there shouldn't be much in the way of deletes. So, how safe is it to run chkdsk on my SSD drive? The model of SSD that I have is reported as "Samsung SSD PB22-JS3 2.5".

    Read the article

  • sox mix nested scripts on amazon ec2 rhel linux

    - by Ray
    I'm trying to use "sox" to mix some audio files. The command works great on my Mac terminal sox -m audio.wav "| sox upload.wav -p trim 2 1 pad 6" final.wav This mixes (not concatenate) audio.wav and a section of upload.wav from the 2nd second to the 3rd second and adds 6 seconds of padding in the front, and outputs to final.wav Now the problem is, the SAME EXACT command does NOT work my Amazon EC2 RHEL box. (sox is installed correctly). I get the following error sox soxio: Can't open input file `| sox upload.wav -p trim 2 2 pad 6': No such file or directory For some reason RedHat doesn't like the double quotes. Even though it is documented to be used this way. Thanks for your help!

    Read the article

  • Photoshop How to save selection to PNG

    - by Aniti
    I have a largish PSD file with a couple of hundred layers, that I would like to extract selected areas from into PNG files. Areas can consist of a couple of layers. Being new to Photoshop, I have been using the following workaround. Duplicate needed layers into a new scratch PSD file of same size, TRIM to transparency, Save As PNG, undo TRIM, hide layers, rinse and repeat... I suppose I could do it without the scratch file and just crop selection, Save As PNG and undo, but there must be a nicer method. What other ways are there to accomplish this export of a selected area to PNG? EDIT: This is on Windows Xp running Photoshop CS3 Extended

    Read the article

  • How to get the child elementsvalue , when the parent element contains different number of child Elem

    - by Subhen
    Hi, I have the following XML Structure: <DIDL-Lite xmlns="urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:upnp="urn:schemas-upnp-org:metadata-1-0/upnp/" xmlns:dlna="urn:schemas-dlna-org:metadata-1-0/"> <item id="1268" parentID="20" restricted="1"> <upnp:class>object.item.audioItem.musicTrack</upnp:class> <dc:title>Hey</dc:title> <dc:date>2010-03-17T12:12:26</dc:date> <upnp:albumArtURI dlna:profileID="PNG_TN" xmlns:dlna="urn:schemas-dlna-org:metadata-1-0">URL/albumart/22.png</upnp:albumArtURI> <upnp:icon>URL/albumart/22.png</upnp:icon> <dc:creator>land</dc:creator> <upnp:artist>sland</upnp:artist> <upnp:album>Change</upnp:album> <upnp:genre>Rock</upnp:genre> <res protocolInfo="http-get:*:audio/mpeg:DLNA.ORG_PN=MP3;DLNA.ORG_OP=01;DLNA.ORG_CI=0;DLNA.ORG_FLAGS=01700000000000000000000000000000" size="9527987" duration="0:03:58">URL/1268.mp3</res> <res protocolInfo="http-get:*:image/png:DLNA.ORG_PN=PNG_TN;DLNA.ORG_CI=01;DLNA.ORG_FLAGS=00f00000000000000000000000000000" colorDepth="24" resolution="160x160">URL/albumart/22.png</res> </item> <item id="1269" parentID="20" restricted="1"> <upnp:class>object.item.audioItem.musicTrack</upnp:class> <dc:title>Indian </dc:title> <dc:date>2010-03-17T12:06:32</dc:date> <upnp:albumArtURI dlna:profileID="PNG_TN" xmlns:dlna="urn:schemas-dlna-org:metadata-1-0">URL/albumart/13.png</upnp:albumArtURI> <upnp:icon>URL/albumart/13.png</upnp:icon> <dc:creator>MC</dc:creator> <upnp:artist>MC</upnp:artist> <upnp:album>manimal</upnp:album> <upnp:genre>Rap</upnp:genre> <res protocolInfo="http-get:*:audio/mpeg:DLNA.ORG_PN=MP3;DLNA.ORG_OP=01;DLNA.ORG_CI=0;DLNA.ORG_FLAGS=01700000000000000000000000000000" size="8166707" duration="0:03:24">URL/1269.mp3</res> <res protocolInfo="http-get:*:image/png:DLNA.ORG_PN=PNG_TN;DLNA.ORG_CI=01;DLNA.ORG_FLAGS=00f00000000000000000000000000000" colorDepth="24" resolution="160x160">URL/albumart/13.png</res> </item> <item id="1277" parentID="20" restricted="1"> <upnp:class>object.item.videoItem.movie</upnp:class> <dc:title>IronMan_TeaserTrailer-full_NEW.mpg</dc:title> <dc:date>2010-03-17T12:50:24</dc:date> <upnp:genre>Unknown</upnp:genre> <res protocolInfo="http-get:*:video/mpeg:DLNA.ORG_PN=(NULL);DLNA.ORG_OP=01;DLNA.ORG_CI=0;DLNA.ORG_FLAGS=01700000000000000000000000000000" size="98926592" resolution="1920x1080" duration="0:02:30">URL/1277.mpg</res> </item> </DIDL-Lite> Here in the last Elemnt Item , there are few missing elements like icon,albumArtURi ..etc. Now whhile Ity to access the Values by following LINQ to XML query, var vAudioData = from xAudioinfo in xResponse.Descendants(ns + "DIDL-Lite").Elements(ns + "item").Where(x=>!x.Elements(upnp+"album").l orderby ((string)xAudioinfo.Element(upnp + "artist")).Trim() select new RMSMedia { strAudioTitle = ((string)xAudioinfo.Element(dc + "title")).Trim(),//((string)xAudioinfo.Attribute("audioAlbumcoverImage")).Trim()=="" ? ((string)xAudioinfo.Element("Song")).Trim():"" }; It show object reference is not set to reference of object. I do undersrand this is because of missing elements, is there any way I can pre-check if the elements exist , or check the number of elemnts inside item or any other way. Any help is deeply appreciated. Thanks, Subhen

    Read the article

  • GroupLayout: JScrollPane in TextArea is not working

    - by Dozent
    i'm new in java and recently started to develop an simple application. For the moment i have a problem with JScrollPanne, it's not able to scroll down (or up) when the text in textarea more than size of area. I have looked to some solutions, but all of them were for FlowLayot (GridLayout and BoxLayout), but not for GroupLayout. Here is the code: JPanel conent_p = new JPanel(); conent_p.setBorder(new TitledBorder(null, "", TitledBorder.LEADING, TitledBorder.TOP, null, null)); JLabel lblItemName = new JLabel("Item name:"); itemField = new JTextField(); itemField.setColumns(10); JLabel lblMxPrice = new JLabel("Max price:"); mpriceField = new JTextField(); mpriceField.setColumns(10); JLabel lblQuantity = new JLabel("Quantity:"); quanField = new JTextField(); quanField.setColumns(10); JLabel lblDelivery = new JLabel("Delivery:"); delivField = new JTextField(); delivField.setColumns(10); JLabel lblLogcat = new JLabel("LogCat:"); final JTextArea txtConsole = new JTextArea(); txtConsole.setEditable(false); txtConsole.setLineWrap(true); txtConsole.setWrapStyleWord(true); sbrText = new JScrollPane(txtConsole); sbrText.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); // Now create a new TextAreaOutputStream to write to our JTextArea control and wrap a // PrintStream around it to support the println/printf methods. PrintStream out = new PrintStream(new TextAreaOutputStream(txtConsole)); // redirect standard output stream to the TextAreaOutputStream System.setOut(out); // redirect standard error stream to the TextAreaOutputStream System.setErr(out); GroupLayout gl_conent_p = new GroupLayout(conent_p); gl_conent_p.setHorizontalGroup( gl_conent_p.createParallelGroup(Alignment.LEADING) .addGroup(gl_conent_p.createSequentialGroup() .addContainerGap() .addGroup(gl_conent_p.createParallelGroup(Alignment.LEADING) .addComponent(lblMxPrice, Alignment.TRAILING) .addComponent(lblItemName, Alignment.TRAILING) .addComponent(lblLogcat, Alignment.TRAILING)) .addGap(18) .addGroup(gl_conent_p.createParallelGroup(Alignment.LEADING) .addGroup(gl_conent_p.createSequentialGroup() .addGroup(gl_conent_p.createParallelGroup(Alignment.LEADING, false) .addComponent(itemField, GroupLayout.PREFERRED_SIZE, 365, GroupLayout.PREFERRED_SIZE) .addGroup(gl_conent_p.createSequentialGroup() .addComponent(mpriceField, GroupLayout.PREFERRED_SIZE, 80, GroupLayout.PREFERRED_SIZE) .addGap(18) .addComponent(lblQuantity) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(quanField, 0, 0, Short.MAX_VALUE) .addGap(18) .addComponent(lblDelivery) .addPreferredGap(ComponentPlacement.RELATED) .addComponent(delivField, GroupLayout.PREFERRED_SIZE, 80, GroupLayout.PREFERRED_SIZE) .addPreferredGap(ComponentPlacement.RELATED))) .addGap(100)) .addGroup(gl_conent_p.createSequentialGroup() .addComponent(txtConsole, GroupLayout.PREFERRED_SIZE, 345, GroupLayout.PREFERRED_SIZE) .addComponent(sbrText) .addContainerGap()))) ); gl_conent_p.setVerticalGroup( gl_conent_p.createParallelGroup(Alignment.LEADING) .addGroup(gl_conent_p.createSequentialGroup() .addContainerGap() .addGroup(gl_conent_p.createParallelGroup(Alignment.BASELINE) .addComponent(lblItemName) .addComponent(itemField, GroupLayout.PREFERRED_SIZE, 20, GroupLayout.PREFERRED_SIZE)) .addGap(20) .addGroup(gl_conent_p.createParallelGroup(Alignment.LEADING) .addGroup(gl_conent_p.createParallelGroup(Alignment.BASELINE) .addComponent(lblDelivery) .addComponent(delivField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)) .addGroup(gl_conent_p.createParallelGroup(Alignment.BASELINE) .addComponent(lblMxPrice) .addComponent(mpriceField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE) .addComponent(lblQuantity) .addComponent(quanField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))) .addGap(55) .addGroup(gl_conent_p.createParallelGroup(Alignment.BASELINE) .addComponent(lblLogcat) .addComponent(txtConsole, GroupLayout.PREFERRED_SIZE, 200, GroupLayout.PREFERRED_SIZE) .addComponent(sbrText)) .addContainerGap()) ); conent_p.setLayout(gl_conent_p); getContentPane().add(conent_p, BorderLayout.NORTH); JButton btnBuy = new JButton("Buy"); btnBuy.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent ev) { try { String title = itemField.getText().trim(); String mprice = mpriceField.getText().trim(); String quantity = quanField.getText().trim(); String deliver = delivField.getText().trim(); Item_CONCEPT item = new Item_CONCEPT(); item.setName(title); item.setDelivery(Integer.parseInt(deliver)); item.setStartPrice(0); item.setMaxPrice(Integer.parseInt(mprice)); myAgent.existsSeller(item); Date date = new Date(); DateFormat df = new SimpleDateFormat("dd.MM.yy HH:mm"); System.out.println(df.format(date)+": Buyer orders an item: "+item.getName()); //Clearing all fields itemField.setText(""); quanField.setText(""); delivField.setText(""); //txtConsole.setText(""); mpriceField.setText(""); } catch (Exception e) { JOptionPane.showMessageDialog(BuyerGUI.this, "A field is filled incorrectly. "+e.getMessage()+" is invalid.", "Error", JOptionPane.ERROR_MESSAGE); } } } );![enter image description here][1]

    Read the article

  • How to parse JSON data from web more faster [closed]

    - by Kaidul Islam Sazal
    I have json inventory inventory.json on the server like this: [ { "body" : "SUV", "color" : { "ext" : "White diamond pearl", "int" : "Taupe" }, "id" : "276181", "make" : "Acura", "miles" : 35949, "model" : "RDX", "pic" : [ { "full" : "http://images1.dealercp.com/90961/000JNBD/001_0292.jpg" } ], "power" : { "drive" : "Front wheel drive", "eng" : "2.3L DOHC PGM-FI 16-VALVE", "trans" : "Automatic" }, "price" : { "net" : 29488 }, "stock" : "6942", "trim" : "AWD 4dr Tech Pkg SUV", "vin" : "5J8TB2H53BA000334", "year" : 2011 }, { "body" : "Sedan", "color" : { "ext" : "Premium white pearl", "int" : "Taupe" }, "id" : "275622", "make" : "Acura", "miles" : 40923, "model" : "TSX", "pic" : [ { "full" : "http://images1.dealercp.com/90961/000JMC6/001_1765.jpg" } ], "power" : { "drive" : "Front wheel drive", "eng" : "2.4L L4 MPI DOHC 16V", "trans" : "Automatic" }, "price" : { "net" : 22288 }, "stock" : "6945", "trim" : "4dr Sdn I4 Auto Sedan", "vin" : "JH4CU2F66AC011933", "year" : 2010 } ] here are two index, There are almost 5000 index like this. I parsed this json like this: var url = "inventory/inventory.json"; $.getJSON(url, function(data){ $.each(data, function(index, item){ //straight-forward loop if(item.year == 2012) { $('#desc').append(item.make + ' ' + item.model + ' ' + '<br/>' + item.price.net + '<br/>' + item.pic[0].full); } }); }); This is working fine.But the problem is that, this searching and fetching process is little bit slow as there are 5000 indexes already and it's increasing day by day. It seems that, it is a straight-forward loop to parse the data and a normal brute-force method. Now I want to know if there any time efiicient way to parse more faster.Any faster method to parse instead of straight-forward loop ?

    Read the article

  • my application did not show toast mesage when network is not available [closed]

    - by Smart Guy
    my application did no show toast message when network is disable if (position == 2) { final ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connMgr .getActiveNetworkInfo(); android.net.NetworkInfo mobile1 = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); if (activeNetworkInfo == null) { Toast.makeText(LoginScreen.this, "No Active Network",Toast.LENGTH_LONG).show(); } else { if (activeNetworkInfo.isConnected()) { btnLogin.setOnClickListener(new OnClickListener() { public void onClick(View view) { String pinemptycheck = pin.getText().toString(); String mobileemptycheck = mobile.getText().toString(); if (pinemptycheck.trim().equals("")||(mobileemptycheck.trim().equals(""))) { Toast.makeText(getApplicationContext(), "Please Enter Correct Information", Toast.LENGTH_LONG).show(); } else { showProgress(); postLoginData(); } } }); } else if (activeNetworkInfo.isConnectedOrConnecting()) { Toast.makeText(LoginScreen.this, "network is Connecting", Toast.LENGTH_LONG) .show(); else if (mobile1.isAvailable()) { btnLogin.setOnClickListener(new OnClickListener() { public void onClick(View view) { showProgress(); postLoginData(); } }); } else if (!mobile1.isAvailable()) { Toast.makeText(LoginScreen.this,"No other Connection Found ",Toast.LENGTH_LONG).show(); btnLogin.setOnClickListener(new OnClickListener() { public void onClick(View v) { Toast.makeText(LoginScreen.this," No other Connection Found", Toast.LENGTH_LONG).show(); } }); }}}

    Read the article

  • (PHP) Validation, Security and Speed - Does my app have these?

    - by Devner
    Hi all, I am currently working on a building community website in PHP. This contains forms that a user can fill right from registration to lot of other functionality. I am not an Object-oriented guy, so I am using functions most of the time to handle my application. I know I have to learn OOPS, but currently need to develop this website and get it running soon. Anyway, here's a sample of what I let my app. do: Consider a page (register.php) that has a form where a user has 3 fields to fill up, say: First Name, Last Name and Email. Upon submission of this form, I want to validate the form and show the corresponding errors to the users: <form id="form1" name="form1" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>"> <label for="name">Name:</label> <input type="text" name="name" id="name" /><br /> <label for="lname">Last Name:</label> <input type="text" name="lname" id="lname" /><br /> <label for="email">Email:</label> <input type="text" name="email" id="email" /><br /> <input type="submit" name="submit" id="submit" value="Submit" /> </form> This form will POST the info to the same page. So here's the code that will process the POST'ed info: <?php require("functions.php"); if( isset($_POST['submit']) ) { $errors = fn_register(); if( count($errors) ) { //Show error messages } else { //Send welcome mail to the user or do database stuff... } } ?> <?php //functions.php page: function sql_quote( $value ) { if( get_magic_quotes_gpc() ) { $value = stripslashes( $value ); } else { $value = addslashes( $value ); } if( function_exists( "mysql_real_escape_string" ) ) { $value = mysql_real_escape_string( $value ); } return $value; } function clean($str) { $str = strip_tags($str, '<br>,<br />'); $str = trim($str); $str = sql_quote($str); return $str; } foreach ($_POST as &$value) { if (!is_array($value)) { $value = clean($value); } else { clean($value); } } foreach ($_GET as &$value) { if (!is_array($value)) { $value = clean($value); } else { clean($value); } } function validate_name( $fld, $min, $max, $rule, $label ) { if( $rule == 'required' ) { if ( trim($fld) == '' ) { $str = "$label: Cannot be left blank."; return $str; } } if ( isset($fld) && trim($fld) != '' ) { if ( isset($fld) && $fld != '' && !preg_match("/^[a-zA-Z\ ]+$/", $fld)) { $str = "$label: Invalid characters used! Only Lowercase, Uppercase alphabets and Spaces are allowed"; } else if ( strlen($fld) < $min or strlen($fld) > $max ) { $curr_char = strlen($fld); $str = "$label: Must be atleast $min character &amp; less than $max char. Entered characters: $curr_char"; } else { $str = 0; } } else { $str = 0; } return $str; } function validate_email( $fld, $min, $max, $rule, $label ) { if( $rule == 'required' ) { if ( trim($fld) == '' ) { $str = "$label: Cannot be left blank."; return $str; } } if ( isset($fld) && trim($fld) != '' ) { if ( !eregi('^[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.([a-zA-Z]{2,4})$', $fld) ) { $str = "$label: Invalid format. Please check."; } else if ( strlen($fld) < $min or strlen($fld) > $max ) { $curr_char = strlen($fld); $str = "$label: Must be atleast $min character &amp; less than $max char. Entered characters: $curr_char"; } else { $str = 0; } } else { $str = 0; } return $str; } function val_rules( $str, $val_type, $rule='required' ){ switch ($val_type) { case 'name': $val = validate_name( $str, 3, 20, $rule, 'First Name'); break; case 'lname': $val = validate_name( $str, 10, 20, $rule, 'Last Name'); break; case 'email': $val = validate_email( $str, 10, 60, $rule, 'Email'); break; } return $val; } function fn_register() { $errors = array(); $val_name = val_rules( $_POST['name'], 'name' ); $val_lname = val_rules( $_POST['lname'], 'lname', 'optional' ); $val_email = val_rules( $_POST['email'], 'email' ); if ( $val_name != '0' ) { $errors['name'] = $val_name; } if ( $val_lname != '0' ) { $errors['lname'] = $val_lname; } if ( $val_email != '0' ) { $errors['email'] = $val_email; } return $errors; } //END of functions.php page ?> OK, now it might look like there's a lot, but lemme break it down target wise: 1. I wanted the foreach ($_POST as &$value) and foreach ($_GET as &$value) loops to loop through the received info from the user submission and strip/remove all malicious input. I am calling a function called clean on the input first to achieve the objective as stated above. This function will process each of the input, whether individual field values or even arrays and allow only tags and remove everything else. The rest of it is obvious. Once this happens, the new/cleaned values will be processed by the fn_register() function and based on the values returned after the validation, we get the corresponding errors or NULL values (as applicable). So here's my questions: 1. This pretty much makes me feel secure as I am forcing the user to correct malicious data and won't process the final data unless the errors are corrected. Am I correct? Does the method that I follow guarantee the speed (as I am using lots of functions and their corresponding calls)? The fields of a form differ and the minimum number of fields I may have at any given point of time in any form may be 3 and can go upto as high as 100 (or even more, I am not sure as the website is still being developed). Will having 100's of fields and their validation in the above way, reduce the speed of application (say upto half a million users are accessing the website at the same time?). What can I do to improve the speed and reduce function calls (if possible)? 3, Can I do something to improve the current ways of validation? I am holding off object oriented approach and using FILTERS in PHP for the later. So please, I request you all to suggest me way to improve/tweak the current ways and suggest me if the script is vulnerable or safe enough to be used in a Live production environment. If not, what I can do to be able to use it live? Thank you all in advance.

    Read the article

  • webscraper grabbing images, but not entering info into database

    - by Jason
    Hello, again. I'm having more issues with my script entering info into my database. The script below grabs a page, strips down the necessary info, then downloads the related image file. After that, it is supposed to enter the information gleaned from the URL into the database. For some reason, the script seems to iterate through the URLs, as I get downloaded images for each URL, but each URL's product is not entered into the database. The script will insert the first product's categories and product info, and then it just stops, and continues to download images. Any suggestions? <?php define('IN_PHPBB', true); $phpbb_root_path = (defined('PHPBB_ROOT_PATH')) ? PHPBB_ROOT_PATH : './'; $phpEx = substr(strrchr(__FILE__, '.'), 1); include($phpbb_root_path . 'common.' . $phpEx); include($phpbb_root_path . 'includes/simple_html_dom.' . $phpEx); // Start session management $user->session_begin(); $auth->acl($user->data); $user->setup(); set_time_limit(259200); function save($in, $out) { $ch = curl_init ($in); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_BINARYTRANSFER,1); $rawdata=curl_exec($ch); curl_close ($ch); if(file_exists($out)) { unlink($out); } $fp = fopen($out,'x'); fwrite($fp, $rawdata); fclose($fp); } function scrape($i) { $url = 'http:/xxxxxxxx/index.php?main_page=product_info&products_id='.$i.'&zenid=e4b7dde8de02e1df005d4549e2e3e529'; echo "$url -- "; $exists = file_get_contents($url); if ($exists != false) { $html = file_get_html($url); foreach($html->find('body') as $html) { $test = $html->find('#productName', 0); if ($test) { $item['title'] = trim($html->find('#productName', 0)->plaintext); $item['price'] = trim($html->find('#productPrices', 0)->plaintext); $item['cat'] = $html->find('#navBreadCrumb', 0)->plaintext; list($home, $item['cat'], $item['subcat'], $title) = explode("::", $item['cat']); $item['cat'] = str_replace("&nbsp;", "", $item['cat']); $item['subcat'] = str_replace("\n", "", str_replace("&nbsp;", "", $item['subcat'])); $item['desc'] = trim($html->find('#productDescription', 0)->plaintext); $item['model'] = $html->find('ul#productDetailsList', 0)->find('li', 0)->plaintext; $item['model'] = explode(":", $item['model']); $item['model'] = trim($item['model'][1]); $item['manufacturer'] = $html->find('ul#productDetailsList', 0)->find('li', 1)->plaintext; $item['manufacturer'] = explode(":", $item['manufacturer']); $item['manufacturer'] = trim($item['manufacturer'][1]); foreach($html->find('img') as $img) { if($img->alt == $item['title']) { $item['img_sm'] = $img->src; } } $ret[] = $item; } } $html->clear(); unset($html); unset($item); return $ret; } else { echo "Could not find page<br />"; } unset($exists); } $i = 1; $end = 9999999; while($i < $end) { $ret = scrape($i); if(isset($ret)) { foreach($ret as $v) { $item['title'] = $v['title']; $item['price'] = $v['price']; $item['desc'] = $v['desc']; $item['model'] = $v['model']; $item['manufacturer'] = $v['manufacturer']; $item['image'] = $v['image']; $item['cat'] = $v['cat']; $item['subcat'] = $v['subcat']; $item['img_sm'] = $v['img_sm']; } unset($ret); unset($v); $sm_img_src = "http://xxxxxx/".$item['img_sm']; $ext = strrchr($item['img_sm'], '.'); $filename = $item['model'] . $ext; $lg_img_src = "http://xxxxx/images/STC/".$filename; $new_sm = "./rip_images/small/{$filename}"; $new_lg = "./rip_images/large/{$filename}"; $item['image'] = $filename; save($lg_img_src,$new_lg); save($sm_img_src,$new_sm); //see if parent cat exists $sql = 'SELECT cat_id FROM ' . SHOP_CAT_TABLE . ' WHERE cat_name = "'.$db->sql_escape($item['cat']).'"'; $result = $db->sql_query($sql); $parent = $db->sql_fetchrow($result); $db->sql_freeresult($result); // if not exists if($parent['cat_id'] == '') { //add the parent cat to the db $sql_ary = array( 'cat_name' => $item['cat'], 'cat_parent' => 0 ); $sql = 'INSERT INTO '.SHOP_CAT_TABLE.' '.$db->sql_build_array('INSERT', $sql_ary); $db->sql_query($sql); $cat_id = $db->sql_nextid(); //see if subcat exists $sql = 'SELECT cat_id FROM ' . SHOP_CAT_TABLE . ' WHERE cat_name = "'.$db->sql_escape($item['subcat']).'"'; $result = $db->sql_query($sql); $row = $db->sql_fetchrow($result); $db->sql_freeresult($result); // if not exists if($row['cat_id'] == '') { //add subcat to db $sql_ary = array( 'cat_name' => $db->sql_escape($item['subcat']), 'cat_parent' => $cat_id ); $sql = 'INSERT INTO '.SHOP_CAT_TABLE.' '.$db->sql_build_array('INSERT', $sql_ary); $db->sql_query($sql); $item_cat = $db->sql_nextid(); } else //if exists { $item_cat = $row['cat_id']; } } else //if parent cat exists { //see if subcat exists $sql = 'SELECT cat_id FROM ' . SHOP_CAT_TABLE . ' WHERE cat_name = "'.$db->sql_escape($item['subcat']).'"'; $result = $db->sql_query($sql); $row = $db->sql_fetchrow($result); $db->sql_freeresult($result); // if not exists if($row['cat_id'] == '') { //add the subcat to the db $sql_ary = array( 'cat_name' => $db->sql_escape($item['subcat']), 'cat_parent' => $parent['cat_id'] ); $sql = 'INSERT INTO '.SHOP_CAT_TABLE.' '.$db->sql_build_array('INSERT', $sql_ary); $db->sql_query($sql); $item_cat = $db->sql_nextid(); } else //if exists { $item_cat = $row['cat_id']; } } $sql_ary = array( 'item_title' => $db->sql_escape($item['title']), 'item_price' => $db->sql_escape($item['price']), 'item_desc' => $db->sql_escape($item['desc']), 'item_model' => $db->sql_escape($item['model']), 'item_manufacturer' => $db->sql_escape($item['manufacturer']), 'item_image' => $db->sql_escape($item['image']), 'item_cat' => $db->sql_escape($item_cat) ); $sql = 'INSERT INTO ' . SHOP_ITEM_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary); $db->sql_query($sql); garbage_collection(); echo 'Done<br />'; } $i++; unset($item); } ?>

    Read the article

  • Generically correcting data before save with Entity Framework

    - by koevoeter
    Been working with Entity Framework (.NET 4.0) for a week now for a data migration job and needed some code that generically corrects string values in the database. You probably also have seen things like empty strings instead of NULL or non-trimmed texts ("United States       ") in "old" databases, and you don't want to apply a correcting function on every column you migrate. Here's how I've done this (extending the partial class of my ObjectContext):public partial class MyDatacontext{    partial void OnContextCreated()    {        SavingChanges += OnSavingChanges;    }     private void OnSavingChanges(object sender, EventArgs e)    {        foreach (var entity in GetPersistingEntities(sender))        {            foreach (var propertyInfo in GetStringProperties(entity))            {                var value = (string)propertyInfo.GetValue(entity, null);                 if (value == null)                {                    continue;                }                 if (value.Trim().Length == 0 && IsNullable(propertyInfo))                {                    propertyInfo.SetValue(entity, null, null);                }                else if (value != value.Trim())                {                    propertyInfo.SetValue(entity, value.Trim(), null);                }            }        }    }     private IEnumerable<object> GetPersistingEntities(object sender)    {        return ((ObjectContext)sender).ObjectStateManager            .GetObjectStateEntries(EntityState.Added | EntityState.Modified)             .Select(e => e.Entity);    }    private IEnumerable<PropertyInfo> GetStringProperties(object entity)    {        return entity.GetType().GetProperties()            .Where(pi => pi.PropertyType == typeof(string));    }    private bool IsNullable(PropertyInfo propertyInfo)    {        return ((EdmScalarPropertyAttribute)propertyInfo             .GetCustomAttributes(typeof(EdmScalarPropertyAttribute), false)            .Single()).IsNullable;    }}   Obviously you can use similar code for other generic corrections.

    Read the article

  • More SharePoint 2010 Expression Builders

    - by Ricardo Peres
    Introduction Following my last post, I decided to publish the whole set of expression builders that I use with SharePoint. For all who don’t know about expression builders, they allow us to employ a declarative approach, so that we don’t have to write code for “gluing” things together, like getting a value from the query string, the page’s underlying SPListItem or the current SPContext and assigning it to a control’s property. These expression builders are for some quite common scenarios, I use them quite often, and I hope you find them useful as well. SPContextExpression This expression builder allows us to specify an expression to be processed on the SPContext.Current property object. For example: 1: <asp:Literal runat="server" Text=“<%$ SPContextExpression:Site.RootWeb.Lists[0].Author.LoginName %>”/> It is identical to having the following code: 1: String authorName = SPContext.Current.Site.RootWeb.Lists[0].Author.LoginName; SPFarmProperty Returns a property stored on the farm level: 1: <asp:Literal runat="server" Text="<%$ SPFarmProperty:SomeProperty %>"/> Identical to: 1: Object someProperty = SPFarm.Local.Properties["SomeProperty"]; SPField Returns the value of a selected page’s list item field: 1: <asp:Literal runat="server" Text="<%$ SPField:Title %>"/> Does the same as: 1: String title = SPContext.Current.ListItem["Title"] as String; SPIsInAudience Checks if the current user belongs to an audience: 1: <asp:CheckBox runat="server" Checked="<%$ SPIsInAudience:SomeAudience %>"/> Equivalent to: 1: AudienceManager audienceManager = new AudienceManager(SPServiceContext.Current); 2: Audience audience = audienceManager.Audiences["SomeAudience"]; 3: Boolean isMember = audience.IsMember(SPContext.Current.Web.User.LoginName); SPIsInGroup Checks if the current user belongs to a group: 1: <asp:CheckBox runat="server" Checked="<%$ SPIsInGroup:SomeGroup %>"/> The equivalent C# code is: 1: SPContext.Current.Web.CurrentUser.Groups.OfType<SPGroup>().Any(x => String.Equals(x.Name, “SomeGroup”, StringComparison.OrdinalIgnoreCase)); SPProperty Returns the value of a user profile property for the current user: 1: <asp:Literal runat="server" Text="<%$ SPProperty:LastName %>"/> Where the same code in C# would be: 1: UserProfileManager upm = new UserProfileManager(SPServiceContext.Current); 2: UserProfile u = upm.GetUserProfile(false); 3: Object property = u["LastName"].Value; SPQueryString Returns a value passed on the query string: 1: <asp:GridView runat="server" PageIndex="<%$ SPQueryString:PageIndex %>" /> Is equivalent to (no SharePoint code this time): 1: Int32 pageIndex = Convert.ChangeType(typeof(Int32), HttpContext.Current.Request.QueryString["PageIndex"]); SPWebProperty Returns the value of a property stored at the site level: 1: <asp:Literal runat="server" Text="<%$ SPWebProperty:__ImagesListId %>"/> You can get the same result as: 1: String imagesListId = SPContext.Current.Web.AllProperties["__ImagesListId"] as String; Code OK, let’s move to the code. First, a common abstract base class, mainly for inheriting the conversion method: 1: public abstract class SPBaseExpressionBuilder : ExpressionBuilder 2: { 3: #region Protected static methods 4: protected static Object Convert(Object value, PropertyInfo propertyInfo) 5: { 6: if (value != null) 7: { 8: if (propertyInfo.PropertyType.IsAssignableFrom(value.GetType()) == false) 9: { 10: if (propertyInfo.PropertyType.IsEnum == true) 11: { 12: value = Enum.Parse(propertyInfo.PropertyType, value.ToString(), true); 13: } 14: else if (propertyInfo.PropertyType == typeof(String)) 15: { 16: value = value.ToString(); 17: } 18: else if ((typeof(IConvertible).IsAssignableFrom(propertyInfo.PropertyType) == true) && (typeof(IConvertible).IsAssignableFrom(value.GetType()) == true)) 19: { 20: value = System.Convert.ChangeType(value, propertyInfo.PropertyType); 21: } 22: } 23: } 24:  25: return (value); 26: } 27: #endregion 28:  29: #region Public override methods 30: public override CodeExpression GetCodeExpression(BoundPropertyEntry entry, Object parsedData, ExpressionBuilderContext context) 31: { 32: if (String.IsNullOrEmpty(entry.Expression) == true) 33: { 34: return (new CodePrimitiveExpression(String.Empty)); 35: } 36: else 37: { 38: return (new CodeMethodInvokeExpression(new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(this.GetType()), "GetValue"), new CodePrimitiveExpression(entry.Expression.Trim()), new CodePropertyReferenceExpression(new CodeArgumentReferenceExpression("entry"), "PropertyInfo"))); 39: } 40: } 41: #endregion 42:  43: #region Public override properties 44: public override Boolean SupportsEvaluate 45: { 46: get 47: { 48: return (true); 49: } 50: } 51: #endregion 52: } Next, the code for each expression builder: 1: [ExpressionPrefix("SPContext")] 2: public class SPContextExpressionBuilder : SPBaseExpressionBuilder 3: { 4: #region Public static methods 5: public static Object GetValue(String expression, PropertyInfo propertyInfo) 6: { 7: SPContext context = SPContext.Current; 8: Object expressionValue = DataBinder.Eval(context, expression.Trim().Replace('\'', '"')); 9:  10: expressionValue = Convert(expressionValue, propertyInfo); 11:  12: return (expressionValue); 13: } 14:  15: #endregion 16:  17: #region Public override methods 18: public override Object EvaluateExpression(Object target, BoundPropertyEntry entry, Object parsedData, ExpressionBuilderContext context) 19: { 20: return (GetValue(entry.Expression, entry.PropertyInfo)); 21: } 22: #endregion 23: }   1: [ExpressionPrefix("SPFarmProperty")] 2: public class SPFarmPropertyExpressionBuilder : SPBaseExpressionBuilder 3: { 4: #region Public static methods 5: public static Object GetValue(String propertyName, PropertyInfo propertyInfo) 6: { 7: Object propertyValue = SPFarm.Local.Properties[propertyName]; 8:  9: propertyValue = Convert(propertyValue, propertyInfo); 10:  11: return (propertyValue); 12: } 13:  14: #endregion 15:  16: #region Public override methods 17: public override Object EvaluateExpression(Object target, BoundPropertyEntry entry, Object parsedData, ExpressionBuilderContext context) 18: { 19: return (GetValue(entry.Expression, entry.PropertyInfo)); 20: } 21: #endregion 22: }   1: [ExpressionPrefix("SPField")] 2: public class SPFieldExpressionBuilder : SPBaseExpressionBuilder 3: { 4: #region Public static methods 5: public static Object GetValue(String fieldName, PropertyInfo propertyInfo) 6: { 7: Object fieldValue = SPContext.Current.ListItem[fieldName]; 8:  9: fieldValue = Convert(fieldValue, propertyInfo); 10:  11: return (fieldValue); 12: } 13:  14: #endregion 15:  16: #region Public override methods 17: public override Object EvaluateExpression(Object target, BoundPropertyEntry entry, Object parsedData, ExpressionBuilderContext context) 18: { 19: return (GetValue(entry.Expression, entry.PropertyInfo)); 20: } 21: #endregion 22: }   1: [ExpressionPrefix("SPIsInAudience")] 2: public class SPIsInAudienceExpressionBuilder : SPBaseExpressionBuilder 3: { 4: #region Public static methods 5: public static Object GetValue(String audienceName, PropertyInfo info) 6: { 7: Debugger.Break(); 8: audienceName = audienceName.Trim(); 9:  10: if ((audienceName.StartsWith("'") == true) && (audienceName.EndsWith("'") == true)) 11: { 12: audienceName = audienceName.Substring(1, audienceName.Length - 2); 13: } 14:  15: AudienceManager manager = new AudienceManager(); 16: Object value = manager.IsMemberOfAudience(SPControl.GetContextWeb(HttpContext.Current).CurrentUser.LoginName, audienceName); 17:  18: if (info.PropertyType == typeof(String)) 19: { 20: value = value.ToString(); 21: } 22:  23: return(value); 24: } 25:  26: #endregion 27:  28: #region Public override methods 29: public override Object EvaluateExpression(Object target, BoundPropertyEntry entry, Object parsedData, ExpressionBuilderContext context) 30: { 31: return (GetValue(entry.Expression, entry.PropertyInfo)); 32: } 33: #endregion 34: }   1: [ExpressionPrefix("SPIsInGroup")] 2: public class SPIsInGroupExpressionBuilder : SPBaseExpressionBuilder 3: { 4: #region Public static methods 5: public static Object GetValue(String groupName, PropertyInfo info) 6: { 7: groupName = groupName.Trim(); 8:  9: if ((groupName.StartsWith("'") == true) && (groupName.EndsWith("'") == true)) 10: { 11: groupName = groupName.Substring(1, groupName.Length - 2); 12: } 13:  14: Object value = SPControl.GetContextWeb(HttpContext.Current).CurrentUser.Groups.OfType<SPGroup>().Any(x => String.Equals(x.Name, groupName, StringComparison.OrdinalIgnoreCase)); 15:  16: if (info.PropertyType == typeof(String)) 17: { 18: value = value.ToString(); 19: } 20:  21: return(value); 22: } 23:  24: #endregion 25:  26: #region Public override methods 27: public override Object EvaluateExpression(Object target, BoundPropertyEntry entry, Object parsedData, ExpressionBuilderContext context) 28: { 29: return (GetValue(entry.Expression, entry.PropertyInfo)); 30: } 31: #endregion 32: }   1: [ExpressionPrefix("SPProperty")] 2: public class SPPropertyExpressionBuilder : SPBaseExpressionBuilder 3: { 4: #region Public static methods 5: public static Object GetValue(String propertyName, System.Reflection.PropertyInfo propertyInfo) 6: { 7: SPServiceContext serviceContext = SPServiceContext.GetContext(HttpContext.Current); 8: UserProfileManager upm = new UserProfileManager(serviceContext); 9: UserProfile up = upm.GetUserProfile(false); 10: Object propertyValue = (up[propertyName] != null) ? up[propertyName].Value : null; 11:  12: propertyValue = Convert(propertyValue, propertyInfo); 13:  14: return (propertyValue); 15: } 16:  17: #endregion 18:  19: #region Public override methods 20: public override Object EvaluateExpression(Object target, BoundPropertyEntry entry, Object parsedData, ExpressionBuilderContext context) 21: { 22: return (GetValue(entry.Expression, entry.PropertyInfo)); 23: } 24: #endregion 25: }   1: [ExpressionPrefix("SPQueryString")] 2: public class SPQueryStringExpressionBuilder : SPBaseExpressionBuilder 3: { 4: #region Public static methods 5: public static Object GetValue(String parameterName, PropertyInfo propertyInfo) 6: { 7: Object parameterValue = HttpContext.Current.Request.QueryString[parameterName]; 8:  9: parameterValue = Convert(parameterValue, propertyInfo); 10:  11: return (parameterValue); 12: } 13:  14: #endregion 15:  16: #region Public override methods 17: public override Object EvaluateExpression(Object target, BoundPropertyEntry entry, Object parsedData, ExpressionBuilderContext context) 18: { 19: return (GetValue(entry.Expression, entry.PropertyInfo)); 20: } 21: #endregion 22: }   1: [ExpressionPrefix("SPWebProperty")] 2: public class SPWebPropertyExpressionBuilder : SPBaseExpressionBuilder 3: { 4: #region Public static methods 5: public static Object GetValue(String propertyName, PropertyInfo propertyInfo) 6: { 7: Object propertyValue = SPContext.Current.Web.AllProperties[propertyName]; 8:  9: propertyValue = Convert(propertyValue, propertyInfo); 10:  11: return (propertyValue); 12: } 13:  14: #endregion 15:  16: #region Public override methods 17: public override Object EvaluateExpression(Object target, BoundPropertyEntry entry, Object parsedData, ExpressionBuilderContext context) 18: { 19: return (GetValue(entry.Expression, entry.PropertyInfo)); 20: } 21: #endregion 22: } Registration You probably know how to register them, but here it goes again: add this following snippet to your Web.config file, inside the configuration/system.web/compilation/expressionBuilders section: 1: <add expressionPrefix="SPContext" type="MyNamespace.SPContextExpressionBuilder, MyAssembly, Culture=neutral, Version=1.0.0.0, PublicKeyToken=xxx" /> 2: <add expressionPrefix="SPFarmProperty" type="MyNamespace.SPFarmPropertyExpressionBuilder, MyAssembly, Culture=neutral, Version=1.0.0.0, PublicKeyToken=xxx" /> 3: <add expressionPrefix="SPField" type="MyNamespace.SPFieldExpressionBuilder, MyAssembly, Culture=neutral, Version=1.0.0.0, PublicKeyToken=xxx" /> 4: <add expressionPrefix="SPIsInAudience" type="MyNamespace.SPIsInAudienceExpressionBuilder, MyAssembly, Culture=neutral, Version=1.0.0.0, PublicKeyToken=xxx" /> 5: <add expressionPrefix="SPIsInGroup" type="MyNamespace.SPIsInGroupExpressionBuilder, MyAssembly, Culture=neutral, Version=1.0.0.0, PublicKeyToken=xxx" /> 6: <add expressionPrefix="SPProperty" type="MyNamespace.SPPropertyExpressionBuilder, MyAssembly, Culture=neutral, Version=1.0.0.0, PublicKeyToken=xxx" /> 7: <add expressionPrefix="SPQueryString" type="MyNamespace.SPQueryStringExpressionBuilder, MyAssembly, Culture=neutral, Version=1.0.0.0, PublicKeyToken=xxx" /> 8: <add expressionPrefix="SPWebProperty" type="MyNamespace.SPWebPropertyExpressionBuilder, MyAssembly, Culture=neutral, Version=1.0.0.0, PublicKeyToken=xxx" /> I’ll leave it up to you to figure out the best way to deploy this to your server!

    Read the article

  • Mysterious dbboon folder with proxy.php file on my godaddy account

    - by Paul
    When doing some web maintenance today, I noticed a strange new folder on my GoDaddy hosting account at the root level named "dbboon", with a single file inside, called proxy.php. It's code is listed below, and seems to be some sort of proxy function. I was kind of troubled because I didn't put it there. I googled all this to learn more, but didn't find anything, except for the proxy file happened to be also stored at pastebin.com: http://pastebin.com/PQsSPbCr I called GoDaddy and they confirmed that it belonged to them, said it was put there by their advanced hosting group for testing purposes but didn't have any more information. I thought this was all really weird: why would they put something in my folder without giving me a heads-up, and why would they need to do something like this? anybody know anything about this? <?php $version = '1.2'; if(isset($_GET['dbboon_version'])) { echo '{"version":"' . $version . '"}'; exit; } function dbboon_parseHeaders($subject) { global $version; $subject = trim($subject); $parsed = Array(); $len = strlen($subject); $position = $field = 0; $position = strpos($subject, "\r\n") + 2; while(isset($subject[$position])) { $nextC = strpos($subject, ':', $position); $fieldName = substr($subject, $position, ($nextC-$position)); $position += strlen($fieldName) + 1; $fieldValue = NULL; while(1) { $nextCrlf = strpos($subject, "\r\n", $position - 1); if(FALSE === $nextCrlf) { $t = substr($subject, $position); $position = $len; } else { $t = substr($subject, $position, $nextCrlf-$position); $position += strlen($t) + 2; } $fieldValue .= $t; if(!isset($subject[$position]) || (' ' != $subject[$position] && "\t" != $subject[$position])) { break; } } $parsed[strtolower($fieldName)] = trim($fieldValue); if($position > $len) { echo '{"result":false,"error":{"code":4,"message":"Communication error, unable to contact proxy service.","version":"' . $version . '"}}'; exit; } } return $parsed; } if(!function_exists('http_build_query')) { function http_build_query($data, $prefix = '', $sep = '', $key = '') { $ret = Array(); foreach((array) $data as $k => $v) { if(is_int($k) && NULL != $prefix) { $k = urlencode($prefix . $k); } if(!empty($key) || $key === 0) { $k = $key . '[' . urlencode($k) . ']'; } if(is_array($v) || is_object($v)) { array_push($ret, http_build_query($v, '', $sep, $k)); } else { array_push($ret, $k . '=' . urlencode($v)); } } if(empty($sep)) { $sep = '&'; } return implode($sep, $ret); } } $host = 'dbexternalsubscriber.secureserver.net'; $get = http_build_query($_GET); $post = http_build_query($_POST); $url = $get ? "?$get" : ''; $fp = fsockopen($host, 80, $errno, $errstr); if($fp) { $payload = "POST /embed/$url HTTP/1.1\r\n"; $payload .= "Host: $host\r\n"; $payload .= "Content-Length: " . strlen($post) . "\r\n"; $payload .= "Content-Type: application/x-www-form-urlencoded\r\n"; $payload .= "Connection: Close\r\n\r\n"; $payload .= $post; fwrite($fp, $payload); $httpCode = NULL; $response = NULL; $timeout = time() + 15; do { while($line = fgets($fp)) { $response .= $line; if(!trim($line)) { break; } } } while($timeout > time() && NULL === $response); $headers = dbboon_parseHeaders($response); if(isset($headers['transfer-encoding']) && 'chunked' === $headers['transfer-encoding']) { do { $cSize = $read = hexdec(trim(fgets($fp))); while($read > 0) { $buff = fread($fp, $read); $read -= strlen($buff); $response .= $buff; } $response .= fgets($fp); } while($cSize > 0); } else { preg_match('/Content-Length:\s([0-9]+)\r\n/msi', $response, $match); if(!isset($match[1])) { echo '{"result":false,"error":{"code":3,"message":"Communication error, unable to contact proxy service.","version":"' . $version . '"}}'; exit; } else { while($match[1] > 0) { $buff = fread($fp, $match[1]); $match[1] -= strlen($buff); $response .= $buff; } } } fclose($fp); if(!$pos = strpos($response, "\r\n\r\n")) { echo '{"result":false,"error":{"code":2,"message":"Communication error, unable to contact proxy service.","version":"' . $version . '"}}'; exit; } echo substr($response, $pos + 4); } else { echo '{"result":false,"error":{"code":1,"message":"Communication error, unable to contact proxy service.","version":"' . $version . '"}}'; exit; }

    Read the article

  • How to remove illegal characters from path and filenames?

    - by Gary Willoughby
    I need a robust and simple way to remove illegal path and file characters from a simple string. I've used the below code but it doesn't seem to do anything, what am i missing? using System; using System.IO; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { string illegal = "\"M<>\"\\a/ry/ h**ad:>> a\\/:*?\"<>| li*tt|le|| la\"mb.?"; illegal = illegal.Trim(Path.GetInvalidFileNameChars()); illegal = illegal.Trim(Path.GetInvalidPathChars()); Console.WriteLine(illegal); Console.ReadLine(); } } }

    Read the article

  • Security failure - This is not a secure document but has security embed parameters

    - by dimitris mistriotis
    I try to create a private version and therefore I used something like this in php: var scribd_doc = scribd.Document.getDoc( 28394353, 'xxx'); scribd_doc.addParam("use_ssl", true); scribd_doc.addParam('public', false); scribd_doc.grantAccess("cbccf6e7-1ff7-9034-8a7c-a0c2a5b225ed", <?php echo "'" . trim($_COOKIE['PHPSESSID']) . "'" ?>, <?php echo "'" . scribd_calculate_signature($documentID = '28394353', $sessionID = trim($_COOKIE['PHPSESSID']), $userID = "cbccf6e7-1ff7-9034-8a7c-a0c2a5b225ed") . "'" ?>); ... ... scribd_doc.write( 'embedded_flash' ); Which is the api of scribd for javascript with the addition of the signature. My result is the "Security failure - This is not a secure document but has security embed parameters" Error, which is not well documented. The document is set to private. Any ideas?

    Read the article

  • VB.NET add an element to the XML document with LINQ to XML

    - by Bayonian
    Hi, I'm adding an element to existing XML doc with the following code: Dim theXMLSource As String = Server.MapPath("~/Demo/") & "LabDemo.xml" Dim nodeElement As XElement Dim attrAndValue As XElement = _ <LabService> <ServiceType> <%= txtServiceType.Text.Trim %> </ServiceType> <Level> <%= txtLevel.Text.Trim %> </Level> </LabService> nodeElement.Add(New XElement(attrAndValue)) nodeElement.Save(theXMLSource) It makes error like this: System.NullReferenceException: Object reference not set to an instance of an object. Object reference not set to an instance of an object. Error line: nodeElement.Add(New XElement(attrAndValue)) I debugged it but I couldn't get the error yet. Can you show what the problem is? Thank you

    Read the article

  • The second argument to copy() function cannot be a directory

    - by Jorm
    Anyone know why this: $title = trim($_POST['title']); $description = trim($_POST['description']); // Array of allowed image file formats $allowedExtensions = array('jpeg', 'jpg', 'jfif', 'png', 'gif', 'bmp'); foreach ($_FILES as $file) { if ($file['tmp_name'] > '') { if (!in_array(end(explode(".", strtolower($file['name']))), $allowedExtensions)) { echo '<div class="error">Invalid file type.</div>'; } } } if (strlen($title) < 3) echo '<div class="error">Too short title</div>'; else if (strlen($description) > 70) echo '<div class="error">Too long desccription.</div>'; else { move_uploaded_file($_FILES['userfile']['tmp_name'], 'c:\wamp\www\uploads\images/'); } Gives: Warning: move_uploaded_file() [function.move-uploaded-file]: The second argument to copy() function cannot be a directory in C:\wamp\www\upload.php on line 41 Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move 'C:\wamp\tmp\php1AB.tmp' to 'c:\wamp\www\uploads\images/' in C:\wamp\www\upload.php on line 41

    Read the article

  • JQGrid and JQuery Autocomplete

    - by Neff
    When implementing JQGrid 4.3.0, Jquery 1.6.2, and JQuery UI 1.8.16 Ive come across an issue with the Inline edit. When the inline edit is activated, some of the elements get assigned an auto complete. When the inline edit is canceld or saved, the auto complete does not always go away (selecting text by double clicking it then hitting delete, then hitting escape to exit row edit). Leaving the auto complete controls in edit mode when the row is no longer considered in edit mode. Perhaps you can tell me if there is a problem with the initialization or if I you are aware of an event post-"afterrestorefunc" that the fields can be returned to their "original" state. Original state being displayed as data in the JQGrid row. I've tried removing the DOM after row close, .remove() and .empty(): ... "afterrestorefunc": function(){ $('.ui-autocomplete-input').remove(); } ... but that causes other issues, such as the jqgrid is not able to find the cell when serializing the row for data or edit, and requires a refresh of the page, not just jqgrid, to be able to once again see the data from that row. Auto complete functionality for the element is created on the double click of the row: function CreateCustomSearchElement(value, options, selectiontype) { ... var el; el = document.createElement("input"); ... $(el).autocomplete({ source: function (request, response) { $.ajax({ url: '<%=ResolveUrl("~/Services/AutoCompleteService.asmx/GetAutoCompleteResponse") %>', data: "{ 'prefixText': '" + request.term + "', 'contextKey': '" + options.name + "'}", dataType: "json", type: "POST", contentType: "application/json; charset=utf-8", success: function (data) { response($.map(data.d, function (item) { return { label: Trim(item), value: Trim(item), searchVal: Trim(item) } })) } }); }, select: function (e, item) { //Select is on the event of selection where the value and label have already been determined. }, minLength: 1, change: function (event, ui) { //if the active element was not the search button //... } }).keyup(function (e) { if (e.keyCode == 8 || e.keyCode == 46) { //If the user hits backspace or delete, check the value of the textbox before setting the searchValue //... } }).keydown(function (e) { //if keycode is enter key and there is a value, you need to validate the data through select or change(onblur) if (e.keyCode == '13' && ($(el).val())) { return false; } if (e.keyCode == '220') { return false } }); } Other Sources: http://www.trirand.com/jqgridwiki/doku.php?id=wiki:inline_editing http://api.jqueryui.com/autocomplete/ Update: I tried only creating the autocomplete when the element was focused, and removing it when onblur. That did not resolve the issue either. It seems to just need the autocomplete dropdown to be triggered.

    Read the article

  • Fast way to test if a port is in use using Python

    - by directedition
    I have a python server that listens on a couple sockets. At startup, I try to connect to these sockets before listening, so I can be sure that nothing else is already using that port. This adds about three seconds to my server's startup (which is about .54 seconds without the test) and I'd like to trim it down. Since I'm only testing localhost, I think a timeout of about 50 milliseconds is more than ample for that. Unfortunately, the socket.setdefaulttimeout(50) method doesn't seem to work for some reason. How I can trim this down?

    Read the article

  • Piping SoX in Python - subprocess alternative?

    - by Cochise Ruhulessin
    I use SoX in an application. The application uses it to apply various operations on audiofiles, such as trimming. This works fine: from subprocess import Popen, PIPE kwargs = {'stdin': PIPE, 'stdout': PIPE, 'stderr': PIPE} pipe = Popen(['sox','-t','mp3','-', 'test.mp3','trim','0','15'], **kwargs) output, errors = pipe.communicate(input=open('test.mp3','rb').read()) if errors: raise RuntimeError(errors) This will cause problems on large files hower, since read() loads the complete file to memory; which is slow and may cause the pipes' buffer to overflow. A workaround exists: from subprocess import Popen, PIPE import tempfile import uuid import shutil import os kwargs = {'stdin': PIPE, 'stdout': PIPE, 'stderr': PIPE} tmp = os.path.join(tempfile.gettempdir(), uuid.uuid1().hex + '.mp3') pipe = Popen(['sox','test.mp3', tmp,'trim','0','15'], **kwargs) output, errors = pipe.communicate() if errors: raise RuntimeError(errors) shutil.copy2(tmp, 'test.mp3') os.remove(tmp) So the question stands as follows: Are there any alternatives to this approach, aside from writing a Python extension to the Sox C API?

    Read the article

  • Recommendations on Triming Large Amounts of Text from a DOM Object

    - by aronchick
    I'm doing some in browser editing, and I have some content that's on the order of around 20k characters long in a <pre>. So it looks something like: <pre> Text 1 Text 2 Text 3 Text 4 [...] Text 20,000 </pre> I'd like to use jquery to trim it down when someone hits a button to chop, but I'm having trouble doing it without overloading the browser. Assume I know that the character numbers are at 16,510 - 17,888, and what I'd like to do is trim it. I was using: jQuery('#textsection').html(jQuery('textarea').html().substr(range.start)); But browsers seem to enjoy crashing when I do this. Alternatives?

    Read the article

  • getView only shows Flagged Backgrounds for drawn Views, It does not show Flagged Background when scroll to view more items on list

    - by Leoa
    I am trying to create a listview that receives a flagged list of items to indicate a status to the user. I have been able to create the flag display by using a yellow background (see image at bottom). In Theory, the flagged list can have many flagged items in it. However in my app, only the first three flagged backgrounds are shown. I believe this is because they are initially drawn to the screen. The Flagged background that are not drawn initially to the screen do not show. I'd like to know how to get the remaining flags to show in the list. ListView Recycling: The backgrounds in the listView are being recycled in getView(). This recycling goes from position 0 to position 9. I have flags that need to match at positions 13, 14 and so on. Those positions are not being displayed. listView.getCheckedItemPositions() for multiple selections: This method will not work in my case because the user will not selected the flags. The flags are coming from the server. setNotifyOnChange() and/or public virtual void SetNotifyOnChange (bool notifyOnChange): I'm not adding new data to the list, so I don't see how this method would work for my program. Does this method communicate to getview when it is recycling data? I was unable to find an answer to this in my research. public void registerDataSetObserver: This may be overkill for my problem, but is it possible to have an observer object that keeps track of the all the positions in my items list and in my flag list no matter if the view is recycled and match them on the screen? Code: package com.convention.notification.app; import java.util.Iterator; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.content.Context; import android.graphics.Color; import android.os.Bundle; import android.text.Html; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.TextView; public class NewsRowAdapter extends ArrayAdapter<Item> { private Activity activity; private List<Item> items; private Item objBean; private int row; private List<Integer> disable; View view ; int disableView; public NewsRowAdapter(Activity act, int resource, List<Item> arrayList, List<Integer> disableList) { super(act, resource, arrayList); this.activity = act; this.row = resource; this.items = arrayList; this.disable=disableList; System.out.println("results of delete list a:"+disable.toString()); } public int getCount() { return items.size(); } public Item getItem(int position) { return items.get(position); } public long getItemId(int position) { return position; } @Override public int getItemViewType(int position) { for(int k =0;k < disable.size();k++){ if(position==disable.get(k)){ //System.out.println( "is "+position+" value of disable "+disable.get(k)); disableView=disable.get(k); //AdapterView.getItemAtPosition(position); } } return position; } @Override public View getView(final int position, View convertView, ViewGroup parent) { View view = convertView; ViewHolder holder; if (view == null) { LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = inflater.inflate(row, null); getItemViewType(position); long id=getItemId(position); if(position==disableView){ view.setBackgroundColor(Color.YELLOW); System.out.println(" background set to yellow at position "+position +" disableView is at "+disableView); }else{ view.setBackgroundColor(Color.WHITE); System.out.println(" background set to white at position "+position +" disableView is at "+disableView); } //ViewHolder is a custom class that gets TextViews by name: tvName, tvCity, tvBDate, tvGender, tvAge; holder = new ViewHolder(); /* setTag Sets the tag associated with this view. A tag can be used to * mark a view in its hierarchy and does not have to be unique * within the hierarchy. Tags can also be used to store data within * a view without resorting to another data structure. */ view.setTag(holder); } else { //the Object stored in this view as a tag holder = (ViewHolder) view.getTag(); } if ((items == null) || ((position + 1) > items.size())) return view; objBean = items.get(position); holder.tv_event_name = (TextView) view.findViewById(R.id.tv_event_name); holder.tv_event_date = (TextView) view.findViewById(R.id.tv_event_date); holder.tv_event_start = (TextView) view.findViewById(R.id.tv_event_start); holder.tv_event_end = (TextView) view.findViewById(R.id.tv_event_end); holder.tv_event_location = (TextView) view.findViewById(R.id.tv_event_location); if (holder.tv_event_name != null && null != objBean.getName() && objBean.getName().trim().length() > 0) { holder.tv_event_name.setText(Html.fromHtml(objBean.getName())); } if (holder.tv_event_date != null && null != objBean.getDate() && objBean.getDate().trim().length() > 0) { holder.tv_event_date.setText(Html.fromHtml(objBean.getDate())); } if (holder.tv_event_start != null && null != objBean.getStartTime() && objBean.getStartTime().trim().length() > 0) { holder.tv_event_start.setText(Html.fromHtml(objBean.getStartTime())); } if (holder.tv_event_end != null && null != objBean.getEndTime() && objBean.getEndTime().trim().length() > 0) { holder.tv_event_end.setText(Html.fromHtml(objBean.getEndTime())); } if (holder.tv_event_location != null && null != objBean.getLocation () && objBean.getLocation ().trim().length() > 0) { holder.tv_event_location.setText(Html.fromHtml(objBean.getLocation ())); } return view; } public class ViewHolder { public TextView tv_event_name, tv_event_date, tv_event_start, tv_event_end, tv_event_location /*tv_event_delete_flag*/; } } Logcat: 06-12 20:54:12.058: I/System.out(493): item disalbed is at postion :0 06-12 20:54:12.058: I/System.out(493): item disalbed is at postion :4 06-12 20:54:12.069: I/System.out(493): item disalbed is at postion :5 06-12 20:54:12.069: I/System.out(493): item disalbed is at postion :13 06-12 20:54:12.069: I/System.out(493): item disalbed is at postion :14 06-12 20:54:12.069: I/System.out(493): item disalbed is at postion :17 06-12 20:54:12.069: I/System.out(493): results of delete list :[0, 4, 5, 13, 14, 17] 06-12 20:54:12.069: I/System.out(493): results of delete list a:[0, 4, 5, 13, 14, 17] 06-12 20:54:12.069: I/System.out(493): set adapaer to list view called; 06-12 20:54:12.128: I/System.out(493): background set to yellow at position 0 disableView is at 0 06-12 20:54:12.628: I/System.out(493): background set to white at position 1 disableView is at 0 06-12 20:54:12.678: I/System.out(493): background set to white at position 2 disableView is at 0 06-12 20:54:12.708: I/System.out(493): background set to white at position 3 disableView is at 0 06-12 20:54:12.738: I/System.out(493): background set to yellow at position 4 disableView is at 4 06-12 20:54:12.778: I/System.out(493): background set to yellow at position 5 disableView is at 5 06-12 20:54:12.808: I/System.out(493): background set to white at position 6 disableView is at 5 06-12 20:54:12.838: I/System.out(493): background set to white at position 7 disableView is at 5 This is a link to my first question a day ago: Change Background on a specific row based on a condition in Custom Adapter I appreciate your help!

    Read the article

  • New to programming

    - by Shaun
    I have a form (Quote) with an auto-number ID, on the form at the moment are two subforms that show different items (sub 1 shows partition modules sub 2 shows partition abutments) both forms use the same parts tables to build them. Both forms are linked to the quote form using the ID. All works well until the forms is refreshed or re-loaded, subform 1 shows the module names and quantities and blank spaces for the abutment names but shows the quantiews for the abutments, the reverse of this is shown in the abutments subform 2. When the lists for the variuos types and the detailed parts lists are printed they are correct. This seems to be only a visual problem. All based on Access 2003. Subform 1 SELECT Quote_Modules.ModuleID, Quote_Modules.QuoteID, Quote_Modules.ModuleDescription, Quote_Modules.ModuleQty, Quote.Style, Quote.Trim FROM Quote INNER JOIN Quote_Modules ON Quote.QuoteID=Quote_Modules.QuoteID ORDER BY Quote_Modules.ModuleID; Subform 2 SELECT Quote_Modules.ModuleID, Quote_Modules.QuoteID, Quote_Modules.ModuleDescription, Quote_Modules.ModuleQty, Quote.Style, Quote.Trim FROM Quote INNER JOIN Quote_Modules ON Quote.QuoteID=Quote_Modules.QuoteID ORDER BY Quote_Modules.ModuleID;

    Read the article

  • R: Using sapply on vector of POSIXct

    - by Chris
    I have what may be a very simple question. I want to process a column of POSIXct objects from a dataframe and generate a vector of datetime strings. I tried to use the following sapply call dt <- sapply(df$datetime, function(x) format(x,"%Y-%m-%dT%H:%M:%S")) but to no avail. I keep getting the following error Error in prettyNum(.Internal(format(x, trim, digits, nsmall, width, 3L, : invalid 'trim' argument When I apply this function to a single POSIXct object from the column, I have no problem. So I'm stumped at the moment about what the problem is. Do I need to do something special with POSIXct objects?

    Read the article

< Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >