int UnixSocketAdapter::getLines(string& lines)
{
  int err = get_lines(buffer,CTRL_MSGBUF_SIZE);
  if(err != -1)
    lines = buffer;
  return err;
}
Ejemplo n.º 2
0
int main(){
	
	char *temp;
	char filename[40];
	int i;
	int x;

	printf("\nEntrer le nom du fichier a ouvrir  : ");
	fgets(filename, sizeof(filename), stdin);

		i=0;
		while(filename[i] && filename[i] != '\n') i++;
		filename[i] = '\0';
	
	printf("\nIndiquer le mot rechercher : ");
	fgets(str_search,sizeof(str_search), stdin);
		
		i=0;
		while(filename[i] && filename[i] != '\n') i++;
		filename[i] = '\0';

	if((fp = fopen(filename, "r")) == NULL )
	{
		fprintf(stderr, "Erreur lors de la lecture");
		exit(EXIT_FAILURE);
	}
	
	get_lines(fp, str_search);
	fclose(fp);
	exit(EXIT_SUCCESS);
	
	}
Ejemplo n.º 3
0
static void norm_acc(t_atoms *atoms, int nres,
                     real av_area[], real norm_av_area[])
{
    int     i, n, n_surf;

    char    surffn[] = "surface.dat";
    char  **surf_res, **surf_lines;
    double *surf;

    n_surf = get_lines(surffn, &surf_lines);
    snew(surf, n_surf);
    snew(surf_res, n_surf);
    for (i = 0; (i < n_surf); i++)
    {
        snew(surf_res[i], 5);
        sscanf(surf_lines[i], "%s %lf", surf_res[i], &surf[i]);
    }

    for (i = 0; (i < nres); i++)
    {
        n = search_str(n_surf, surf_res, *atoms->resinfo[i].name);
        if (n != -1)
        {
            norm_av_area[i] = av_area[i] / surf[n];
        }
        else
        {
            fprintf(stderr, "Residue %s not found in surface database (%s)\n",
                    *atoms->resinfo[i].name, surffn);
        }
    }
}
bool
AsciiProcessor::ins_line( const char * buf,
                          int fref,
                          BuilderBase * build,
                          const char * & next )
{
    int id = 0, lay = 0, fil = 0;
    RGBcolor col( 0, 0, 0 );

    if ( ! get_obj_attr( buf, id, lay, col, fil, next ) )
    {
        return CMD_ERR;
    }

    int num = get_lines( next, lines, next );

    if ( num < 1 )
    {
        return CMD_ERR;
    }

    if ( num == 1 )
    {
        build->set_cmd_insert_line( fref, id, lines.tab[0], lay, col );
    }
    else
    {
        build->set_cmd_insert_lines( fref, id, lines.cur_size, lines.tab, lay, col );
    }

    return CMD_OK;
}
Ejemplo n.º 5
0
    void operator ()(parse_state &state)
    {
      state.lines = get_lines(state.plain);
      if(state.lines.size() < 2)
      { throw std::runtime_error("insufficient lines in plain render"); }

      std::string name{ state.lines[0] };
      str::replace(str::trim(name), " ", ""); /* Don't allow spaces in the filename. */
      if(state.output_file.empty())
      { state.output_file = state.output_dir + name + ".3"; }

      /* First two lines are always the same. */
      state.lines[0] = ".TH " + name + " 3 "
                       "\"" + state.creation_date + "\" \"" + state.version + "\" "
                       "\"C++ Standard Libary\"";
      state.lines[1] = "Synopsis";

      groff_detail::section(state.lines);
      groff_detail::highlight(state.lines);

      std::ofstream ofs{ state.output_file };
      if(state.verbose)
      { std::cout << "output: " << state.output_file << std::endl; }
      if(!ofs.is_open())
      { throw std::runtime_error("failed to open file for writing: " + state.output_file); }
      std::copy(std::begin(state.lines), std::end(state.lines),
                std::ostream_iterator<std::string>(ofs, "\n"));
    }
Ejemplo n.º 6
0
	std::string builder::writer_t::finalize() const
	{
		std::string result;
		int lvl = 0;

		for (const std::string &line : get_lines(build()))
		{
			if (line.empty())
			{
				result += "\n";
			}
			else
			{
				std::size_t line_pos = std::string::npos;

				line_pos = std::string::npos;
				while ((line_pos = line.find('}', line_pos + 1)) != std::string::npos)
				{
					--lvl;
				}

				result += std::string(lvl, '\t') + line + "\n";

				while ((line_pos = line.find('{', line_pos + 1)) != std::string::npos)
				{
					++lvl;
				}
			}
		}

		return result;
	}
