NODE *llput(NODE *args) {
    NODE *lst, *arg, *val = UNBOUND, *lastnode = NIL, *tnode = NIL;

    if (is_word(cadr(args)) && is_word(car(args)) &&
	    getstrlen(cnv_node_to_strnode(car(args))) == 1)
	return lword(cons(cadr(args), cons(car(args), NIL)));

    arg = car(args);
    lst = list_arg(cdr(args));
    if (NOT_THROWING) {
	val = NIL;
	while (lst != NIL) {
	    tnode = cons(car(lst), NIL);
	    if (val == NIL) {
		val = tnode;
	    } else {
		setcdr(lastnode, tnode);
	    }
	    lastnode = tnode;
	    lst = cdr(lst);
	    if (check_throwing) break;
	}
	if (val == NIL)
	    val = cons(arg, NIL);
	else
	    setcdr(lastnode, cons(arg, NIL));
    }
    return(val);
}
Exemple #2
0
static int match_wchange(struct ExecCtx *ctx, const struct Op *op, const char *str, struct GMatch *gm)
{
	bool prevw = (str == ctx->str_start) ? false : is_word(str[-1]);
	bool curw = is_word(str[0]);
	bool ischange = prevw ^ curw;

	if ((op->type == OP_WCHANGE) ? ischange : !ischange)
		return do_match(ctx, op->next, str, gm);
	return REG_NOMATCH;
}
NODE *lfput(NODE *args) {
    NODE *lst, *arg;

    if (is_word(cadr(args)) && is_word(car(args)) &&
	    getstrlen(cnv_node_to_strnode(car(args))) == 1)
	return lword(args);

    arg = car(args);
    lst = list_arg(cdr(args));
    if (NOT_THROWING)
	return cons(arg,lst);
    else
	return UNBOUND;
}
Exemple #4
0
void retrieve_words(const jsa_counterexamplet &ce, __CPROVER_jsa_word_t *words)
{
  assert(std::is_sorted(ce.begin(), ce.end(), compare_assignment));
  size_t index=0;
  for (const jsa_counterexamplet::value_type &assignment : ce)
    if (is_word(assignment)) words[index++]=to_integer(assignment.second);
}
Exemple #5
0
void				loop(t_list **list, t_token **cur_tok, char *input)
{
	int			index;
	char		cur;
	char		prev;

	ft_init(&index, &cur, &prev, input);
	while (cur)
	{
		if ((*cur_tok)->token && is_operator(prev) && !is_newline(cur))
			rule_1(*cur_tok, list, input, &index);
		else if (is_quoting(cur))
			handle_quoting(*cur_tok, list, input, &index);
		else if (is_start_of_expansion(cur) || is_operator(cur))
			rule_34(*cur_tok, list, input, &index);
		else if (is_newline(cur) || is_whitespace(cur))
			rule_56(*cur_tok, list, input, &index);
		else if ((*cur_tok)->token && is_word(prev))
			build_token(*cur_tok, cur);
		else if (cur == '#')
			discard_comment(input, &index);
		else
			build_token(*cur_tok, cur);
		prev = cur;
		cur = input[++index];
	}
}
Exemple #6
0
int main()
{
	int i, j, k, n;
	char *p, *q;

	read();

	wordlen = (int *)malloc(nr_words * sizeof(int));
	for (i = 0; i < nr_words; i++)
		wordlen[i] = strlen(words[i]);

	wordmrk = (unsigned char *)malloc(i = ((nr_words + 7) / 8));
	memset(wordmrk, '\0', i);

	for (i = 0; i < nr_words; i++) {
		n = wordlen[i];
		for (j = i + 1; j < nr_words && wordlen[j] > n; j++) {
			p = words[i];
			q = words[j];
			for (k = 0; k < n && *p++ == *q++; k++);

			if (k == n && is_word(q))
				MARKWORD(j);
			else if (k < n)
				break;
		}
	}

	for (i = 0; i < nr_words; i++)
		if (ISMARKED(i))
			printf("%s\n", words[i]);

	fflush(stdout);
	return 0;
}
Exemple #7
0
void		lexer(char *line, t_lex *lst)
{
	int		param[3];

	param[2] = 0;
	while (*line)
	{
		no_space(&line);
		if (!*line)
			break ;
		if ((is_token(line, param)))
		{
			add_token(&lst, param);
			line = line + param[1];
		}
		else if ((is_word(line, param)))
		{
			add_word(&lst, param, line);
			line = line + param[1];
		}
		else
		{
			add_word(&lst, NULL, line);
			line++;
		}
	}
	parser(&lst);
}
Exemple #8
0
FULL_CHAR *SymName(OBJECT s)
{ OBJECT p;
  if( s == nilobj )  return AsciiToFull("<nilobj>");
  Parent(p, Up(s));
  assert( is_word(type(p)), "SymName: !is_word(type(p))!" );
  return string(p);
} /* end SymName */
Exemple #9
0
/* Unbox a word. */
Word word_unbox(Boxed reference) {
  assert(reference);
  assert(is_word(reference));
  Word value = word_value(reference);
  boxed_free(reference);
  return value;
}
Exemple #10
0
void kitten_isw(Boxed stack, Boxed definitions) {
  assert(stack);
  assert(is_quotation(stack));
  Boxed a = pop(stack);
  push(stack, integer_new(is_word(a)));
  boxed_free(a);
}
void log_word(std::map<std::string, word_info> &map, std::string word, int line, int p) {
    if(!is_word(word)) return;
    word_info info;
    if(map.count(word) > 0) info = map[word];
    word_pos pos(line, p);
    info.pos.push_back(pos);
    map[word] = info;
}
Exemple #12
0
static OBJECT ReadMacro(OBJECT *token, OBJECT curr_encl, OBJECT encl)
{ OBJECT t, res;

  /* find macro name and insert into symbol table */
  SuppressScope();
  Dispose(*token);  t = LexGetToken();
  if( !is_word(type(t)) )
  { Error(5, 24, "%s ignored (name is missing)", WARN, &fpos(t), KW_MACRO);
    debug1(ANY, D, "offending type is %s", Image(type(t)));
    UnSuppressScope();
    *token = t;
    return nilobj;
  }
  res = InsertSym(string(t), MACRO, &fpos(t), 0, FALSE,TRUE,0,curr_encl,nilobj);
  if( curr_encl != encl )  visible(res) = TRUE;
  UnSuppressScope();

  /* find alternative names for this symbol */
  Dispose(t);  t = LexGetToken();
  while( is_word(type(t)) )
  {
    InsertAlternativeName(string(t), res, &fpos(t));
    Dispose(t);  t = LexGetToken();
  }

  /* find opening left brace */
  if( type(t) != LBR )
  { Error(5, 25, "%s ignored (opening %s is missing)",
      WARN, &fpos(t), KW_MACRO, KW_LBR);
    *token = t;
    return nilobj;
  }
  
  /* read macro body */
  ReadTokenList(t, res);
  Dispose(t);

  /* clean up (kill final RBR, dispose macro name) and exit */
  t = pred(sym_body(res), PARENT);
  sym_body(res) = Delete(t, PARENT);
  Dispose(t);
  recursive(res) = FALSE;
  *token = nilobj;
  return res;
} /* end ReadMacro */
Exemple #13
0
CFSArray<CFSWString> tokens2words(CFSArray<CFSWString> a) {
    CFSArray<CFSWString> temp_array;
    CFSArray<CFSWString> res;
    for (INTPTR i = 0; i < a.GetSize(); i++) {
        CFSWString s = a[i];

        if (is_abbreviation(s, temp_array) > 0) {
            for (INTPTR i = 0; i < temp_array.GetSize(); i++)
                res.AddItem(temp_array[i]);
        } else
            if (is_word(s))
            res.AddItem(s);
        else {
            CFSArray<CFSWString> carray;
            make_ctype_array(s, carray);
            for (INTPTR ictype = 0; ictype < carray.GetSize(); ictype++) {
                INTPTR c_type = ctype(carray[ictype].GetAt(0));
                if (c_type == 1) { //Tähed
                    if (is_word(carray[ictype])) res.AddItem(carray[ictype]);
                    else { // kui on sodipodi
                        explode(carray[ictype], L"", temp_array);
                        for (INTPTR i_temp = 0; i_temp < temp_array.GetSize(); i_temp++)
                            res.AddItem(replace_schar(temp_array[i_temp]));
                    }
                } else
                    if (c_type == 2) { //Sümbolid
                    explode(carray[ictype], L"", temp_array);
                    for (INTPTR i_temp = 0; i_temp < temp_array.GetSize(); i_temp++)
                        res.AddItem(replace_schar(temp_array[i_temp]));
                } else
                    if (c_type == 3) { //Numbrid
                    CFSWString nr = int_to_words(carray[ictype]);
                    explode(nr, sp, temp_array);
                    for (INTPTR i_temp = 0; i_temp < temp_array.GetSize(); i_temp++)
                        if (temp_array[i_temp].GetLength() > 0)
                            res.AddItem(temp_array[i_temp]);
                }
            }
        }
    } // iga token

    return res;
}
Exemple #14
0
OBJECT ParameterCheck(OBJECT x, OBJECT env)
{ OBJECT link, y, res, prnt_env, par, prnt;
  debug2(DCE, DD, "ParameterCheck(%s, %s)", EchoObject(x), EchoObject(env));
  assert( type(x) == CLOSURE, "ParameterCheck given non-CLOSURE!");

  /* case x is a parameter */
  prnt = SearchEnv(env, enclosing(actual(x)));
  if( prnt == nilobj )
  { debug0(DCE, DD, "ParameterCheck returning nilobj (prnt fail)");
    return nilobj;
  }
  prnt_env = GetEnv(prnt);
  for( link = Down(prnt);  link != prnt;  link = NextDown(link) )
  { Child(par, link);
    if( type(par) == PAR && actual(par) == actual(x) )
    {	assert( Down(par) != par, "ParameterCheck: Down(par)!");
	Child(y, Down(par));
	res = is_word(type(y)) ? CopyObject(y, no_fpos) : nilobj;
	debug1(DCE, DD, "  ParameterCheck returning %s", EchoObject(res));
	return res;
    }
  }

  /* case x is a default parameter */
  y = sym_body(actual(x));
  if( y == nilobj )
  { res = nilobj;
  }
  else if( is_word(type(y)) )
  { res = CopyObject(y, &fpos(y));
  }
  else if( type(y) == CLOSURE && is_par(type(actual(y))) )
  { res = ParameterCheck(y, prnt_env);
  }
  else
  { res = nilobj;
  }
  debug1(DCE, DD, "ParameterCheck returning %s", EchoObject(res));
  return res;
} /* end ParameterCheck */
Exemple #15
0
void parse_words(ordered_tree_str_t * doc,char ** line, int lineno)
{
	char * word = strtok(*line," ");
	char * delim = " ";
	char *result = NULL;
	result = strtok( *line, delim );
	while( result != NULL ) 
	{
		if(is_word(result))
			ordered_tree_str_add(doc,result);
		result = strtok( NULL, delim );
	}
}
Exemple #16
0
/* Apply one quotation to another. */
void quotation_apply(Boxed target, Boxed source, Boxed definitions) {
  assert(target);
  assert(source);
  assert(is_quotation(target));
  assert(is_quotation(source));
  int i;
  for (i = 0; i < quotation_size(source); ++i) {
    if (is_word(quotation_data(source)[i]))
      word_apply(word_value(quotation_data(source)[i]), target, definitions);
    else
      quotation_push(target, boxed_copy(quotation_data(source)[i]));
  }
}
 factor_type gather(icontext_type& context, const vertex_type& vertex, 
                    edge_type& edge) const {
   vertex_type other_vertex = get_other_vertex(edge, vertex);
   // VIOLATING THE ABSTRACTION!
   vertex_data& vdata = graph_type::vertex_type(vertex).data();
   // VIOLATING THE ABSTRACTION!
   vertex_data& other_vdata = other_vertex.data();
   factor_type& doc_topic_count = 
     is_doc(vertex) ? vdata.factor : other_vdata.factor;
   factor_type& word_topic_count = 
     is_word(vertex) ? vdata.factor : other_vdata.factor;
   ASSERT_EQ(doc_topic_count.size(), NTOPICS);
   ASSERT_EQ(word_topic_count.size(), NTOPICS);
   // run the actual gibbs sampling 
   factor_type& belief = edge.data().belief;
   const uint32_t count = edge.data().count;
   // Resample the topics
   double sum = 0, old_sum = 0;
   for(size_t t = 0; t < NTOPICS; ++t) {
     old_sum += belief[t];
     doc_topic_count[t] -= belief[t];
     word_topic_count[t] -= belief[t];
     GLOBAL_TOPIC_COUNT[t] -= belief[t];
     const double n_dt = 
       std::max(count_type(doc_topic_count[t]), count_type(0));
     ASSERT_GE(n_dt, 0);
     const double n_wt = 
       std::max(count_type(word_topic_count[t]), count_type(0)); 
     ASSERT_GE(n_wt, 0);
     const double n_t  = 
       std::max(count_type(GLOBAL_TOPIC_COUNT[t]), count_type(0)); 
     ASSERT_GE(n_t, 0);
     belief[t] = (ALPHA + n_dt) * (BETA + n_wt) / (BETA * NWORDS + n_t);
     sum += belief[t];
   } // End of loop over each token
   ASSERT_GT(sum, 0);
   if(old_sum == 0) {
     size_t asg = graphlab::random::multinomial(belief);
     for(size_t i = 0; i < NTOPICS; ++i) belief[i] = 0;
     belief[asg] = count;
     return belief;
   }
   for(size_t t = 0; t < NTOPICS; ++t) {
     belief[t] = count * (belief[t]/sum);
     doc_topic_count[t] += belief[t];
     word_topic_count[t] += belief[t];
     GLOBAL_TOPIC_COUNT[t] += belief[t];
   }
   return belief;
 } // end of gather
