Search Results

Search found 54 results on 3 pages for 'strstr'.

Page 2/3 | < Previous Page | 1 2 3  | Next Page >

  • string manipulation without alloc mem in c

    - by Mike
    I'm wondering if there is another way of getting a sub string without allocating memory. To be more specific, I have a string as: const char *str = "9|0\" 940 Hello"; Currently I'm getting the 940, which is the sub-string I want as, char *a = strstr(str,"9|0\" "); char *b = substr(a+5, 0, 3); // gives me the 940 Where substr is my sub string procedure. The thing is that I don't want to allocate memory for this by calling the sub string procedure. Is there a much easier way?, perhaps by doing some string manipulation and not alloc mem. I'll appreciate any feedback.

    Read the article

  • string parsing and substring in c

    - by Josh
    I'm trying to parse the string below in a good way so I can get the sub-string stringI-wantToGet: const char *str = "Hello \"FOO stringI-wantToGet BAR some other extra text"; str will vary in length but always same pattern - FOO and BAR What I had in mind was something like: const char *str = "Hello \"FOO stringI-wantToGet BAR some other extra text"; char *probe, *pointer; probe = str; while(probe != '\n'){ if(probe = strstr("\"FOO")!=NULL) probe++ else probe = ""; // Nulterm part if(pointer = strchr(probe, ' ')!=NULL) pointer = '\0'; // not sure here, I was planning to separate it with \0's } Any help will be appreciate it.

    Read the article

  • Finding all instances of a substring in a string

    - by Mr Aleph
    In my last question I asked about parsing the links out of an HTML page. Since I haven't found a solution yet I thought I tried something else in the meantime: search for every <a href= and copy whatever is there until I hit a </a>. Now, my C is a bit rusty but I do remember i can use strstr() to get the first instance of that string, but how do I get the rest? Any help is appreciated. PS: No. This is not homework on school or something like that. Just so you know.

    Read the article

  • parsing Two-dimensional array in c

    - by gitter78
    I'm trying to parse an array that looks like the one below: char *arr[][2] = { { "1", "Purple" }, { "2", "Blue" }, { "22", "Red" }, ... }; I was thinking having a loop as: char *func(char *a){ for(i = 0; i<sizeof(arr)/sizeof(arr[0]);i++){ if(strstr(a,arr[i][0])!=NULL) return arr[i][1]; } } char *out; const char *hello = "this is my 2 string"; out = func(hello); In this case, I'm trying to get the second value based on the first one: Purple, Blue Red, etc.. The question is how would go in parsing this and instead of printing out the value, return the value. UPDATE/FIXED: It has been fixed above. Thanks

    Read the article

  • PHP 5.3 Namespaces should i use every PHP function with backslash?

    - by lhwparis
    Hi, im now using namespaces in PHP 5.3 now there is a fallback mechanism for functions which dont exist in the namespace. so php every time checks if the function exists in namespace and then tries to load it from global space. So what about all php internal functions? strstr for example? Should i now use every php internal function with a \ ? to avoid php first checking the namespace? is this fallback a huge performance drop? what do you think?

    Read the article

  • PHP - Search array in array

    - by Anonymous2011
    I have tried googling for the past one hour straight now and tried many ways to search for an array, in an array. My objective is, to find a keyword in the URL, and the keywords are in a txt file. This is what i have so far - but doesn't work. $file = "keywords.txt"; $open = fopen($file,'r'); $data = fread($open,filesize($file)); $data = explode(" ",$data); $url = (!empty($_SERVER['HTTPS'])) ? "https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'] : "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']; $url = parse_url($url); //parse the URL into an array foreach($data as $d) { if(strstr($d,$url)) { echo "yes"; } } This works WITHOUT the text file, or array - but that's not what i want. I'd appreciate it if anyone can assist me.

    Read the article

  • "exception at 0x53C227FF (msvcr110d.dll)" with SOIL library

    - by Sean M.
    I'm creating a game in C++ using OpenGL, and decided to go with the SOIL library for image loading, as I have used it in the past to great effect. The problem is, in my newest game, trying to load an image with SOIL throws the following runtime error: This error points to this part: // SOIL.c int query_NPOT_capability( void ) { /* check for the capability */ if( has_NPOT_capability == SOIL_CAPABILITY_UNKNOWN ) { /* we haven't yet checked for the capability, do so */ if( (NULL == strstr( (char const*)glGetString( GL_EXTENSIONS ), "GL_ARB_texture_non_power_of_two" ) ) ) //############ it points here ############// { /* not there, flag the failure */ has_NPOT_capability = SOIL_CAPABILITY_NONE; } else { /* it's there! */ has_NPOT_capability = SOIL_CAPABILITY_PRESENT; } } /* let the user know if we can do non-power-of-two textures or not */ return has_NPOT_capability; } Since it points to the line where SOIL tries to access the OpenGL extensions, I think that for some reason SOIL is trying to load the texture before an OpenGL context is created. The problem is, I've gone through the entire solution, and there is only one place where SOIL has to load a texture, and it happens long after the OpenGL context is created. This is the part where it loads the texture... //Init glfw if (!glfwInit()) { fprintf(stderr, "GLFW Initialization has failed!\n"); exit(EXIT_FAILURE); } printf("GLFW Initialized.\n"); //Process the command line arguments processCmdArgs(argc, argv); //Create the window glfwWindowHint(GLFW_SAMPLES, g_aaSamples); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); g_mainWindow = glfwCreateWindow(g_screenWidth, g_screenHeight, "Voxel Shipyard", g_fullScreen ? glfwGetPrimaryMonitor() : nullptr, nullptr); if (!g_mainWindow) { fprintf(stderr, "Could not create GLFW window!\n"); closeOGL(); exit(EXIT_FAILURE); } glfwMakeContextCurrent(g_mainWindow); printf("Window and OpenGL rendering context created.\n"); //Create the internal rendering components prepareScreen(); //Init glew glewExperimental = GL_TRUE; int err = glewInit(); if (err != GLEW_OK) { fprintf(stderr, "GLEW initialization failed!\n"); fprintf(stderr, "%s\n", glewGetErrorString(err)); closeOGL(); exit(EXIT_FAILURE); } printf("GLEW initialized.\n"); <-- Sucessfully creates an OpenGL context //Initialize the app g_app = new App(); g_app->PreInit(); g_app->Init(); g_app->PostInit(); <-- Loads the texture (after the context is created) ...and debug printing to the console CONFIRMS that the OpenGL context was created before the texture loading was attempted. So my question is if anyone is familiar with this specific error, or knows if there is a specific instance as to why SOIL would think OpenGL isn't initialized yet.

    Read the article

  • Remote Socket Read In Multi-Threaded Application Returns Zero Bytes or EINTR (104)

    - by user39891
    Hi. Am a c-coder for a while now - neither a newbie nor an expert. Now, I have a certain daemoned application in C on a PPC Linux. I use PHP's socket_connect as a client to connect to this service locally. The server uses epoll for multiplexing connections via a Unix socket. A user submitted string is parsed for certain characters/words using strstr() and if found, spawns 4 joinable threads to different websites simultaneously. I use socket, connect, write and read, to interact with the said webservers via TCP on their port 80 in each thread. All connections and writes seems successful. Reads to the webserver sockets fail however, with either (A) all 3 threads seem to hang, and only one thread returns -1 and errno is set to 104. The responding thread takes like 10 minutes - an eternity long:-(. *I read somewhere that the 104 (is EINTR?), which in the network context suggests that ...'the connection was reset by peer'; or (B) 0 bytes from 3 threads, and only 1 of the 4 threads actually returns some data. Isn't the socket read/write thread-safe? I use thread-safe (and reentrant) libc functions such as strtok_r, gethostbyname_r, etc. *I doubt that the said webhosts are actually resetting the connection, because when I run a single-threaded standalone (everything else equal) all things works perfectly right, but of course in series not parallel. There's a second problem too (oops), I can't write back to the client who connect to my epoll-ed Unix socket. My daemon application will hang and hog CPU 100% for ever. Yet nothing is written to the clients end. Am sure the client (a very typical PHP socket application) hasn't closed the connection whenever this is happening - no error(s) detected either. Any ideas? I cannot figure-out whatever is wrong even with Valgrind, GDB or much logging. Kindly help where you can.

    Read the article

  • Choose variable based on users choice from picklist.

    - by Kelbizzle
    I have this form. Basically what I want is to send a auto-response with a different URL based on what the user picks in the "attn" picklist. I've been thinking I could have a different variable for each drop down value. It will then pass this variable on to the mail script that will choose which URL to insert inside the auto response that is sent. It gives me a headache thinking about it sometimes. What's the easiest way to accomplish this? Am I making more work for myself? I really don't know because I'm no programmer. Thanks in advance! Here is the form: <form name="contact_form" method="post" action="sendemail_reports.php" onsubmit="return validate_form ( );"> <div id='zohoWebToLead' align=center> <table width="100%" border="0" align="center" cellpadding="0" cellspacing="0" class="txt_body"> <table border=0 cellspacing=0 cellpadding=5 width=480 style='border-bottom-color: #999999; border-top-color: #999999; border-bottom-style: none; border-top-style: none; border-bottom-width: 1px; border-top-width: 2px; background-color:transparent;'> <tr> <td width='75%'><table width=480 border=0 cellpadding=5 cellspacing=0 style='border-bottom-color: #999999; border-top-color: #999999; border-bottom-style: none; border-top-style: none; border-bottom-width: 1px; border-top-width: 2px; background-color:transparent;'> <input type="hidden" name="ip" value="'.$ipi.'" /> <input type="hidden" name="httpref" value="'.$httprefi.'" /> <input type="hidden" name="httpagent" value="'.$httpagenti.'" /> <tr></tr> <tr> <td colspan='2' align='left' style='border-bottom-color: #dadada; border-bottom-style: none; border-bottom-width: 2px; color:#000000; font-family:sans-serif; font-size:14px;'><strong>Send us an Email</strong></td> </tr> <tr> <td nowrap style='font-family:sans-serif;font-size:12px;font-weight:bold' align='right' width='25%'> First Name   : </td> <td width='75%'><input name='visitorf' type='text' size="48" maxlength='40' /></td> </tr> <tr> <td nowrap style='font-family:sans-serif;font-size:12px;font-weight:bold' align='right' width='25%'>Last Name   :</td> <td width='75%'><input name='visitorfl' type='text' size="48" maxlength='80' /></td> </tr> <tr> <td nowrap style= 'font-family:sans-serif;font-size:12px;font-weight:bold' align='right' width='25%'> Email Adress  : </td> <td width='75%'><input name='visitormail' type='text' size="48" maxlength='100' /></td> </tr> <tr> <td nowrap style='font-family:sans-serif;font-size:12px;font-weight:bold' align='right' width='25%'> Phone   : </td> <td width='75%'><input name='visitorphone' type='text' size="48" maxlength='30' /></td> </tr> <td nowrap style='font-family:sans-serif;font-size:12px;font-weight:bold' align='right' width='25%'> Subject   : </td> <td width='75%'><select name="attn" size="1"> <option value=" Investment Opportunities ">Investment Opportunities </option> <option value=" Vacation Rentals ">Vacation Rentals </option> <option value=" Real Estate Offerings ">Real Estate Offerings </option> <option value=" Gatherings ">Gatherings </option> <option value=" General ">General </option> </select></td> <tr> <td nowrap style= 'font-family:sans-serif;font-size:12px;font-weight:bold' align='right' width='25%'> Message   :<br /> <em>(max 5000 char)</em></td> <td width='75%'><textarea name='notes' maxlength='5000' cols="48" rows="3"></textarea></td> </tr> <tr> <td colspan=2 align=center style=''><input name='save' type='submit' class="boton" value=Send mail /> &nbsp; &nbsp; <input type='reset' name='reset' value=Reset class="boton" /></td> </tr> </table></td> </tr> </table> </div> </form> Here is the mail script: <?php //the 3 variables below were changed to use the SERVER variable $ip = $_SERVER['REMOTE_ADDR']; $httpref = $_SERVER['HTTP_REFERER']; $httpagent = $_SERVER['HTTP_USER_AGENT']; $visitorf = $_POST['visitorf']; $visitorl = $_POST['visitorl']; $visitormail = $_POST['visitormail']; $visitorphone = $_POST['visitorphone']; $notes = $_POST['notes']; $attn = $_POST['attn']; //additional headers $headers = 'From: Me <[email protected]>' . "\n" ; $headers = 'Bcc: [email protected]' . "\n"; if (eregi('http:', $notes)) { die ("Do NOT try that! ! "); } if(!$visitormail == "" && (!strstr($visitormail,"@") || !strstr($visitormail,"."))) { echo "<h2>Use Back - Enter valid e-mail</h2>\n"; $badinput = "<h2>Feedback was NOT submitted</h2>\n"; echo $badinput; die ("Go back! ! "); } if(empty($visitorf) || empty($visitormail) || empty($notes )) { echo "<h2>Use Back - fill in all fields</h2>\n"; die ("Use back! ! "); } $todayis = date("l, F j, Y, g:i a") ; $subject = "I want to download the report about $attn"; $notes = stripcslashes($notes); $message = "$todayis [EST] \nAttention: $attn \nMessage: $notes \nFrom: $visitorf $visitorl ($visitormail) \nTelephone Number: $visitorphone \nAdditional Info : IP = $ip \nBrowser Info: $httpagent \nReferral : $httpref\n"; //check if the function even exists if(function_exists("mail")) { //send the email mail($_SESSION['email'], $subject, $message, $headers) or die("could not send email"); } else { die("mail function not enabled"); } header( "Location: http://www.domain.com/thanks.php" ); ?>

    Read the article

  • Why is the framerate (fps) capped at 60?

    - by dennmat
    ISSUE I recently moved a project from my laptop to my desktop(machine info below). On my laptop the exact same code displays the fps(and ms/f) correctly. On my desktop it does not. What I mean by this is on the laptop it will display 300 fps(for example) where on my desktop it will show only up to 60. If I add 100 objects to the game on the laptop I'll see my frame rate drop accordingly; the same test on the desktop results in no change and the frames stay at 60. It takes a lot(~300) entities before I'll see a frame drop on the desktop, then it will descend. It seems as though its "theoretical" frames would be 400 or 500 but will never actually get to that and only do 60 until there's too much to handle at 60. This 60 frame cap is coming from no where. I'm not doing any frame limiting myself. It seems like something external is limiting my loop iterations on the desktop, but for the last couple days I've been scratching my head trying to figure out how to debug this. SETUPS Desktop: Visual Studio Express 2012 Windows 7 Ultimate 64-bit Laptop: Visual Studio Express 2010 Windows 7 Ultimate 64-bit The libraries(allegro, box2d) are the same versions on both setups. CODE Main Loop: while(!abort) { frameTime = al_get_time(); if (frameTime - lastTime >= 1.0) { lastFps = fps/(frameTime - lastTime); lastTime = frameTime; avgMspf = cumMspf/fps; cumMspf = 0.0; fps = 0; } /** DRAWING/UPDATE CODE **/ fps++; cumMspf += al_get_time() - frameTime; } Note: There is no blocking code in the loop at any point. Where I'm at My understanding of al_get_time() is that it can return different resolutions depending on the system. However the resolution is never worse than seconds, and the double is represented as [seconds].[finer-resolution] and seeing as I'm only checking for a whole second al_get_time() shouldn't be responsible. My project settings and compiler options are the same. And I promise its the same code on both machines. My googling really didn't help me much, and although technically it's not that big of a deal. I'd really like to figure this out or perhaps have it explained, whichever comes first. Even just an idea of how to go about figuring out possible causes, because I'm out of ideas. Any help at all is greatly appreciated. EDIT: Thanks All. For any others that find this to disable vSync(windows only) in opengl: First get "wglext.h". It's all over the web. Then you can use a tool like GLee or just write your own quick extensions manager like: bool WGLExtensionSupported(const char *extension_name) { PFNWGLGETEXTENSIONSSTRINGEXTPROC _wglGetExtensionsStringEXT = NULL; _wglGetExtensionsStringEXT = (PFNWGLGETEXTENSIONSSTRINGEXTPROC) wglGetProcAddress("wglGetExtensionsStringEXT"); if (strstr(_wglGetExtensionsStringEXT(), extension_name) == NULL) { return false; } return true; } and then create and setup your function pointers: PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = NULL; PFNWGLGETSWAPINTERVALEXTPROC wglGetSwapIntervalEXT = NULL; if (WGLExtensionSupported("WGL_EXT_swap_control")) { // Extension is supported, init pointers. wglSwapIntervalEXT = (PFNWGLSWAPINTERVALEXTPROC) wglGetProcAddress("wglSwapIntervalEXT"); // this is another function from WGL_EXT_swap_control extension wglGetSwapIntervalEXT = (PFNWGLGETSWAPINTERVALEXTPROC) wglGetProcAddress("wglGetSwapIntervalEXT"); } Then just call wglSwapIntervalEXT(0) to disable vSync and 1 to enable vSync. I found the reason this is windows only is that openGl actually doesn't deal with anything other than rendering it leaves the rest up to the OS and Hardware. Thanks everyone saved me a lot of time!

    Read the article

  • Finding and Printing all Links within a DIV

    - by Abs
    Hello all, I am trying to find all links in a div and then printing those links. I am using the Simple HTML Dom to parse the HTML file. Here is what I have so far, please read the inline comments and let me know where I am going wrong. include('simple_html_dom.php'); $html = file_get_html('tester.html'); $articles = array(); //find the div the div with the id abcde foreach($html->find('#abcde') as $article) { //find all a tags that have a href in the div abcde foreach($article->find('a[href]') as $link){ //if the href contains singer then echo this link if(strstr($link, 'singer')){ echo $link; } } } What currently happens is that the above takes a long time to load (never got it to finish). I printed what it was doing in each loop since it was too long to wait and I find that its going through things I don't need it to! This suggests my code is wrong. The HTML is basically something like this: <div id="abcde"> <!-- lots of html elements --> <!-- lots of a tags --> <a href="singer/tom" /> <img src="image..jpg" /> </a> </div> Thanks all for any help

    Read the article

  • Socket Read In Multi-Threaded Application Returns Zero Bytes or EINTR (104)

    - by user309670
    Hi. Am a c-coder for a while now - neither a newbie nor an expert. Now, I have a certain daemoned application in C on a PPC Linux. I use PHP's socket_connect as a client to connect to this service locally. The server uses epoll for multiplexing connections via a Unix socket. A user submitted string is parsed for certain characters/words using strstr() and if found, spawns 4 joinable threads to different websites simultaneously. I use socket, connect, write and read, to interact with the said webservers via TCP on their port 80 in each thread. All connections and writes seems successful. Reads to the webserver sockets fail however, with either (A) all 3 threads seem to hang, and only one thread returns -1 and errno is set to 104. The responding thread takes like 10 minutes - an eternity long:-(. *I read somewhere that the 104 (is EINTR?), which in the network context suggests that ...'the connection was reset by peer'; or (B) 0 bytes from 3 threads, and only 1 of the 4 threads actually returns some data. Isn't the socket read/write thread-safe? I use thread-safe (and reentrant) libc functions such as strtok_r, gethostbyname_r, etc. *I doubt that the said webhosts are actually resetting the connection, because when I run a single-threaded standalone (everything else equal) all things works perfectly right, but of course in series not parallel. There's a second problem too (oops), I can't write back to the client who connect to my epoll-ed Unix socket. My daemon application will hang and hog CPU 100% for ever. Yet nothing is written to the clients end. Am sure the client (a very typical PHP socket application) hasn't closed the connection whenever this is happening - no error(s) detected either. Any ideas? I cannot figure-out whatever is wrong even with Valgrind, GDB or much logging. Kindly help where you can.

    Read the article

  • Reading a CSV with file_get_contents in PHP

    - by JPro
    I am reading a 'kind' of csv file and exploding it and storing it in array. The file I am reading has this structure Id,Log,Res,File mydb('Test1','log1','Pass','lo1.txt'). mydb('Test2','log2','Pass','lo2.txt'). mydb('Test3','log3','Pass','lo3.txt'). Now what I am trying to do is : reading the last record in my database, get the Name, lets say in this case 'Test1' and then I am searching through my file and where I can find the position of 'Test1' and get the next lines in the file, extract the ID,s and add it to database. I am getting the position of desired string in the file, but I am not sure how to get the next lines too. Here's my code so far. <?php mysql_connect("localhost", "root", "") or die(mysql_error()); mysql_select_db("testing") or die(mysql_error()); $result = mysql_query("select ID from table_1 order by S_no DESC limit 1") or die(mysql_error()); $row = mysql_fetch_array( $result ); $a = $row['ID']; echo 'Present Top Row is '.$a.'<br>'; $addresses = explode("\n", file_get_contents('\\\\fil1\\logs\\tes.pl')); foreach($addresses as $val) { $pos = strstr($val, $a); if ($pos === false) { } else { echo "The string <br> '$a' <br>was found in the string <br>'$val' <br>"; echo " and exists at position <br>$pos<br>"; } }

    Read the article

  • Swing GUI using JNI crashes

    - by Div
    Hi, A java swing application(GUI) using JNI code to communicate with native C code. The Swing application launches properly and works fine. The GUI is used to start some customized system level tests(io,memory,cpu) and show their progress. The tests have to be left running at-least overnight to get the results. But, the next morning, GUI crashes and throws following message. Any pointers on source of the issue will be greatly appreciated. Java version: java 1.5 / java 1.6 OS: Solaris 10. Thanks, Div =============MESSAGES================== # uname -a SunOS Generic_127127-11 sun4v sparc SUNW, # # # # An unexpected error has been detected by HotSpot Virtual Machine: # # SIGSEGV (0xb) at pc=0xff268924, pid=9473, tid=272 # # Java VM: Java HotSpot(TM) Server VM (1.5.0_14-b03 mixed mode) # Problematic frame: # C [libc.so.1+0x68924] strstr+0x20 # # An error report file with more information is saved as hs_err_pid9473.log # # If you would like to submit a bug report, please visit: # HotSpot Virtual Machine Error Reporting Page # ============================= Another machine: # A fatal error has been detected by the Java Runtime Environment: # # SIGSEGV (0xb) at pc=0xff231fd0, pid=1406, tid=180 # # JRE version: 6.0_18-b07 # Java VM: Java HotSpot(TM) Server VM (16.0-b13 mixed mode solaris-sparc ) # Problematic frame: # C [libc.so.1+0x31fd0] strcpy+0x70 # # An error report file with more information is saved as: # /usr/sunvts/bin/hs_err_pid1406.log #

    Read the article

  • Socket Read In Multi-Threaded Application Returns Zero Bytes or EINTR (-1)

    - by user309670
    Hi. Am a c-coder for a while now - neither a newbie nor an expert. Now, I have a certain daemoned application in C on a PPC Linux. I use PHP's socket_connect as a client to connect to this service locally. The server uses epoll for concurrent connections via a Unix socket. A user submitted string is parsed for certain characters/words using strstr() and if found, spawns 4 joinable threads to different websites simultaneously. I use socket, connect, write and read, to interact with the said webservers via TCP on port 80 in each thread. All connections and writes seems successful. Reads to the webserver sockets fail however, with either (A) all 3 threads seem to hang, and only one thread returns -1 and errno is set to 104. The responding thread takes like 10 minutes - an eternity long:-(. *I read somewhere that the 104 (is EINTR) suggests that ...'the connection was reset by peer', or (B) 0 bytes from 3 threads, and only 1 of the 4 threads actually returns some data. Isn't the socket read/write thread-safe? Otherwise, use thread-safe (and reentrant) libc functions such as strtok_r, gethostbyname_r, etc. *I doubt that the said webhosts are actually resetting the connection, because when I run a single-threaded standalone (everything else equal) all things works perfectly right. There's a second problem too (oops), I can't write back to the client who connect to my epoll-ed Unix socket. My daemon application will hang and hog CPU 100% for ever. Yet nothing is written to the clients end. Am sure the client (a very typical PHP socket application) hasn't closed the connection whenever this is happening - no error(s) detected either. I cannot figure-out whatever is wrong even with Valgrind or GDB

    Read the article

  • Parse error: syntax error, unexpected T_STRING in...

    - by rabidmachine9
    I' making this class to catch twitter posts but I get the error : Parse error: syntax error, unexpected T_STRING in /Applications/XAMPP/xamppfiles/htdocs/classTest/Twitter.php on line 29 I cant find what's wrong...any ideas? class TwitterGrub{ function twitterCapture($user = 'myUsername',$password = 'myPass') { $ch = curl_init("https://twitter.com/statuses/user_timeline.xml"); curl_setopt($ch, CURLOPT_HEADER, 1); curl_setopt($ch,CURLOPT_TIMEOUT, 30); curl_setopt($ch,CURLOPT_USERPWD,$user . ":" . $password); curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0); $result=curl_exec ($ch); $data = strstr($result, '<?'); $xml = new SimpleXMLElement($data); return $xml; } function twitterDisplay($twitNum){ $xml = this->twitterCapture(); for($i= 0; $i<$twitNum; $i++){ echo "<div class='curvebox'>".$xml->status[$i]->text."</div>"; } } }

    Read the article

  • PHP unlink OR rewrite own/current file by itself

    - by Email
    Hi Task: Cut or erase a file after first walk-through. i have an install file called "index.php" which creates another php file. <? /* here some code*/ $fh = fopen($myFile, 'w') or die("can't open file"); $stringData = "<?php \n echo 'hallo, *very very long text*'; \n ?>"; fwrite($fh, $stringData); /*herecut"/ /*here some code */ after the creation of the new file this file is called and i intent to erase the filecreation call since it is very long and only needed on first install. i therefor add to the above code echo 'hallo, *very very long text*'; \n ***$new= file_get_contents('index.php'); \n $findme = 'habanot'; $pos = strpos($new, $findme); if ($pos === false) { $marker='herecut';\n $new=strstr($new,$marker);\n $new='<?php \n /*habanot*/\n'.$new;\n $fh = fopen('index.php', 'w') or die 'cant open file'); $stringData = $new; fwrite($fh, $stringData); fclose($fh);*** ?>"; fwrite($fh, $stringData);]} Isnt there an easier way or a function to modify the current file or even "self destroy" a file after first call? Regards

    Read the article

  • PHP – Slow String Manipulation

    - by Simon Roberts
    I have some very large data files and for business reasons I have to do extensive string manipulation (replacing characters and strings). This is unavoidable. The number of replacements runs into hundreds of thousands. It's taking longer than I would like. PHP is generally very quick but I'm doing so many of these string manipulations that it's slowing down and script execution is running into minutes. This is a pain because the script is run frequently. I've done some testing and found that str_replace is fastest, followed by strstr, followed by preg_replace. I've also tried individual str_replace statements as well as constructing arrays of patterns and replacements. I'm toying with the idea of isolating string manipulation operation and writing in a different language but I don't want to invest time in that option only to find that improvements are negligible. Plus, I only know Perl, PHP and COBOL so for any other language I would have to learn it first. I'm wondering how other people have approached similar problems? I have searched and I don't believe that this duplicates any existing questions.

    Read the article

  • Works for Short Input, Fails for Long Input. How to Solve?

    - by r0ach
    I've this program which finds substring in a string. It works for small inputs. But fails for long inputs. Here's the program: //Find Substring in given String #include <stdio.h> #include <string.h> main() { //Variable Initialization int i=0,j=0,k=0; char sentence[50],temp[50],search[50]; //Gets Strings printf("Enter Sentence: "); fgets(sentence,50,stdin); printf("Enter Search: "); fgets(search,50,stdin); //Actual Work Loop while(sentence[i]!='\0') { k=i;j=0; while(sentence[k]==search[j]) { temp[j]=sentence[k]; j++; k++; } if(strcmp(temp,search)==0) break; i++; } //Output Printing printf("Found string at: %d \n",k-strlen(search)); } Works for: Enter Sentence: good evening Enter Search: evening Found string at 6 Fails for: Enter Sentence: dear god please make this work Enter Search: make Found string at 25 Which is totally wrong. Can any expert find me a solution? P.S: This is kinda like reinventing the wheel since strstr() has this functionality. But I'm trying for a non-library way of doing it.

    Read the article

  • [ask][php] find dynamic filename exist

    - by r4ccoon
    hi. i am writing a cache module in php. it tries to write a cache with a $string+timestamp as a filename. i dont have problem with writing the cache. the problem is i do a foreach loop to get the cache that i want. this is the logic that i use for getting the cache foreach ($filenames as $filename){ if(strstr($filename,$cachename)){//if found if(check_timestamp($filename,time())) display_cace($filename); break; } } but when it tries to get and read the cache, it slows the server down. imagine that i have 10000 cache file in a folder, and i need to check for every file in that cache folder. so how do you think the best way of doing this. here i explain again, because even me still dont understand my written question.. :D i write cache file with this format filename_timestamp.. e.g cache_function_random_news_191982899010 in a folder ./cache/ when i want to get the cache, i only pass "cache_function_random_news_" and check recursively on that folder. if i find something with that needle on a file name, display it, and break. but checking recursively on a 10000 files in a folder is not a good thing yeah? please give me your opinion ok, that would clarify more. thanks.

    Read the article

  • An issue on object orientation in php

    - by rabidmachine9
    Hello people, I have come up to issues while I'm trying to write some classes, here is an example: I have this class called TwitterGrub and I cant call it like that: $c = new TwitterGrub(); $c->twitterDisplay(); here is the class itself: <?php class TwitterGrub{ function twitterCapture($user = 'username',$password = 'pass') { $ch = curl_init("https://twitter.com/statuses/user_timeline.xml"); curl_setopt($ch, CURLOPT_HEADER, 1); curl_setopt($ch,CURLOPT_TIMEOUT, 30); curl_setopt($ch,CURLOPT_USERPWD,$user . ":" . $password); curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0); $result=curl_exec ($ch); $data = strstr($result, '<?'); $xml = new SimpleXMLElement($data); return $xml; } function twitterDisplay($twitNum = 2){ $xml = $this::twitterCapture(); for($i= 0; $i<$twitNum; $i++){ echo "<div class= 'curvebox'>".$xml->status[$i]->text."</div>"; } } } ?> The problem is that everytime I want to change the username or password I have to jump back to class definition and that makes things not modular... and in many ways it feels wrong. So the question is what would be the proper way to chance my username and password through the objects interface and then call twitterDisplay() method with the new data?Hope that makes sense. Thanks in advance

    Read the article

  • C++ Regarding cin.ignore()

    - by user1578897
    i would hope someone can modify my code as its so buggy. sometime its work, sometime it dont.. so let me explain more.. Text file data is as below Line3D, [70, -120, -3], [-29, 1, 268] Line3D, [25, -69, -33], [-2, -41, 58] To read the above line.. i use the following char buffer[30]; cout << "Please enter filename: "; cin.ignore(); getline(cin,filename); readFile.open(filename.c_str()); //if successfully open if(readFile.is_open()) { //record counter set to 0 numberOfRecords = 0; while(readFile.good()) { //input stream get line by line readFile.getline(buffer,20,','); if(strstr(buffer,"Point3D")) { Point3D point3d_tmp; readFile>>point3d_tmp; // and so on... Then i did a overload on the ifstream for Line3d ifstream& operator>>(ifstream &input,Line3D &line3d) { int x1,y1,z1,x2,y2,z2; //get x1 input.ignore(2); input>>x1; //get y1 input.ignore(); input>>y1; //get z1 input.ignore(); input>>z1; //get x2 input.ignore(4); input>>x2; //get y2 input.ignore(); input>>y2; //get z2 input.ignore(); input>>z2; input.ignore(2); Point3D pt1(x1,y1,z1); Point3D pt2(x2,y2,z2); line3d.setPt1(pt1); line3d.setPt2(pt2); line3d.setLength(); } But the issue is the record work sometime and sometime it dont.. what i mean is if at this point //i add a cout cout << x1 << y1 << z1; cout << x2 << y2 << z2; //its works! Point3D pt1(x1,y1,z1); Point3D pt2(x2,y2,z2); line3d.setPt1(pt1); line3d.setPt2(pt2); line3d.setLength(); but if i take away the cout it dont work. how do i change my cin.ignore() so the data can be handle properly , consider number range is -999 to 999

    Read the article

  • Does boost::asio makes excessive small heap allocations or am I wrong?

    - by Poni
    #include <cstdlib> #include <iostream> #include <boost/bind.hpp> #include <boost/asio.hpp> using boost::asio::ip::tcp; class session { public: session(boost::asio::io_service& io_service) : socket_(io_service) { } tcp::socket& socket() { return socket_; } void start() { socket_.async_read_some(boost::asio::buffer(data_, max_length - 1), boost::bind(&session::handle_read, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } void handle_read(const boost::system::error_code& error, size_t bytes_transferred) { if (!error) { data_[bytes_transferred] = '\0'; if(NULL != strstr(data_, "quit")) { this->socket().shutdown(boost::asio::ip::tcp::socket::shutdown_both); this->socket().close(); // how to make this dispatch "handle_read()" with a "disconnected" flag? } else { boost::asio::async_write(socket_, boost::asio::buffer(data_, bytes_transferred), boost::bind(&session::handle_write, this, boost::asio::placeholders::error)); socket_.async_read_some(boost::asio::buffer(data_, max_length - 1), boost::bind(&session::handle_read, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } } else { delete this; } } void handle_write(const boost::system::error_code& error) { if (!error) { // } else { delete this; } } private: tcp::socket socket_; enum { max_length = 1024 }; char data_[max_length]; }; class server { public: server(boost::asio::io_service& io_service, short port) : io_service_(io_service), acceptor_(io_service, tcp::endpoint(tcp::v4(), port)) { session* new_session = new session(io_service_); acceptor_.async_accept(new_session->socket(), boost::bind(&server::handle_accept, this, new_session, boost::asio::placeholders::error)); } void handle_accept(session* new_session, const boost::system::error_code& error) { if (!error) { new_session->start(); new_session = new session(io_service_); acceptor_.async_accept(new_session->socket(), boost::bind(&server::handle_accept, this, new_session, boost::asio::placeholders::error)); } else { delete new_session; } } private: boost::asio::io_service& io_service_; tcp::acceptor acceptor_; }; int main(int argc, char* argv[]) { try { if (argc != 2) { std::cerr << "Usage: async_tcp_echo_server <port>\n"; return 1; } boost::asio::io_service io_service; using namespace std; // For atoi. server s(io_service, atoi(argv[1])); io_service.run(); } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } return 0; } While experimenting with boost::asio I've noticed that within the calls to async_write()/async_read_some() there is a usage of the C++ "new" keyword. Also, when stressing this echo server with a client (1 connection) that sends for example 100,000 times some data, the memory usage of this program is getting higher and higher. What's going on? Will it allocate memory for every call? Or am I wrong? Asking because it doesn't seem right that a server app will allocate, anything. Can I handle it, say with a memory pool? Another side-question: See the "this-socket().close();" ? I want it, as the comment right to it says, to dispatch that same function one last time, with a disconnection error. Need that to do some clean-up. How do I do that? Thank you all gurus (:

    Read the article

  • One url to image, few results

    - by Misiur
    Hi! I'm trying to show programmers that some captchas are too weak, and i'm breaking them. Now i've got something like this: Function: <?php function cbreak($image) { $info = getimagesize($image); $width = $info[0]; $height = $info[1]; $img = imagecreatefromgif($image); $map = array(); for($y=0; $y<$height; $y++) { for($x=0; $x<$width; $x++) { $color = imagecolorsforindex($img, imagecolorat($img, $x, $y)); $map[$x][$y] = ($color['red'] + $color['blue'] + $color['green'] > 750) ? TRUE : FALSE; } } echo '<pre>'; for($y=0; $y<$height; $y++) { for($x=0; $x<$width; $x++) { echo ($map[$x][$y] == TRUE) ? 'X' : '-'; } echo '<br>'; } echo '</pre>'; $sum = ''; for($x=0; $x<$width; $x++) { $count = 0; for($y=0; $y<$height; $y++) { if($map[$x][$y] == TRUE) $count++; } $sum .= ($count == 0) ? 'X' : $count; } $sum = preg_replace('#X+#', 'X', $sum); $sum = trim($sum, 'X'); $letters = explode('X', $sum); $patterns = array( /* Still not here */ ); $token = ''; for($i=0; $i<count($letters); $i++) { $token .= $patterns[$letters[$i]]; } echo $token; } ?> Action: <?php $cl = curl_init("http://www.takeagift.pl/rejestracja"); curl_setopt($cl, CURLOPT_RETURNTRANSFER, 1); $r = curl_exec($cl); $pattern = "/src=[\"'].*[\"']?/i"; preg_match_all($pattern, $r, $images); $c = array(); for($i=0; $i<sizeof($images[0]); $i++) { if(strstr($images[0][$i], 'captcha') !== false) { $c = $images[0][$i]; } } $s1 = substr($c, 0, -8); echo $s1."<br />"; $s = substr($s1, 5, -1); echo $s."<br />"; curl_close($cl); ?> <img src="http://www.takeagift.pl/includes/modules/captcha.php?1270900968" /><br /> <img src="http://www.takeagift.pl/includes/modules/captcha.php?1270900968" /><br /> <img src="http://www.takeagift.pl/includes/modules/captcha.php?1270900968" /><br /> <img src="http://www.takeagift.pl/includes/modules/captcha.php?1270900968" /><br /> <img src="http://www.takeagift.pl/includes/modules/captcha.php?1270900968" /><br /> <?php include('cb.php'); cbreak("http://www.takeagift.pl/includes/modules/captcha.php?1270900968"); ?> Don't look at preg_match i still haven't learned regexp. So as You can see links are same: (captcha.php?1270900968), but the result - not. Help me, please (i'm not doing it to spam this portal)

    Read the article

  • Identifier is undefined

    - by hawk
    I wrote the following code in C++ using VS2012 Express. void ac_search( uint num_patterns, uint pattern_length, const char *patterns, uint num_records, uint record_length, const char *records, int *matches, Node* trie) { // Irrelevant code omitted. } vector<int> ac_benchmark_search( uint num_patterns, uint pattern_length, const char *patterns, uint num_records, uint record_length, const char *records, double &time) { // Prepare the container for the results vector<int> matches(num_records * num_patterns); Trie T; Node* trie = T.addWord(records, num_records, record_length); // error line ac_search(num_patterns, pattern_length, patterns, num_records, record_length, records, matches.data(), trie); // Irrelevant code omitted. return matches; } I get the error identifier "ac_search" is undefined at the function invoking line. I am a bit confused here. because the function ac_search is declared as a global (not inside any container). Why can't I call it at this place? Am I missing something? Update I tried ignore irrelevant code and then included it gradually and found that everything is fine until I include the outer loop of ac_search I get the aforementioned error. here is updated code of the function ac_search: void ac_cpu_string_search(uint num_patterns, uint pattern_length, const char *patterns, uint num_records, uint record_length, const char *records, int *matches, Node* trie) { // Loop over all records //for (uint record_number = 0; record_number < num_records; ++record_number) //{ // // Loop over all patterns for (uint pattern_number = 0; pattern_number < num_patterns; ++pattern_number) { // Execute string search const char *ptr_record = &records[record_number * record_length]; const char *ptr_match = std::strstr(ptr_record, &patterns[pattern_number * pattern_length]); // If pattern was found, then calculate offset, otherwise result is -1 if (ptr_match) { matches[record_number * num_patterns + pattern_number] = static_cast<int>(std::distance(ptr_record, ptr_match)); } else { matches[record_number * num_patterns + pattern_number] = -1; } // } //} } Update 2 I think the error has something to do with the function addWord which belongs to the class Trie. When I commented out this function, I did not get the error anymore. Node* Trie::addWord(const char *records, uint num_records, uint record_length) { // Loop over all records for (uint record_number = 0; record_number < num_records; ++record_number) { const char *ptr_record = &records[record_number * record_length]; string s = ptr_record; Node* current = root; if ( s.length() == 0 ) { current->setWordMarker(); // an empty word return; } for ( int i = 0; i < s.length(); i++ ) { Node* child = current->findChild(s[i]); if ( child != NULL ) { current = child; } else { Node* tmp = new Node(); tmp->setContent(s[i]); current->appendChild(tmp); current = tmp; } if ( i == s.length() - 1 ) current->setWordMarker(); } return current; } void ac_search( uint num_patterns, uint pattern_length, const char *patterns, uint num_records, uint record_length, const char *records, int *matches, Node* trie) { // Irrelevant code omitted. } vector<int> ac_benchmark_search( uint num_patterns, uint pattern_length, const char *patterns, uint num_records, uint record_length, const char *records, double &time) { // Prepare the container for the results vector<int> matches(num_records * num_patterns); Trie T; Node* trie = T.addWord(records, num_records, record_length); // error line ac_search(num_patterns, pattern_length, patterns, num_records, record_length, records, matches.data(), trie); // Irrelevant code omitted. return matches; }

    Read the article

< Previous Page | 1 2 3  | Next Page >