Ejemplo n.º 7
0
page * add_str_to_page(char * str, int type, book *b, page *p)
{
	char ** lines=NULL;
	char ** newlines=NULL;
	char ** newlines_ptr;
	int i;

	if(!str) return NULL;
	if(!p)p=add_page(b);
	
	newlines=get_lines(str, b->max_width);
	newlines_ptr = newlines;
	lines=p->lines;
	
	for(i=0;*lines;i++,lines++);

	if(type==_AUTHOR){
		*lines++=(char*)calloc(1,sizeof(char));
	} else if (type==_TITLE){
		*lines++=(char*)calloc(1,sizeof(char));
	}

	for(;newlines && *newlines;i++) {
		if(type==_AUTHOR){
			memmove(*newlines+1,*newlines,strlen(*newlines)+1);
			**newlines = to_color_char (c_orange3);
		} else if(type==_TITLE){
			memmove(*newlines+1,*newlines,strlen(*newlines)+1);
			**newlines = to_color_char (c_orange4);
		}
		if(i>=b->max_lines){
			*lines=NULL;
			p=add_page(b);
			lines=p->lines;
			i=0;
		}
		*lines++=*newlines++;
		// Grum: don't free *newlines, it's the pointer to actual line.
		// It's this pointer that is copied to p->lines, not the data
		// that it points to.
		//free(*newlines);
	}
	// This is a temporary array that holds the pointers to the lines. It 
	// can safely be freed.
	free(newlines_ptr);

	if(i<b->max_lines){
		if(type==_AUTHOR){
			*lines++=(char*)calloc(1,sizeof(char));
		} else if (type==_TITLE){
			*lines++=(char*)calloc(1,sizeof(char));
		}
	}
	*lines=NULL;

	return p;
}
Ejemplo n.º 8
0
void avim_group_impl::forward_client_message(std::string data)
{
	auto avs = get_lines(m_groupdef);
	// 打开 groupdef 文件
	// 为每个 avim 执行一次 send
	for (auto avaddress : avs )
	{
		m_core.async_sendto(avaddress, data, [](boost::system::error_code){});
	}
}
Ejemplo n.º 9
0
static void
fake_new_process (tracker_t *tracker, pid_t pid)
{
    char **lines;
    gboolean done = FALSE;

    if ((lines = get_lines ("/proc/%d/cmdline", pid)))
    {
	if (lines[0] && strlen (lines[0]) > 0)
	{
	    tracker_add_process (tracker, pid, lines[0]);

	    done = TRUE;
	}

	g_strfreev (lines);
    }

    if (!done && (lines = get_lines ("/proc/%d/status", pid)))
    {
        int i;

        for (i = 0; lines[i] != NULL; ++i)
        {
            if (strncmp ("Name:", lines[i], 5) == 0)
            {
		char *name = g_strstrip (strchr (lines[i], ':') + 1);

		if (strlen (name) > 0)
		{
		    tracker_add_process (tracker, pid, name);
		    done = TRUE;
		    break;
		}
	    }
	}

	g_strfreev (lines);
    }

    if (!done)
	g_print ("failed to fake %d\n", pid);
}
Ejemplo n.º 10
0
/* Handle input by separating into lines and calling handle_header for each */
static int handle_buffer(conn_t* conn, char* buffer, int buf_size)
{
    int i;
    char* lines[MAX_HEADERS];
    char* body;

    char first_line[MAX_HEADER_SIZE];

    switch (conn->state) {

    case READING_HEADERS:

        /* Set up lines[0] with the remnant from the previous read */
        strncpy(first_line, conn->local_buffer, sizeof(first_line));
        lines[0] = first_line;

        /* Split into lines (saving fragment in conn->local_buffer) */
        body = get_lines(conn, lines, buffer, buf_size);

        for (i = 0; i < MAX_HEADERS; i++)
            handle_header(conn, lines[i]);
        
        if (body == NULL)
            /* Done for now; we're still reading headers */
            return ST_CONTINUE;

        /* Otherwise, body points to the body of the reply */

        if (verbose > 1)
            fputs("End Of Headers\n", stderr);

        conn->state = RECEIVING_DATA;
        buf_size = body - buffer;
        buffer = body;
        /* FALLTHROUGH */

    case RECEIVING_DATA:
        /*
         * In the future, we'll actually be testing the returned
         * object to make sure the data is correct. (And the code
         * needs to handle the "chunked" transfer encoding.) For now,
         * we just discard it.
         */
        if (verbose > 3)
            fprintf(stderr, "%s", buffer);
        break;

    default:
        fprintf(stderr, "Fatal error -- bad state %s\n",
                state_names[conn->state]);
        break;
    }

    return ST_CONTINUE;
}
Ejemplo n.º 11
0
void main( string a )
{
  string output, file_name1, file_name2;
  string *lines1, *lines2;
  string *ONEnotTWO, *TWOnotONE;

  if( !a || 2 != sscanf( a, "%s %s", file_name1, file_name2 ) )
  {
    write( "Syntax: diff <file1> <file2>\n" ); 
    return;
  }
  lines1 = get_lines( file_name1 );
  lines2 = get_lines( file_name2 );
  if( !pointerp( lines1 ) || !pointerp( lines2 ) )
  {
    write( "No comparison made.\n" );
    return;
  }
  if( lines1 == lines2 )
  {
    write( file_name1 + " and " + file_name2 + " are the same file.\n" );
    return;
  }
  ONEnotTWO = filter_array( lines1, "sort", this_object(), lines2 );
  TWOnotONE = filter_array( lines2, "sort", this_object(), lines1 );
  if( ONEnotTWO == TWOnotONE )
  {
    write( file_name1 + " and " + file_name2 + " have the same lines.\n" );
    return;
  }
  output = "[In " + file_name1 + " but not in " + file_name2 + ":]\n" +
	   implode( ONEnotTWO, "\n" ) + "\n" +
	   "\n[In " + file_name2 + " but not in " + file_name1 + ":]\n" +
	   implode( TWOnotONE, "\n" ) + "\n";
 
  more( explode(output, "\n") );
 
  return;
}
Ejemplo n.º 12
0
t_specbond *get_specbonds(int *nspecbond)
{
    const char  *sbfile = "specbond.dat";

    t_specbond  *sb = NULL;
    char         r1buf[32], r2buf[32], a1buf[32], a2buf[32], nr1buf[32], nr2buf[32];
    double       length;
    int          nb1, nb2;
    char       **lines;
    int          nlines, i, n;

    nlines = get_lines(sbfile, &lines);
    if (nlines > 0)
    {
        snew(sb, nlines);
    }

    n = 0;
    for (i = 0; (i < nlines); i++)
    {
        if (sscanf(lines[i], "%s%s%d%s%s%d%lf%s%s",
                   r1buf, a1buf, &nb1, r2buf, a2buf, &nb2, &length, nr1buf, nr2buf) != 9)
        {
            fprintf(stderr, "Invalid line '%s' in %s\n", lines[i], sbfile);
        }
        else
        {
            sb[n].res1    = gmx_strdup(r1buf);
            sb[n].res2    = gmx_strdup(r2buf);
            sb[n].newres1 = gmx_strdup(nr1buf);
            sb[n].newres2 = gmx_strdup(nr2buf);
            sb[n].atom1   = gmx_strdup(a1buf);
            sb[n].atom2   = gmx_strdup(a2buf);
            sb[n].nbond1  = nb1;
            sb[n].nbond2  = nb2;
            sb[n].length  = length;
            n++;
        }
        sfree(lines[i]);
    }
    if (nlines > 0)
    {
        sfree(lines);
    }
    fprintf(stderr, "%d out of %d lines of %s converted successfully\n",
            n, nlines, sbfile);

    *nspecbond = n;

    return sb;
}
Ejemplo n.º 13
0
static uint8_t tick(void) {


	tetris_update();

	for(int i = 0; i < 3; i++)
	{
		int lines = get_lines(i);
		fill_8x6(i * 36 +15,5, 3,0,0,0);
		draw_number_8x6(i * 36 + 15,5, lines, 3, ' ' ,255,255,255);
	}

	return 0;
}
Ejemplo n.º 14
0
stack<string>* LogParser::get_last_lines() {
	stack<string>* sLines=new stack<string>();
	int total_lines=log_lines;
	set_num_lines();

	if(log_lines==total_lines) {
		return NULL;
	}

	int num_lines=log_lines-total_lines;
	get_lines(num_lines, sLines);

	return sLines;
}
Ejemplo n.º 15
0
int main(int argc, char **argv)
{
	FILE *fp;

	columns = get_columns() + 1;
	lines = get_lines() - 1;

	//TODO UTF-8
	linebuf = malloc(columns);
	if (!linebuf) {
		perror(NULL);
		return EXIT_FAILURE;
	}

	switch (argc) {
	case 1:
		fp = stdin;
		break;

	case 2:
		argv++;
		fp = fopen(*argv, "r");
		if (!fp) {
			perror(*argv);
			return EXIT_FAILURE;
		}

		break;

	default:
		fprintf(stderr, "Missing filename\n");
		return EXIT_FAILURE;
	}

	for (;;) {
		bool done = show(fp);

		fputs("--More--", stdout);
		done |= process();
		putchar('\n');

		if (done)
			break;
	}

	fclose(fp);

	return 0;
}
Ejemplo n.º 16
0
int main(){
	
	int number_of_lines;
	number_of_lines = get_lines(lines);

	if(number_of_lines < 0)
	{
		puts("Erreur d'Allocation mémoire");
	exit(EXIT_FAILURE);
	}

	sort(lines, number_of_lines);
	print_strings(lines, number_of_lines);
	return 0;
}
Ejemplo n.º 17
0
void read_bfac(char *fn, int *n_bfac, double **bfac_val, int **bfac_nr)
{
  int  i;
  char **bfac_lines;

  *n_bfac = get_lines(fn, &bfac_lines);
  snew(*bfac_val, *n_bfac);
  snew(*bfac_nr, *n_bfac);
  fprintf(stderr, "Reading %d B-factors from %s\n",*n_bfac,fn);
  for(i=0; (i<*n_bfac); i++) {
    /*fprintf(stderr, "Line %d: %s",i,bfac_lines[i]);*/
    sscanf(bfac_lines[i],"%d %lf",&(*bfac_nr)[i],&(*bfac_val)[i]);
    /*fprintf(stderr," nr %d val %g\n",(*bfac_nr)[i],(*bfac_val)[i]);*/
  }
  
}
Ejemplo n.º 18
0
int main(int argc, char** argv) {
	int chunks = 10;
	int lines = 0;
	long size = 0;
	char* finame = NULL;

	if (argc < 4) {
		printf("Usage: %s <input_file> <chunks> -b | -l [lines] | -e <size>\n\t-b split file based on size (bytes)\n\t-l split file based on number of lines\n\t-e extract first <size> bytes (<chunks> can take any value)\n", argv[0]);
		return -1;
	}

	finame = argv[1];
	chunks = atoi(argv[2]);

	switch(argv[3][1]) {
	case 'b':
		
		break;
	case 'l':
		if (argc > 4) {
                	lines = atoi(argv[4]);
        	} else {
                	lines = get_lines(finame);
	                printf("No of lines: %d\n", lines);
        	}

		printf("Splitting file %s with %d lines in %d chunks!\n", finame, lines, chunks);
		split_v2(finame, lines, chunks);
		printf("\nDone.\n");

		break;
	case 'e':
		if (argc > 4) {
			size = atol(argv[4]);
                } else {
			printf("No extracting size given!\n");
			return -1;
                }
		extract(finame, size);
		break;
	default:
		printf("Unsupported option %s\n", argv[3]);
		return -2;
	}

	return 0;
}
Ejemplo n.º 19
0
static const uint8_t *
get_vdso_bytes (size_t *length)
{
    static const uint8_t *bytes = NULL;
    static size_t n_bytes = 0;
    static gboolean has_data;

    if (!has_data)
    {
        char **lines = get_lines ("/proc/%d/maps", getpid());
        int i;

        for (i = 0; lines[i] != NULL; ++i)
        {
            char file[256];
            gulong start;
            gulong end;
            int count = sscanf (
                lines[i], "%lx-%lx %*15s %*x %*x:%*x %*u %255s",
                &start, &end, file);

            if (count == 3 && strcmp (file, "[vdso]") == 0)
            {
                n_bytes = end - start;

                /* Dup the memory here so that valgrind will only
                 * report one 1 byte invalid read instead of
                 * a ton when the elf parser scans the vdso
                 *
                 * The reason we get a spurious invalid read from
                 * valgrind is that we are getting the address directly
                 * from /proc/maps, and valgrind knows that its mmap()
                 * wrapper never returned that address. But since it
                 * is a legal mapping, it is legal to read it.
                 */
                bytes = g_memdup ((uint8_t *)start, n_bytes);

                has_data = TRUE;
            }
        }
    }

    if (length)
        *length = n_bytes;

    return bytes;
}
Ejemplo n.º 20
0
void read_cross_halo(char *cross_url)
{
	int i=0, N=0;
	double a;
	char dummy[512];
	FILE *cross_file = fopen(cross_url, "r");

		crossHaloes = (struct halo*) calloc(1, sizeof(struct halo));

		N = get_lines(cross_file, cross_url);
		fprintf(stderr, "Reading cross correlation file %s, %d lines\n", cross_url, N);
		N = 0;
		
		while(!feof(cross_file))
		{
			N++;
			
			if(N<2)
			fgets(dummy, 512, cross_file);

			if(N>1)
			{
				crossHaloes = (struct halo*) realloc(crossHaloes, N * sizeof(struct halo));
				fscanf(cross_file, "%lf\t", &crossHaloes[N-1].Mvir);
				fscanf(cross_file, "%f\t", &crossHaloes[N-1].Rvir);
				fscanf(cross_file, "%f\t", &crossHaloes[N-1].Msub);
				fscanf(cross_file, "%d\t", &crossHaloes[N-1].n_part);
				fscanf(cross_file, "%f\t", &crossHaloes[N-1].X[0]);
				fscanf(cross_file, "%f\t", &crossHaloes[N-1].X[1]);
				fscanf(cross_file, "%f\t", &crossHaloes[N-1].X[2]);
				fscanf(cross_file, "%f\t", &crossHaloes[N-1].c_nfw);
				fscanf(cross_file, "%f\t", &crossHaloes[N-1].abs_th_vir);
				fscanf(cross_file, "%f\t", &crossHaloes[N-1].lambda);
				fscanf(cross_file, "%f\t", &crossHaloes[N-1].shape);
				fscanf(cross_file, "%f\t", &crossHaloes[N-1].triax);
#ifdef GAS
				fscanf(cross_file, "%f\t", &crossHaloes[N-1].gas_only.T_mw);
				fscanf(cross_file, "%f\t", &crossHaloes[N-1].gas_only.b_fraction);
#endif
			}
		}

	Ncross = N;

	fprintf(stderr, "Found %d cross haloes\n", N);
}
Ejemplo n.º 21
0
static void
fake_new_map (tracker_t *tracker, pid_t pid)
{
    char **lines;

    if ((lines = get_lines ("/proc/%d/maps", pid)))
    {
        int i;

        for (i = 0; lines[i] != NULL; ++i)
        {
            char file[256];
            gulong start;
            gulong end;
            gulong offset;
            gulong inode;
            int count;

	    file[255] = '\0';

            count = sscanf (
                lines[i], "%lx-%lx %*15s %lx %*x:%*x %lu %255s",
                &start, &end, &offset, &inode, file);

            if (count == 5)
            {
                if (strcmp (file, "[vdso]") == 0)
                {
                    /* For the vdso, the kernel reports 'offset' as the
                     * the same as the mapping addres. This doesn't make
                     * any sense to me, so we just zero it here. There
                     * is code in binfile.c (read_inode) that returns 0
                     * for [vdso].
                     */
                    offset = 0;
                    inode = 0;
                }

		tracker_add_map (tracker, pid, start, end, offset, inode, file);
            }
        }

        g_strfreev (lines);
    }
}
Ejemplo n.º 22
0
/**
 * USE: Provide sample points and how many to setup_hough() transformation and plot those points
 * using plot_point() with each index of points you want to convert. The use print_classifier()
 * or get_lines() to see the lines extracted.
 */