Exemple #18
0
NODE *runparse(NODE *ndlist) {
    NODE *curnd = NIL, *outline = NIL, *tnode = NIL, *lastnode = NIL;
    char *str;

    if (nodetype(ndlist) == RUN_PARSE)
		return parsed__runparse(ndlist);
    if (!is_list(ndlist)) {
	    err_logo(BAD_DATA_UNREC, ndlist);
	    return(NIL);
    }
    if (ndlist != NIL && is_word(curnd=car(ndlist)) && getstrlen(curnd) >= 2 &&
	(str=getstrptr(curnd)) && *str++ == '#' && *str == '!')
	    return NIL;	    /* shell-script #! treated as comment line */
    while (ndlist != NIL) {
	curnd = car(ndlist);
	ndlist = cdr(ndlist);
	if (!is_word(curnd))
	    tnode = cons(curnd, NIL);
	else {
	    if (!numberp(curnd))
		tnode = runparse_node(curnd, &ndlist);
	    else
		tnode = cons(cnv_node_to_numnode(curnd), NIL);
	}
	if (tnode != NIL) {
	    if (outline == NIL) outline = tnode;
	    else setcdr(lastnode, tnode);
	    lastnode = tnode;
	    while (cdr(lastnode) != NIL) {
		lastnode = cdr(lastnode);
		if (check_throwing) break;
	    }
	}
	if (check_throwing) break;
    }
    return(outline);
}
Exemple #19
0
// Allow object keys to be without quotation,
// but then restrict to ([a-zA-Z0-9_])+
bool JSON::parse_json_key() {
  const char* begin;
  JSON_VAL v;
  u_char c;

  mark_pos();
  c = peek();
  if (c == '"') {
    return parse_json_string(true);
  }

  begin = pos;
  c = peek();
  if (c == 0) {
    error(SYNTAX_ERROR, "Got EOS when expecting an object key.");
    return false;
  } else if (is_word(c) == false) {
    error(SYNTAX_ERROR, "Expected an object key, which can be a double-quoted (\") string or a simple string (only alphanumeric characters and underscore, separated by whitespace) that doesn't need to be quoted.");
    return false;
  }

  for (;;) {
    c = peek();
    // Allow the key to be delimited by control characters and the object key-value separator ':'
    if (c <= ' ' || c == ':') {
      break;
    } else if (is_word(c) == false) {
      error(SYNTAX_ERROR, "Object key need to be quoted, or consist entirely of alphanumeric characters and underscores.");
      return false;
    }
    next();
  }

  v.str.start = begin;
  v.str.length = pos - begin;
  return callback(JSON_KEY, &v, level);
}
Exemple #20
0
/* Percorre T1 ordenadamente */
void printTokens(int onlyWords)
{
  int n = STcount();
  int i;
  Item item;
  printf("n=%d\n",n);
  for(i=0;i<n;i++)
  {
    item = STselect(i);
    if(!onlyWords)
      printf("%s\n",item->word);
    else if(is_word(item->word))
      printf("%s\n",item->word);
  }
}
Exemple #21
0
/* Percorre T2 ordenadamente */
void printLemmas(int printWords)
{
  int n = ST2count();
  int i,j;
  Item2 item;
  printf("Lemmas n=%d\n",n);
  for(i=0;i<n;i++)
  {
    item = ST2select(i);
    /* Todas as palavras do texto em sua versao lematizada */
    if(is_word(item->Lemma))
    {
      printf("%s -> ",item->Lemma);
      /* Imprimir palavras tambem? */
      if(printWords)
        for(j=0;j<item->n_words;j++)
        {
          if(!is_word(item->words[j])) continue;
          printf("[%s] ",item->words[j]);
        }
      printf("\n");
    }
  }
}
Exemple #22
0
void PDF_PrintGraphicObject(OBJECT x)
{ OBJECT y, link;
  debug3(DPF, D, "PDF_PrintGraphicObject(%s %s %s)",
    EchoFilePos(&fpos(x)), Image(type(x)), EchoObject(x));
  switch( type(x) )
  {
    case WORD:
    case QWORD:

      PDFPage_WriteGraphic(out_fp, string(x));
      break;
	

    case ACAT:
    
      for( link = Down(x);  link != x;  link = NextDown(link) )
      {	Child(y, link);
	if( type(y) == GAP_OBJ )
	{
	  if( vspace(y) > 0 )  PDFPage_Write(out_fp, "\n");
	  else if( hspace(y) > 0 ) PDFPage_Write(out_fp, " ");
	}
	else if( is_word(type(y)) || type(y) == ACAT )
	  PDF_PrintGraphicObject(y);
	else if( type(y) == WIDE || is_index(type(y)) )
	{
	  /* ignore: @Wide, indexes are sometimes inserted by Manifest */
	}
	else
	{ Error(50, 2, "error in left parameter of %s",
	    WARN, &fpos(x), KW_GRAPHIC);
	  debug1(DPF, D, "  type(y) = %s, y =", Image(type(y)));
	  ifdebug(DPF, D, DebugObject(y));
	}
      }
      break;


    default:
    
      Error(50, 3, "error in left parameter of %s", WARN, &fpos(x), KW_GRAPHIC);
      debug1(DPF, D, "  type(x) = %s, x =", Image(type(x)));
      ifdebug(DPF, D, DebugObject(x));
      break;

  }
  debug0(DPF, D, "PDF_PrintGraphicObject returning");
} /* end PDF_PrintGraphicObject */
Exemple #23
0
void printAll(char *word, int detailLevel)
{
  int i;
  Item2 item2;
  char *lemma;
  Item item = STsearch(word);
  if(item == NULL)
  {
    printf("Palavra <%s> nao encontrada.\n", word);
  }else
  {
    lemma = item->Lemma;
    item2 = ST2search(lemma);
    for(i=0;i<item2->n_words;i++)
      if(is_word(item2->words[i]))
        printExact(item2->words[i], detailLevel);
  }
}
Exemple #24
0
static void ReadLangDef(OBJECT encl)
{ OBJECT t, names, inside;
  
  New(names, ACAT);
  t = LexGetToken();
  while( is_word(type(t)) )
  { Link(names, t);
    t = LexGetToken();
  }
  if( type(t) != LBR )
  { Error(5, 4, "expected opening %s of langdef here", WARN, &fpos(t), KW_LBR);
    Dispose(t);
    return;
  }
  inside = Parse(&t, encl, FALSE, FALSE);
  inside = ReplaceWithTidy(inside, ACAT_TIDY);
  LanguageDefine(names, inside);
  return;
} /* end ReadLangDef */
Exemple #25
0
void ReadDatabaseDef(unsigned typ, OBJECT encl)
{ OBJECT symbs, t, fname;
  New(symbs, ACAT);
  t = LexGetToken();
  while( type(t)==CLOSURE || (type(t)==WORD && string(t)[0]==CH_SYMSTART) )
  { if( type(t) == CLOSURE )
    { Link(symbs, t);
    }
    else
    { Error(5, 7, "unknown or misspelt symbol %s", WARN, &fpos(t), string(t));
      Dispose(t);
    }
    t = LexGetToken();
  }
  if( type(t) != LBR )
  { Error(5, 8, "symbol name or %s expected here (%s declaration)",
      WARN, &fpos(t), KW_LBR, KW_DATABASE);
    Dispose(t);
    return;
  }
  if( Down(symbs) == symbs )
  { Error(5, 9, "symbol names missing in %s declaration",
      WARN, &fpos(t), KW_DATABASE);
  }
  fname = Parse(&t, encl, FALSE, FALSE);
  fname = ReplaceWithTidy(fname, ACAT_TIDY);
  if( !is_word(type(fname)) )
  { Error(5, 10, "name of %s file expected here", WARN, &fpos(fname),
      KW_DATABASE);
    DisposeObject(fname);
    return;
  }
  if( StringEndsWith(string(fname), DATA_SUFFIX) )
  { Error(5, 47, "%s suffix should be omitted in %s clause", WARN,
      &fpos(fname), DATA_SUFFIX, KW_DATABASE);
    DisposeObject(fname);
    return;
  }
  if( Down(symbs) != symbs )
    (void) DbLoad(fname, typ == DATABASE ? DATABASE_PATH : SYSDATABASE_PATH,
      TRUE, symbs, InMemoryDbIndexes);
} /* end ReadDatabaseDef */
Exemple #26
0
void ReadIncGRepeatedDef(unsigned typ, OBJECT encl)
{ OBJECT t, fname;
  t = LexGetToken();
  if( type(t) != LBR )
  { Error(5, 5, "left brace expected here in %s declaration",
      WARN, &fpos(t), KW_INCG_REPEATED);
    Dispose(t);
    return;
  }
  fname = Parse(&t, encl, FALSE, FALSE);
  fname = ReplaceWithTidy(fname, ACAT_TIDY);
  if( !is_word(type(fname)) )
  { Error(5, 6, "name of %s file expected here", WARN, &fpos(fname),
      KW_INCG_REPEATED);
    DisposeObject(fname);
    return;
  }
  debug0(DFS, D, "  calling PS_IncGRepeated from ReadPrependDef");
  incg_type(fname) = (typ == INCG_REPEATED ? INCGRAPHIC : SINCGRAPHIC);
  PS_IncGRepeated(fname);
} /* end ReadPrependDef */
Exemple #27
0
void ReadPrependDef(unsigned typ, OBJECT encl)
{ OBJECT t, fname;
  FILE_NUM fnum;
  t = LexGetToken();
  if( type(t) != LBR )
  { Error(5, 5, "left brace expected here in %s declaration",
      WARN, &fpos(t), KW_PREPEND);
    Dispose(t);
    return;
  }
  fname = Parse(&t, encl, FALSE, FALSE);
  fname = ReplaceWithTidy(fname, ACAT_TIDY);
  if( !is_word(type(fname)) )
  { Error(5, 6, "name of %s file expected here", WARN, &fpos(fname),KW_PREPEND);
    DisposeObject(fname);
    return;
  }
  debug0(DFS, D, "  calling DefineFile from ReadPrependDef");
  fnum = FileNum(string(fname), STR_EMPTY);
  if( fnum == NO_FILE || FileType(fnum) != PREPEND_FILE )
    DefineFile(string(fname), STR_EMPTY, &fpos(fname), PREPEND_FILE,
	   typ == PREPEND ? INCLUDE_PATH : SYSINCLUDE_PATH);

} /* end ReadPrependDef */
Exemple #28
0
/* Retrieve the value of a word. */
Word word_value(Boxed reference) {
  assert(reference);
  assert(is_word(reference));
  return reference->value->data.as_word;
}
int main(int argc, char * argv[]){
    int i;
    int sock, connected, bytes_recieved, opt_val = 1;
    struct sockaddr_in server_addr, client_addr;
    int sin_size;

    char send_data[1024], recv_data[1024];
    FILE * out_fp;

    if((sock = socket(AF_INET, SOCK_STREAM, 0)) == -1){
        perror("Error creating socket");
        exit(1);
    }

    if(setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &opt_val, sizeof(int)) == -1){
        perror("Error setting socket options");
        exit(1);

    }

    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(5000);
    server_addr.sin_addr.s_addr = INADDR_ANY;
    bzero(&(server_addr.sin_zero), 8);

    if(bind(sock, (struct sockaddr *) &server_addr, sizeof(struct sockaddr)) == -1){
        perror("Error binding port");
        exit(1);
    }

    if(listen(sock, 100)){
        perror("Error listening");
        exit(1);
    }

    root = create_tree(fopen("../data/twl06.txt", "r"));

    while(1){
        sin_size = sizeof(struct sockaddr_in);
        connected = accept(sock, (struct sockaddr *) &client_addr, &sin_size);
        //fprintf(stderr, "CONNECTION: %s:%d\n", inet_ntoa(client_addr.sin_addr),ntohs(client_addr.sin_port));

        bytes_recieved = recv(connected, recv_data, 1024, 0);
        if(bytes_recieved == 0){
            close(connected);
            continue;
        }
        if(recv_data[bytes_recieved - 1] == '\n')
            recv_data[bytes_recieved - 1] = '\0';
        else
            recv_data[bytes_recieved] = '\0';

        out_fp = fdopen(connected, "w+");

        if(recv_data[0] == 's'){
            i = 1;
            while(recv_data[i] && recv_data[i] != '_') i++;
            if (recv_data[i] == '_'){
                recv_data[i] = '\0';
                find_steals(root, recv_data + 1, recv_data + i + 1, out_fp);
            }
            else
                find_steals(root, recv_data + 1, 0, out_fp);
        }
        else if(recv_data[0] == 'w')
            fprintf(out_fp, is_word(root, recv_data + 1) ? "YES\n" : "NO\n");

        fclose(out_fp);
        close(connected);

    }

    close(sock);
    return 0;
}
Exemple #30
0
int handle_request(FILE* fid) {
	char buf[256];
	char fn[256];
	int set;
	int get;
	int getall;
	int filenum;
	int fieldnum;
	int lastfieldnum;
	int maxfields;
	char* nextword;

	//printf("Fileno %i:\n", fileno(fid));
	if (!fgets(buf, 256, fid)) {
		fprintf(stderr, "Error: failed to read a line of input.\n");
		fflush(stderr);
		fclose(fid);
		return -1;
	}
	//printf("Got request %s\n", buf);
	get = set = getall = 0;
	if (is_word(buf, "get ", &nextword)) {
		get = 1;
	} else if (is_word(buf, "set ", &nextword)) {
		set = 1;
	} else if (is_word(buf, "getall ", &nextword)) {
		getall = 1;
	}

	if (!(get || set || getall)) {
		fprintf(stderr, "Error: malformed command.\n");
		fclose(fid);
		return -1;
	}

	if (get || set) {
		if (sscanf(nextword, "%i %i", &filenum, &fieldnum) != 2) {
			fprintf(stderr, "Error: malformed request: %s\n", buf);
			fflush(stderr);
			fclose(fid);
			return -1;
		}
	} else if (getall) {
		if (sscanf(nextword, "%i %i %i %i", &filenum, &fieldnum, &lastfieldnum, &maxfields) != 4) {
			fprintf(stderr, "Error: malformed request: %s\n", buf);
			fflush(stderr);
			fclose(fid);
			return -1;
		}
		if (lastfieldnum < fieldnum) {
			fprintf(stderr, "Error: invalid \"getall\" request: lastfieldnum must be >= firstfieldnum.\n");
			fflush(stderr);
			fclose(fid);
			return -1;
		}
	}

	sprintf(fn, solvedfnpattern, filenum);

	if (get) {
		int val;
		printf("Get %s [%i].\n", fn, fieldnum);
		fflush(stdout);
		val = solvedfile_get(fn, fieldnum);
		if (val == -1) {
			fclose(fid);
			return -1;
		} else {
			fprintf(fid, "%s %i %i\n", (val ? "solved" : "unsolved"),
					filenum, fieldnum);
			fflush(fid);
		}
		return 0;
	} else if (set) {
		printf("Set %s [%i].\n", fn, fieldnum);
		fflush(stdout);
		if (solvedfile_set(fn, fieldnum)) {
			fclose(fid);
			return -1;
		}
		fprintf(fid, "ok\n");
		fflush(fid);
		return 0;
	} else if (getall) {
		int i;
		il* list;
		printf("Getall %s [%i : %i], max %i.\n", fn, fieldnum, lastfieldnum, maxfields);
		fflush(stdout);
		fprintf(fid, "unsolved %i", filenum);
		list = solvedfile_getall(fn, fieldnum, lastfieldnum, maxfields);
		if (list) {
			for (i=0; i<il_size(list); i++)
				fprintf(fid, " %i", il_get(list, i));
			il_free(list);
		}
		fprintf(fid, "\n");
		fflush(fid);
		return 0;
	}
	return -1;
}