예제 #1
0
/* CENTRAL METHOD to parse and render html request*/
int handle(cchar* q0,int conn){
	int len=(int)strlen(q0);
	if(len>1000){
		p("checkSanity len>1000");
		return 0;// SAFETY!
	}
    char* q=editable(q0);
	checkSanity(q,len);
    while(q[0]=='/')q++;
	enum result_format format = html;//txt; html DANGER WITH ROBOTS
	enum result_verbosity verbosity = normal;

	if (eq(q, "favicon.ico"))return 0;
    if(contains(q,"robots.txt")){
        Writeline(conn,"User-agent: *\n");
        Writeline("Disallow: /\n");
        return 0;
    }
	
	char* jsonp=strstr(q,"jsonp");// ?jsonp=fun
	if(jsonp){
		jsonp[-1]=0;
		jsonp+=6;
		format = json;
		}
	else jsonp=(char*)"parseResults";

	if (endsWith(q, ".json")) {
        format = json;
        q[len-5]=0;
    }
    
	if (endsWith(q, ".xml")) {
        format = xml;
        q[len-4]=0;
    }
    
	if (endsWith(q, ".csv")||endsWith(q, ".tsv")) {
        format = csv;
        q[len-4]=0;
    }
    
	if (endsWith(q, ".txt")) {
        format = txt;
        q[len-4]=0;
    }
    
	if (endsWith(q, ".html")) {
		format = html;
		q[len-5]=0;
	}
	if (startsWith(q, ".js")) {
		q[len-3]=0;
		Writeline(conn, jsonp);
		Writeline(conn, "(");
		format = js;
	}
	// todo : dedup!!
	if (startsWith(q, "all/")) {
		cut_to(q," +");
		cut_to(q," -");
		q = q + 4;
		showExcludes=false;
		verbosity = alle;
	}
	if (startsWith(q, "long/")){
		verbosity =  longer;
		q = q + 5;
	}
	if (startsWith(q, "full/")) {
		verbosity =  verbose;
		q = q + 5;
	}
	if (startsWith(q, "verbose/")) {
		verbosity = verbose;
		q = q + 8;
	}
	if (startsWith(q, "short/")) {
		verbosity = shorter;
		q = q + 6;
	}

	if (startsWith(q, "html/")) {
        format = html;
        if(!contains(q,".")&&!contains(q,":"))
			verbosity=verbose;
        q = q + 5;
    }
	if (startsWith(q, "plain/")) {
		format = txt;
		q = q + 6;
	}
	if (startsWith(q, "text/")) {
		format = txt;
		q = q + 5;
	}
	if (startsWith(q, "txt/")) {
		format = txt;
		q = q + 4;
	}
	if (startsWith(q, "xml/")) {
		format = xml;
		q = q + 4;
	}
	if (startsWith(q, "csv/")||startsWith(q, "tsv/")) {
		format = csv;
		q = q + 4;
	}
	if (startsWith(q, "json/")) {
		format = json;
		q = q + 5;
	}
	if (startsWith(q, "js/")) {
		q = q + 3;
		Writeline(conn, jsonp);
		Writeline(conn, "(");
		format = js;
	}
	if (startsWith(q, "long/")) {
		verbosity = longer;
		q = q + 5;
	}
	if (startsWith(q, "verbose/")) {
		verbosity = verbose;
		q = q + 8;
	}
	if (startsWith(q, "short/")) {
		verbosity = shorter;
		q = q + 6;
	}
	if (startsWith(q, "excludes/")||startsWith(q, "includes/")||startsWith(q, "excluded/")||startsWith(q, "included/")||startsWith(q, "showview/")) {
        showExcludes=true;
        verbosity=longer;
		q = q + 9;
	}
    else showExcludes=false;
    excluded.clear();
    included.clear();
    
    if(contains(q,"statement count")){Writeline(conn,itoa((int)context->statementCount).data());return 0;}
    if(contains(q,"node count")){Writeline(conn,itoa(context->nodeCount).data());return 0;}
    
    
	if (startsWith(q, "all/")) {
        cut_to(q," +");
        cut_to(q," -");
		q = q + 4;
		showExcludes=false;
		verbosity = alle;
	}
//	bool get_topic=false;
	bool get_topic=true;
	bool sort=false;
	if (startsWith(q, "ee/")||startsWith(q, "ee ")) {
		q[2]=' ';
		get_topic=true;
	}
	if (startsWith(q, "entities/")) {
		q[8]=' ';
		get_topic=true;
//		verbosity=longer;
	}
	if(hasWord(q)) loadView(q);
    
    if(contains(q,"exclude")||contains(q,"include")){
        verbosity=normal;
        showExcludes=true;
    }
	p(q);
    // !!!!!!!!!!!!!!!!!!!!!!!!!!!
	//
    NodeVector all = parse(q); // <<<<<<<< HANDLE QUERY WITH NETBASE!
    //
    // !!!!!!!!!!!!!!!!!!!!!!!!!!!

	autoIds=false;
    int size=(int)all.size();
    if(showExcludes){
        for (int i = 0; i < size; i++) {
        // todo : own routine!!!
        Node* node = (Node*) all[i];
        if(!contains(all,getAbstract(node->name)))
            all.push_back(getAbstract(node->name));
        N parent= getType(node);
        if(parent){
            if(!contains(all,parent))all.push_back(parent);
            N abs= getAbstract(parent->name);
            if(parent&&!contains(all,abs))all.push_back(abs);
        }
        }
        show(excluded);
    }
    
    const char* html_block="<!DOCTYPE html><html><head><META HTTP-EQUIV='CONTENT-TYPE' CONTENT='text/html; charset=UTF-8'/></head>"\
							"<body><div id='netbase_results'></div>\n<script>var results=";
    //    if((int)all.size()==0)Writeline("0");
	//	Writeline(conn,q);
	char buff[10000];

	bool use_json= format == json || format == js || format == html;
	if (format == xml && (startsWith(q,"select")||contains(q," where "))){Writeline(conn,query2(q));return 0;}
	if (format == xml)Writeline(conn, "<results>\n");
	if (format == html)Writeline(conn,html_block);
	if (use_json)Writeline(conn, "{\"results\":[\n");
	const char* statement_format_xml = "   <statement id='%d' subject=\"%s\" predicate=\"%s\" object=\"%s\" sid='%d' pid='%d' oid='%d'/>\n";
	const char* statement_format_text = "   $%d %s %s %s %d->%d->%d\n";
	const char* statement_format_json = "      { \"id\":%d, \"subject\":\"%s\", \"predicate\":\"%s\", \"object\":\"%s\", \"sid\":%d, \"pid\":%d, \"oid\":%d}";
	const char* statement_format_csv = "%d\t%s\t%s\t%s\t%d\t%d\t%d\n";
	const char* statement_format = 0;
	if (format == xml)statement_format = statement_format_xml;
	if (format == html)statement_format = statement_format_json;
	if (format == json)statement_format = statement_format_json;
	if (format == txt)statement_format = statement_format_text;
	if (format == csv)statement_format = statement_format_csv;
    
	const char* entity_format = 0;
	const char* entity_format_txt = "%s #%d (statements:%d) %s\n";
	const char* entity_format_xml = "<entity name=\"%s\" id='%d' statementCount='%d' description='%s'>\n";
	const char* entity_format_json = "   {\"name\":\"%s\", \"id\":%d, \"statementCount\":%d, \"description\":\"%s\"";
   	const char* entity_format_csv = "%s\t%d\t%d\t%s\n";
    if(all.size()==1)entity_format_csv = "";//statements!
	if (format == xml)entity_format = entity_format_xml;
	if (format == txt)entity_format = entity_format_txt;
	if (format == csv)entity_format = entity_format_csv;
	if (use_json)	  entity_format = entity_format_json;
	Node* last=0;
    warnings=0;
    char* entity=0;
    if(startsWith(q,"all")){
        entity=(char*)cut_to(q," ");
        entity=keep_to(entity,"limit");
    }
   	sortNodes(all);
	int count=(int)all.size();
	int good=0;
	for (int i = 0; i < count && i<resultLimit; i++) {
		Node* node = (Node*) all[i];
		if(!checkNode(node))continue;
		if(node->id==0)continue;
		if(last==node)continue;
		if(eq(node->name,"◊"))continue;
		last=node;
        if(verbosity ==normal && entity&& eq(entity,node->name))continue;
		char* text=getText(node);
//		if(use_json && get_topic){
//			if(empty(text))continue;//! no description = no entity? BAD for amazon etc
//			if(isAbstract(node))continue;
//			N t=getTopic(node);
//		}
		good++;
		if (use_json)if(good>1)Writeline(conn, "},\n");
		sprintf(buff, entity_format, node->name, node->id,node->statementCount,text);
		Writeline(conn, buff);
//        if(verbosity != alle && !get_topic)
//			loadView(node);
		bool got_topic=false;
		if(use_json && get_topic){
			N c=getClass(node);
			N t=getTopic(node);
			N ty=getType(node);
//			if(!c)c=t;
			if(!t)t=ty;
			if(t==node)t=ty;
			if(t!=Entity && checkNode(t)){
				got_topic=true;
				Writeline(conn, ",\n\t \"topicid\":"+itoa(t->id));
				Writeline(conn, ", \"topic\":\""+string(t->name)+"\"");
			}
			if(c && c!=t){
				Writeline(conn, ",\n\t \"classid\":"+itoa(c->id));
				Writeline(conn, ", \"class\":\""+string(c->name)+"\"");
			}
			if(ty&& c!=ty && ty!=t){
				Writeline(conn, ",\n\t \"typeid\":"+itoa(ty->id));
				Writeline(conn, ", \"type\":\""+string(ty->name)+"\"");
			}
		}
		if(use_json)// && (verbosity==verbose||verbosity==shorter))// lol // just name
			Writeline(conn, ", \"kind\":"+itoa(node->kind));
		if((use_json)&&!showExcludes&&node->statementCount>1 && getImage(node)!="")
			Writeline(", \"image\":\""+replace_all(replace_all(getImage(node,150,/*thumb*/true),"'","%27"),"\"","%22")+"\"");
//		if((use_json)&&getText(node)[0]!=0)
//			Writeline(", \"description\":\""+string(getText(node))+"\"");
		Statement* s = 0;
		if (format==csv|| verbosity == verbose || verbosity == longer|| verbosity == alle || showExcludes || ( all.size() == 1 && !(verbosity == shorter))) {
			int count=0;
            //            Writeline(",image:\""+getImage(node->name)+"\"");
			if (use_json)Writeline(conn, ",\n\t \"statements\":[\n");

//			sortStatements(
			deque<Statement*> statements;// sort
			while ((s = nextStatement(node, s))&&count++<lookupLimit){// resultLimit
				if (!checkStatement(s))break;
//				if(!got_topic &&( s->predicate==_Type|| s->predicate==_SuperClass)){
//					addStatementToNode(node, s->id(), true);// next time
//				}
				if(get_topic &&!got_topic && verbosity != verbose && (s->predicate>100 || s->predicate<-100))
					continue;// only important stuff here!
				// filter statements

				if(s->object==0)continue;
//				if(eq(s->Predicate()->name,"Offizielle Website") && !contains(s->Object()->name,"www"))
//					continue;
				if (s->subject==node->id and s->predicate!=4)//_instance
					statements.push_front(s);
				else statements.push_back(s);
			}
//			if(get_topic && verbosity!=shorter){
//				NV topics=getTopics(node);
//				N s=topics[0];
//				for (int j = 0; j < topics.size() && j<=resultLimit; j++) {
//					N s=topics[j];
//					Temporary statement (node,topic,s)
//					statements.push_front(s);
//				}
//			}




			int good=0;
			for (int j = 0; j < statements.size() && j<=resultLimit; j++) {
				s=statements.at(j);
//			while ((s = nextStatement(node, s))&&count++<resultLimit) {
                if(format==csv&&all.size()>1)break;// entities vs statements
                p(s);
				if(verbosity!=alle&&checkHideStatement(s)){warnings++;continue;}
				fixLabels(s);
				if(!(verbosity==verbose||verbosity==alle) && (s->Predicate()==Instance||s->Predicate()==Type))continue;
				if(use_json && good>0)Writeline(conn, ",\n");
				char* objectName=s->Object()->name;

				if(s->Predicate()==Instance){
					N type=findProperty(s->Object(),Type->name,0,50);
					if(  checkNode(type))
						objectName=(char*)(concat(concat(objectName, ": "),type->name));
				}
				sprintf(buff, statement_format, s->id(), s->Subject()->name, s->Predicate()->name, objectName, s->Subject()->id, s->Predicate()->id, s->Object()->id);
				Writeline(conn, buff);
				good++;
			}
			if (use_json)Writeline(conn, "]");
		}
		if (format == xml)Writeline(conn, "</entity>\n");
		//		string img=getImage(node->name);
		//		if(img!="")Writeline(conn,"<img src=\""+img+"\"/>");
	}

	if (use_json || format == html || format == js)Writeline(conn,good>0?"}\n]}":"]}");
	if (format == xml)Writeline(conn, "</results>\n");
	if(format == js)Writeline(conn, ")");// jsonp
		const char* html_end=";\n</script>\n<script src='http://pannous.net/netbase.js'></script></body></html>\n";
	if(format == html)Writeline(conn, html_end);
	//		sprintf(buff,	"<script src='/js/%s'></script>",q0);
	//		Writeline(conn, buff);
	//	}
    pf("Warnings/excluded: %d\n",warnings);
    return 0;// 0K
}
예제 #2
0
int main(int argc, char** argv)
{
  int i, j, count;
  FILE* f;

  char *prefix, *titleString, *temperature;

  int format; /* 0: PS  1: PNG  2: GIF  3: JPEG */
  int machine;

  char* buffer; /* for system() and fopen() */
  char* plotFile;

  /* functions to call - either PS or PNG */
  void (*init)();
  void (*title)(char*);
  void (*border)();
  void (*grid)();
  void (*plotDot)(int, int, double);
  void (*vertCenter)(char*, int);
  void (*horzCenter)(char*, int);
  void (*selection)(char*, int);

  g_filter = 0;
  g_grid = -1;
  g_dotSize = -1;
  g_top = g_left = g_size = -1;
  g_selectedI = g_selectedJ = -1;
  format = 0;
  machine = 0;
  titleString = NULL;
  g_cutoffValue = 0;
  getColor = getColorLogLog;
  g_epsilon = 0.01;
  temperature = "37";

  while ((count = getopt_long(argc, argv, "Vht:c:e:g:d:u:l:s:f:i:j:p:r:mo:", OPTIONS, NULL)) != -1)
    {
      if (count == 'V')
	version("hybrid-plot-ng");
      else if (count == 'h' || count == '?')
	{
	  puts("Usage: hybrid-plot-ng [options] <file prefix>");
	  puts("");
	  puts("Options:");
	  puts("-V, --version");
	  puts("-h, --help");
	  puts("-t, --temperature=<temperature>");
	  puts("-c, --colors=(linear | log | double) (defaults to double)");
	  puts("-e, --epsilon=<color epsilon> (defaults to .01)");
	  puts("-g, --grid=<grid spacing>");
	  puts("-d, --dot=<dot size>");
	  puts("-u, --top=<initial i>");
	  puts("-l, --left=<initial j>");
	  puts("-s, --size=<size of square>");
	  printf("-f, --format=(ps");
#if HAVE_GD_PNG
	  printf(" | png");
#endif
#if HAVE_GD_GIF
	  printf(" | gif");
#endif
#if HAVE_GD_JPEG
	  printf(" | jpeg");
#endif
	  puts(") (defaults to ps)");
	  puts("-i, --i=<selected i>");
	  puts("-j, --j=<selected j>");
	  puts("-p, --title=<plot title>");
	  puts("-r, --filter=(on | off) (defaults to off)");
	  puts("-o, --cutoff=<store cutoff>");
	  puts("");
	  puts("Report bugs to " PACKAGE_BUGREPORT);
	  return EXIT_SUCCESS;
	}
      else if (count == 't')
	temperature = optarg;
      else if (count == 'c')
	{
	  if (!strcmp(optarg, "linear"))
	    getColor = getColorLinear;
	  else if (!strcmp(optarg, "log"))
	    getColor = getColorLog;
	  else if (!strcmp(optarg, "double"))
	    getColor = getColorLogLog;
	}
      else if (count == 'e')
	g_epsilon = atof(optarg);
      else if (count == 'g')
	g_grid = atoi(optarg);
      else if (count == 'd')
	g_dotSize = atoi(optarg);
      else if (count == 'u')
	g_top = atoi(optarg);
      else if (count == 'l')
	g_left = atoi(optarg);
      else if (count == 's')
	g_size = atoi(optarg);
      else if (count == 'f')
	{
	  if (!strcmp(optarg, "ps"))
	    format = 0;
	  else if (!strcmp(optarg, "png"))
	    format = 1;
	  else if (!strcmp(optarg, "gif"))
	    format = 2;
	  else if (!strcmp(optarg, "jpeg"))
	    format = 3;
	}
      else if (count == 'i')
	g_selectedI = atoi(optarg);
      else if (count == 'j')
	g_selectedJ = atoi(optarg);
      else if (count == 'p')
	  {
	    titleString = xmalloc(strlen(optarg) + 1);
	    strcpy(titleString, optarg);
	  }
      else if (count == 'r')
	{
	  if (!strcmp(optarg, "on"))
	    g_filter = 1;
	  else if (!strcmp(optarg, "off"))
	    g_filter = 0;
	}
      else if (count == 'm')
	machine = 1;
      else if (count == 'o')
	g_cutoffValue = atof(optarg);
   }

  if (optind >= argc)
    {
      fputs("Error: no prefix specified\nRun 'hybrid-plot-ng -h' for help\n", stderr);
      return EXIT_FAILURE;
    }

  plotFile = xmalloc(strlen(argv[optind]) + 107);
  strcpy(plotFile, argv[optind]);

  for (i = 0; i <= strlen(argv[optind]); ++i)
    {
      if (argv[optind][i] == '-')
	{
	  g_ss = 0;
	  argv[optind][i] = 0;
	  break;
	}
      else if (argv[optind][i] == 0)
	{
	  g_ss = 1;
	  break;
	}
    }

  g_file1 = argv[optind];
  if (g_ss) /* from hybrid-ss */
    g_file2 = g_file1;
  else      /* from hybrid */
    g_file2 = argv[optind] + i + 1;

  if (g_ss)
    prefix = g_file1;
  else
    {
      prefix = xmalloc(strlen(g_file1) + 1 + strlen(g_file2) + 1);
      strcpy(prefix, g_file1);
      strcat(prefix, "-");
      strcat(prefix, g_file2);
    }

  if (!(f = fopen(g_file1, "rt")))
    {
      buffer = xmalloc(strlen(g_file1) + 5);
      strcpy(buffer, g_file1);
      strcat(buffer, ".seq");
      if (!(f = fopen(buffer, "rt")))
	{
	  perror(buffer);
	  return EXIT_FAILURE;
	}
      free(buffer);
    }
  input(f, &g_name1, &g_string1);
  fclose(f);
  if (!g_name1)
    g_name1 = g_file1;
  g_len1 = strlen(g_string1);

  if (g_ss)
    {
      g_name2 = g_name1;
      g_string2 = g_string1;
      g_len2 = g_len1;
    }
  else
    {
      if (!(f = fopen(g_file2, "rt")))
	{
	  buffer = xmalloc(strlen(g_file2) + 5);
	  strcpy(buffer, g_file2);
	  strcat(buffer, ".seq");
	  if (!(f = fopen(buffer, "rt")))
	    {
	      perror(buffer);
	      return EXIT_FAILURE;
	    }
	  free(buffer);
	}
      input(f, &g_name2, &g_string2);
      fclose(f);
      if (!g_name2)
	g_name2 = g_file2;;
      g_len2 = strlen(g_string2);
    }

  strcat(plotFile, ".");
  strcat(plotFile, temperature);
  strcat(plotFile, ".plot");

  if (!(f = fopen(plotFile, "rt")))
    {
      perror(plotFile);
      return EXIT_FAILURE;
    }
  g_scores = inputRecords(f);
  fclose(f);
  free(plotFile);

  if (!titleString)
    {
      titleString = xmalloc(1 + strlen(g_name1) + 7 + strlen(g_name2) + 5 + strlen(temperature) + 9);
      if (g_ss)
	sprintf(titleString, "'%s' at %s degrees", g_name1, temperature);
      else
	sprintf(titleString, "'%s' vs. '%s' at %s degrees", g_name1, g_name2, temperature);
    }

  if (g_top == -1 || g_left == -1 || g_size == -1)
    {
      g_top = g_left = 1;
      g_size = g_len1 > g_len2 ? g_len1 : g_len2;
      fixSize();
    }

  g_dotSpacing = (double) 484 / g_size;
  if (g_dotSize == -1)
    g_dotSize = roundInt(g_dotSpacing);
  if (g_dotSize < 1)
    g_dotSize = 1;
  if (g_grid < 0)
    {
      g_grid = g_size / 8;
      fixGrid();
    }
  if (g_grid)
    {
      g_labels = g_grid;
      fixLabels();
    }

  init = initPS;
  title = titlePS;
  border = borderPS;
  grid = gridPS;
  plotDot = plotDotPS;
  vertCenter = vertCenterPS;
  horzCenter = horzCenterPS;
  selection = selectionPS;
#if HAVE_GD
  if (format)
    {
      init = initPNG;
      title = titlePNG;
      border = borderPNG;
      grid = gridPNG;
      plotDot = plotDotPNG;
      vertCenter = vertCenterPNG;
      horzCenter = horzCenterPNG;
      selection = selectionPNG;
    }
#endif

  buffer = xmalloc(strlen(prefix) + 1 + strlen(temperature) + 5);
  strcpy(buffer, prefix);
  strcat(buffer, ".");
  strcat(buffer, temperature);
  if (format == 0)
    {
      strcat(buffer, ".ps");
      g_file = fopen(buffer, "wt");
    }
  else
    {
      if (format == 1)
	strcat(buffer, ".png");
      else if (format == 2)
	strcat(buffer, ".gif");
      else
	strcat(buffer, ".jpg");
      g_file = fopen(buffer, "wb");
#if HAVE_GD
      g_image = gdImageCreate(612, 612);
#endif
    }
  if (!g_file)
    {
      perror(buffer);
      return EXIT_FAILURE;
    }
  free(buffer);

  init();

  title(titleString);

  border();

  grid();

  for (i = 1; i <= g_len1; ++i)
    for (j = 1; j <= g_len2; ++j)
      if (g_scores[(i - 1) * g_len2 + j - 1] >= g_cutoffValue)
	if (g_filter == 0 || filter(i, j))
	  plotDot(i, j, g_scores[(i - 1) * g_len2 + j - 1]);

  if (g_selectedI > 0 && g_selectedJ > 0)
    {
      buffer = xmalloc(24);
      sprintf(buffer, "Selected: (%d-%c, %d-%c), %g",
	      g_selectedI, g_string1[g_selectedI - 1],
	      g_selectedJ, g_string2[g_selectedJ - 1],
	      g_scores[(g_selectedI - 1) * g_len2 + g_selectedJ - 1]);
      selection(buffer, g_gray);
    }

  if (format == 1)
#if HAVE_GD_PNG
    gdImagePng(g_image, g_file)
#endif
      ;
  else if (format == 2)
#if HAVE_GD_GIF
    gdImageGif(g_image, g_file)
#endif
      ;
  else if (format == 3)
#if HAVE_GD_JPEG
    gdImageJpeg(g_image, g_file, -1)
#endif
      ;

  fclose(g_file);

  if (machine)
    {
      /* save configuration */
      buffer = xmalloc(strlen(prefix) + 5);
      strcpy(buffer, prefix);
      strcat(buffer, ".cfg");
      if (!(f = fopen(buffer, "wt")))
	{
	  perror(buffer);
	  return EXIT_FAILURE;
	}
      free(buffer);
      fprintf(f, "%f\n", g_dotSpacing);
      fprintf(f, "%d\n", g_size);
      fclose(f);
    }

  return 0;
}