int main(int argc, char **argv) {

	// Get points from image
	SIZE_TYPE size;
	POINT_TYPE *points = NULL;
	sizep_t count = get_points("sample_small.bmp", &points, &size);

	/*
	 *  points 		: Array of points
	 *  num_points	: Number of points in the array
	 *  threshold	: Threshold to consider line intersection
	 *  tolerance_t	: Tolerance (in grades) to consider two lines are the same
	 *  tolerance_r	: Distance (in pixels) to consider two lines are the same
	 *  precision	: Precision for degrees (10 = decimals, 100 = cents...)
	 *  size		: Size of the image
	 *  max_lines	: Lines to look for (value -1 falls back to 500)
	 */
	clock_t cp = clock();
	setup_hough(points, count, 12, 15.0, 5.0, 1, size, 10000);

	// Plot every point and measure clock ticks
	int n;
	for (n=0; n<_num_points; n++) {
		plot_point(n);
	}
	printf("_plot_point() ticks: %.4f\n", ((double)(clock()-cp))/1000000l);
	print_accumulator("accumulator.bmp");
	print_classifier();//*/

	// Get lines from classifier
	LINE_TYPE *lines;
	sizep_t clines = get_lines(&lines);

	// Print lines
	print_lines("output.bmp", "sample.bmp", lines, clines, 10);
	print_lines("output_small.bmp", "sample_small.bmp", lines, clines, 1);

	// Free memory
	finish_hough();
	free(lines);
	free(points);
	printf("All clear!");

	return EXIT_SUCCESS;
}
Ejemplo n.º 23
0
static gmx_bool *bPhobics(int nres, char *resnm[])
{
    int       i, nb;
    char    **cb;
    gmx_bool *bb;

    nb = get_lines("phbres.dat", &cb);
    snew(bb, nres);

    for (i = 0; (i < nres); i++)
    {
        if (search_str(nb, cb, resnm[i]) != -1)
        {
            bb[i] = TRUE;
        }
    }
    return bb;
}
Ejemplo n.º 24
0
static uint8_t tick(void) {


	tetris_update();

	int lines = get_lines(0);
		
	if(lines > highscore)
	{
		flash_db_write(ADDR_TETRIS_HIGHSCORE,lines);
		highscore = lines;
	}
	fill_8x6(15,5, 3,0,0,0);
	draw_number_8x6(15,5, lines, 3, ' ' ,255,255,255);
	draw_text_8x6(5, 90, "Highscore",255,255,255);
	fill_8x6(5,100, 3,0,0,0);
	draw_number_8x6(5,100, highscore, 3, '0' ,255,255,255);

	return 0;
}
Ejemplo n.º 25
0
static pdfout_data *
parser_parse (fz_context *ctx, pdfout_parser *parse)
{
  parser *p = (parser *) parse;

  if (p->finished)
    pdfout_throw (ctx, "call to finished outline wysiwyg parser");
  p->finished = true;
  
  pdfout_data *lines = get_lines (ctx, p);
  if (pdfout_data_array_len (ctx, lines) == 0)
    return lines;
  
  pdfout_data *tokens = get_tokens (ctx, lines);
  pdfout_data *outline = token_parse(ctx, tokens);
  
  pdfout_data_drop (ctx, tokens);
  pdfout_data_drop (ctx, lines);

  return outline;
}
Ejemplo n.º 26
0
void read_interp_table(char * URL) 
{
	int npts=0, k=0;
	double hh, zz;
	char dummyline[2048];
	FILE * file=NULL;
	
	file = fopen(URL,"r");
	npts = get_lines(file);
	
		if(file==NULL)
		{
			fprintf(stderr,"%s %s \n", "\nError in read_interp_table(). Could not open file: ", URL );
			exit(0);
		}

		if(ThisTask==0) 
			fprintf(stdout, " Found VDE hubble table h(a) file, allocating memory ... \n");

		HubTable.npts   = npts;
		HubTable.a      = (double *) calloc(npts, sizeof(double));
		HubTable.hubble = (double *) calloc(npts, sizeof(double));

			for(k=0; k<npts; k++)
			{
				fgets(dummyline,2048,file);

					// VDE Table contains only z and H 
		        	sscanf(dummyline, "%lf %lf", &zz, &hh);
				HubTable.a[npts - k - 1] = 1./(1.+zz);
			
				//NOTE: we need to tabulate H^2 in order 
				//      to be consistent with the calls to getH_a()
			HubTable.hubble[npts - k - 1] = hh*hh; 
		}

	fclose(file);
}
Ejemplo n.º 27
0
void avim_group_impl::internal_loop_coroutine(boost::asio::yield_context yield_context)
{

	for(;!m_quitting;)
	{
		std::string sender, data;

		m_core.async_recvfrom(sender, data, yield_context);

		if(is_group_message(data))
		{
			if (group_message_get_sender(data) == sender)
			{
				// 转发
				recive_client_message(data);

				// 看是否能解码 group 消息
				if (!is_encrypted_message(data))
				{
					auto im = decode_im_message(data);

					std::vector<avim_msg> avmsg;

					for (const message::avim_message& im_item : im.impkt.avim())
					{
						avim_msg item;
						if (im_item.has_item_text())
						{
							item.text = im_item.item_text().text();
						}
						if (im_item.has_item_image())
						{
							item.image = im_item.item_image().image();
						}
						avmsg.push_back(item);
					}
					on_message(m_me_addr, im.sender, avmsg);
				}
			}
		}
        else if (is_control_message(data))
		{
			// 无非就是获取群列表嘛!
			std::string _sender;
			auto bufmsg = decode_control_message(data, _sender);

			if (bufmsg->GetTypeName() == "proto.group.list_request")
			{
				auto list_request= reinterpret_cast<proto::group::list_request*>(bufmsg.get());

				proto::group::list_response list_response;
				list_response.set_result(proto::group::list_response::OK);

				auto avs =  get_lines(m_groupdef);

				for ( auto a : avs )
					list_response.add_list()->assign(a);

				m_core.async_sendto(sender, encode_control_message(list_response), yield_context);
			}
		}
	}
}
Ejemplo n.º 28
0
static gint
line_numbers_expose (GtkWidget      *widget,
                     GdkEventExpose *event)
{
	GtkTextView *text_view;
	GdkWindow *win;
//	GtkStyle *style;
	PangoLayout *layout;
	PangoAttrList *alist;
	PangoAttribute *attr;
	GArray *numbers;
	GArray *pixels;
	gint y1, y2;
	gint count;
	gint layout_width;
	gint justify_width = 0;
	gint i;
//	gchar *str;
	gchar str [8];  /* we don't expect more than ten million lines */
	GdkGC *gc;
	gint height;
	
	if (line_number_visible){{{{{	// omit calculation
	
	text_view = GTK_TEXT_VIEW (widget);
	
	/* See if this expose is on the line numbers window */
/*	left_win = gtk_text_view_get_window (text_view,
	                                     GTK_TEXT_WINDOW_LEFT);
	right_win = gtk_text_view_get_window (text_view,
	                                      GTK_TEXT_WINDOW_RIGHT);
	
	if (event->window == left_win)
	{
		type = GTK_TEXT_WINDOW_LEFT;
		target = event->window;
	}
	else if (event->window == right_win)
	{
		type = GTK_TEXT_WINDOW_RIGHT;
		target = right_win;
	}
	else
		return FALSE;
*/	
	win = gtk_text_view_get_window (text_view,
	                                GTK_TEXT_WINDOW_LEFT);
	if (event->window != win)
		return FALSE;
	
//	style = gtk_style_copy (widget->style);
//	style = gtk_style_copy (gtk_widget_get_default_style());
	
	y1 = event->area.y;
	y2 = y1 + event->area.height;
	
	gtk_text_view_window_to_buffer_coords (text_view,
	                                       GTK_TEXT_WINDOW_LEFT,
	                                       0,
	                                       y1,
	                                       NULL,
	                                       &y1);
	
	gtk_text_view_window_to_buffer_coords (text_view,
	                                       GTK_TEXT_WINDOW_LEFT,
	                                       0,
	                                       y2,
	                                       NULL,
	                                       &y2);
	
	numbers = g_array_new (FALSE, FALSE, sizeof (gint));
	pixels = g_array_new (FALSE, FALSE, sizeof (gint));
	
	get_lines (text_view,
	           y1,
	           y2,
	           pixels,
	           numbers,
	           &count);
	
	/* a zero-lined document should display a "1"; we don't need to worry about
	scrolling effects of the text widget in this special case */
	
	if (count == 0)
	{
		gint y = 0;
		gint n = 0;
		count = 1;
		g_array_append_val (pixels, y);
		g_array_append_val (numbers, n);
	}
	
DV({g_print("Painting line numbers %d - %d\n",
			g_array_index(numbers, gint, 0),
			g_array_index(numbers, gint, count - 1));	});
	
	layout = gtk_widget_create_pango_layout (widget, "");
	
//	str = g_strdup_printf ("%d", gtk_text_buffer_get_line_count(text_view->buffer));
	g_snprintf (str, sizeof (str),
			"%d", MAX (99, gtk_text_buffer_get_line_count(text_view->buffer)));
	pango_layout_set_text (layout, str, -1);
//	g_free (str);
	
	pango_layout_get_pixel_size (layout, &layout_width, NULL);
	
	min_number_window_width = calculate_min_number_window_width(widget);
	if (layout_width > min_number_window_width)
		gtk_text_view_set_border_window_size (text_view,
			GTK_TEXT_WINDOW_LEFT, layout_width + margin + submargin);
	else {
//		if ((gtk_text_view_get_border_window_size (text_view, GTK_TEXT_WINDOW_LEFT) - 5) > layout_width) {
			gtk_text_view_set_border_window_size (text_view,
				GTK_TEXT_WINDOW_LEFT, min_number_window_width + margin + submargin);
//		}
		justify_width = min_number_window_width - layout_width;
	}
	
	pango_layout_set_width (layout, layout_width);
	pango_layout_set_alignment (layout, PANGO_ALIGN_RIGHT);
	
	alist = pango_attr_list_new();
	attr = pango_attr_foreground_new(
		widget->style->text_aa->red,
		widget->style->text_aa->green,
		widget->style->text_aa->blue);
	attr->start_index = 0;
	attr->end_index = G_MAXUINT;
	pango_attr_list_insert(alist, attr);
	pango_layout_set_attributes(layout, alist);
	pango_attr_list_unref(alist);
	
	/* Draw fully internationalized numbers! */
	
	i = 0;
	while (i < count)
	{
		gint pos;
		
		gtk_text_view_buffer_to_window_coords (text_view,
		                                       GTK_TEXT_WINDOW_LEFT,
		                                       0,
		                                       g_array_index (pixels, gint, i),
		                                       NULL,
		                                       &pos);
		
//		str = g_strdup_printf ("%d", g_array_index (numbers, gint, i) + 1);
		g_snprintf (str, sizeof (str),
				"%d", g_array_index (numbers, gint, i) + 1);
		
		pango_layout_set_text (layout, str, -1);
		
		gtk_paint_layout (widget->style,
		                  win,
		                  GTK_WIDGET_STATE (widget),
		                  FALSE,
		                  NULL,
		                  widget,
		                  NULL,
#if GTK_CHECK_VERSION(2, 6, 0)  // Is this solution???
		                  layout_width + justify_width + margin / 2 + 1,
#else
		                  layout_width + justify_width + margin / 2,
#endif
		                  pos,
		                  layout);
//		g_free (str);
		
		++i;
	}
	
	g_array_free (pixels, TRUE);
	g_array_free (numbers, TRUE);
	
	g_object_unref (G_OBJECT (layout));
//	g_object_ref (G_OBJECT (style));
	
	/* don't stop emission, need to draw children */
	
	}}}}}
Ejemplo n.º 29
0
int gmx_wheel(int argc, char *argv[])
{
    const char       *desc[] = {
        "[THISMODULE] plots a helical wheel representation of your sequence.",
        "The input sequence is in the [REF].dat[ref] file where the first line contains",
        "the number of residues and each consecutive line contains a residue "
        "name."
    };
    gmx_output_env_t *oenv;
    static real       rot0  = 0;
    static gmx_bool   bNum  = TRUE;
    static char      *title = NULL;
    static int        r0    = 1;
    t_pargs           pa [] = {
        { "-r0",  FALSE, etINT, {&r0},
          "The first residue number in the sequence" },
        { "-rot0", FALSE, etREAL, {&rot0},
          "Rotate around an angle initially (90 degrees makes sense)" },
        { "-T",   FALSE, etSTR, {&title},
          "Plot a title in the center of the wheel (must be shorter than 10 characters, or it will overwrite the wheel)" },
        { "-nn",  FALSE, etBOOL, {&bNum},
          "Toggle numbers" }
    };
    t_filenm          fnm[] = {
        { efDAT, "-f", NULL,  ffREAD  },
        { efEPS, "-o", NULL,  ffWRITE }
    };
#define NFILE asize(fnm)

    int    i, nres;
    char **resnm;

    if (!parse_common_args(&argc, argv, 0, NFILE, fnm, asize(pa), pa,
                           asize(desc), desc, 0, NULL, &oenv))
    {
        return 0;
    }

    for (i = 1; (i < argc); i++)
    {
        if (std::strcmp(argv[i], "-r0") == 0)
        {
            r0 = std::strtol(argv[++i], NULL, 10);
            fprintf(stderr, "First residue is %d\n", r0);
        }
        else if (std::strcmp(argv[i], "-rot0") == 0)
        {
            rot0 = strtod(argv[++i], NULL);
            fprintf(stderr, "Initial rotation is %g\n", rot0);
        }
        else if (std::strcmp(argv[i], "-T") == 0)
        {
            title = gmx_strdup(argv[++i]);
            fprintf(stderr, "Title will be '%s'\n", title);
        }
        else if (std::strcmp(argv[i], "-nn") == 0)
        {
            bNum = FALSE;
            fprintf(stderr, "No residue numbers\n");
        }
        else
        {
            gmx_fatal(FARGS, "Incorrect usage of option %s", argv[i]);
        }
    }

    nres = get_lines(ftp2fn(efDAT, NFILE, fnm), &resnm);
    if (bNum)
    {
        wheel(ftp2fn(efEPS, NFILE, fnm), nres, resnm, r0, rot0, title);
    }
    else
    {
        wheel2(ftp2fn(efEPS, NFILE, fnm), nres, resnm, rot0, title);
    }

    return 0;
}
Ejemplo n.º 30
0
// Wait for input from user, quit if recieved 'q' keypress
void Menu::get_keyboard_input() {
    while (! dying) {
        // Check if we need to resize window display
        if (is_term_resized(screen_lines, screen_cols)) {
            reframe_resized_window();
        }

        // Check if we need to update content (i.e. been longer than 5 seconds)
        std::chrono::steady_clock::time_point current_time = std::chrono::steady_clock::now();
        if (current_time > (last_update + std::chrono::seconds(5))) {
            get_lines();
        }

        // Update window display after each key press
        print_window();

        // This is blocking
        ch = getch();
        switch(ch) {
            case KEY_UP:
            case 'k':
                move_cursor_up();
                break;
            case KEY_DOWN:
            case 'j':
                move_cursor_down();
                break;
            case KEY_LEFT:
            case 'h':
                move_cursor_left();
                break;
            case KEY_RIGHT:
            case 'l':
                move_cursor_right();
                break;
            case 'q':
                endwin();
                dying = true;
                break;
            case KEY_PPAGE:
                handle_page_up();
                break;
            case KEY_NPAGE:
                handle_page_down();
                break;
            case KEY_HOME:
                handle_home();
                break;
            case KEY_END:
                handle_end();
                break;
            case KEY_ENTER:
            case 10:
            case 13:
                handle_enter_key();
                break;
            default:
                // Uncoded key, ignore
                break;
        }
    }
}