Search Results

Search found 567 results on 23 pages for 'stdin'.

Page 5/23 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • what would be the c# equivalent of this code snippet?

    - by Dervin Thunk
    I don't really understand Perl, so I was wondering if someone could give me a hint about what it is this code is asking of STDIN, and how to say this in C#. Thanks. $TMPFILE = "xxx.tmp"; if (! -f STDIN) { open TMPFILE, "> $TMPFILE" or die "Couldn't open `$TMPFILE' for writing: $!; aborting"; print TMPFILE while <STDIN>; close TMPFILE; open STDIN, "< $TMPFILE" or die "Couldn't open `$TMPFILE' for reading: $!; aborting"; unlink $TMPFILE; }

    Read the article

  • Why doesn't `stdin.read()` read entire buffer?

    - by Shookie
    I've got the following code: def get_input(self): """ Reads command from stdin, returns its JSON form """ json_string = sys.stdin.read() print("json string is: "+json_string) json_data =json.loads(json_string) return json_data It reads a json string that was sent to it from another process. The json is read from stdin. For some reason I get the following output: json string is: <Some json here> json string is: Traceback (most recent call last): File "/Users/Matan/Documents/workspace/ProjectSH/addonmanager/addon_manager.py", line 63, in <module> manager.accept_commands() File "/Users/Matan/Documents/workspace/ProjectSH/addonmanager/addon_manager.py", line 49, in accept_commands json_data = self.get_input() File "/Users/Matan/Documents/workspace/ProjectSH/addonmanager/addon_manager.py", line 42, in get_input json_data =json.loads(json_string) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 338, in loads return _default_decoder.decode(s) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 365, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 383, in raw_decode raise ValueError("No JSON object could be decoded") So for some reason it reads an empty string from stdin instead of reading only the json. I've checked, and the code that writes to this process's stdin writes to it only once. What's wrong here?

    Read the article

  • Why doesn't file detect the mime-type of mp3 properly?

    - by Grumbel
    Something odd I recently encountered, running file --mime-type on a collection of MP3 gets the mime-time wrong a third of the time: $ for i in */*.mp3; do cat "$i"| file --mime-type -; done | sort | uniq -c 140 /dev/stdin: application/octet-stream 309 /dev/stdin: audio/mpeg There doesn't seem to be any obvious reason, as even MP3s from the same source, will sometimes fail and sometimes not. Bug, feature or anything obvious I am missing here?

    Read the article

  • All my Ubuntu VMs have apt-get update problems

    - by kashani
    I'm running Virtualbox 4.1 on an x86_64 Windows 7 host. I've got a collection of 12.04 and 10.04 LTS VMs I use to create debs for work. In the last week I started noticing problems on the 12.04 VMs. Tried the usual apt-get clean bit which didn't help. I rolled a new 11.10 VM for testing a Worpress upgrade. This VM has never been able to run apt-get update without errors. The interesting errors look like this: Get: 8 http://security.ubuntu.com oneiric-security/main Translation-en_US [344 B] 14% [7 Sources 48686/877 kB 6%] [Waiting for headers]bzip2: (stdin) is not a bzip2 file. Hit http://security.ubuntu.com oneiric-security/multiverse Translation-en Hit http://security.ubuntu.com oneiric-security/restricted Translation-en Hit http://security.ubuntu.com oneiric-security/universe Translation-en 22% [7 Sources 127526/877 kB 15%] [Waiting for headers]/usr/bin/xz: (stdin): File format not recognized and ends with /usr/bin/xz: (stdin): File format not recognized Ign http://us.archive.ubuntu.com oneiric/main Translation-en_US Ign http://us.archive.ubuntu.com oneiric-updates/main Translation-en_US Fetched 18.5 MB in 47s (392 kB/s) W: GPG error: http://us.archive.ubuntu.com oneiric InRelease: File /var/lib/apt/lists/partial/us.archive.ubuntu.com_ubuntu_dists_oneiric_InRelease doesn't start with a clearsigned message W: GPG error: http://security.ubuntu.com oneiric-security InRelease: File /var/lib/apt/lists/partial/security.ubuntu.com_ubuntu_dists_oneiric-security_InRelease doesn't start with a clearsigned message xv-utils, lzma, etc are all installed. I've reinstalled the VM from scratch three times and up at the same point.

    Read the article

  • design for a wrapper around command-line utilities

    - by hatchetman82
    im trying to come up with a design for a wrapper for use when invoking command line utilities in java. the trouble with runtime.exec() is that you need to keep reading from the process' out and err streams or it hangs when it fills its buffers. this has led me to the following design: public class CommandLineInterface { private final Thread stdOutThread; private final Thread stdErrThread; private final OutputStreamWriter stdin; private final History history; public CommandLineInterface(String command) throws IOException { this.history = new History(); this.history.addEntry(new HistoryEntry(EntryTypeEnum.INPUT, command)); Process process = Runtime.getRuntime().exec(command); stdin = new OutputStreamWriter(process.getOutputStream()); stdOutThread = new Thread(new Leech(process.getInputStream(), history, EntryTypeEnum.OUTPUT)); stdOutThread.setDaemon(true); stdOutThread.start(); stdErrThread = new Thread(new Leech(process.getErrorStream(), history, EntryTypeEnum.ERROR)); stdErrThread.setDaemon(true); stdErrThread.start(); } public void write(String input) throws IOException { this.history.addEntry(new HistoryEntry(EntryTypeEnum.INPUT, input)); stdin.write(input); stdin.write("\n"); stdin.flush(); } } public class Leech implements Runnable{ private final InputStream stream; private final History history; private final EntryTypeEnum type; private volatile boolean alive = true; public Leech(InputStream stream, History history, EntryTypeEnum type) { this.stream = stream; this.history = history; this.type = type; } public void run() { BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); String line; try { while(alive) { line = reader.readLine(); if (line==null) break; history.addEntry(new HistoryEntry(type, line)); } } catch (Exception e) { e.printStackTrace(); } } } my issue is with the Leech class (used to "leech" the process' out and err streams and feed them into history - which acts like a log file) - on the one hand reading whole lines is nice and easy (and what im currently doing), but it means i miss the last line (usually the prompt line). i only see the prompt line when executing the next command (because there's no line break until that point). on the other hand, if i read characters myself, how can i tell when the process is "done" ? (either complete or waiting for input) has anyone tried something like waiting 100 millis since the last output from the process and declaring it "done" ? any better ideas on how i can implement a nice wrapper around things like runtime.exec("cmd.exe") ?

    Read the article

  • Logging to MySQL without empty rows/skipped records?

    - by Lee Ward
    I'm trying to figure out how to make Squid proxy log to MySQL. I know ACL order is pretty important but I'm not sure if I understand exactly what ACLs are or do, it's difficult to explain, but hopefully you'll see where I'm going with this as you read! I have created the lines to make Squid interact with a helper in squid.conf as follows: external_acl_type mysql_log %LOGIN %SRC %PROTO %URI php /etc/squid3/custom/mysql_lg.php acl ex_log external mysql_log http_access allow ex_log The external ACL helper (mysql_lg.php) is a PHP script and is as follows: error_reporting(0); if (! defined(STDIN)) { define("STDIN", fopen("php://stdin", "r")); } $res = mysql_connect('localhost', 'squid', 'testsquidpw'); $dbres = mysql_select_db('squid', $res); while (!feof(STDIN)) { $line = trim(fgets(STDIN)); $fields = explode(' ', $line); $user = rawurldecode($fields[0]); $cli_ip = rawurldecode($fields[1]); $protocol = rawurldecode($fields[2]); $uri = rawurldecode($fields[3]); $q = "INSERT INTO logs (id, user, cli_ip, protocol, url) VALUES ('', '".$user."', '".$cli_ip."', '".$protocol."', '".$uri."');"; mysql_query($q) or die (mysql_error()); if ($fault) { fwrite(STDOUT, "ERR\n"); }; fwrite(STDOUT, "OK\n"); } The configuration I have right now looks like this: ## Authentication Handler auth_param ntlm program /usr/bin/ntlm_auth --helper-protocol=squid-2.5-ntlmssp auth_param ntlm children 30 auth_param negotiate program /usr/bin/ntlm_auth --helper-protocol=squid-2.5-basic auth_param negotiate children 5 # Allow squid to update log external_acl_type mysql_log %LOGIN %SRC %PROTO %URI php /etc/squid3/custom/mysql_lg.php acl ex_log external mysql_log http_access allow ex_log acl localnet src 172.16.45.0/24 acl AuthorizedUsers proxy_auth REQUIRED acl SSL_ports port 443 acl Safe_ports port 80 # http acl Safe_ports port 21 # ftp acl Safe_ports port 443 # https acl CONNECT method CONNECT acl blockeddomain url_regex "/etc/squid3/bl.acl" http_access deny blockeddomain deny_info ERR_BAD_GENERAL blockeddomain # Deny requests to certain unsafe ports http_access deny !Safe_ports # Deny CONNECT to other than secure SSL ports http_access deny CONNECT !SSL_ports # Allow the internal network access to this proxy http_access allow localnet # Allow authorized users access to this proxy http_access allow AuthorizedUsers # FINAL RULE - Deny all other access to this proxy http_access deny all From testing, the closer to the bottom I place the logging lines the less it logs. Oftentimes, it even places empty rows in to the MySQL table. The file-based logs in /var/log/squid3/access.log are correct but many of the rows in the access logs are missing from the MySQL logs. I can't help but think it's down to the order I'm putting lines in because I want to log everything to MySQL, unauthenticated requests, blocked requests, which category blocked a specific request. The reason I want this in MySQL is because I'm trying to have everything managed via a custom web-based frontend and want to avoid using any shell commands and access to system log files if I can help it. The end result is to make it as easy as possible to maintain without keeping staff waiting on the phone whilst I add a new rule and reload the server! Hopefully someone can help me out here because this is very much a learning experience for me and I'm pretty stumped. Many thanks in advance for any help!

    Read the article

  • Squid - Logging to MySQL without empty rows/skipped records?

    - by Lee Ward
    I'm trying to figure out how to make Squid proxy log to MySQL. I know ACL order is pretty important but I'm not sure if I understand exactly what ACLs are or do, it's difficult to explain, but hopefully you'll see where I'm going with this as you read! I have created the lines to make Squid interact with a helper in squid.conf as follows: external_acl_type mysql_log %LOGIN %SRC %PROTO %URI php /etc/squid3/custom/mysql_lg.php acl ex_log external mysql_log http_access allow ex_log The external ACL helper (mysql_lg.php) is a PHP script and is as follows: error_reporting(0); if (! defined(STDIN)) { define("STDIN", fopen("php://stdin", "r")); } $res = mysql_connect('localhost', 'squid', 'testsquidpw'); $dbres = mysql_select_db('squid', $res); while (!feof(STDIN)) { $line = trim(fgets(STDIN)); $fields = explode(' ', $line); $user = rawurldecode($fields[0]); $cli_ip = rawurldecode($fields[1]); $protocol = rawurldecode($fields[2]); $uri = rawurldecode($fields[3]); $q = "INSERT INTO logs (id, user, cli_ip, protocol, url) VALUES ('', '".$user."', '".$cli_ip."', '".$protocol."', '".$uri."');"; mysql_query($q) or die (mysql_error()); if ($fault) { fwrite(STDOUT, "ERR\n"); }; fwrite(STDOUT, "OK\n"); } The configuration I have right now looks like this: ## Authentication Handler auth_param ntlm program /usr/bin/ntlm_auth --helper-protocol=squid-2.5-ntlmssp auth_param ntlm children 30 auth_param negotiate program /usr/bin/ntlm_auth --helper-protocol=squid-2.5-basic auth_param negotiate children 5 # Allow squid to update log external_acl_type mysql_log %LOGIN %SRC %PROTO %URI php /etc/squid3/custom/mysql_lg.php acl ex_log external mysql_log http_access allow ex_log acl localnet src 172.16.45.0/24 acl AuthorizedUsers proxy_auth REQUIRED acl SSL_ports port 443 acl Safe_ports port 80 # http acl Safe_ports port 21 # ftp acl Safe_ports port 443 # https acl CONNECT method CONNECT acl blockeddomain url_regex "/etc/squid3/bl.acl" http_access deny blockeddomain deny_info ERR_BAD_GENERAL blockeddomain # Deny requests to certain unsafe ports http_access deny !Safe_ports # Deny CONNECT to other than secure SSL ports http_access deny CONNECT !SSL_ports # Allow the internal network access to this proxy http_access allow localnet # Allow authorized users access to this proxy http_access allow AuthorizedUsers # FINAL RULE - Deny all other access to this proxy http_access deny all From testing, the closer to the bottom I place the logging lines the less it logs. Oftentimes, it even places empty rows in to the MySQL table. The file-based logs in /var/log/squid3/access.log are correct but many of the rows in the access logs are missing from the MySQL logs. I can't help but think it's down to the order I'm putting lines in because I want to log everything to MySQL, unauthenticated requests, blocked requests, which category blocked a specific request. The reason I want this in MySQL is because I'm trying to have everything managed via a custom web-based frontend and want to avoid using any shell commands and access to system log files if I can help it. The end result is to make it as easy as possible to maintain without keeping staff waiting on the phone whilst I add a new rule and reload the server! Hopefully someone can help me out here because this is very much a learning experience for me and I'm pretty stumped. Many thanks in advance for any help!

    Read the article

  • warning: assignment makes pointer from integer without a cast

    - by FILIaS
    Im new in programming c with arrays and files. Im just trying to run the following code but i get warnings like that: warning: assignment makes pointer from integer without a cast Any help? It might be silly... but I cant find what's wrong. FILE *fp; FILE *cw; char filename_game[40],filename_words[40]; int main() { while(1) { /* Input filenames. */ printf("\n Enter the name of the file with the cryptwords array: \n"); gets(filename_game); printf("\n Give the name of the file with crypted words:\n"); gets(filename_words); /* Try to open the file with the game */ if (fp=fopen("crypt.txt","r")!=NULL) { printf("\n Successful opening %s \n",filename_game); fclose(fp); puts("\n Enter x to exit,any other to continue! \n "); if ( (getc(stdin))=='x') break; else continue; } else { fprintf(stderr,"ERROR!%s \n",filename_game); puts("\n Enter x to exit,any other to continue! \n"); if (getc(stdin)=='x') break; else continue; } /* Try to open the file with the names. */ if (cw=fopen("words.txt","r")!=NULL) { printf("\n Successful opening %s \n",filename_words); fclose(cw); puts("\n Enter x to exit,any other to continue \n "); if ( (getc(stdin))=='x') break; else continue; } else { fprintf(stderr,"ERROR!%s \n",filename_words); puts("\n Enter x to exit,any other to continue! \n"); if (getc(stdin)=='x') break; else continue; } } return 0; }

    Read the article

  • While loop not reading in the last item

    - by Gandalf StormCrow
    I'm trying to read in a multi line string then split it then print it .. here is the string : 1T1b5T!1T2b1T1b2T!1T1b1T2b2T!1T3b1T1b1T!3T3b1T!1T3b1T1b1T!5T1*1T 11X21b1X 4X1b1X When I split the string with ! I get this without the last line string : 1T1b5T 1T1b5T1T2b1T1b2T 1T2b1T1b2T1T1b1T2b2T 1T1b1T2b2T1T3b1T1b1T 1T3b1T1b1T3T3b1T 3T3b1T1T3b1T1b1T 1T3b1T1b1T5T1*1T 5T1*1T11X21b1X 11X21b1X Here is my code : import java.io.BufferedInputStream; import java.util.Scanner; public class Main { public static void main(String args[]) { Scanner stdin = new Scanner(new BufferedInputStream(System.in)); while (stdin.hasNext()) { for (String line : stdin.next().split("!")) { System.out.println(line); for (int i = 0; i < line.length(); i++) { System.out.print(line.charAt(i)); } } } } } Where did I make the mistake, why is not reading in the last line? After I read in all lines properly I should go trough each line if I encounter number I should print the next char the n times the number I just read, but that is long way ahead first I need help with this. Thank you UPDATE : Here is how the output should look like : 1T1b5T 1T2b1T1b2T 1T1b1T2b2T 1T3b1T1b1T 3T3b1T 1T3b1T1b1T 5T1*1T 11X21b1X 4X1b1X Here is a solution in C(my friend solved it not me), but I'd stil wanted to do it in JAVA : #include <stdio.h> int main (void) { char row[134]; for (;fgets (row,134,stdin)!=NULL;) { int i,j=0; for (i=0;row[i]!='\0';i++) { if (row[i]<='9'&&row[i]>='1') j+=(row[i]-'0'); else if ((row[i]<='Z'&&row[i]>='A')||row[i]=='*') for (;j;j--) printf ("%c",row[i]); else if (row[i]=='b') for (;j;j--) printf (" "); else if (row[i]=='!'||row[i]=='\n') printf ("\n"); } } return 0; }

    Read the article

  • Selectively search and replace certain lines using a regular expression

    - by eneveu
    I have a file containing a lot of SQL statements, such as: CREATE TABLE "USER" ( "ID" INTEGER PRIMARY KEY, "NAME" CHARACTER VARYING(50) NOT NULL, "AGE" INTEGER NOT NULL ); COPY "USER" (id, name, age) FROM stdin; 1 Skywalker 19 2 Kenobi 57 I want the column names in the COPY statements to be uppercased and quoted: COPY "USER" ("ID", "NAME", "AGE") FROM stdin; Using sed, I found the following regexp: sed -r 's/([( ])(\w+)([,)])/\1"\U\2\E"\3/g' It does replace the column names, but it is not selective enough, and replaces other words in the file: ~/test]$sed -r 's/([( ])(\w+)([,)])/\1"\U\2\E"\3/g' star_wars_example CREATE TABLE "USER" ( "ID" INTEGER PRIMARY "KEY", "NAME" CHARACTER VARYING("50")NOT "NULL", "AGE" INTEGER NOT NULL ); COPY "USER" ("ID", "NAME", "AGE") FROM stdin; 1 Skywalker 19 2 Kenobi 57 To avoid this problem, I want sed to only apply my regexp to the lines starting with COPY and ending with FROM stdin;. I have looked into lookahead / lookbehind, but they are not supported in sed. They seem to be supported in super-sed, but I am currently using Cygwin (Windows is mandatory here...) and it does not seem available in the package list. Is there a way to force sed to only consider specific line? I've considered piping my file through grep before applying sed, but other lines will then disappear from the output. Am I missing something obvious? It would be great if the answer was easily applicable on a default Cygwin install. I guess I could try installing super-sed on cygwin, but I'd like to know if there are more obvious ideas

    Read the article

  • Read large amount of data from file in Java

    - by Crozin
    Hello I've got text file that contains 1 000 002 numbers in following formation: 123 456 1 2 3 4 5 6 .... 999999 100000 Now I need to read that data and allocate it to int variables (the very first two numbers) and all the rest (1 000 000 numbers) to an array int[]. It's not a hard task, but - it's horrible slow. My first attempt was java.util.Scanner: Scanner stdin = new Scanner(new File("./path")); int n = stdin.nextInt(); int t = stdin.nextInt(); int array[] = new array[n]; for (int i = 0; i < n; i++) { array[i] = stdin.nextInt(); } It works as excepted but it takes about 7500 ms to execute. I need to fetch that data in up to several hundred of milliseconds. Then I tried java.io.BufferedReader: Using BufferedReader.readLine() and String.split() I got the same results in about 1700 ms, but it's still too many. How can I read that amount of data in less that 1 second? The final result should be equal to: int n = 123; int t = 456; int array[] = { 1, 2, 3, 4, ..., 999999, 100000 };

    Read the article

  • Undefined method 'size' for #<File:text.txt> (NoMethodError)

    - by user1354456
    This is the code I am running, it does fine until I get to line 15. The command I run is: ruby ex16.rb text.txt. This is a practice sample I'm writing which is meant to be a simple little text editor: filename = ARGV.first script = $0 puts "We're going to erase #{filename}." puts "if you don't want that, hit CTRL-C (^C)." puts "If you do want that, hit RETURN." print "? " STDIN.gets puts "Opening the file..." target = File.open(filename, 'w') puts "Truncating the file. Goodbye!" target.truncate(target.size) puts "Now I'm going to ask you for three lines." print "line 1: "; line1 = STDIN.gets.chomp() print "line 2: "; line2 = STDIN.gets.chomp() print "line 3: "; line3 = STDIN.gets.chomp()undefined method 'size' puts "I'm going to write these to the file." target.write(line1) target.write("\n") target.write(line2) target.write("\n") target.write(line3) target.write("\n") puts "And finally, we close it." target.close()

    Read the article

  • Xubuntu 9.10 LiveCD on USB fails with error can't open /dev/sr0: no medium found

    - by EricJLN
    Using Ubuntu's USB Startup Disk Creator (usb-creator-gtk), I created a LiveUSB from the Xubuntu 9.10 LiveCD. When booting, it stalls up with the Xubuntu mouse splash screen displayed. In attempting to troubleshoot, I used Ctrl-Alt-F1 to check out the first virtual terminal. On that screen, I see over and over again the lines: stdin: I/O error stdin: error 0 /init: line 1: can't open /dev/sr0: No medium found

    Read the article

  • Properly using subprocess.PIPE in python?

    - by Gordon Fontenot
    I'm trying to use subprocess.Popen to construct a sequence to grab the duration of a video file. I've been searching for 3 days, and can't find any reason online as to why this code isn't working, but it keeps giving me a blank result: import sys import os import subprocess def main(): the_file = "/Volumes/Footage/Acura/MDX/2001/Crash Test/01 Acura MDX Front Crash.mov" ffmpeg = subprocess.Popen(['/opt/local/bin/ffmpeg', '-i', the_file], stdout = subprocess.PIPE, ) grep = subprocess.Popen(['grep', 'Duration'], stdin = subprocess.PIPE, stdout = subprocess.PIPE, ) cut = subprocess.Popen(['cut', '-d', ' ', '-f', '4'], stdin = subprocess.PIPE, stdout = subprocess.PIPE, ) sed = subprocess.Popen(['sed', 's/,//'], stdin = subprocess.PIPE, stdout = subprocess.PIPE, ) duration = sed.communicate() print duration if __name__ == '__main__': main()

    Read the article

  • c language:make fgets to keep taking input until I press enter twice?

    - by wello horld
    hi I would like to ask how I would modify this code for the question: (It only accepts one input then prints it out. I want it to keep going until I hit enter (\n) twice. #include <stdio.h> #define MAXLENGTH 1000 int main(void) { char string[MAXLENGTH]; fgets(string, MAXLENGTH, stdin ); printf("%s\n", string); return 0; } I'm confused at the fgets(string, MAXLENGTH, stdin ); line, what does stdin mean/do?

    Read the article

  • The Collatz Sequence problem

    - by Gandalf StormCrow
    I'm trying to solve this problem, its not a homework question, its just code I'm submitting to uva.onlinejudge.org so I can learn better java trough examples. Here is the problem sample input : 3 100 34 100 75 250 27 2147483647 101 304 101 303 -1 -1 Here is simple output : Case 1: A = 3, limit = 100, number of terms = 8 Case 2: A = 34, limit = 100, number of terms = 14 Case 3: A = 75, limit = 250, number of terms = 3 Case 4: A = 27, limit = 2147483647, number of terms = 112 Case 5: A = 101, limit = 304, number of terms = 26 Case 6: A = 101, limit = 303, number of terms = 1 The thing is this has to execute within 3sec time interval otherwise your question won't be accepted as solution, here is with what I've come up so far, its working as it should just the execution time is not within 3 seconds, here is code : import java.util.Scanner; class Main { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); int start; int limit; int terms; int a = 0; while (stdin.hasNext()) { start = stdin.nextInt(); limit = stdin.nextInt(); if (start > 0) { terms = getLength(start, limit); a++; } else { break; } System.out.println("Case "+a+": A = "+start+", limit = "+limit+", number of terms = "+terms); } } public static int getLength(int x, int y) { int length = 1; while (x != 1) { if (x <= y) { if ( x % 2 == 0) { x = x / 2; length++; }else{ x = x * 3 + 1; length++; } } else { length--; break; } } return length; } } And yes here is how its meant to be solved : An algorithm given by Lothar Collatz produces sequences of integers, and is described as follows: Step 1: Choose an arbitrary positive integer A as the first item in the sequence. Step 2: If A = 1 then stop. Step 3: If A is even, then replace A by A / 2 and go to step 2. Step 4: If A is odd, then replace A by 3 * A + 1 and go to step 2. And yes my question is how can I make it work inside 3 seconds time interval?

    Read the article

  • 23warning: assignment makes pointer from integer without a cast

    - by FILIaS
    Im new in programming c with arrays and files. Im just trying to run the following code but i get warnings like that: 23 44 warning: assignment makes pointer from integer without a cast Any help? It might be silly... but I cant find what's wrong. #include<stdio.h> FILE *fp; FILE *cw; char filename_game[40],filename_words[40]; int main() { while(1) { /* Input filenames. */ printf("\n Enter the name of the file with the cryptwords array: \n"); gets(filename_game); printf("\n Give the name of the file with crypted words:\n"); gets(filename_words); /* Try to open the file with the game */ if (fp=fopen("crypt.txt","r")!=NULL) //line23 { printf("\n Successful opening %s \n",filename_game); fclose(fp); puts("\n Enter x to exit,any other to continue! \n "); if ( (getc(stdin))=='x') break; else continue; } else { fprintf(stderr,"ERROR!%s \n",filename_game); puts("\n Enter x to exit,any other to continue! \n"); if (getc(stdin)=='x') break; else continue; } /* Try to open the file with the names. */ if (cw=fopen("words.txt","r")!=NULL) //line 44 { printf("\n Successful opening %s \n",filename_words); fclose(cw); puts("\n Enter x to exit,any other to continue \n "); if ( (getc(stdin))=='x') break; else continue; } else { fprintf(stderr,"ERROR!%s \n",filename_words); puts("\n Enter x to exit,any other to continue! \n"); if (getc(stdin)=='x') break; else continue; } } return 0; }

    Read the article

  • UNIX pipes on C block on read

    - by Toni Cárdenas
    I'm struggling to implement a shell with pipelines for class. typedef struct { char** cmd; int in[2]; int out[2]; } cmdio; cmdio cmds[MAX_PIPE + 1]; Commands in the pipeline are read and stored in cmds. cmdio[i].in is the pair of file descriptors of the input pipe returned by pipe(). For the first command, which reads from terminal input, it is just {fileno(stdin), -1}. cmdin[i].outis similar for the output pipe/terminal output. cmdio[i].in is the same as cmd[i-1].out. For example: $ ls -l | sort | wc CMD: ls -l IN: 0 -1 OUT: 3 4 CMD: sort IN: 3 4 OUT: 5 6 CMD: wc IN: 5 6 OUT: -1 1 We pass each command to process_command, which does a number of things: for (cmdi = 0; cmds[cmdi].cmd != NULL; cmdi++) { process_command(&cmds[cmdi]); } Now, inside process_command: if (!(pid_fork = fork())) { dup2(cmd->in[0], fileno(stdin)); dup2(cmd->out[1], fileno(stdout)); if (cmd->in[1] >= 0) { if (close(cmd->in[1])) { perror(NULL); } } if (cmd->out[0] >= 0) { if (close(cmd->out[0])) { perror(NULL); } } execvp(cmd->cmd[0], cmd->cmd); exit(-1); } The problem is that reading from the pipe blocks forever: COMMAND $ ls | wc Created pipe, in: 5 out: 6 Foreground pid: 9042, command: ls, Exited, info: 0 [blocked running read() within wc] If, instead of exchanging the process with execvp, I just do this: if (!(pid_fork = fork())) { dup2(cmd->in[0], fileno(stdin)); dup2(cmd->out[1], fileno(stdout)); if (cmd->in[1] >= 0) { if (close(cmd->in[1])) { perror(NULL); } } if (cmd->out[0] >= 0) { if (close(cmd->out[0])) { perror(NULL); } } char buf[6]; read(fileno(stdin), buf, 5); buf[5] = '\0'; printf("%s\n", buf); exit(0); } It happens to work: COMMAND $ cmd1 | cmd2 | cmd3 | cmd4 | cmd5 Pipe creada, in: 11 out: 12 Pipe creada, in: 13 out: 14 Pipe creada, in: 15 out: 16 Pipe creada, in: 17 out: 18 hola! Foreground pid: 9251, command: cmd1, Exited, info: 0 Foreground pid: 9252, command: cmd2, Exited, info: 0 Foreground pid: 9253, command: cmd3, Exited, info: 0 Foreground pid: 9254, command: cmd4, Exited, info: 0 hola! Foreground pid: 9255, command: cmd5, Exited, info: 0 What could be the problem?

    Read the article

  • convert Ruby to C languge

    - by alaamh
    I have seen this sample written in Ruby code, how i can simulate it in C language? Open3.popen3(command) do |stdin, stdout, stderr| @stop_stdin = stdin while !stdout.eof do output = stdout.read(1024 * 100) list_pipes.each do |out| out.print output end end end

    Read the article

  • Debug CGI by simulation

    - by Jonathan
    I basically want to debug a cgi programm with gdb by emulating the environment variables and stdin stream. How do I set the variables and stdin? I am using lampp and gdb. Thanks!

    Read the article

  • Trouble calling a method from an external class

    - by Bradley Hobbs
    Here is my employee database program: import java.util.*; import java.io.*; import java.io.File; import java.io.FileReader; import java.util.ArrayList; public class P { //Instance Variables private static String empName; private static String wage; private static double wages; private static double salary; private static double numHours; private static double increase; // static ArrayList<String> ARempName = new ArrayList<String>(); // static ArrayList<Double> ARwages = new ArrayList<Double>(); // static ArrayList<Double> ARsalary = new ArrayList<Double>(); static ArrayList<Employee> emp = new ArrayList<Employee>(); public static void main(String[] args) throws Exception { clearScreen(); printMenu(); question(); exit(); } public static void printArrayList(ArrayList<Employee> emp) { for (int i = 0; i < emp.size(); i++){ System.out.println(emp.get(i)); } } public static void clearScreen() { System.out.println("\u001b[H\u001b[2J"); } private static void exit() { System.exit(0); } private static void printMenu() { System.out.println("\t------------------------------------"); System.out.println("\t|Commands: n - New employee |"); System.out.println("\t| c - Compute paychecks |"); System.out.println("\t| r - Raise wages |"); System.out.println("\t| p - Print records |"); System.out.println("\t| d - Download data |"); System.out.println("\t| u - Upload data |"); System.out.println("\t| q - Quit |"); System.out.println("\t------------------------------------"); System.out.println(""); } public static void question() { System.out.print("Enter command: "); Scanner q = new Scanner(System.in); String input = q.nextLine(); input.replaceAll("\\s","").toLowerCase(); boolean valid = (input.equals("n") || input.equals("c") || input.equals("r") || input.equals("p") || input.equals("d") || input.equals("u") || input.equals("q")); if (!valid){ System.out.println("Command was not recognized; please try again."); printMenu(); question(); } else if (input.equals("n")){ System.out.print("Enter the name of new employee: "); Scanner stdin = new Scanner(System.in); empName = stdin.nextLine(); System.out.print("Hourly (h) or salaried (s): "); Scanner stdin2 = new Scanner(System.in); wage = stdin2.nextLine(); wage.replaceAll("\\s","").toLowerCase(); if (!(wage.equals("h") || wage.equals("s"))){ System.out.println("Input was not h or s; please try again"); } else if (wage.equals("h")){ System.out.print("Enter hourly wage: "); Scanner stdin4 = new Scanner(System.in); wages = stdin4.nextDouble(); Employee emp1 = new HourlyEmployee(empName, wages); emp.add(emp1); printMenu(); question();} else if (wage.equals("s")){ System.out.print("Enter annual salary: "); Scanner stdin5 = new Scanner(System.in); salary = stdin5.nextDouble(); Employee emp1 = new SalariedEmployee(empName, salary); printMenu(); question();}} else if (input.equals("c")){ for (int i = 0; i < emp.size(); i++){ System.out.println("Enter number of hours worked by " + emp.get(i) + ":"); } Scanner stdin = new Scanner(System.in); numHours = stdin.nextInt(); System.out.println("Pay: " + emp1.computePay(numHours)); System.out.print("Enter number of hours worked by " + empName); Scanner stdin2 = new Scanner(System.in); numHours = stdin2.nextInt(); System.out.println("Pay: " + emp1.computePay(numHours)); printMenu(); question();} else if (input.equals("r")){ System.out.print("Enter percentage increase: "); Scanner stdin = new Scanner(System.in); increase = stdin.nextDouble(); System.out.println("\nNew Wages"); System.out.println("---------"); // System.out.println(Employee.toString()); printMenu(); question(); } else if (input.equals("p")){ printArrayList(emp); printMenu(); question(); } else if (input.equals("q")){ exit(); } } } Here is one of the class files: public abstract class Employee { private String name; private double wage; protected Employee(String name, double wage){ this.name = name; this.wage = wage; } public String getName() { return name; } public double getWage() { return wage; } public void setName(String name) { this.name = name; } public void setWage(double wage) { this.wage = wage; } public void percent(double wage, double percent) { wage *= percent; } } And here are the errors: P.java:108: cannot find symbol symbol : variable emp1 location: class P System.out.println("Pay: " + emp1.computePay(numHours)); ^ P.java:112: cannot find symbol symbol : variable emp1 location: class P System.out.println("Pay: " + emp1.computePay(numHours)); ^ 2 errors I'm trying to the get paycheck to print out but i'm having trouble with how to call the method. It should take the user inputed numHours and calculate it then print on the paycheck for each employee. Thanks!

    Read the article

  • Perl Term::ReadKey don't wait for newline

    - by tim
    In a perl script, I'm trying to accept input without blocking and without echoing the characters entered (The script is producing output and I want to have 'hotkeys' to alter its behaviour). I got as far as using use Term::ReadKey; ReadMode( "cbreak", STDIN ); if($input = ReadKey($pause_time, STDIN)){ #process input } But once the user types anything then the script stops until a newline is entered. I'd like the input to be processed per-character, without waiting for a newline.

    Read the article

  • Can't send commands via SSH to Juniper firewalls

    - by Massimo
    I have some Juniper SSG firewalls which I need to manage, and I'd like to be able to send commands to them from some monitoring scripts. I configured SSH access using public keys, and I'm able to automatically login to the firewalls. When I run SSH interactively, everything works fine: $ssh <firewall IP> FIREWALL-> <command> <command output> FIREWALL-> exit Connection to <firewall IP> closed. $ But when I try to run the command from the command line, it doesn't work: $ssh <firewall IP> <command> $ This, of course, works fine when sending a command to a remote Linux box: $ssh <linux box IP> <command> <command output> $ Why is this happening? What is the difference between running SSH interactively and specifying the command to run on the SSH command line? Update: It also works fine with a Cisco router. Only these Juniper firewalls seem to behave this way. From the debug output from SSH, it looks like the connection gets established correctly, but the Juniper box replies with an EOF when sending the command, while instead the Linux box replies with the actual command output: Linux: debug1: Authentication succeeded (publickey). debug1: channel 0: new [client-session] debug2: channel 0: send open debug1: Entering interactive session. debug2: callback start debug2: client_session2_setup: id 0 debug1: Sending command: uptime debug2: channel 0: request exec confirm 0 debug2: callback done debug2: channel 0: open confirm rwindow 0 rmax 32768 debug2: channel 0: rcvd adjust 131072 debug1: client_input_channel_req: channel 0 rtype exit-status reply 0 16:44:44 up 25 days, 1:06, 3 users, load average: 0.08, 0.02, 0.01 debug2: channel 0: rcvd eof debug2: channel 0: output open -> drain debug2: channel 0: obuf empty debug2: channel 0: close_write debug2: channel 0: output drain -> closed debug2: channel 0: rcvd close debug2: channel 0: close_read debug2: channel 0: input open -> closed debug2: channel 0: almost dead debug2: channel 0: gc: notify user debug2: channel 0: gc: user detached debug2: channel 0: send close debug2: channel 0: is dead debug2: channel 0: garbage collecting debug1: channel 0: free: client-session, nchannels 1 debug1: Transferred: stdin 0, stdout 0, stderr 0 bytes in 0.1 seconds debug1: Bytes per second: stdin 0.0, stdout 0.0, stderr 0.0 debug1: Exit status 0 Juniper: debug1: Authentication succeeded (publickey). debug1: channel 0: new [client-session] debug2: channel 0: send open debug1: Entering interactive session. debug2: callback start debug2: client_session2_setup: id 0 debug1: Sending environment. debug1: Sending env LANG = en_US.UTF-8 debug2: channel 0: request env confirm 0 debug1: Sending command: get system debug2: channel 0: request exec confirm 0 debug2: callback done debug2: channel 0: open confirm rwindow 2048 rmax 1024 debug2: channel 0: rcvd eof debug2: channel 0: output open -> drain debug2: channel 0: obuf empty debug2: channel 0: close_write debug2: channel 0: output drain -> closed debug1: client_input_channel_req: channel 0 rtype exit-status reply 0 debug2: channel 0: rcvd close debug2: channel 0: close_read debug2: channel 0: input open -> closed debug2: channel 0: almost dead debug2: channel 0: gc: notify user debug2: channel 0: gc: user detached debug2: channel 0: send close debug2: channel 0: is dead debug2: channel 0: garbage collecting debug1: channel 0: free: client-session, nchannels 1 debug1: Transferred: stdin 0, stdout 0, stderr 0 bytes in 0.2 seconds debug1: Bytes per second: stdin 0.0, stdout 0.0, stderr 0.0 debug1: Exit status 1

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >