Similar to echoserver, but this one handles multiple clients by forking the process.

This is a simple echo server that I've written while learning sockets programming.
Compile the server and run it. You can connect to it using telnet like this:

telnet localhost 1337

Disconnect the client by typing "/quit" without quotes.

You are doing strange chain of action from init return through each methods return, which is very bizare for me. why not just do the sequence of calls in main program?

This is the same program without the class.

#!/usr/bin/env python

import random 
import cPickle

#path of the dump file
filepath = '/home/deewakar/python/hangman/wordsdict.pkl'

#inset some random hints for the player
def insert_hints(length, keylist, secret_word):
    randint = random.randint
    #if the word contains 7 or more letters, you'll get 3 hints
    if length >= 7: hints = 3
    else: hints = 1
    for x in xrange(hints):
        a = randint(1, length - 1)
        keylist[a-1] = secret_word[a-1]

    return hints, keylist

def test_input(guess, secret_word, keylist, mistakes, used_keys ):
    #if the guessed letter matches
    if guess in secret_word:
        indexes = [i for i, item in enumerate(secret_word) if item == guess]
        for index in indexes:
            keylist[index] = guess
            used_keys.append(guess)

    #if the guessed letter didn't match
    else:
        used_keys.append(guess)
        mistakes += 1
    print "used letters ",set(used_keys),'\n'

    return keylist, mistakes

#load the pickled word dictionary
def load_dict():
    try :
        dumpfile = open(filepath, "r")
    except IOError:
        print "Couldn't open the dictionary file 'wordsdict.pkl'"
        quit()

    dictionary = cPickle.load(dumpfile)
    words = dictionary.keys()
    return dumpfile, dictionary, words

#randomly choose a word for the challenge
def prepare_word(words):
    secret_word = random.choice(words)
    #don't count trailing spaces
    length = len(secret_word.rstrip())
    keylist = ['_' for x in xrange(length)]
    hints, keylist = insert_hints(length, keylist, secret_word)
    return secret_word, keylist, hints

#display the challenge
def ask(keylist, secret_word, dictionary):
    print ' '.join(keylist), ":", dictionary[secret_word] 

#take input from the player
def input_loop(secret_word, mistakes, ...

Without the picled dictionary I can not run the program so that is how far I can comment now (zipped and attached File would help).

That was a serious mistake on my part.

This is a simple hangman game that I wrote using my beginner python skills. Though this game is playable, there must be lots of things I must've been doing wrong or the methods I'm using here may be not so pythonic. So I want some suggestions on how to improve this game.
The 'wordsdict.pkl' file contains a pickled dict with words as keys and meanings as their values.

e.g. {'word': 'its meaning'}

And here's how you use strtok (you know... for future references).
[CODE]#include <stdio.h>

include <string.h>

int main(void){
char line[20] = "Process0 12 1"; // suppose this is the first line read by fgets
char delim=" ";
char
result = NULL;
result=strtok(line,delim);
if(result != NULL)
printf("process:%s\n",result);//store process in an array
result=strtok(NULL,delim);//first argument NULL except first call to strtok
printf("quanta:%s\n",result);//store quanta in another array,you can use atoi to change
//quanta to integer type

result=strtok(NULL,delim);//first argument NULL except first call to strtok
printf("priority:%s\n",result);//store priority in another array

return 0;
}
[/CODE]

[QUOTE=Gribouillis;1728291]If you want to use s, write
[code=python]
s = [x for x in s if x!= 'r']

or

s = list(x for x in s if x!= 'r')
[/code]
there is a small difference with s[:] because this code create a new list for the name s. With s[:] it only fills the same list object with new elements. For example try this
[code=python]
a = ['b','a','r','r','i','s','t','e','r']
b = a
c = a
b = [x for x in b if x != 'r']
print a
c[:] = [x for x in c if x != 'r']
print a

print id(a), id(b), id(c)
[/code]
If you want to learn more about generator expressions, read about generators and the iterator protocol in the python documentation, but you can postpone this a little if you are new to python.[/QUOTE]
Thanks for the quick reply, I really appreciate it.

[QUOTE]Conclusion: don't modify the size of a list while iterating on this list, use a copy if necessary.[/QUOTE]yes using a copy solves the problem thank you but I have couple of questions about the second method.
If I understood correctly [CODE]s[:] = (x for x in s if x != 'r')[/CODE]means reconstruct the list s from the components of the list s itself (interating through them ) but skip the element 'r' right?
Also why can't we use just s instead of s[:].
[CODE]s=(x for x in s if x!= 'r')

s
<generator object <genexpr> at 0xa80ff54>
[/CODE]

If there's a list like below
[CODE]s=['b','a','r','r','i','s','t','e','r'][/CODE]
and if I tried to remove every 'r' from the list like this
[CODE]>>> for x in s:
if(x=='r'):
s.remove(x)[/CODE]
it gives the following result.
[CODE]>>> s
['b', 'a', 'i', 's', 't', 'e', 'r'][/CODE]
Why isn't the last 'r' removed from the list.

[QUOTE]The program runs and compiles. When I enter the two words, it gives me a bunch of random stuff when printing[/QUOTE]That's because scanf is not used like this
[CODE]scanf(x1,x2,MAXFORTHIS,stdin);[/CODE]
[URL="

[QUOTE=MrNo;1704619][CODE]#include <stdio.h>

include <string.h>

int main()
{
int count = 0;
char doc;
FILE
inp;

printf("Enter the file name: ");
scanf("%s", doc);

inp=fopen(doc, "r");

while((doc = fgetc(doc)) != EOF)
{
    if (doc == ' ')
        count++;
}

fclose(doc);

printf("%s contains %d words\n",doc,count);

return 0;

}
[/CODE]

So basically I'm a little bit confused. I believe the logic of my program is correct; file pointer is declared, and I do have a character to store my array, it reads the file, and counts all the words pending a space in front/between/etc. Basically the program should ask the used the used to input the name of the file they're scanning. The file opens and goes through the program and outputs a line that tells the user the # of words in the file that was inputted.

My problem has been compiling it.

I'm getting this:

wordcount.c: In function ‘main’:
wordcount.c:13:5: warning: passing argument 1 of ‘fopen’ makes pointer from integer without a cast [enabled by default]
/usr/include/stdio.h:271:14: note: expected ‘const char restrict’ but argument is of type ‘char’
wordcount.c:15:5: warning: passing argument 1 of ‘fgetc’ makes pointer from integer without a cast [enabled by default]
/usr/include/stdio.h:535:12: note: expected ‘struct FILE
’ but argument is of type ‘char’
wordcount.c:21:5: warning: passing argument 1 of ‘fclose’ makes pointer from integer without a cast [enabled by default]
/usr/include/stdio.h:236:12: note: expected ‘struct FILE ’ but argument is of type ‘char’[/QUOTE]
The root of all problems in your program is this line[CODE] char
doc;[/CODE]
[B]Walt[/B] is ...

[QUOTE]anyone can tell me what this line does?[/QUOTE]clearly, it's returning the uppercase of the character given to the function.The first return statement only works if the condition cl>='a'(i.e.97 in decimal) AND cl<='z'(i.e 122 in decimal).If it does so then the second return statement is not executed, but if it does not then the second return statement is executed and returns whatever character was given to the function.So if you give any upper case characters or symbols then they will be returned unchanged.But if you give any lower case characters, let's suppose 'b'
then this line [CODE]return ('A' + c1 - 'a'); [/CODE]looks like this
[CODE]return (65+98-97);
//or
return(0x41+0x62-0x61);[/CODE]
this [URL="

[QUOTE]The case choices does not run after the input of the integers 0 or 1.[/QUOTE]
You're missing '&'before 'choice' in your 'scanf' statement .
[CODE]scanf("%d",&choice);[/CODE]
and another(important!) thing,look at this
[CODE]int number, integer,choice;
int ArrayN[20];

for(i=0;i<20;i++)
{
printf("Enter 20 Integers\n");
scanf("%d", &number);
printf("ArrayN[%d]=%d\n",i,number);//well, that's stupid!
}[/CODE]
You have to assign values to the array
[CODE]scanf("%d",&Array[i]);//like this
// ..or like this
Array[i]=number[/CODE]
Good Luck! with the rest of the code for searching and all that.

[QUOTE]Can you tell me why use size_t and not int for orig_len and rep_len?[/QUOTE]
Using size_t instead of just plain int or unsigned int makes your code more portable since the size of int types vary across platforms.
Also the above standard functions expect their third argument to be of size_t type.
[CODE]char stpncpy(char restrict s1, const char restrict s2, size_t n);
int strncmp(const char
s1, const char *s2, size_t n);[/CODE]

First of all, use code tags whenever you post any code.See that CODE thingy, click that and paste your well formatted code in between.

There's no use of this #include<conio.h>in your code and why this char studentanswer[30][30+1]; why not just declare it like this

char studentanswer[30][31];

Since you're opening the file 'examdat.txt' for reading, make sure that it is in the same directory as your program is or use the full path.

int status = fgetAnswers(&numberofstudent, ans, inp); You are passing arguments without assigning any values to them.

[QUOTE][CODE]fflush(stdin);[/CODE][/QUOTE]Didn't you read my previous post ? How many times do I have to tell you that you should not use fflush() with stdin.In the c standards, it is only defined to use with the output streams.
[QUOTE]I have another problem with the following program I have tried which tests if sides form a right angled triangle or not. [/QUOTE]First of all, if you have another problem and the current problem is resolved then you should mark this thread URL="

[QUOTE]oh I get the point then. So, in other words it fflush can be used instead of always creating a double getchar() in the end of each prog. [/QUOTE]
No, you don't. I've already said that fflush() should not be used with input streams, it is made to use with output streams only.People usually use getchar() at the end to consume the data that might be left in the input buffer. That could be replaced with this[CODE]while (((ch = getchar()) != '\n') && (ch != EOF))//has no body ;[/CODE]But still at least a character is left in the buffer.

[QUOTE]I see where Diwakar has made several test submissions. Any new idea's you're trying, Diwakar? [/QUOTE]No, I just couldn't believe it was showing "time limit exceeded " for the code I submitted.But yes,I tweaked it a little bit,didn't help much.I replaced the multiplications with bit shifts, did a little work to reduce the redundancy during marking off composites and printed the primes at a tab distance rather than one at each line.
[CODE]void sive(int size) {
int i,j,k,l;
char sieve = calloc(size, 1);
for (i=2,k=1,l=2; i
i <= size; i=(k<<1)+1,k++,l=i<<1) {
if (!sieve[i]) {
for(j = i*i; j < size; j+=l) {sieve[j]=1; }
}
}
for (i=2,j=0; i<size; i++) {
if (!sieve[i]) { sieve[j++]=i; }
}

free(sieve);
}[/CODE]But I'm not out of ideas yet.You may have seen guys mentioning Segmented sieve in the forum there.I haven't understood the concept thoroughly, though I have read about it couple of times but you know all those mathematical symbols drive me nuts.I remember someone wrote on one of the other forums that you first produce a list of primes within a small range and use those primes intelligently to produce other larger primes.Hmm, what does that mean?
And also about the Sieve of Eratosthenes, We're now using a whole integer (of the 'sieve' array) to represent a bit that marks composite, instead can we use just a single bit to represent that.
Once, I was very fascinated by the [URL="

[QUOTE]Am i correct if I understand I/O buffer
as the temporary memory stored/inputted in the variables? [/QUOTE]
see [URL="

[QUOTE]This is a piece of code from some book.[/QUOTE]Is that [URL="

[ICODE]'fflush(stdout)'[/ICODE] forces the data (if any)in the I/O buffer to be written to the screen .Including a '\n' character(if suitable) in the [ICODE]'printf'[/ICODE] itself also does the same thing.[CODE]printf("incorrect value\n");[/CODE]Remember that [ICODE]fflush[/ICODE] is only used with output streams.Calling [ICODE]fflush[/ICODE] with [ICODE]NULL [/ICODE]argument flushes all the opened streams.

[QUOTE]Every call to printf() incurs a small expense, because printf() can decode a boatload of formats, etc.[/QUOTE]Yeah,I couldn't agree with you more.[QUOTE]Second topic:

Just an idea, completely untested.

What if we took in ALL the queries from the tester, into an array, and quickly sorted them (time: maybe 0.2-1.0 seconds). Then we start the prime finding loop, and as soon as we find one, (in Sieve loop), that matches the next request, we print it solo, just that one number and newline.***[/QUOTE]
Now we're talking! That's a brilliant idea. I wondered, why would you need the number of queries in the input at first, since you're given all the numbers for which you have to find the primes for.Now I know, you're supposed to use that in your code, it's like a hint right? [QUOTE]Maybe print out 512 numbers with each call to printf()?[/QUOTE]Hmm, interesting!
[QUOTE]@Diwakar, I inserted part of your sieve loop (the nested for loop at the bottom of it), and found I wasn't getting all the prime numbers - lots of them, but not all. You may want to check it (but it could be just the interaction between my loop logic, and yours, in the top half of the larger loop). [/QUOTE]It may be possible since i haven't tested it for all five million! But until now it has been giving correct answers.I'll check that and inform you later.
By the way, your quicksort looks fast, I'll give that a try too.

[QUOTE]I guess it just adds ret statement and pops whatever is in the eax register. [/QUOTE]Sorry, there was a typo in the above line. I mean,pops whatever is in the [B]stack to the[/B] eax register(i.e.last pushed value).

I guess it just adds[ICODE] ret[/ICODE] statement and pops whatever is in the [ICODE]eax[/ICODE] register.

[QUOTE]Then why it is not giving any warning with [CODE]gcc -o test_cal test_cal.c[/CODE][/QUOTE]Well that's not mine (or gcc's) problem, it's your job to follow good programming practices.

The answer is in your error message
[CODE]cc1: warnings being treated as errors
test_cal.c: In function ‘calsum’:
test_cal.c:20: error: control reaches end of non-void function[/CODE]Since function calsum is non-void(means returns something), so you should add a return statement.
[CODE]return d;[/CODE]

It's a very , very messy code.Here are few things that I saw, that could be potentially causing the problem.
1.You have named many things "Information".First the struct for book data[CODE]/Structure for book information /
typedef struct Information
{
char subject [MAXIMUM_TITLE];
char author [MAXIMUM_AUTHOR];
int edition;
int year;
float price;
} Book;[/CODE] and then this[CODE]static Book Information;[/CODE]I don't know what's that for.And finally a pointer to Book to use with malloc.[CODE]Information = (Book ) malloc(book_number sizeof(Information)); [/CODE]
2.you are allocating space dynamically for a pointer variable.[CODE]Information = (Book
) malloc(book_number sizeof(Information)); [/CODE]should be replaced with this:[CODE]Information = (Book ) malloc(book_number * sizeof(Book)); [/CODE]I guess, you have to replace all the 'Information's with 'Book's in the code that follows.
3.At least the code should be syntactically correct, then it will be easy to find the bugs that aren't caught by the compiler. for e.g. see this declaration[CODE]Book getBookInformation(int inventory);//if returns nothing, return 'void'[/CODE]But see the definition of the function 'getBookInformation', it returns nothing.
I hope above things will help you fix your code,and in addition don't ignore compiler warning messages, they could be very helpful while debugging your code.
P.S. may be compiling them as a single source at first, may be less tiresome and less time consuming and then you can distribute them in multiple files afterwards.

[QUOTE=Adak]CSE, do you submit code or is it an executable file that gets tested?[/QUOTE]No,you just have to submit your code.
I compiled and ran your both programs and it took about 16 seconds for the version with direct numbers and about 13 seconds for the version with char array( intel core 2 duo, 2.22 GHz).The chars version was not accepted by my ide, so I had to build it in the command line.
Then I submitted the program I was working on( after editing a little bit),
[CODE]#include <stdio.h>

include <stdlib.h>

define SIZE 86028122

int arr[5000000]={0};

void sieve(int size) {
int i,j,k;
char sieve = calloc(size, 1);
for (i=2,k=1; i
i <= size; i=k2+1,k++) {
if (!sieve[i]) {
for(j = i
i; j < size; j=j+i) {sieve[j]=1; }
}
}
for (i=2,j=0; i<size; i++) {
if (!sieve[i]) { arr[j++]=i; }
}

   free(sieve);

}
int main(void) {

sieve(SIZE);

char number[15],*file=NULL;
int n,flag=0;
while((file = fgets(number,sizeof(number),stdin)) !=NULL && flag!=1){
    n=atoi(number);
    if(!flag){
        flag=n;continue;}

     printf("%d\n",arr[n-1]);
     flag--;

}

   return 0;

}
[/CODE]I submitted it because, it was taking about 4.79 seconds on my PC and only 2.26 seconds on [URL="www.ideone.com"]ideone[/URL] which the site recommends to test your code.But it shows time limit exceeded whenever I submit it to [URL="

[QUOTE]The code compiles[/QUOTE]That totally amazes me.[QUOTE] but when I run the program it stops responding once it enters the while loop [/QUOTE]So there's a strong possibility that the problem lies on your while loop statement.
[QUOTE][CODE] while (fgetc(inFile) != EOF) != NULL) {[/CODE][/QUOTE]'fgetc' returns EOF when read error occurs or the EOF is reached.So this is enough[CODE]while(fgetc(inFile)!=EOF)[/CODE]But wait a minute, the file pointer you declared has a name 'inputFile'.Also that you're using fgetc just to detect the EOF seems a bad idea to me.Instead just read the whole line at a time and extract the information you need one by one.

Alright guys, I registered in to that site and submitted the following code, but it didn't accept the code as a valid answer.The time taken by the code I submitted was 1.23 as shown in the site.
[CODE]#include <stdio.h>

include <stdlib.h>

define SIZE 50000000

int arr[SIZE]={0};

void sieve(int size) {
int i,j,k;
char sieve = calloc(size, 1);
for (i=2,k=1; i
i <= size; i=k2+1,k++) {
if (!sieve[i]) {
for(j = i
i; j < size; j=j+i) {sieve[j]=1; }
}
}
for (i=2,j=0,k=1; i<size; i++) {

   if (!sieve[i]) { arr[j++]=i; }
   }
   free(sieve);

}
int main() {

sieve(SIZE);

char number[15],*file;
int n,flag=0;
while((file = fgets(number,sizeof(number),stdin)) !=NULL && flag!=1){
    n=atoi(number);
    if(!flag){
        flag=n;continue;}

     printf("%d\n",arr[n-1]);
     flag--;

}

   return 0;

}
[/CODE] That means my interpretation of the challenge was wrong.But what else could it be?