Search Results

Search found 1848 results on 74 pages for 'printf'.

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

  • Memory allocation problem C/Cpp Windows critical error

    - by Andrew
    Hi! I have a code that need to be "translated" from C to Cpp, and i cant understand, where's a problem. There is the part, where it crashes (windows critical error send/dontSend): nDim = sizeMax*(sizeMax+1)/2; printf("nDim = %d sizeMax = %d\n",nDim,sizeMax); hamilt = (double*)malloc(nDim*sizeof(double)); printf("End hamilt alloc. %d allocated\n",(nDim*sizeof(double))); transProb = (double*)malloc(sizeMax*sizeMax*sizeof(double)); printf("End transProb alloc. %d allocated\n",(sizeMax*sizeMax*sizeof(double))); eValues = (double*)malloc(sizeMax*sizeof(double)); printf("eValues allocated. %d allocated\n",(sizeMax*sizeof(double))); eVectors = (double**)malloc(sizeMax*sizeof(double*)); printf("eVectors allocated. %d allocated\n",(sizeMax*sizeof(double*))); if(eVectors) for(i=0;i<sizeMax;i++) { eVectors[i] = (double*)malloc(sizeMax*sizeof(double)); printf("eVectors %d-th element allocated. %d allocated\n",i,(sizeMax*sizeof(double))); } eValuesPrev = (double*)malloc(sizeMax*sizeof(double)); printf("eValuesPrev allocated. %d allocated\n",(sizeMax*sizeof(double))); eVectorsPrev = (double**)malloc(sizeMax*sizeof(double*)); printf("eVectorsPrev allocated. %d allocated\n",(sizeMax*sizeof(double*))); if(eVectorsPrev) for(i=0;i<sizeMax;i++) { eVectorsPrev[i] = (double*)malloc(sizeMax*sizeof(double)); printf("eVectorsPrev %d-th element allocated. %d allocated\n",i,(sizeMax*sizeof(double))); } Log: nDim = 2485 sizeMax = 70 End hamilt alloc. 19880 allocated End transProb alloc. 39200 allocated eValues allocated. 560 allocated eVectors allocated. 280 allocated So it crashes at the start of the loop of allocation. If i delete this loop it crashes at the next line of allocation. Does it mean that with the numbers like this i have not enough memory?? Thank you.

    Read the article

  • Unexpected output from Bubblesort program with MSVC vs TCC

    - by Sujith S Pillai
    One of my friends sent this code to me, saying it doesn't work as expected: #include<stdio.h> void main() { int a [10] ={23, 100, 20, 30, 25, 45, 40, 55, 43, 42}; int sizeOfInput = sizeof(a)/sizeof(int); int b, outer, inner, c; printf("Size is : %d \n", sizeOfInput); printf("Values before bubble sort are : \n"); for ( b = 0; b &lt; sizeOfInput; b++) printf("%d\n", a[b]); printf("End of values before bubble sort... \n"); for ( outer = sizeOfInput; outer &gt; 0; outer-- ) { for ( inner = 0 ; inner &lt; outer ; inner++) { printf ( "Comparing positions: %d and %d\n",inner,inner+1); if ( a[inner] &gt; a[inner + 1] ) { int tmp = a[inner]; a[inner] = a [inner+1]; a[inner+1] = tmp; } } printf ( "Bubble sort total array size after inner loop is %d :\n",sizeOfInput); printf ( "Bubble sort sizeOfInput after inner loop is %d :\n",sizeOfInput); } printf ( "Bubble sort total array size at the end is %d :\n",sizeOfInput); for ( c = 0 ; c &lt; sizeOfInput; c++) printf("Element: %d\n", a[c]); } I am using Micosoft Visual Studio Command Line Tool for compiling this on a Windows XP machine. cl /EHsc bubblesort01.c My friend gets the correct output on a dinosaur machine (code is compiled using TCC there). My output is unexpected. The array mysteriously grows in size, in between. If you change the code so that the variable sizeOfInput is changed to sizeOfInputt, it gives the expected results! A search done at Microsoft Visual C++ Developer Center doesn't give any results for "sizeOfInput". I am not a C/C++ expert, and am curious to find out why this happens - any C/C++ experts who can "shed some light" on this? Unrelated note: I seriously thought of rewriting the whole code to use quicksort or merge sort before posting it here. But, after all, it is not Stooge sort... Edit: I know the code is not correct (it reads beyond the last element), but I am curious why the variable name makes a difference.

    Read the article

  • Bluetooth service problem

    - by hara
    hi I need to create a custom bluetooth service and I have to develop it using c++. I read a lot of examples but I didn't success in publishing a new service with a custom UUID. I need to specify a UUID in order to be able to connect to the service from an android app. This is what i wrote: GUID service_UUID = { /* 00000003-0000-1000-8000-00805F9B34FB */ 0x00000003, 0x0000, 0x1000, {0x80, 0x00, 0x00, 0x80, 0x5F, 0x9B, 0x34, 0xFB} }; SOCKET s, s2; SOCKADDR_BTH sab if (WSAStartup(MAKEWORD(2, 2), &wsd) != 0) return 1; printf("installing a new service\n"); s = socket(AF_BTH, SOCK_STREAM, BTHPROTO_RFCOMM); if (s == INVALID_SOCKET) { printf ("Socket creation failed, error %d\n", WSAGetLastError()); return 1; } memset (&sab, 0, sizeof(sab)); sab.addressFamily = AF_BTH; sab.port = BT_PORT_ANY; sab.serviceClassId = service_UUID; if (0 != bind(s, (SOCKADDR *) &sab, sizeof(sab))) { printf ("bind() failed with error code %d\n", WSAGetLastError()); closesocket (s); return 1; } int result=sizeof(sab); getsockname(s,(SOCKADDR *) &sab, &result ); printSOCKADDR_BTH(sab); if(listen (s, 5) == 0) printf("listen() is OK! Listening for connection... :)\n"); else printf("listen() failed with error code %d\n", WSAGetLastError()); printf("waiting connection"); for ( ; ; ) { int ilen = sizeof(sab2); s2 = accept (s, (SOCKADDR *)&sab2, &ilen); printf ("accepted"); } if(closesocket(s) == 0) printf("closesocket() pretty fine!\n"); if(WSACleanup () == 0) printf("WSACleanup() is OK!\n"); return 0; When i print the SOCKADDR_BTH structure retrieved with get getsockname i get an UUID that is not the mine. Furthermore if i use the UUID read from getsockname to connect the Android application the connection fails with this exception: java.io.IOException: Service discovery failed Could you help me?? Thanks!

    Read the article

  • How to calculate the maximum block length in C of a binary number

    - by user1664272
    I want to reiterate the fact that I am not asking for direct code to my problem rather than wanting information on how to reach that solution. I asked a problem earlier about counting specific integers in binary code. Now I would like to ask how one comes about counting the maximum block length within binary code. I honestly just want to know where to get started and what exactly the question means by writing code to figure out the "Maximum block length" of an inputted integers binary representation. Ex: Input 456 Output: 111001000 Number of 1's: 4 Maximum Block Length: ? Here is my code so far for reference if you need to see where I'm coming from. #include <stdio.h> int main(void) { int integer; // number to be entered by user int i, b, n; unsigned int ones; printf("Please type in a decimal integer\n"); // prompt fflush(stdout); scanf("%d", &integer); // read an integer if(integer < 0) { printf("Input value is negative!"); // if integer is less than fflush(stdout); return; // zero, print statement } else{ printf("Binary Representation:\n", integer); fflush(stdout);} //if integer is greater than zero, print statement for(i = 31; i >= 0; --i) //code to convert inputted integer to binary form { b = integer >> i; if(b&1){ printf("1"); fflush(stdout); } else{ printf("0"); fflush(stdout); } } printf("\n"); fflush(stdout); ones = 0; //empty value to store how many 1's are in binary code while(integer) //while loop to count number of 1's within binary code { ++ones; integer &= integer - 1; } printf("Number of 1's in Binary Representation: %d\n", ones); // prints number fflush(stdout); //of ones in binary code printf("Maximum Block Length: \n"); fflush(stdout); printf("\n"); fflush(stdout); return 0; }//end function main

    Read the article

  • I'd like to know why a function executes fine when called from x but not when called from y

    - by Roland
    When called from archive(), readcont(char *filename) executes fine! Called from runoptions() though, it fails to list the files "archived"! why is this? The program must run in terminal. Use -h as a parameter to view the usage. This program is written to "archive" text files into ".rldzip" files. readcont( char *x) should show the files archived in file (*x) a) Successful call Use the program to archive 3 text files: rldzip.exe a.txt b.txt c.txt FILEXY -a archive() will call readcont and it will work showing the files archived after the binary FILEXY will be created. b) Unsuccessful call After the file is created, use: rldzip.exe FILEXY.rldzip -v You can see that the function crashes! I'd like to know why is this happening! /* Sa se scrie un program care: a) arhiveaza fisiere b) dezarhiveaza fisierele athivate */ #include<stdio.h> #include<stdlib.h> #include<conio.h> #include<string.h> struct content{ char *text; char *flname; }*arc; FILE *f; void readcont(char *x){ FILE *p; if((p = fopen(x, "rb")) == NULL){ perror("Critical error: "); exit(EXIT_FAILURE); } content aux; int i; fread(&i, sizeof(int), 1, p); printf("\nFiles in %s \n\n", x); while(i-- >1 && fread(&aux, sizeof(struct content), 1, p) != 0) printf("%s \n", aux.flname); fclose(p); printf("\n\n"); } void archive(int argc, char **argv){ int i; char inttext[5000], textline[1000]; //Allocate dynamic memory for the content to be archived! arc = (content*)malloc(argc * sizeof(content)); for(i=1; i< argc; i++) { if((f = fopen(argv[i], "r")) == NULL){ printf("%s: ", argv[i]); perror(""); exit(EXIT_FAILURE); } while(!feof(f)){ fgets(textline, 5000, f); strcat(inttext, textline); } arc[i-1].text = (char*)malloc(strlen(inttext) + 1); strcpy(arc[i-1].text, inttext); arc[i-1].flname = (char*)malloc(strlen(argv[i]) + 1); strcpy(arc[i-1].flname, argv[i]); fclose(f); } char *filen; filen=(char*)malloc(strlen(argv[argc])+1+7); strcpy(filen, argv[argc]); strcat(filen, ".rldzip"); f = fopen(filen, "wb"); fwrite(&argc, sizeof(int), 1, f); fwrite(arc, sizeof(content), argc, f); fclose(f); printf("Success! "); for(i=1; i< argc; i++) { (i==argc-1)? printf("and %s ", argv[i]) : printf("%s ", argv[i]); } printf("compressed into %s", filen); readcont(filen); free(filen); } void help(char *v){ printf("\n\n----------------------RLDZIP----------------------\n\nUsage: \n\n Archive n files: \n\n%s $file[1] $file[2] ... $file[n] $output -a\n\nExample:\n%s a.txt b.txt c.txt output -a\n\n\n\nView files:\n\n %s $file.rldzip -v\n\nExample:\n %s fileE.rldzip -v\n\n", v, v, v, v); } void runoptions(int c, char **v){ int i; if(c < 2){ printf("Arguments missing! Use -h for help"); } else{ for(i=0; i<c; i++) if(strcmp(v[i], "-h") == 0){ help(v[0]); exit(2); } for(i=0; i<c; i++) if(strcmp(v[i], "-v") == 0){ if(c != 3){ printf("Arguments misused! Use -h for help"); exit(2); } else { printf("-%s-", v[1]); readcont(v[1]); } } } if(strcmp(v[c-1], "-a") == 0) archive(c-2, v); } main(int argc, char **argv) { runoptions(argc, argv); }

    Read the article

  • "Use of uninitialised value" despite of memset

    - by Framester
    Hi there, I allocate a 2d array and use memset to fill it with zeros. #include<stdio.h> #include<string.h> #include<stdlib.h> void main() { int m=10; int n =10; int **array_2d; array_2d = (int**) malloc(m*sizeof(int*)); if(array_2d==NULL) { printf("\n Could not malloc 2d array \n"); exit(1); } for(int i=0;i<m;i++) { ((array_2d)[i])=malloc(n*sizeof(int)); memset(((array_2d)[i]),0,sizeof(n*sizeof(int))); } for(int i=0; i<10;i++){ for(int j=0; j<10;j++){ printf("(%i,%i)=",i,j); fflush(stdout); printf("%i ", array_2d[i][j]); } printf("\n"); } } Afterwards I use valgrind [1] to check for memory errors. I get following error: Conditional jump or move depends on uninitialised value(s) for line 24 (printf("%i ", array_2d[i][j]);). I always thought memset is the function to initialize arrays. How can I get rid off this error? Thanks! Valgrind output: ==3485== Memcheck, a memory error detector ==3485== Copyright (C) 2002-2009, and GNU GPL'd, by Julian Seward et al. ==3485== Using Valgrind-3.5.0-Debian and LibVEX; rerun with -h for copyright info ==3485== Command: ./a.out ==3485== (0,0)=0 (0,1)===3485== Use of uninitialised value of size 4 ==3485== at 0x409E186: _itoa_word (_itoa.c:195) ==3485== by 0x40A1AD1: vfprintf (vfprintf.c:1613) ==3485== by 0x40A8FFF: printf (printf.c:35) ==3485== by 0x8048724: main (playing_with_valgrind.c:39) ==3485== ==3485== ==3485== ---- Attach to debugger ? --- [Return/N/n/Y/y/C/c] ---- ==3485== Conditional jump or move depends on uninitialised value(s) ==3485== at 0x409E18E: _itoa_word (_itoa.c:195) ==3485== by 0x40A1AD1: vfprintf (vfprintf.c:1613) ==3485== by 0x40A8FFF: printf (printf.c:35) ==3485== by 0x8048724: main (playing_with_valgrind.c:39) [1] valgrind --tool=memcheck --leak-check=yes --show-reachable=yes --num-callers=20 --track-fds=yes --db-attach=yes ./a.out [gcc-cmd] gcc -std=c99 -lm -Wall -g3 playing_with_valgrind.c

    Read the article

  • Does this have anything to do with endian-ness?

    - by eSKay
    This piece of code: #include<stdio.h> void hello() { printf("hello\n"); } void bye() { printf("bye\n"); } int main() { printf("%p\n", hello); printf("%p\n", bye); return 0; } output on my machine: 0x80483f4 0x8048408 [second address is bigger in value] on Codepad 0x8048541 0x8048511 [second address is smaller in value] Does this have anything to do with endian-ness of the machines? If not, Why the difference in the ordering of the addresses? Also, Why the difference in the difference? 0x8048541 - 0x8048511 = 0x30 0x8048408 - 0x80483f4 = 0x14 Btw, I just checked. This code (taken from here) says that both the machines are Little-Endian #include<stdio.h> int main() { int num = 1; if(*(char *)&num == 1) printf("Little-Endian\n"); else printf("Big-Endian\n"); return 0; }

    Read the article

  • write 2d array to a file in C (Operating system)

    - by Bobj-C
    Hello All, I used to use the code below to Write an 1D array to a File: FILE *fp; float floatValue[5] = { 1.1F, 2.2F, 3.3F, 4.4F, 5.5F }; int i; if((fp=fopen("test", "wb"))==NULL) { printf("Cannot open file.\n"); } if(fwrite(floatValue, sizeof(float), 5, fp) != 5) printf("File read error."); fclose(fp); /* read the values */ if((fp=fopen("test", "rb"))==NULL) { printf("Cannot open file.\n"); } if(fread(floatValue, sizeof(float), 5, fp) != 5) { if(feof(fp)) printf("Premature end of file."); else printf("File read error."); } fclose(fp); for(i=0; i<5; i++) printf("%f ", floatValue[i]); My question is if i want to write and read 2D array ??

    Read the article

  • Unexpected output while using Microsoft Visual Studio 2008 (Express Edition) C++ Command Line Tool

    - by Sujith S Pillai
    One of my friends sent this code to me, saying it doesn't work as expected: #include<stdio.h> void main() { int a [10] ={23, 100, 20, 30, 25, 45, 40, 55, 43, 42}; int sizeOfInput = sizeof(a)/sizeof(int); int b, outer, inner, c; printf("Size is : %d \n", sizeOfInput); printf("Values before bubble sort are : \n"); for ( b = 0; b < sizeOfInput; b++) printf("%d\n", a[b]); printf("End of values before bubble sort... \n"); for ( outer = sizeOfInput; outer > 0; outer-- ) { for ( inner = 0 ; inner < outer ; inner++) { printf ( "Comparing positions: %d and %d\n",inner,inner+1); if ( a[inner] > a[inner + 1] ) { int tmp = a[inner]; a[inner] = a [inner+1]; a[inner+1] = tmp; } } printf ( "Bubble sort total array size after inner loop is %d :\n",sizeOfInput); printf ( "Bubble sort sizeOfInput after inner loop is %d :\n",sizeOfInput); } printf ( "Bubble sort total array size at the end is %d :\n",sizeOfInput); for ( c = 0 ; c < sizeOfInput; c++) printf("Element: %d\n", a[c]); } I am using Micosoft Visual Studio Command Line Tool for compiling this on a Windows XP machine. cl /EHsc bubblesort01.c My friend gets the correct output on a dinosaur machine (code is compiled using TCC there). My output is unexpected. The array mysteriously grows in size, in between. If you change the code so that the variable sizeOfInput is changed to sizeOfInputt, it gives the expected results! A search done at Microsoft Visual C++ Developer Center doesn't give any results for "sizeOfInput". I am not a C/C++ expert, and am curious to find out why this happens - any C/C++ experts who can "shed some light" on this? Unrelated note: I seriously thought of rewriting the whole code to use quicksort or merge sort before posting it here. But, after all, it is not Stooge sort...

    Read the article

  • Users using Perl script to bypass Squid Proxy

    - by mk22
    The users on our network have been using a perl script to bypass our Squid proxy restrictions. Is there any way we can block this script from working?? #!/usr/bin/perl ######################################################################## # (c) 2008 Indika Bandara Udagedara # [email protected] # http://indikabandara19.blogspot.com # # ---------- # LICENCE # ---------- # This work is protected under GNU GPL # It simply says # " you are hereby granted to do whatever you want with this # except claiming you wrote this." # # # ---------- # README # ---------- # A simple tool to download via http proxies which enforce a download # size limit. Requires curl. # This is NOT a hack. This uses the absolutely legal HTTP/1.1 spec # Tested only for squid-2.6. Only squids will work with this(i think) # Please read the verbose README provided kindly by Rahadian Pratama # if u r on cygwin and think this documentation is not enough :) # # The newest version of pget is available at # http://indikabandara.no-ip.com/~indika/pget # # ---------- # USAGE # ---------- # + Edit below configurations(mainly proxy) # + First run with -i <file> giving a sample file of same type that # you are going to download. Doing this once is enough. # eg. to download '.tar' files first run with # pget -i my.tar ('my.tar' should be a real file) # + Run with # pget -g <URL> # # ######################################################################## ######################################################################## # CONFIGURATIONS - CHANGE THESE FREELY ######################################################################## # *magic* file # pls set absolute path if in cygwin my $_extFile = "./pget.ext" ; # download in chunks of below size my $_chunkSize = 1024*1024; # in Bytes # the proxy that troubles you my $_proxy = "192.168.0.2:3128"; # proxy URL:port my $_proxy_auth = "user:pass"; # proxy user:pass # whereis curl # pls set absolute path if in cygwin my $_curl = "/usr/bin/curl"; ######################################################################## # EDIT BELOW ONLY IF YOU KNOW WHAT YOU ARE DOING ######################################################################## use warnings; my $_version = "0.1.0"; PrintBanner(); if (@ARGV == 0) { PrintHelp(); exit; } PrimaryValidations(); my $val; while(scalar(@ARGV)) { my $arg = shift(@ARGV); if($arg eq '-h') { PrintHelp(); } elsif($arg eq '-i') { $val = shift(@ARGV); if (!defined($val)) { printf("-i option requires a filename\n"); exit; } Init($val); } elsif($arg eq '-g') { $val = shift(@ARGV); if (!defined($val)) { printf("-g option requires a URL\n"); exit; } GetURL($val); } elsif($arg eq '-c') { $val = shift(@ARGV); if (!defined($val)) { printf("-c option requires a URL\n"); exit; } ContinueURL($val); } else { printf ("Unknown option %s\n", $arg); PrintHelp(); } } sub GetURL { my ($URL) = @_; chomp($URL); my $fileName = GetFileName($URL); my %mapExt; my $first; my $readLen; my $ext = GetExt($fileName); ReadMap($_extFile, \%mapExt); if ( exists($mapExt{$ext})) { $first = $mapExt{$ext}; GetFile($URL, $first, $fileName, 0); } else { die "Unknown ext in $fileName. Rerun with -i <fileName>"; } } sub ContinueURL { my ($URL) = @_; chomp($URL); my $fileName = GetFileName($URL); my $fileSize = 0; $fileSize = -s $fileName; printf("Size = %d\n", $fileSize); my $first = -1; if ( $fileSize > 0 ) { $fileSize -= 1; GetFile($URL, $first, $fileName, $fileSize); } else { GetURL($URL); } } sub Init { my ($fileName) = @_; my ($key, $value); my %mapExt; my $ext = GetExt($fileName); if ( $ext eq "") { die "Cannot get ext of \'$fileName\'"; } ReadMap($_extFile, \%mapExt); my $b = GetFirst($fileName); $mapExt{$ext} = $b; WriteMap($_extFile, \%mapExt); print "I handle\n"; while ( ($key, $value) = each(%mapExt) ) { print "\t$key -> $value\n"; } } sub GetExt { my ($name) = @_; my @x = split(/\./, $name); my $ext = ""; if (@x != 1) { $ext = pop @x; } return $ext; } sub ReadMap { my($fileName, $mapRef) = @_; my $f; my @arr; open($f, '<', $fileName) or die "Couldn't open $fileName"; my %map = %{$mapRef}; while (<$f>) { my $line = $_; chomp($line); @arr = split(/[ \t]+/, $line, 2); $mapRef->{ $arr[0]} = $arr[1]; } printf("known ext\n"); while (($key, $value) = each(%$mapRef)) { print("$key, $value\n"); } close($f); } sub WriteMap { my ($fileName, $mapRef) = @_; my $f; my @arr; open($f, '>', $fileName) or die "Couldn't open $fileName"; my ($k, $v); while( ($k, $v) = each(%{$mapRef})) { print $f "$k" . "\t$v\n"; } close($f); } sub PrintHelp { print "usage: -h Print this help -i <filename> Initialize for this filetype -g <URL> Get this URL\n -c <URL> Continue this URL\n" } sub GetFirst { my ($fileName) = @_; my $f; open($f, "<$fileName") or die "Couldn't open $fileName"; my $buffer = ""; my $first = -1; binmode($f); sysread($f, $buffer, 1, 0); close($f); $first = ord($buffer); return $first; } sub GetFirstFromMap { } sub GetFileName { my ($URL) = @_; my @x = split(/\//, $URL); my $fileName = pop @x; return $fileName; } sub GetChunk { my ($URL, $file, $offset, $readLen) = @_; my $end = $offset + $_chunkSize - 1; my $curlCmd = "$_curl -x $_proxy -u $_proxy_auth -r $offset-$end -# \"$URL\""; print "$curlCmd\n"; my $buff = `$curlCmd`; ${$readLen} = syswrite($file, $buff, length($buff)); } sub GetFile { my ($URL, $first, $outFile, $fileSize) = @_; my $readLen = 0; my $start = $fileSize + 1; my $file; open($file, "+>>$outFile") or die "Couldn't open $outFile to write"; if ($fileSize <= 0) { my $uc = pack("C", $first); syswrite ($file, $uc, 1); } do { GetChunk($URL, $file, $start ,\$readLen); $start = $start + $_chunkSize; $fileSize += $readLen; }while ($readLen == $_chunkSize); printf("Downloaded %s(%d bytes).\n", $outFile, $fileSize); close($file); } sub PrintBanner { printf ("pget version %s\n", $_version); printf ("There is absolutely NO WARRANTY for pget.\n"); printf ("Use at your own risk. You have been warned.\n\n"); } sub PrimaryValidations { unless( -e "$_curl") { printf("ERROR:curl is not at %s. Pls install or provide correct path.\n", $_curl); exit; } unless( -e "$_extFile") { printf("extFile is not at %s. Creating one\n", $_extFile); `touch $_extFile`; } if ( $_chunkSize <= 0) { printf ("Invalid chunk size. Using 1Mb as default.\n"); $_chunkSize = 1024*1024; } }

    Read the article

  • how to generate number pattern in triangular form

    - by Vignesh Vicky
    I want to print this pattern like right angled triangle 0 909 89098 7890987 678909876 56789098765 4567890987654 345678909876543 23456789098765432 1234567890987654321 I wrote following code # include<stdio.h> # include<conio.h> void main() { clrscr(); int i,j,x,z,k,f=1; for ( i=10;i>=1;i--,f++) { for(j=1;j<=f;j++,k--) { k=i; if(k!=10) { printf("%d",k); } if(k==10) { printf("0"); } } for(x=1;x<f;x++,z--) { z=9; printf("%d",z); } printf("%d/n"); } getch(); } what is wrong with this code? when i check manually it seems correct but when compiled gives different pattern

    Read the article

  • Parsing mathematical experssions with two values that have parenthesis and minus signs

    - by user45921
    I'm trying to parse equations like these which only has two values or the square root of a certain value from a text file: 100+100 -100-100 -(100)+(-100) sqrt(100) by the minues signs, parenthesis and the operator symbol in the middle and the square root, and I have no idea how to start off... I've got the file part done and the simple calculation parts except that I couldnt get my program to solve the equations in the above. #include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> main(){ FILE *fp; char buff[255], sym,sym2,del1,del2,del3,del4; double num1, num2; int ret; fp = fopen("input.txt","r"); while(fgets(buff,sizeof(buff),fp)!=NULL){ char *tok = buff; sscanf(tok,"%lf%c%lf",&num1,&sym,&num2); switch(sym){ case '+': printf("%lf\n", num1+num2); break; case '-': printf("%lf\n", num1-num2); break; case '*': printf("%lf\n", num1*num2); break; case '/': printf("%lf\n", num1/num2); break; default: printf("The input value is not correct\n"); break; } } fclose(fp); } that is what have I written for the other basic operations without parenthesis and the minus sign for the second value and it works great for the simple ones. I'm using a switch method to calculate the add, sub, mul and divide but I'm not sure how to properly use the sscanf function (if I am not using it properly) or if there is another way using a function like strtok to properly parse the parenthesis and the minus signs. Any kind help?

    Read the article

  • Small script to look for Project Replication actions that have failed

    - by Trond Strømme
    Today when looking at a couple of projects on a ZFS 7320 Storage Appliance I noticed on one project that one of its replication actions had failed, as I hadn't checked the Recent Alerts log yet I was not aware of this. I decided to write a small script to check if there were others that had failed. Nothing fancy, just a loop through all projects, look at the project's replication child and compare the values of the last_sync and last_try properties and print the result if they're not equal. (There are probably more sensible ways of doing this, but at least it involves me getting the chance to put on my headphones and doing just a little bit of coding.) script // this script will locate failed project level replication // it will look at the sync times for 'last_sync' and 'last_try' // and compare these, if they deviate you should investigate. // NOTE! this code is offered 'as is' Run at your own risk, // it will probably work as intended, but in now way can I // (or Oracle) be held responsible if your server starts behaving // like a three year old kid in a candy store.. (not that mine do, // they are very well behaved boys...) run('configuration'); run('storage'); printf('Host: %s, pool: %s\n', get('owner'),get('pool')); run('cd /'); run('shares'); proj=list(); printf("total projects: %d\n",proj.length +'\n'); // just for project level replication for(i=0;i<proj.length;i++){ run('select '+proj[i]); run('replication'); //get all replication actions preps = list(); for(j=0;j<preps.length;j++){ run('select ' + preps[j]); last_sync = get('last_sync'); last_try = get('last_try'); // printf("target %s\n", get('target')); //why the flip does this not get the proper name? if(!( last_sync.valueOf() === last_try.valueOf())){ printf("sync has failed for %s %s\n", proj[i], get('target')); }else{ // printf("OK %s %s\n", proj[i], get('target')); } run('done'); //done with the replica action } run('done'); run('done'); } printf("finished\n"); For a more on how to run the script, or testing it please look at my previous post. Sample output: Host: elb1sn01, pool: exalogic total projects: 45 sync has failed for ACSExalogicSystem cb3a24fe-ad60-c90f-d15d-adaafd595639 finished

    Read the article

  • Problem in udp socket programing in c

    - by Md. Talha
    I complile the following C code of UDP client after I run './udpclient localhost 9191' in terminal.I put "Enter Text= " as Hello, but it is showing error in sendto as below: Enter text: hello hello : error in sendto()guest-1SDRJ2@md-K42F:~/Desktop$ " Note: I open 1st the server port as below in other terminal ./server 9191. I beleive there is no error in server code. The udp client is not passing message to server. If I don't use thread , the message is passing .But I have to do it by thread. UDP client Code: /* simple UDP echo client */ #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <stdio.h> #include <pthread.h> #define STRLEN 1024 static void *readdata(void *); static void *writedata(void *); int sockfd, n, slen; struct sockaddr_in servaddr; char sendline[STRLEN], recvline[STRLEN]; int main(int argc, char *argv[]) { pthread_t readid,writeid; struct sockaddr_in servaddr; struct hostent *h; if(argc != 3) { printf("Usage: %s <proxy server ip> <port>\n", argv[0]); exit(0); } /* create hostent structure from user entered host name*/ if ( (h = gethostbyname(argv[1])) == NULL) { printf("\n%s: error in gethostbyname()", argv[0]); exit(0); } /* create server address structure */ bzero(&servaddr, sizeof(servaddr)); /* initialize it */ servaddr.sin_family = AF_INET; memcpy((char *) &servaddr.sin_addr.s_addr, h->h_addr_list[0], h->h_length); servaddr.sin_port = htons(atoi(argv[2])); /* get the port number from argv[2]*/ /* create a UDP socket: SOCK_DGRAM */ if ( (sockfd = socket(AF_INET,SOCK_DGRAM, 0)) < 0) { printf("\n%s: error in socket()", argv[0]); exit(0); } pthread_create(&readid,NULL,&readdata,NULL); pthread_create(&writeid,NULL,&writedata,NULL); while(1) { }; close(sockfd); } static void * writedata(void *arg) { /* get user input */ printf("\nEnter text: "); do { if (fgets(sendline, STRLEN, stdin) == NULL) { printf("\n%s: error in fgets()"); exit(0); } /* send a text */ if (sendto(sockfd, sendline, sizeof(sendline), 0, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0) { printf("\n%s: error in sendto()"); exit(0); } }while(1); } static void * readdata(void *arg) { /* wait for echo */ slen = sizeof(servaddr); if ( (n = recvfrom(sockfd, recvline, STRLEN, 0, (struct sockaddr *) &servaddr, &slen)) < 0) { printf("\n%s: error in recvfrom()"); exit(0); } /* null terminate the string */ recvline[n] = 0; fputs(recvline, stdout); }

    Read the article

  • Please help me debug this little C program on dynamic two-dimensional array? [migrated]

    - by azhi
    I am a newbie here. I have written a little C program, which is to create a two-dimensional matrix. Here is the code: #include <stdio.h> #include <stdlib.h> int **CreatMatrix(int m,int n){ int **Matrix; int i; Matrix=(int**)malloc(m*sizeof(int*)); for(i=0;i<m;i++){ Matrix[i]=(int*)malloc(n*sizeof(int)); } return Matrix; } int main(){ int m,n; int **A; printf("Please input the size of the Matrix: "); scanf("%d%d",&m,&n); A=CreatMatrix(m,n); printf("Please input the entries of the Matrix, which should be integers!\n"); int i,j; for(i=0;i<m;i++){ for(j=0;j<n;j++){ scanf("%d",&A[i][j]); } } printf("The Matrix that you input is:\n"); for(i=0;i<m;i++){ for(j=0;j<n;j++){ printf("%3d ",A[i][j]); } printf("\n"); } for(i=0;i<m;i++) free(A[i]); free(A); } I have run it, and it works fine. But I am not sure if it is right? Can anyone help me debug it?

    Read the article

  • Why is n given the initial value of 1 in this loop?

    - by notypist
    From Kochan's "Programming in C": Input: printf ("TABLE OF TRIANGULAR NUMBERS\n\n"); printf (" n Sum from 1 to n\n"); printf ("--- ---------------\n"); triangularNumber = 0; for(n=1; n<=10; ++n){ triangularNumber += n; ? printf (" %i", n); } Output (only partly pasted): TABLE OF TRIANGULAR NUMBERS n = 1 Sum from 1 to n = 1 n = 2 Sum from 1 to n = 2 Question: I understand the purpose of this, but here's what I can't get my head around: If within the loop we assign an initial value of "1" to "n", then we check if n<=10, and if that's true (which it should be with the initial value), we then add "1" to n. Shouldn't (and I know it shouldn't, just don't understand why) the initial value displayed in our table be n=2 ? Thanks in advance for your patience and effort!

    Read the article

  • How to use pipes for nonblocking IPC (UART emulation)

    - by codebauer
    I would like to write some test/emulation code that emulates a serial port connection. The real code looks like this: DUT <- UART - testtool.exe My plan is to use create a test application (CodeUnderTest.out) on linux that forks to launch testool.out with two (read & write) named pipes as arguments. But I cannot figure out how to make all the pipe IO non-blocking! The setup would look like this:. CodeUnderTest.out <- named pipes - testTool.out (lauched from CodeUnderTest.out) I have tried opening the pipes as following: open(wpipe,O_WRONLY|O_NONBLOCK); open(rpipe,O_RDONLY|O_NONBLOCK); But the write blocks until the reader opens the wpipe. Next I tried the following: open(wpipe,O_RDWR|O_NONBLOCK); open(rpipe,O_RDONLY|O_NONBLOCK); But then the reader of the first message never gets any data (doesn't block though) I also tried adding open and close calls around each message, but that didn't work either... Here is some test code: #include <stdio.h> #include <sys/types.h> #include <unistd.h> #include <fcntl.h> pid_t pid; char* rpipe, *wpipe,*x; FILE *rh,*wh; int rfd,wfd; void openrpipe( void ) { rfd = open(rpipe,O_RDONLY|O_NONBLOCK); rh = fdopen(rfd,"rb"); printf("%sopeningr %x\n",x,rh); } void openwpipe( void ) { //Fails when reader not already opened //wfd = open(wpipe,O_WRONLY|O_NONBLOCK); wfd = open(wpipe,O_RDWR|O_NONBLOCK); wh = fdopen(wfd,"wb"); printf("%sopeningw %x\n",x,wh); } void closerpipe( void ) { int i; i = fclose(rh); printf("%sclosingr %d\n",x,i); } void closewpipe( void ) { int i; i = fclose(wh); printf("%sclosingw %d\n",x,i); } void readpipe( char* expect, int len) { char buf[1024]; int i=0; printf("%sreading\n",x); while(i==0) { //printf("."); i = fread(buf,1,len,rh); } printf("%sread (%d) %s\n",x,i,buf); } void writepipe( char* data, int len) { int i,j; printf("%swriting\n",x); i = fwrite(data,1,len,rh); j = fflush(rh); //No help! printf("%sflush %d\n",x,j); printf("%swrite (%d) %s\n",x,i,data); } int main(int argc, char **argv) { rpipe = "readfifo"; wpipe = "writefifo"; x = ""; pid = fork(); if( pid == 0) { wpipe = "readfifo"; rpipe = "writefifo"; x = " "; openrpipe(); openwpipe(); writepipe("paul",4); readpipe("was",3); writepipe("here",4); closerpipe(); closewpipe(); exit(0); } openrpipe(); openwpipe(); readpipe("paul",4); writepipe("was",3); readpipe("here",4); closerpipe(); closewpipe(); return( -1 ); } BTW: To use the testocd above you need to pipes in the cwd: mkfifo ./readfifo mkfifo ./writefifo

    Read the article

  • Errors with parameter datatype in PostgreSql query

    - by John
    Im trying to execute a query to postgresql using the following code. It's written in C/C++ and I keep getting the following error when declaring a cursor: DECLARE CURSOR failed: ERROR: could not determine data type of parameter $1 Searching on here and on google, I can't find a solution. Can anyone find where I have made and error and why this is happening? thanks! void searchdb( PGconn *conn, char* name, char* offset ) { // Will hold the number of field in table int nFields; // Start a transaction block PGresult *res = PQexec(conn, "BEGIN"); if (PQresultStatus(res) != PGRES_COMMAND_OK) { printf("BEGIN command failed: %s", PQerrorMessage(conn)); PQclear(res); exit_nicely(conn); } // Clear result PQclear(res); printf("BEGIN command - OK\n"); //set the values to use const char *values[3] = {(char*)name, (char*)RESULTS_LIMIT, (char*)offset}; //calculate the lengths of each of the values int lengths[3] = {strlen((char*)name), sizeof(RESULTS_LIMIT), sizeof(offset)}; //state which parameters are binary int binary[3] = {0, 0, 1}; res = PQexecParams(conn, "DECLARE emprec CURSOR for SELECT name, id, 'Events' as source FROM events_basic WHERE name LIKE '$1::varchar%' UNION ALL " " SELECT name, fsq_id, 'Venues' as source FROM venues_cache WHERE name LIKE '$1::varchar%' UNION ALL " " SELECT name, geo_id, 'Cities' as source FROM static_cities WHERE name LIKE '$1::varchar%' OR FIND_IN_SET('$1::varchar%', alternate_names) != 0 LIMIT $2::int4 OFFSET $3::int4", 3, //number of parameters NULL, //ignore the Oid field values, //values to substitute $1 and $2 lengths, //the lengths, in bytes, of each of the parameter values binary, //whether the values are binary or not 0); //we want the result in text format // Fetch rows from table if (PQresultStatus(res) != PGRES_COMMAND_OK) { printf("DECLARE CURSOR failed: %s", PQerrorMessage(conn)); PQclear(res); exit_nicely(conn); } // Clear result PQclear(res); res = PQexec(conn, "FETCH ALL in emprec"); if (PQresultStatus(res) != PGRES_TUPLES_OK) { printf("FETCH ALL failed"); PQclear(res); exit_nicely(conn); } // Get the field name nFields = PQnfields(res); // Prepare the header with table field name printf("\nFetch record:"); printf("\n********************************************************************\n"); for (int i = 0; i < nFields; i++) printf("%-30s", PQfname(res, i)); printf("\n********************************************************************\n"); // Next, print out the record for each row for (int i = 0; i < PQntuples(res); i++) { for (int j = 0; j < nFields; j++) printf("%-30s", PQgetvalue(res, i, j)); printf("\n"); } PQclear(res); // Close the emprec res = PQexec(conn, "CLOSE emprec"); PQclear(res); // End the transaction res = PQexec(conn, "END"); // Clear result PQclear(res); }

    Read the article

  • Issue on file existence in C

    - by darkie15
    Hi All, Here is my code which checks if the file exists : #include<stdio.h> #include<zlib.h> #include<unistd.h> #include<string.h> int main(int argc, char *argv[]) { char *path=NULL; FILE *file = NULL; char *fileSeparator = "/"; size_t size=100; int index ; printf("\nArgument count is = %d", argc); if (argc <= 1) { printf("\nUsage: ./output filename1 filename2 ..."); printf("\n The program will display human readable information about the PNG file provided"); } else if (argc > 1) { for (index = 1; index < argc;index++) { path = getcwd(path, size); strcat(path, fileSeparator); printf("\n File name entered is = %s", argv[index]); strcat(path,argv[index]); printf("\n The complete path of the file name is = %s", path); if (access(path, F_OK) != -1) { printf("File does exist"); } else { printf("File does not exist"); } path=NULL; } } return 0; } On running the command ./output test.txt test2.txt The output is: $ ./output test.txt test2.txt Argument count is = 3 File name entered is = test.txt The complete path of the file name is = /home/welcomeuser/test.txt File does not exist File name entered is = test2.txt The complete path of the file name is = /home/welcomeuser/test2.txt File does not exist Now test.txt does exist on the system: $ ls assignment.c output.exe output.exe.stackdump test.txt and yet test.txt is shown as a file not existing. Please help me understand the issue here. Also, please feel free to post any suggestions to improve the code/avoid a bug. Regards, darkie

    Read the article

  • C socket programming: client send() but server select() doesn't see it

    - by Fantastic Fourier
    Hey all, I have a server and a client running on two different machines where the client send()s but the server doesn't seem to receive the message. The server employs select() to monitor sockets for any incoming connections/messages. I can see that when the server accepts a new connection, it updates the fd_set array but always returns 0 despite the client send() messages. The connection is TCP and the machines are separated by like one router so dropping packets are highly unlikely. I have a feeling that it's not select() but perhaps send()/sendto() from client that may be the problem but I'm not sure how to go about localizing the problem area. while(1) { readset = info->read_set; ready = select(info->max_fd+1, &readset, NULL, NULL, &timeout); } above is the server side code where the server has a thread that runs select() indefinitely. rv = connect(sockfd, (struct sockaddr *) &server_address, sizeof(server_address)); printf("rv = %i\n", rv); if (rv < 0) { printf("MAIN: ERROR connect() %i: %s\n", errno, strerror(errno)); exit(1); } else printf("connected\n"); sleep(3); char * somemsg = "is this working yet?\0"; rv = send(sockfd, somemsg, sizeof(somemsg), NULL); if (rv < 0) printf("MAIN: ERROR send() %i: %s\n", errno, strerror(errno)); printf("MAIN: rv is %i\n", rv); rv = sendto(sockfd, somemsg, sizeof(somemsg), NULL, &server_address, sizeof(server_address)); if (rv < 0) printf("MAIN: ERROR sendto() %i: %s\n", errno, strerror(errno)); printf("MAIN: rv is %i\n", rv); and this is the client side where it connects and sends messages and returns connected MAIN: rv is 4 MAIN: rv is 4 any comments or insightful insights are appreciated.

    Read the article

  • Doubt in switch case

    - by user302593
    Hi.. When i executes the following program it get the user input for account details and then print it correctly...But it cannot read the opt value(y/n)..it automatically calls again..i want to exit the program when i press n value... please help to solve this problem.. char opt; do { //Getting user input printf("\n Enter the Account Number:\n "); scanf("%d",&gAccNo_i); printf("\n Enter the Account Holder's Name:\n "); scanf("%s",gCustName_c); printf("\n Enter the Balance Amount:\n "); scanf("%f",&gBlncAmt_f); //Printing the inputted data. printf("\n Account Number : %d",gAccNo_i); printf("\n Customer Name : %s",gCustName_c); printf("\n Balance Amount : %f",gBlncAmt_f); printf("\n Do u want to wish to continue?(y/n)"); scanf("%c",&opt); }while(opt!='n');

    Read the article

  • Strange IP address showing up with OS X ssh

    - by user50799
    I was futzing around with DTrace on Mac OS X and found the following script that prints out information about connections being established: $ cat script.d syscall::connect:entry { printf("execname: %s\n", execname); printf("pid: %d\n", pid); printf("sockfd: %d\n",arg0); socks = (struct sockaddr*)copyin(arg1, arg2); hport = (uint_t)socks->sa_data[0]; lport = (uint_t)socks->sa_data[1]; hport <<= 8; port = hport + lport; printf("Port number: %d\n", port); printf("IP address: %d.%d.%d.%d\n", socks->sa_data[2], socks->sa_data[3], socks->sa_data[4], socks->sa_data[5]); printf("======\n"); } I run it in one window: $ sudo dtrace -s ./script.d Then I ssh to another machine from another window. I get this output from my dtrace window: CPU ID FUNCTION:NAME 0 18696 connect:entry execname: ssh pid: 5446 sockfd: 3 Port number: 22 IP address: 192.168.0.207 ====== 0 18696 connect:entry execname: ssh pid: 5446 sockfd: 5 Port number: 12148 IP address: 109.112.47.108 ====== ^C The first IP address I can explain (192.168.0.207), that's the machine I'm connecting to. But what's with the 109.112.47.108 machine? It doesn't show up in tcpdump nor netstat -an Is there something with my dtrace code or my understanding of how the connect system call works?

    Read the article

  • Choosing a VS project type (C++)

    - by typoknig
    Hi all, I do not use C++ much (I try to stick to the easier stuff like Java and VB.NET), but the lately I have not had a choice. When I am picking a project type in VS for some C++ source I download, what project type should I pick? I had just been sticking with Win32 Console Applications, but I just downloaded some code (below) that will not work right even when it compiles with out errors. I have tried to use a CLR Console Application and an empty project too, and have changed many variables along the way, but I cannot get this code to work. I noticed that this code does not have "int main()" at its beginning, does that have something to do with it? Anyways, here is the code, got it from here: /* Demo of modified Lucas-Kanade optical flow algorithm. See the printf below */ #ifdef _CH_ #pragma package <opencv> #endif #ifndef _EiC #include "cv.h" #include "highgui.h" #include <stdio.h> #include <ctype.h> #endif #include <windows.h> #define FULL_IMAGE_AS_OUTPUT_FILE #define cvMirror cvFlip //IplImage *image = 0, *grey = 0, *prev_grey = 0, *pyramid = 0, *prev_pyramid = 0, *swap_temp; IplImage **buf = 0; IplImage *image1 = 0; IplImage *imageCopy=0; IplImage *image = 0; int win_size = 10; const int MAX_COUNT = 500; CvPoint2D32f* points[2] = {0,0}, *swap_points; char* status = 0; //int count = 0; //int need_to_init = 0; //int night_mode = 0; int flags = 0; //int add_remove_pt = 0; bool bLButtonDown = false; //bool bstopLoop = false; CvPoint pt, pt1,pt2; //IplImage* img1; FILE* FileDest; char* strImageDir = "E:\\Projects\\TSCreator\\Images"; char* strItemName = "b"; int imageCount=0; int bFirstFace = 1; // flag for first face int mode = 1; // Mode 1 - Haar Traing Sample Creation, 2 - HMM sample creation, Mode = 3 - Both Harr and HMM. //int startImgeNo = 1; bool isEqualRation = false; //Weidth to height ratio is equal //Selected Image data IplImage *selectedImage = 0; int selectedX = 0, selectedY = 0, currentImageNo = 0, selectedWidth = 0, selectedHeight= 0; CvRect selectedROI; void saveFroHarrTraining(IplImage *src, int x, int y, int width, int height, int imageCount); void saveForHMMTraining(IplImage *src, CvRect roi,int imageCount); // Code for draw ROI Cropping Image void on_mouse( int event, int x, int y, int flags, void* param ) { char f[200]; CvRect reg; if( !image ) return; if( event == CV_EVENT_LBUTTONDOWN ) { bLButtonDown = true; pt1.x = x; pt1.y = y; } else if ( event == CV_EVENT_MOUSEMOVE ) //Draw the selected area rectangle { pt2.x = x; pt2.y = y; if(bLButtonDown) { if( !image1 ) { /* allocate all the buffers */ image1 = cvCreateImage( cvGetSize(image), 8, 3 ); image1->origin = image->origin; points[0] = (CvPoint2D32f*)cvAlloc(MAX_COUNT*sizeof(points[0][0])); points[1] = (CvPoint2D32f*)cvAlloc(MAX_COUNT*sizeof(points[0][0])); status = (char*)cvAlloc(MAX_COUNT); flags = 0; } cvCopy( image, image1, 0 ); //Equal Weight-Height Ratio if(isEqualRation) { pt2.y = pt1.y + (pt2.x-pt1.x); } //Max Height and Width is the image width and height if(pt2.x>image->width) { pt2.x = image->width; } if(pt2.y>image->height) { pt2.y = image->height; } CvPoint InnerPt1 = pt1; CvPoint InnerPt2 = pt2; if ( InnerPt1.x > InnerPt2.x) { int tempX = InnerPt1.x; InnerPt1.x = InnerPt2.x; InnerPt2.x = tempX; } if ( pt2.y < InnerPt1.y ) { int tempY = InnerPt1.y; InnerPt1.y = InnerPt2.y; InnerPt2.y = tempY; } InnerPt1.y = image->height - InnerPt1.y; InnerPt2.y = image->height - InnerPt2.y; CvFont font; double hScale=1.0; double vScale=1.0; int lineWidth=1; cvInitFont(&font,CV_FONT_HERSHEY_SIMPLEX|CV_FONT_ITALIC, hScale,vScale,0,lineWidth); char size [200]; reg.x = pt1.x; reg.y = image->height - pt2.y; reg.height = abs (pt2.y - pt1.y); reg.width = InnerPt2.x -InnerPt1.x; //print width and heght of the selected reagion sprintf(size, "(%dx%d)",reg.width, reg.height); cvPutText (image1,size,cvPoint(10,10), &font, cvScalar(255,255,0)); cvRectangle(image1, InnerPt1, InnerPt2, CV_RGB(255,0,0), 1); //Mark Selected Reagion selectedImage = image; selectedX = pt1.x; selectedY = pt1.y; selectedWidth = reg.width; selectedHeight = reg.height; selectedROI = reg; //Show the modified image cvShowImage("HMM-Harr Positive Image Creator",image1); } } else if ( event == CV_EVENT_LBUTTONUP ) { bLButtonDown = false; // pt2.x = x; // pt2.y = y; // // if ( pt1.x > pt2.x) // { // int tempX = pt1.x; // pt1.x = pt2.x; // pt2.x = tempX; // } // // if ( pt2.y < pt1.y ) // { // int tempY = pt1.y; // pt1.y = pt2.y; // pt2.y = tempY; // // } // //reg.x = pt1.x; //reg.y = image->height - pt2.y; // //reg.height = abs (pt2.y - pt1.y); ////reg.width = reg.height/3; //reg.width = pt2.x -pt1.x; ////reg.height = (2 * reg.width)/3; #ifdef FULL_IMAGE_AS_OUTPUT_FILE CvRect FullImageRect; FullImageRect.x = 0; FullImageRect.y = 0; FullImageRect.width = image->width; FullImageRect.height = image->height; IplImage *regionFullImage =0; regionFullImage = cvCreateImage(cvSize (FullImageRect.width, FullImageRect.height), image->depth, image->nChannels); image->roi = NULL; //cvSetImageROI (image, FullImageRect); //cvCopy (image, regionFullImage, 0); #else IplImage *region =0; region = cvCreateImage(cvSize (reg.width, reg.height), image1->depth, image1->nChannels); image->roi = NULL; cvSetImageROI (image1, reg); cvCopy (image1, region, 0); #endif //cvNamedWindow("Result", CV_WINDOW_AUTOSIZE); //selectedImage = image; //selectedX = pt1.x; //selectedY = pt1.y; //selectedWidth = reg.width; //selectedHeight = reg.height; ////currentImageNo = startImgeNo; //selectedROI = reg; /*if(mode == 1) { saveFroHarrTraining(image,pt1.x,pt1.y,reg.width,reg.height,startImgeNo); } else if(mode == 2) { saveForHMMTraining(image,reg,startImgeNo); } else if(mode ==3) { saveFroHarrTraining(image,pt1.x,pt1.y,reg.width,reg.height,startImgeNo); saveForHMMTraining(image,reg,startImgeNo); } else { printf("Invalid mode."); } startImgeNo++;*/ } } /* Save popsitive samples for Harr Training. Also add an entry to the PositiveSample.txt with the location of the item of interest. */ void saveFroHarrTraining(IplImage *src, int x, int y, int width, int height, int imageCount) { char f[255] ; sprintf(f,"%s\\%s\\harr_%s%d%d.jpg",strImageDir,strItemName,strItemName,imageCount/10, imageCount%10); cvNamedWindow("Harr", CV_WINDOW_AUTOSIZE); cvShowImage("Harr", src); cvSaveImage(f, src); printf("output%d%d \t ", imageCount/10, imageCount%10); printf("width %d \t", width); printf("height %d \t", height); printf("x1 %d \t", x); printf("y1 %d \t\n", y); char f1[255]; sprintf(f1,"%s\\PositiveSample.txt",strImageDir); FileDest = fopen(f1, "a"); fprintf(FileDest, "%s\\harr_%s%d.jpg 1 %d %d %d %d \n",strItemName,strItemName, imageCount, x, y, width, height); fclose(FileDest); } /* Create Sample Images for HMM recognition algorythm trai ning. */ void saveForHMMTraining(IplImage *src, CvRect roi,int imageCount) { char f[255] ; printf("x=%d, y=%d, w= %d, h= %d\n",roi.x,roi.y,roi.width,roi.height); //Create the file name sprintf(f,"%s\\%s\\hmm_%s%d.pgm",strImageDir,strItemName,strItemName, imageCount); //Create storage for grayscale image IplImage* gray = cvCreateImage(cvSize(roi.width,roi.height), 8, 1); //Create storage for croped reagon IplImage* regionFullImage = cvCreateImage(cvSize(roi.width,roi.height),8,3); //Croped marked region cvSetImageROI(src,roi); cvCopy(src,regionFullImage); cvResetImageROI(src); //Flip croped image - otherwise it will saved upside down cvConvertImage(regionFullImage, regionFullImage, CV_CVTIMG_FLIP); //Convert croped image to gray scale cvCvtColor(regionFullImage,gray, CV_BGR2GRAY); //Show final grayscale image cvNamedWindow("HMM", CV_WINDOW_AUTOSIZE); cvShowImage("HMM", gray); //Save final grayscale image cvSaveImage(f, gray); } int maina( int argc, char** argv ) { CvCapture* capture = 0; //if( argc == 1 || (argc == 2 && strlen(argv[1]) == 1 && isdigit(argv[1][0]))) // capture = cvCaptureFromCAM( argc == 2 ? argv[1][0] - '0' : 0 ); //else if( argc == 2 ) // capture = cvCaptureFromAVI( argv[1] ); char* video; if(argc ==7) { mode = atoi(argv[1]); strImageDir = argv[2]; strItemName = argv[3]; video = argv[4]; currentImageNo = atoi(argv[5]); int a = atoi(argv[6]); if(a==1) { isEqualRation = true; } else { isEqualRation = false; } } else { printf("\nUsage: TSCreator.exe <Mode> <Sample Image Save Path> <Sample Image Save Directory> <Video File Location> <Start Image No> <Is Equal Ratio>\n"); printf("Mode = 1 - Haar Traing Sample Creation. \nMode = 2 - HMM sample creation.\nMode = 3 - Both Harr and HMM\n"); printf("Is Equal Ratio = 0 or 1. 1 - Equal weidth and height, 0 - custom."); printf("Note: You have to create the image save directory in correct path first.\n"); printf("Eg: TSCreator.exe 1 E:\Projects\TSCreator\Images A 11.avi 1 1\n\n"); return 0; } capture = cvCaptureFromAVI(video); if( !capture ) { fprintf(stderr,"Could not initialize capturing...\n"); return -1; } cvNamedWindow("HMM-Harr Positive Image Creator", CV_WINDOW_AUTOSIZE); cvSetMouseCallback("HMM-Harr Positive Image Creator", on_mouse, 0); //cvShowImage("Test", image1); for(;;) { IplImage* frame = 0; int i, k, c; frame = cvQueryFrame( capture ); if( !frame ) break; if( !image ) { /* allocate all the buffers */ image = cvCreateImage( cvGetSize(frame), 8, 3 ); image->origin = frame->origin; //grey = cvCreateImage( cvGetSize(frame), 8, 1 ); //prev_grey = cvCreateImage( cvGetSize(frame), 8, 1 ); //pyramid = cvCreateImage( cvGetSize(frame), 8, 1 ); // prev_pyramid = cvCreateImage( cvGetSize(frame), 8, 1 ); points[0] = (CvPoint2D32f*)cvAlloc(MAX_COUNT*sizeof(points[0][0])); points[1] = (CvPoint2D32f*)cvAlloc(MAX_COUNT*sizeof(points[0][0])); status = (char*)cvAlloc(MAX_COUNT); flags = 0; } cvCopy( frame, image, 0 ); // cvCvtColor( image, grey, CV_BGR2GRAY ); cvShowImage("HMM-Harr Positive Image Creator", image); cvSetMouseCallback("HMM-Harr Positive Image Creator", on_mouse, 0); c = cvWaitKey(0); if((char)c == 's') { //Save selected reagion as training data if(selectedImage) { printf("Selected Reagion Saved\n"); if(mode == 1) { saveFroHarrTraining(selectedImage,selectedX,selectedY,selectedWidth,selectedHeight,currentImageNo); } else if(mode == 2) { saveForHMMTraining(selectedImage,selectedROI,currentImageNo); } else if(mode ==3) { saveFroHarrTraining(selectedImage,selectedX,selectedY,selectedWidth,selectedHeight,currentImageNo); saveForHMMTraining(selectedImage,selectedROI,currentImageNo); } else { printf("Invalid mode."); } currentImageNo++; } } } cvReleaseCapture( &capture ); //cvDestroyWindow("HMM-Harr Positive Image Creator"); cvDestroyAllWindows(); return 0; } #ifdef _EiC main(1,"lkdemo.c"); #endif If I put... #include "stdafx.h" int _tmain(int argc, _TCHAR* argv[]) { return 0; } ... before the previous code (and link it to the correct OpenCV .lib files) it compiles without errors, but does nothing at the command line. How do I make it work?

    Read the article

  • CreateProcessAsUser error 1314

    - by kampi
    Hi! I want create a process under another user. So I use LogonUser and CreateProcessAsUser. But my problem is, that CreatePtocessAsUser always returns the errorcode 1314, which means "A required privilige is not held by the client". So my question is, what I am doing wrong? Or how can i give the priviliges to the handle? (I think the handle should have the privileges, or I am wrong?) Sorry for my english mistakes, but my english knowledge isn't the best :) Plesase help if anyone knows how to correct my application. This a part of my code. STARTUPINFO StartInfo; PROCESS_INFORMATION ProcInfo; TOKEN_PRIVILEGES tp; memset(&ProcInfo, 0, sizeof(ProcInfo)); memset(&StartInfo, 0 , sizeof(StartInfo)); StartInfo.cb = sizeof(StartInfo); HANDLE handle = NULL; if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &handle)) printf("\nOpenProcessError"); if (!LookupPrivilegeValue(NULL,SE_TCB_NAME, //SE_TCB_NAME, &tp.Privileges[0].Luid)) { printf("\nLookupPriv error"); } tp.PrivilegeCount = 1; tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;//SE_PRIVILEGE_ENABLED; if (!AdjustTokenPrivileges(handle, FALSE, &tp, 0, NULL, 0)) { printf("\nAdjustToken error"); } i = LogonUser(user, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, &handle); printf("\nLogonUser return : %d",i); i = GetLastError(); printf("\nLogonUser getlast : %d",i); if (! ImpersonateLoggedOnUser(handle) ) printf("\nImpLoggedOnUser!"); i = CreateProcessAsUser(handle, "c:\\windows\\system32\\notepad.exe",NULL, NULL, NULL, true, CREATE_UNICODE_ENVIRONMENT |NORMAL_PRIORITY_CLASS | CREATE_NEW_CONSOLE, NULL, NULL, &StartInfo, &ProcInfo); printf("\nCreateProcessAsUser return : %d",i); i = GetLastError(); printf("\nCreateProcessAsUser getlast : %d",i); CloseHandle(handle); CloseHandle(ProcInfo.hProcess); CloseHandle(ProcInfo.hThread); Thanks in advance!

    Read the article

  • conversion of DNA to Protein - c structure issue

    - by sam
    I am working on conversion of DNA sequence to Protein sequence. I had completed all program only one error I found there is of structure. dna_codon is a structure and I am iterating over it.In first iteration it shows proper values of structure but from next iteration, it dont show the proper value stored in structure. Its a small error so do not think that I havnt done anything and downvote. I am stucked here because I am new in c for structures. CODE : #include <stdio.h> #include<string.h> void main() { int i, len; char short_codons[20]; char short_slc[1000]; char sequence[1000]; struct codons { char amino_acid[20], slc[20], dna_codon[40]; }; struct codons c1 [20]= { {"Isoleucine", "I", "ATT, ATC, ATA"}, {"Leucine", "L", "CTT, CTC, CTA, CTG, TTA, TTG"}, {"Valine", "V", "GTT, GTC, GTA, GTG"}, {"Phenylalanine", "F", "TTT, TTC"}, {"Methionine", "M", "ATG"}, {"Cysteine", "C", "TGT, TGC"}, {"Alanine", "A", "GCT, GCC, GCA, GCG"}, {"Proline", "P", "CCT, CCC, CCA,CCG "}, {"Threonine", "T", "ACT, ACC, ACA, ACG"}, {"Serine", "S", "TCT, TCC, TCA, TCG, AGT, AGC"}, {"Tyrosine", "Y", "TAT, TAC"}, {"Tryptophan", "W", "TGG"}, {"Glutamine", "Q", "CAA, CAG"}, {"Aspargine","N" "AAT, AAC"}, {"Histidine", "H", "CAT, CAC"}, {"Glutamic acid", "E", "GAA, GAG"}, {"Aspartic acid", "D", "GAT, GAC"}, {"Lysine", "K", "AAA, AAG"}, {"Arginine", "R", "CGT, CGC, CGA, CGG, AGA, AGG"}, {"Stop codons", "Stop", "AA, TAG, TGA"} }; int count = 0; printf("Enter the sequence: "); gets(sequence); char *input_string = sequence; char *tmp_str = input_string; int k; char *pch; while (*input_string != '\0') { char string_3l[4] = {'\0'}; strncpy(string_3l, input_string, 3); printf("\n-----------%s & %s----------", string_3l, tmp_str ); for(k=0;k<20;k++) { //printf("@REAL - %s", c1[0].dna_codon); printf("@ %s", c1[k].dna_codon); int x; x = c1[k].dna_codon; pch = strtok(x, ","); while (pch != NULL) { printf("\n%d : %s with %s", k, string_3l, pch); count=strcmp(string_3l, pch); if(count==0) { strcat(short_slc, c1[k].slc); printf("\n==>%s", short_slc); } pch = strtok (NULL, " ,.-"); } } input_string = input_string+3; } printf("\nProtien sequence is : %s\n", short_slc); } INPUT : TAGTAG OUTPUT : If you see output of printf("\n-----------%s & %s----------", string_3l, tmp_str ); in both iterations, we found that values defined in structure are reduced. I want to know why structure reduces it or its my mistake? because I am stucked here

    Read the article

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