예제 #1
0
파일: main.c 프로젝트: Occams/PPP-2010-2011
int main(int argc, char **argv) {
	int option, steps = 365, delta = 1, body_count;
	char *input = "init.dat", *output = "result.dat";
	bool parallel = false, mpi = false, global_newton = false;
	long double start;
	long double px, py;
	imggen_info img_info;
	body *bodies = NULL;
	
	/* PBM default values */
	img_info.gen_img = false;
	img_info.img_steps = 1000;
	img_info.img_prefix = "PBM";
	img_info.offset = 2;
	img_info.width = 600;
	img_info.heigth = 600;
	
	/* Read cmdline params */
	while ((option = getopt(argc,argv,"phs:d:f:o:i:x:gmn")) != -1) {
		
		switch(option) {
		case 'p': parallel = true; break;
		case 's': steps = atoi(optarg); break;
		case 'd': delta = atoi(optarg); break;
		case 'f': input = optarg; break;
		case 'o': output = optarg; break;
		case 'i': img_info.img_prefix = optarg; break;
		case 'x': img_info.img_steps = atoi(optarg); break;
		case 'g': img_info.gen_img = true; break;
		case 'm': mpi = true; break;
		case 'n': global_newton = true; break;
		default:
			printhelp();
			return 1;
		}
	}
	
	/* Init MPI */
	MPI_Init(&argc, &argv);
	MPI_Comm_size(MPI_COMM_WORLD, &mpi_processors);
	MPI_Comm_rank(MPI_COMM_WORLD, &mpi_self);
	
	/* Validate params */
	if (steps < 0 || delta < 1 || img_info.img_steps < 1) {
		m_printf("Wrong parameter value! Will exit!\n Steps: %i | Delta: %i | Input Filepath: %s", steps, delta, input);
	}
	
	
	bodies = readBodies(fopen(input,"r"), &body_count);
	
	if (bodies == NULL) {
		m_printf("Error while reading input file %s. Will exit now!\n", input);
		MPI_Finalize();
		return 1;
	}
	
	/* Assert that all masses > 0 and any two particles do not share the same position */
	if (!examineBodies(bodies, body_count, &img_info.max_x, &img_info.max_y)) {
		m_printf("Error while reading input file %s. Some value are not permitted!\n", input);
		printBodies(bodies, body_count);
		MPI_Finalize();
		return 1;
	}
	
	totalImpulse(bodies, body_count, &px, &py);
	m_printf("Initial total impulse: px = %Le , py = %Le\n", px, py);
	MPI_Barrier(MPI_COMM_WORLD);
	start = seconds();
	
	if (parallel) {
		m_printf("PARALLEL\n");
		
		if (mpi) {
			m_printf("MPI+OMP\n");
			
			if (global_newton) {
				m_printf("GLOBAL NEWTON\n");
				solve_parallel_mpi_global_newton(bodies, body_count, steps, delta, img_info);
			} else {
				solve_parallel_mpi(bodies, body_count, steps, delta, img_info);
			}
		} else {
			m_printf("OMP\n");
			solve_parallel(bodies, body_count, steps, delta, img_info);
		}
	} else {
		m_printf("SEQUENTIAL\n");
		solve_sequential(bodies, body_count, steps, delta, img_info);
	}
	
	MPI_Barrier(MPI_COMM_WORLD);
	long double elapsed = seconds() - start;
	m_printf("Rate of interactions: %Lf\n", interactions(body_count, steps, elapsed));
	m_printf("Elapsed time: %Lf\n", elapsed);
	totalImpulse(bodies, body_count, &px, &py);
	m_printf("Resulting total impulse: px = %Le , py = %Le\n", px, py);
	
	/* Write result to file */
	FILE *f = fopen(output,"w");
	
	if (f == NULL) {
		m_printf("Error while opening output file %s.\n", output);
		MPI_Finalize();
		return 1;
	}
	
	writeBodies(f, bodies, body_count);
	
	MPI_Finalize();
	return 0;
}
예제 #2
0
파일: devip.c 프로젝트: Vykook/acme-sac
static long
ipwrite(Chan *ch, void *a, long n, vlong off)
{
	Conv *c;
	Proto *x;
	char *p;
	Cmdbuf *cb;
	Fs *f;

	f = ipfs[ch->dev];

	switch(TYPE(ch->qid)) {
	default:
		error(Eperm);
	case Qdata:
		x = f->p[PROTO(ch->qid)];
		c = x->conv[CONV(ch->qid)];
		if(c->sfd < 0)
			error(Ehungup);
		qlock(&c->wlock);
		if(waserror()){
			qunlock(&c->wlock);
			nexterror();
		}
		if(c->headers) {
			if(n < c->headers)
				error(Eshort);
			p = a;
			n = so_send(c->sfd, p + c->headers, n - c->headers, p, c->headers);
			if(n >= 0)
				n += c->headers;
		} else
			n = so_send(c->sfd, a, n, nil, 0);
		poperror();
		qunlock(&c->wlock);
		if(n < 0)
			oserror();
		break;
	case Qarp:
		return arpwrite(a, n);
	case Qndb:
		if(off > strlen(f->ndb))
			error(Eio);
		if(off+n >= sizeof(f->ndb)-1)
			error(Eio);
		memmove(f->ndb+off, a, n);
		f->ndb[off+n] = 0;
		f->ndbvers++;
		f->ndbmtime = seconds();
		break;
	case Qctl:
		x = f->p[PROTO(ch->qid)];
		c = x->conv[CONV(ch->qid)];
		cb = parsecmd(a, n);
		qlock(&c->l);
		if(waserror()){
			qunlock(&c->l);
			free(cb);
			nexterror();
		}
		if(cb->nf < 1)
			error("short control request");
		if(strcmp(cb->f[0], "connect") == 0)
			connectctlmsg(x, c, cb);
		else if(strcmp(cb->f[0], "announce") == 0)
			announcectlmsg(x, c, cb);
		else if(strcmp(cb->f[0], "bind") == 0)
			bindctlmsg(x, c, cb);
		else if(strcmp(cb->f[0], "ttl") == 0){
			/* ignored */
		} else if(strcmp(cb->f[0], "tos") == 0){
			/* ignored */
		} else if(strcmp(cb->f[0], "ignoreadvice") == 0){
			/* ignored */
		} else if(strcmp(cb->f[0], "headers4") == 0){
			if(c->p->stype != S_UDP)
				error(Enoctl);
			c->headers = OUdphdrlenv4;
		} else if(strcmp(cb->f[0], "oldheaders") == 0){
			if(c->p->stype != S_UDP)
				error(Enoctl);
			c->headers = OUdphdrlen;
		} else if(strcmp(cb->f[0], "headers") == 0){
			if(c->p->stype != S_UDP)
				error(Enoctl);
			c->headers = Udphdrlen;
		} else if(strcmp(cb->f[0], "hangup") == 0){
			if(c->p->stype != S_TCP)
				error(Enoctl);
			qunlock(&c->l);
			if(waserror()){
				qlock(&c->l);
				nexterror();
			}
			/* TO DO: check fd status if socket close/hangup interrupted */
			if(c->sfd >= 0 && so_hangup(c->sfd, 1) < 0)
				oserror();
			qlock(&c->l);
			poperror();
			c->sfd = -1;
			c->state = Hungup;
		} else if(strcmp(cb->f[0], "keepalive") == 0){
			if(c->p->stype != S_TCP)
				error(Enoctl);
			if(c->sfd < 0)
				error("not connected");
			so_keepalive(c->sfd, cb->nf>1? atoi(cb->f[1]): 0);
		} else
			error(Enoctl);
		poperror();
		qunlock(&c->l);
		free(cb);
		break;
	}
	return n;
}
예제 #3
0
int 
submain (
    struct vtx_data **graph,	/* data structure for graph */
    int nvtxs,		/* number of vertices in full graph */
    int nedges,		/* number of edges in graph */
    int using_vwgts,		/* are vertex weights being used? */
    int using_ewgts,		/* are edge weights being used? */
    int igeom,		/* geometry dimension if using inertial method */
    float **coords,		/* coordinates of vertices if used */
    char *outassignname,	/* name of assignment output file */
    char *outfilename,		/* in which to print output metrics */
    int *assignment,		/* set number of each vtx (length n) */
    double *goal,			/* desired sizes for each set */
    int architecture,		/* 0=> hypercube, d=> d-dimensional mesh */
    int ndims_tot,		/* total number hypercube dimensions */
    int mesh_dims[3],		/* extent of mesh in 3 directions */
    int global_method,	/* global partitioning algorithm */
    int local_method,		/* local partitioning algorithm */
    int rqi_flag,		/* use RQI/Symmlq eigensolver? */
    int vmax,			/* if so, how many vtxs to coarsen down to */
    int ndims,		/* number of eigenvectors (2^d sets) */
    double eigtol,		/* tolerance on eigenvectors */
    long seed			/* for random graph mutations */
)
{
    extern int ECHO;		/* controls output to file or screen */
    extern int CHECK_INPUT;	/* should I check input for correctness? */
    extern int SEQUENCE;	/* just generate spectal ordering? */
    extern int OUTPUT_ASSIGN;	/* print assignment to a file? */
    extern int OUTPUT_METRICS;	/* controls formatting of output */
    extern int PERTURB;		/* perturb matrix if quad/octasection? */
    extern int NSQRTS;		/* number of square roots to precompute */
    extern int KL_METRIC;	/* KL interset cost: 1=>cuts, 2=>hops */
    extern int LANCZOS_TYPE;	/* type of Lanczos to use */
    extern int REFINE_MAP;	/* use greedy strategy to improve mapping? */
    extern int REFINE_PARTITION;/* number of calls to pairwise_refine to make */
    extern int VERTEX_COVER;	/* use matching to reduce vertex separator? */
    extern int CONNECTED_DOMAINS;	/* force subdomain connectivity at end? */
    extern int INTERNAL_VERTICES;	/* greedily increase internal vtxs? */
    extern int DEBUG_INTERNAL;		/* debug code about force_internal? */
    extern int DEBUG_REFINE_PART;	/* debug code about refine_part? */
    extern int DEBUG_REFINE_MAP;	/* debug code about refine_map? */
    extern int DEBUG_MACH_PARAMS;	/* print out computed machine params? */
    extern int DEBUG_TRACE;	/* trace main execution path */
    extern int PRINT_HEADERS;	/* print section headings for output? */
    extern int TIME_KERNELS;	/* benchmark some numerical kernels? */
    extern double start_time;	/* time code was entered */
    extern double total_time;	/* (almost) total time spent in code */
    extern double check_input_time;	/* time spent checking input */
    extern double partition_time;	/* time spent partitioning graph */
    extern double kernel_time;	/* time spent benchmarking kernels */
    extern double count_time;	/* time spent evaluating the answer */
    extern double print_assign_time;	/* time spent writing output file */
    FILE     *outfile;		/* output file */
    struct vtx_data **graph2;	/* data structure for graph */
    int     hop_mtx[MAXSETS][MAXSETS];	/* between-set hop cost for KL */
    double   *vwsqrt;		/* sqrt of vertex weights (length nvtxs+1) */
    double    time, time1;	/* timing variables */
    char     *graphname, *geomname;	/* names of input files */
    char     *inassignname;	/* name of assignment input file */
    int       old_nsqrts;	/* old value of NSQRTS */
    int       append;		/* append output to existing file? */
    int       nsets;		/* number of sets created by each divide */
    int       nsets_tot;	/* total number of sets */
    int       bits;		/* used in computing hops */
    int       flag;		/* return code from check_input */
    int       old_perturb=0;	/* saves original pertubation flag */
    int       i, j, k;		/* loop counters */
    double    seconds();
    void      setrandom(long int seed);
    int       check_input(), refine_part();
    void      connect_enforce();
    void      setrandom(), makevwsqrt(), balance(), countup();
    void      force_internal(), sequence(), reflect_input();
    void      machine_params(), assign_out(), refine_map();
    void      time_out(), time_kernels(), strout();

    if (DEBUG_TRACE > 0) {
	printf("<Entering submain>\n");
    }

    /* First check all the input for consistency. */

    if (architecture == 1)
	mesh_dims[1] = mesh_dims[2] = 1;
    else if (architecture == 2)
	mesh_dims[2] = 1;
    
    /* Check for simple special case of 1 processor. */
    k = 0;
    if (architecture == 0)
      k = 1 << ndims_tot;
    else if (architecture > 0)
      k = mesh_dims[0] * mesh_dims[1] * mesh_dims[2];

    if (k == 1) {
	for (i = 1; i <= nvtxs; i++) assignment[i] = 0;

        if (OUTPUT_ASSIGN > 0 && outassignname != NULL) {
	    time1 = seconds();
	    assign_out(nvtxs, assignment, k, outassignname);
	    print_assign_time += seconds() - time1;
        }
	return(0);
    }

    graphname = Graph_File_Name;
    geomname = Geometry_File_Name;
    inassignname = Assign_In_File_Name;

    /* Turn of perturbation if using bisection */
    if (ndims == 1) {
        old_perturb = PERTURB;
	PERTURB = FALSE;
    }

    if (ECHO < 0 && outfilename != NULL) { /* Open output file */
	outfile = fopen(outfilename, "r");
	if (outfile != NULL) {
	    append = TRUE;
	    fclose(outfile);
	}
	else append = FALSE;
	outfile = fopen(outfilename, "a");
	if (append) {
	    fprintf(outfile, "\n------------------------------------------------\n\n");
	}
    }
    else {
	outfile = NULL;
    }

    Output_File = outfile;

    if (outfile != NULL && PRINT_HEADERS) {
        fprintf(outfile, "\n                    Chaco 2.0\n");
        fprintf(outfile, "          Sandia National Laboratories\n\n");
    }

    if (CHECK_INPUT) {		/* Check the input for inconsistencies. */
	time1 = seconds();

	flag = check_input(graph, nvtxs, nedges, igeom, coords,
			   graphname, assignment, goal,
			   architecture, ndims_tot, mesh_dims,
			   global_method, local_method, rqi_flag, &vmax, ndims,
			   eigtol);

	check_input_time += seconds() - time1;

	if (flag) {
	    strout("ERROR IN INPUT.\n");
	    return (1);
	}
    }

    if (ECHO != 0) {
	reflect_input(nvtxs, nedges, igeom, graphname, geomname,
		      inassignname, outassignname, outfilename,
		      architecture, ndims_tot, mesh_dims,
		      global_method, local_method, rqi_flag, vmax, ndims,
		      eigtol, seed, outfile);
    }

    if (PRINT_HEADERS) {
        printf("\n\nStarting to partition ...\n\n");
	if (Output_File != NULL ) {
            fprintf(Output_File,
	    "\n\nStarting to partition ... (residual, warning and error messages only)\n\n");
	}
    }

    time = seconds();

    /* Perform some one-time initializations. */
    setrandom(seed);
    machine_params(&DOUBLE_EPSILON, &DOUBLE_MAX);

    if (DEBUG_MACH_PARAMS > 0) {
	printf("Machine parameters:\n");
	printf("  DOUBLE_EPSILON = %e\n", DOUBLE_EPSILON);
	printf("  DOUBLE_MAX = %e\n", DOUBLE_MAX);
    }

    nsets = (1 << ndims);

    old_nsqrts = NSQRTS;
    if (nvtxs < NSQRTS && !using_vwgts) {
	NSQRTS = nvtxs;
    }
    SQRTS = smalloc_ret((NSQRTS + 1) * sizeof(double));
    if (SQRTS == NULL) {
	strout("ERROR: No space to allocate sqrts\n");
	return(1);
    }
    for (i = 1; i <= NSQRTS; i++)
	SQRTS[i] = sqrt((double) i);

    if (using_vwgts && (global_method == 1 || global_method == 2)) {
	vwsqrt = smalloc_ret((nvtxs + 1) * sizeof(double));
	if (vwsqrt == NULL) {
	    strout("ERROR: No space to allocate vwsqrt\n");
	    sfree(SQRTS);
	    NSQRTS = old_nsqrts;
	    return(1);
        }
	makevwsqrt(vwsqrt, graph, nvtxs);
    }
    else
	vwsqrt = NULL;

    if (TIME_KERNELS) {
	time1 = seconds();
	time_kernels(graph, nvtxs, vwsqrt);
	kernel_time += seconds() - time1;
    }

    if (SEQUENCE) {
	sequence(graph, nvtxs, nedges, using_ewgts, vwsqrt,
		 LANCZOS_TYPE, rqi_flag, vmax, eigtol);
	goto End_Label;
    }

    /* Initialize cost function for KL-spiff */
    if (global_method == 1 || local_method == 1) {
	for (i = 0; i < nsets; i++) {
	    hop_mtx[i][i] = 0;
	    for (j = 0; j < i; j++) {
		if (KL_METRIC == 2) {	/* Count hypercube hops */
		    hop_mtx[i][j] = 0;
		    bits = i ^ j;
		    while (bits) {
			if (bits & 1) {
			    ++hop_mtx[i][j];
			}
			bits >>= 1;
		    }
		}
		else if (KL_METRIC == 1) {	/* Count cut edges */
		    hop_mtx[i][j] = 1;
		}
		hop_mtx[j][i] = hop_mtx[i][j];
	    }
	}
예제 #4
0
bool TimeWithDate::operator<= (const TimeWithDate& t) const
{
	return year <= t.year || month <= t.month ||
		day <= t.day || seconds() <= t.seconds();
}
예제 #5
0
bool TimeWithDate::operator== (const TimeWithDate& t) const
{
	return year == t.year && month == t.month &&
		day == t.day && seconds() == t.seconds();
}
예제 #6
0
 /// same as seconds
 RAYTRACER_EXPORTS operator double() const { return seconds(); }
예제 #7
0
int main(int argc,char **argv)
{
   //cout << "Floorplanning Version:" << TIMESTAMP << endl;
   int times=10;
   char filename[80];
   char filename1[80];
   float init_temp=0.9,term_temp=0.3,temp_scale=0.9,cvg_r=0.98;
   int target_cost_A=-1;
   int target_cost_W=-1;
   if(argc<=1){
     printf("Usage: TCGs <filename> [times=%d] [hill_climb_stage=%d]\n",
           times, hill_climb_stage);
     printf("             [avg_ratio=%d]\n",avg_ratio);
     printf("             [inital-temp=%.2f] [terminal-temp=%.2f]\n",
	   init_temp, term_temp);
     printf("             [temp-scale=%.2f]  [convergence-ratio=%.2f\n",
	   temp_scale, cvg_r);
     return 0;
   }else{
     int argi=1;
     if(argi < argc) strcpy(filename,argv[argi++]);
     if(argi < argc) times=atoi(argv[argi++]);
     if(argi < argc) hill_climb_stage=atoi(argv[argi++]);
     if(argi < argc) avg_ratio=atof(argv[argi++]);
     if(argi < argc) target_cost_A=atoi(argv[argi++]); 
     if(argi < argc) target_cost_W=atoi(argv[argi++]); 
     if(argi < argc) init_temp=atof(argv[argi++]);
     if(argi < argc) term_temp=atof(argv[argi++]);
     if(argi < argc) temp_scale=atof(argv[argi++]);
     if(argi < argc) cvg_r=atof(argv[argi++]);
   }
   int area, wire;
   double time_s = seconds();

   Clo_Red_Graph fp;
   fp.read(filename);
   time_t t;
   srand((unsigned) time(&t));
   //fp.show_modules();
   //fp.init_square();
   fp.init();
   //fp.Test(); 
   SA_Floorplanning(fp,init_temp,temp_scale, term_temp,cvg_r,times);
   area=fp.getArea();     
   wire=fp.getWireLength(); 
   cout<<"Area="<< fp.getArea()<<endl;
   cout<<"Wire="<<fp.getWireLength()<<endl;
   time_s = seconds()-time_s;
   strcat(filename, "_final");
   strcpy(filename1, filename);
   if((area<=target_cost_A)&&(wire<=target_cost_W)){
      save_rect_line(filename1, fp, time_s);
   }
   
//   { //log performance and quality
     FILE *fs= fopen(strcat(filename,".res"),"a+");
     //cpu_time area times avg_ratio hill_climb_stage init_temp temp_scale
     fprintf(fs,"%.1f %d %d %d %d %d %.2f %.2f\n",time_s, area, wire, times, 
      hill_climb_stage, int(avg_ratio), init_temp, temp_scale);
     fclose(fs);
//   }
   return 1;
}
예제 #8
0
void 
inertial3d (
    struct vtx_data **graph,	/* graph data structure */
    int nvtxs,		/* number of vtxs in graph */
    int cube_or_mesh,		/* 0 => hypercube, d => d-dimensional mesh */
    int nsets,		/* number of sets to divide into */
    float *x,
    float *y,
    float *z,		/* x, y and z coordinates of vertices */
    int *sets,			/* set each vertex gets assigned to */
    double *goal,			/* desired set sizes */
    int using_vwgts		/* are vertex weights being used? */
)
{
    extern int DEBUG_INERTIAL;	/* debug flag for inertial method */
    extern double inertial_axis_time;	/* time spent computing inertial axis */
    extern double median_time;	/* time spent finding medians */
    double    tensor[3][3];	/* inertia tensor */
    double    evec[3];		/* eigenvector */
    double   *value;		/* values along selected direction to sort */
    double    xcm, ycm, zcm;	/* center of mass in each direction */
    double    xx, yy, zz;	/* elements of inertial tensor */
    double    xy, xz, yz;	/* elements of inertial tensor */
    double    xdif, ydif;	/* deviation from center of mass */
    double    zdif;		/* deviation from center of mass */
    double    eval, res;	/* eigenvalue and error in eval calculation */
    double    vwgt_sum;		/* sum of all the vertex weights */
    double    time;		/* timing parameter */
    int      *space;		/* space required by median routine */
    int       i;		/* loop counter */
    double    seconds();

    void      ch_eigenvec3(), ch_evals3(), rec_median_1();

    /* Compute center of mass and total mass. */
    time = seconds();
    xcm = ycm = zcm = 0.0;
    if (using_vwgts) {
	vwgt_sum = 0;
	for (i = 1; i <= nvtxs; i++) {
	    vwgt_sum += graph[i]->vwgt;
	    xcm += graph[i]->vwgt * x[i];
	    ycm += graph[i]->vwgt * y[i];
	    zcm += graph[i]->vwgt * z[i];
	}
    }
    else {
	vwgt_sum = nvtxs;
	for (i = 1; i <= nvtxs; i++) {
	    xcm += x[i];
	    ycm += y[i];
	    zcm += z[i];
	}
    }

    xcm /= vwgt_sum;
    ycm /= vwgt_sum;
    zcm /= vwgt_sum;

    /* Generate 6 elements of Inertial tensor. */
    xx = yy = zz = xy = xz = yz = 0.0;
    if (using_vwgts) {
	for (i = 1; i <= nvtxs; i++) {
	    xdif = x[i] - xcm;
	    ydif = y[i] - ycm;
	    zdif = z[i] - zcm;
	    xx += graph[i]->vwgt * xdif * xdif;
	    yy += graph[i]->vwgt * ydif * ydif;
	    zz += graph[i]->vwgt * zdif * zdif;
	    xy += graph[i]->vwgt * xdif * ydif;
	    xz += graph[i]->vwgt * xdif * zdif;
	    yz += graph[i]->vwgt * ydif * zdif;
	}
    }
    else {
	for (i = 1; i <= nvtxs; i++) {
	    xdif = x[i] - xcm;
	    ydif = y[i] - ycm;
	    zdif = z[i] - zcm;
	    xx += xdif * xdif;
	    yy += ydif * ydif;
	    zz += zdif * zdif;
	    xy += xdif * ydif;
	    xz += xdif * zdif;
	    yz += ydif * zdif;
	}
    }

    /* Compute eigenvector with maximum eigenvalue. */

    tensor[0][0] = xx;
    tensor[1][1] = yy;
    tensor[2][2] = zz;
    tensor[0][1] = tensor[1][0] = xy;
    tensor[0][2] = tensor[2][0] = xz;
    tensor[1][2] = tensor[2][1] = yz;
    ch_evals3(tensor, &res, &res, &eval);
    ch_eigenvec3(tensor, eval, evec, &res);

    inertial_axis_time += seconds() - time;

    if (DEBUG_INERTIAL > 0) {
	printf("Principle Axis = (%g, %g, %g)\n  Eval=%g, Residual=%e\n",
	       evec[0], evec[1], evec[2], eval, res);
    }

    /* Allocate space for value array. */

    value = smalloc((nvtxs + 1) * sizeof(double));

    /* Calculate value to sort/split on for each cell. */
    /* This is inner product with eigenvector. */
    for (i = 1; i <= nvtxs; i++) {
	value[i] = (x[i] - xcm) * evec[0] + (y[i] - ycm) * evec[1] + (z[i] - zcm) * evec[2];
    }

    /* Now find the median value and partition based upon it. */
    space = smalloc(nvtxs * sizeof(int));
    time = seconds();
    rec_median_1(graph, value, nvtxs, space, cube_or_mesh, nsets, goal,
		 using_vwgts, sets, TRUE);
    median_time += seconds() - time;

    sfree(space);
    sfree(value);
}
예제 #9
0
파일: log.cpp 프로젝트: CasparCG/Server
void append_timestamp(Stream& stream, boost::posix_time::ptime timestamp)
{
    auto date         = timestamp.date();
    auto time         = timestamp.time_of_day();
    auto milliseconds = time.fractional_seconds() / 1000; // microseconds to milliseconds

    std::wstringstream buffer;

    buffer << std::setfill(L'0') << L"[" << std::setw(4) << date.year() << L"-" << std::setw(2)
           << date.month().as_number() << "-" << std::setw(2) << date.day().as_number() << L" " << std::setw(2)
           << time.hours() << L":" << std::setw(2) << time.minutes() << L":" << std::setw(2) << time.seconds() << L"."
           << std::setw(3) << milliseconds << L"] ";

    stream << buffer.str();
}
예제 #10
0
ChartDVBasics::ChartDVBasics(void) 
  : m_dvChart(),
  m_bfTrades( 10 ),
  m_bfBuys( 10 ),
  m_bfSells( 10 ),
  m_bFirstTrade( true ),
  m_rtTickDiffs( m_pricesTickDiffs, seconds( 120 ) ),
  m_rocTickDiffs( m_pricesTickDiffsROC, seconds( 30 ) ),
  m_dblUpTicks( 0.0 ), m_dblMdTicks( 0.0 ), m_dblDnTicks( 0.0 ),
  m_dblUpVolume( 0.0 ), m_dblMdVolume( 0.0 ), m_dblDnVolume( 0.0 ),
  m_ceShortEntries( ou::ChartEntryShape::EShort, ou::Colour::Red ),
  m_ceLongEntries( ou::ChartEntryShape::ELong, ou::Colour::Blue ),
  m_ceShortFills( ou::ChartEntryShape::EFillShort, ou::Colour::Red ),
  m_ceLongFills( ou::ChartEntryShape::EFillLong, ou::Colour::Blue ),
  m_ceShortExits( ou::ChartEntryShape::EShortStop, ou::Colour::Red ),
  m_ceLongExits( ou::ChartEntryShape::ELongStop, ou::Colour::Blue )

{

  m_vInfoBollinger.push_back( infoBollinger( m_quotes, boost::posix_time::seconds(  144 ) ) );
  m_vInfoBollinger.push_back( infoBollinger( m_quotes, boost::posix_time::seconds(  377 ) ) );
  m_vInfoBollinger.push_back( infoBollinger( m_quotes, boost::posix_time::seconds(  987 ) ) );
  m_vInfoBollinger.push_back( infoBollinger( m_quotes, boost::posix_time::seconds( 2584 ) ) );

  m_vInfoBollinger[0].SetProperties( ou::Colour::DarkOliveGreen, "Bollinger1 - 2.4" );
  m_vInfoBollinger[1].SetProperties( ou::Colour::Turquoise, "Bollinger2 - 6.3" );
  m_vInfoBollinger[2].SetProperties( ou::Colour::GreenYellow, "Bollinger3 - 16.5" );
  m_vInfoBollinger[3].SetProperties( ou::Colour::MediumSlateBlue, "Bollinger4 - 54.0" );

  m_dvChart.Add( 0, &m_ceQuoteUpper );
  m_dvChart.Add( 0, &m_ceQuoteLower );
  m_dvChart.Add( 0, &m_ceTrade );
  m_dvChart.Add( 2, &m_ceQuoteSpread );

  m_dvChart.Add( 0, &m_ceShortEntries );
  m_dvChart.Add( 0, &m_ceLongEntries );
  m_dvChart.Add( 0, &m_ceShortFills );
  m_dvChart.Add( 0, &m_ceLongFills );
  m_dvChart.Add( 0, &m_ceShortExits );
  m_dvChart.Add( 0, &m_ceLongExits );

  std::for_each(
    m_vInfoBollinger.begin(), m_vInfoBollinger.end(),
    [this](infoBollinger& ib){
      m_dvChart.Add( 0, &ib.m_ceEma );
      m_dvChart.Add( 0, &ib.m_ceUpperBollinger );
      m_dvChart.Add( 0, &ib.m_ceLowerBollinger );
    //m_dvChart.Add( 5, &ib.m_ceRatio );
// 2018/07/02 TODO: conditional include at some point
//    m_dvChart.Add( 6, &ib.m_ceSlope );
//    m_dvChart.Add( 7, &ib.m_ceSlopeBy2 );
//    m_dvChart.Add( 8, &ib.m_ceSlopeBy3 );
    });

//  m_cemRatio.AddMark(  2.0, ou::Colour::Black, "+2sd" );
//  m_cemRatio.AddMark(  0.0, ou::Colour::Black, "" );//"zero" );
//  m_cemRatio.AddMark( -2.0, ou::Colour::Black, "-2sd" );
//  m_dvChart.Add( 5, &m_cemRatio );

  m_cemSlope.AddMark( 0.0, ou::Colour::Black, "" ); //"zero" );
//  m_dvChart.Add( 6, &m_cemSlope )

  m_cemSlopeBy2.AddMark( 0.0, ou::Colour::Black, "" ); //"zero" );
//  m_dvChart.Add( 7, &m_cemSlopeBy2 );

  m_cemSlopeBy3.AddMark( 0.0, ou::Colour::Black, "" ); //"zero" );
//  m_dvChart.Add( 8, &m_cemSlopeBy3 );

  m_dvChart.Add( 0, &m_ceBars );

  m_dvChart.Add( 1, &m_rVolumes[ VUp ].ceVolumeUp );
  m_dvChart.Add( 1, &m_rVolumes[ VUp ].ceVolumeNeutral );
  m_dvChart.Add( 1, &m_rVolumes[ VUp ].ceVolumeDn );
  m_dvChart.Add( 1, &m_rVolumes[ VDn ].ceVolumeUp );
  m_dvChart.Add( 1, &m_rVolumes[ VDn ].ceVolumeNeutral );
  m_dvChart.Add( 1, &m_rVolumes[ VDn ].ceVolumeDn );

  m_ceQuoteUpper.SetColour( ou::Colour::Red );
  m_ceQuoteLower.SetColour( ou::Colour::Blue );
  m_ceTrade.SetColour( ou::Colour::DarkGreen );
  m_ceQuoteSpread.SetColour( ou::Colour::Black );

  m_ceQuoteSpread.SetName( "Spread" );
  //m_ceQuoteUpper.SetName( "QuoteUpper" );
  //m_ceQuoteLower.SetName( "QuoteLower" );
  //m_ceTrade.SetName( "Trade" );

  m_rVolumes[ VUp ].ceVolumeUp.SetColour( ou::Colour::Green );
  m_rVolumes[ VUp ].ceVolumeNeutral.SetColour( ou::Colour::Yellow );
  m_rVolumes[ VUp ].ceVolumeDn.SetColour( ou::Colour::Red );
  m_rVolumes[ VDn ].ceVolumeUp.SetColour( ou::Colour::Green );
  m_rVolumes[ VDn ].ceVolumeNeutral.SetColour( ou::Colour::Yellow );
  m_rVolumes[ VDn ].ceVolumeDn.SetColour( ou::Colour::Red );

  m_ceZigZag.SetColour( ou::Colour::DarkBlue );

  m_bfTrades.SetOnBarComplete( MakeDelegate( this, &ChartDVBasics::HandleBarCompletionTrades ) );
  m_bfBuys.SetOnBarComplete( MakeDelegate( this, &ChartDVBasics::HandleBarCompletionBuys ) );
  m_bfSells.SetOnBarComplete( MakeDelegate( this, &ChartDVBasics::HandleBarCompletionSells ) );

  m_zigzagPrice.SetOnPeakFound( MakeDelegate( this, &ChartDVBasics::HandleZigZagPeak ) );
  m_zigzagPrice.SetUpDecisionPointFound( MakeDelegate( this, &ChartDVBasics::HandleZigZagUpDp ) );
  m_zigzagPrice.SetDnDecisionPointFound( MakeDelegate( this, &ChartDVBasics::HandleZigZagDnDp ) );
}
예제 #11
0
파일: test.c 프로젝트: lijian8/thnets
int main(int argc, char **argv)
{
	THNETWORK *net;
	float *result;
	int i, n = 0, rc, outwidth, outheight, runs = 1, print = 0, alg = 1, nbatch = 1;
	const char *modelsdir = 0, *inputfile = 0;

	for(i = 1; i < argc; i++)
	{
		if(argv[i][0] != '-')
			continue;
		switch(argv[i][1])
		{
		case 'm':
			if(i+1 < argc)
				modelsdir = argv[++i];
			break;
		case 'i':
			if(i+1 < argc)
				inputfile = argv[++i];
			break;
		case 'a':
			if(i+1 < argc)
				alg = atoi(argv[++i]);
			break;
		case 'p':
			print = 1;
			break;
		case 'r':
			if(i+1 < argc)
				runs = atoi(argv[++i]);
			break;
		case 'b':
			if(i+1 < argc)
			{
				nbatch = atoi(argv[++i]);
				if(nbatch > 256 || nbatch < 1)
					nbatch = 256;
			}
			break;
		}
	}
	if(!modelsdir || !inputfile)
	{
		fprintf(stderr, "Syntax: test -m <models directory> -i <input file>\n");
		fprintf(stderr, "             [-r <number of runs] [-p(rint results)]\n");
		fprintf(stderr, "             [-a <alg=0:norm,1:MM (default),2:virtMM,3:cuDNN,4:cudNNhalf>]\n");
		fprintf(stderr, "             [-b <nbatch>]\n");
		return -1;
	}
	if(alg == 4)
	{
		alg = 3;
		THCudaHalfFloat(1);
	}
	THInit();
	net = THLoadNetwork(modelsdir);
	if(net)
	{
		THMakeSpatial(net);
		if(alg == 0)
			THUseSpatialConvolutionMM(net, 0);
		else if(alg == 1 || alg == 2)
			THUseSpatialConvolutionMM(net, alg);
		else if(alg == 3)
		{
			THNETWORK *net2 = THCreateCudaNetwork(net);
			if(!net2)
				THError("CUDA not compiled in");
			THFreeNetwork(net);
			net = net2;
		}
		if(strstr(inputfile, ".t7"))
		{
			struct thobject input_o;

			rc = loadtorch(inputfile, &input_o, 8);
			if(!rc)
			{
				THFloatTensor *in = THFloatTensor_newFromObject(&input_o);
				// In CuDNN the first one has to do some initializations, so don't count it for timing
				if(alg == 3)
					THProcessFloat(net, in->storage->data, 1, in->size[2], in->size[1], &result, &outwidth, &outheight);
				t = seconds();
				for(i = 0; i < runs; i++)
					n = THProcessFloat(net, in->storage->data, 1, in->size[2], in->size[1], &result, &outwidth, &outheight);
				t = (seconds() - t) / runs;
				THFloatTensor_free(in);
				freeobject(&input_o);
			} else printf("Error loading %s\n", inputfile);
		} else {
			img_t image;

			rc = loadimage(inputfile, &image);
			if(!rc)
			{
				unsigned char *bitmaps[256];
				for(i = 0; i < nbatch; i++)
					bitmaps[i] = image.bitmap;
				// In CuDNN the first one has to do some initializations, so don't count it for timing
				if(alg == 3)
					THProcessImages(net, &image.bitmap, 1, image.width, image.height, 3*image.width, &result, &outwidth, &outheight, 0);
				t = seconds();
				for(i = 0; i < runs; i++)
					n = THProcessImages(net, bitmaps, nbatch, image.width, image.height, 3*image.width, &result, &outwidth, &outheight, 0);
				t = (seconds() - t) / runs;
#ifdef USECUDAHOSTALLOC
				cudaFreeHost(image.bitmap);
#else
				free(image.bitmap);
#endif
			} else printf("Error loading image %s\n", inputfile);
		}
		if(print)
			for(i = 0; i < n; i++)
				printf("(%d,%d,%d): %f\n", i/(outwidth*outheight), i % (outwidth*outheight) / outwidth, i % outwidth, result[i]);
		printf("1 run processing time: %lf\n", t);
        THFreeNetwork(net);
	} else printf("The network could not be loaded: %d\n", THLastError());
#ifdef MEMORYDEBUG
	debug_memorydump(stderr);
#endif
	return 0;
}
예제 #12
0
int main()
{
	//wait_for_light(1);//initialization
	printf("version 1.9.5\n");
	shut_down_in(115);
	
	
	int servo_counter=0;
	while(servo_counter<=3){
		enable_servo(servo_counter);
		servo_counter++;
	}
	//	initialize routine
	set_servo_position(0,2047);
	armUp();
	clawClose();
	//get in front of transport

	straight(1.8,  170);
	rightC(0.28, 100);
	leftC(0.28, -100);
	straight(1.65, 170);
	leftC(0.44, 100);
	printf("completed first dead reckoning\n");
	
	
	//until distance is 5 centimeter
	/*
	int claw_threshold = 13;
	while(analog10(ETport)>claw_threshold){
		back(0.1, -10);
		msleep(1000);
		printf("move once\n");
		printf("%i\n", analog10(ETport));
	}*/
	back(0.25, -20);//pushes against transport
	msleep(2000);
	set_servo_position(0, 500);//puts claw on transport
	msleep(1000);
	printf("done with attaching to transport\n");
	while(digital(8)==0)//goes forward with transport until it hits the wall
	{
		straight(0.1, 100);
		msleep(10);
	}
	printf("at wall\n");
	back(0.15, -50);//backs  up from wall to deposit transport
	set_servo_position(0, 2047);//raises claw
	msleep(1500);
	while(digital(8)==0){//goes forward until it hits wall for second time
		straight(0.1, 100);
		msleep(10);
	}
	
	printf("at wall 2\n");
	
	back(0.35, -100);//goes back and turns left in order to be oriented with left inner wall
	leftC(0.6, 142);
	
	int bump_counter=0;	
	
	while(digital(8)==0){//hits side wall
		straight(0.1, 100);
		msleep(10);
	}
	
	bump_counter++;//has one bump


    int i=0;
    while(i<10){//if hits side wall, pause
		stop(0.2);
		i++;
	}
	
	/*
	==========================
	==========End of routine 1======
	KIPR at the wall
	==========================
	*/
	// Pause here to wait for Create to drop POMS
	
	msleep(1*1000);
	//
	int start=seconds();//  start time
	
	printf("will get out of corner\n");
	
	back(0.5, -100);
	
	while(seconds()-start<=3){//separates back from right angle
		stop(0.1);
	}
	
	right_angle(left);
	
	while(seconds()-start<=5){//separates right angle from straight
		stop(0.1);
	}
	
	double start_drive=seconds();
	
	straight(0.7, 100);//go to poms
	
	
	stop(0.5);
	
	camera_open(LOW_RES);
	
	
	
	/*while(seconds()-start<=20){
		int update_counter=0;
		while(update_counter<10){
			camera_update();
			update_counter++;
		}
		if(get_object_count(chan)==0){
			stop(0.1);
		}
		int x=get_object_center(chan, 0).x;
		int area=get_object_area(chan, 0);	
		if(area<=400){
			navigate(x);
		}
		if(area>=800){
			//if objects are clumped are clumped, area will be automatically larger.
			//this means that KIPR will start earlier than it should. We counter this here
			//straight(0.18, 100);
			straight(0.1, 100);
			break;
		}
	
	}*/
	
	stop(0.1);
	
	printf("object seen\n");

	double end_drive=seconds();//only for simulation. real end and start times would have to be taken from whole routine
	//pick up POMS that are right there
	pickup();
	int offset=(end_drive-start_drive)*(3.0/4.0);;//half of distance from back of launch area to border of launch area
	back((end_drive-start_drive)+1.5,  -100);//go to the back of wall plus a little more to straighten out
	printf("at back wall\n");
	straight(2.0, 100);//goes halway between border and back of launch area
	right_angle(left);//faces transport
	int starpof=seconds();//time after right angle
	while(seconds()-starpof<=2){
		motor(motorL, 0);
		motor(motorR, 0);
	}
	while(digital(8)==0){
		straight(0.1, 100);
	}
	straight(0.1, 100);
	
	printf("touching transport\n");
	
	motor(motorL, 0);
	motor(motorR, 0);
	
	dropoff();//drops poms in launch area
	
	printf("poms in transport\n");
	
	back(0.25, -100);
	int starfop=seconds();
	while(seconds()-starfop<=2){
		motor(motorL, 0);
		motor(motorR, 0);
	}
	int turns=1;
	while(turns<=2){
		right_angle(right);
		stop(0.3);
		turns++;
	}
	

	
	
	/*
	======================
	======Part 2 of routine 2====
	======================
	*/
	while(1){

		stop(0.5);//
		
		while(digital(8)==0){
			straight(0.1, 100);
		}
		back(0.3, -100);
		right_angle(left);
		pickup();
		back((end_drive-start_drive)+1.5, -100);
		straight(2.2, 100);
		right_angle(left);
		while(digital(8)==0){
			straight(0.1, 100);
		}
		dropoff();
		back(0.5, -100);
		right_angle(left);
		right_angle(left);
	}
	
	
	/*while(1){
	
		start=0;
		while(digital(8)==0){
			straight(0.1, 80);
        }
		back(0.5, -100);
		right_angle(right);
		straight(0.5, 100);
		right_angle(right);
		right_angle(right);
		
		while(seconds()-start<=20){
			int update_counter=0;
			while(update_counter<10){
				camera_update();
				update_counter++;
			}
			if(get_object_count(chan)==0){
				stop(0.1);
			}
			int x=get_object_center(chan, 0).x;
			int area=get_object_area(chan, 0);	
			if(area<=400){
				navigate(x);
			}
			if(area>=800){
				//if objects are clumped are clumped, area will be automatically larger.
				//this means that KIPR will start earlier than it should. We counter this here
				//straight(0.18, 100);
				straight(0.1, 100);
				break;
			}
		}
		int servo_counter=1;
	while(servo_counter<=3){
		enable_servo(servo_counter);
		printf("servo %d enabled\n", servo_counter);
		servo_counter++;
	}
	pickup();
	int offset=(end_drive-start_drive)*(3.0/4.0);;//half of distance from back of launch area to border of launch area
	back((end_drive-start_drive)+1.5,  -100);//go to the back of wall plus a little more to straighten out
	printf("at back wall\n");
	straight(1.8, 100);//goes halway between border and back of launch area
	right_angle(left);//faces transport
	int starpof=seconds();//time after right angle
	while(seconds()-starpof<=2){
		motor(motorL, 0);
		motor(motorR, 0);
	}
	while(digital(8)==0){
		straight(0.1, 100);
	}
	straight(0.1, 100);
	
	printf("touching transport\n");
	
	motor(motorL, 0);
	motor(motorR, 0);
	
	dropoff();//drops poms in launch area
	
	printf("poms in transport\n");
	
	back(0.25, -100);
	int starfop=seconds();
	while(seconds()-starfop<=2){
		motor(motorL, 0);
		motor(motorR, 0);
	}
	int turns=1;
	while(turns<=2){
		right_angle(right);
		turns++;
	}
		
	
		repeat_runs++;
		
    }*/
	
	while(1){
		
		int servo_counter=0;//enables servos
		while(servo_counter<=3){
			enable_servo(servo_counter);
			servo_counter++;
		}
		armUp();//raises arm at start

		stop(0.5);
		
		while(digital(TOUCH_SENSOR)==0){//go forward until left wall is contacted
			straight(0.1, 100);
		}
		stop(0.1);
		back(0.3, -100);//back up
		stop(0.1);
		right_angle2(left);//face poms
		stop(0.1);
		back(3+1.5, -100);//back up to rocket wall to straighten out
		stop(0.1);
		straight(3+1.5, 100);//go to poms
		stop(0.1);
		pickup();//pick poms up
		stop(0.1);
		back(3+1.5, -100);// back up until rocket wall
		stop(0.1);
		straight(2.2, 100);//go forward
		stop(0.1);
		right_angle2(left);//turn to face transport
		stop(0.1);
		while(digital(TOUCH_SENSOR)==0){//go forward until transport contacted
			straight(0.1, 100);
		}
		stop(0.1);
		dropoff();//drop poms off
		stop(0.1);
		back(0.5, -100);//back up from transpor
		stop(0.1);
		right_angle2(right);//orient for next iteration
		stop(0.1);
		right_angle2(right);
	}
	
	return 0;
}
예제 #13
0
int main()
{
	int m1=0,m2=3,pageno=0;
	double createDriveTime;
	printf("Start!\n");
	extra_buttons_show();
	while (1)
	{
		while (pageno == 0)
		{
			set_a_button_text("Forward");
			set_b_button_text("Backward");
			set_c_button_text("All Off");
			set_x_button_text("OpenHand");
			set_y_button_text("CloseHand");
			set_z_button_text("Create Page");
			
			if (a_button_clicked())
			{
				printf("Moving forward...\n");
				motor(m1,100);
				motor(m2,100);
				while (!c_button_clicked())
				{
					msleep(1);
				}
				ao();
			}
			if (b_button_clicked())
			{
				printf("Moving backward...\n");
				motor(m1,-100);
				motor(m2,-100);
				while (!c_button_clicked())
				{
					msleep(1);
				}
				ao();
			}
			if (x_button_clicked())
			{
				enable_servo(3);
				set_servo_position(3,0);
				msleep(300);
				disable_servo(3);
			}
			if (y_button_clicked())
			{
				enable_servo(3);
				set_servo_position(3,1300);
				msleep(300);
				disable_servo(3);
			}
			if (z_button_clicked())
			{
				pageno=1;
				create_connect();
			}
		}

		while (pageno == 1)
		{
			set_a_button_text("Create Fwd");
			set_b_button_text("Create Bwd");
			set_c_button_text("Stop");
			set_x_button_text("Turn R");
			set_y_button_text("Turn L");
			set_z_button_text("M S Page");
			
			if (a_button_clicked())
			{
				createDriveTime = 0;
				printf("Create Moving forward w/ spd 100...\n");
				create_drive_straight(100);
				createDriveTime = seconds();
				while (!c_button_clicked())
				{
					msleep(1);
				}
				create_stop();
				printf("Time: %f seconds\n",seconds() - createDriveTime );
			}
			if (b_button_clicked())
			{
				createDriveTime = 0;
				printf("Create Moving backward w/ spd 100...\n");
				create_drive_straight(-100);
				createDriveTime = seconds();
				while (!c_button_clicked())
				{
					msleep(1);
				}
				create_stop();
				printf("Time: %f seconds\n",seconds() - createDriveTime );
			}
			if (x_button_clicked())
			{
				create_drive(-50,0);
				while (!c_button_clicked())
				{
					msleep(1);
				}
				create_stop();
			}
			if (y_button_clicked())
			{
				create_drive(50,0);
				while (!c_button_clicked())
				{
					msleep(1);
				}
				create_stop();
			}
			if (z_button_clicked())
			{
				pageno=0;
				create_disconnect();
			}
		}
	}
	
	return 0;
}
예제 #14
0
const int PIECE_SIZE = 1350;//(1350/188)*188;//piece��С
const int CHUNK_SIZE = ((4 * 1024 * 1024) / PIECE_SIZE)*PIECE_SIZE;//chunk��С
const int PIECE_COUNT_PER_CHUNK = CHUNK_SIZE / PIECE_SIZE;

const int PLAYING_POINT_SLOT_DURATION = 15000;//��̬ʱ������ϵ�£��ڵ㶨λ�۳�

const int FLOOD_OUT_EDGE = 3;//flood ��Ϣ�ij���

const int MAX_DELAY_GUARANTEE = 60000;//msec
const int MIN_DELAY_GUARANTEE = 500;//��С�ӳٱ�֤
const int MAX_BACKFETCH_CNT = 2000;

const int MAX_SUPPORT_BPS = 4 * 1024 * 1024;//Ԥ��֧�ֵ�������ʣ�4Mbit
const int MAX_PKT_BUFFER_SIZE = 32 * 1024;//packet buffer�洢�����packet����

const time_duration HUB_PEER_PEER_PING_INTERVAL = seconds(65);

//////////////////////////////////////////////////////////////////////////
//
const time_duration TRACKER_PEER_PING_INTERVAL = seconds(600);
const time_duration MEMBER_TABLE_EXCHANGE_INTERVAL = seconds(60);
const time_duration SERVER_SEED_PING_INTERVAL = seconds(6);

const int SEED_PEER_CNT = 10000;
const int MIN_SUPER_SEED_PEER_CNT = 5;
const int STREAM_NEIGHTBOR_PEER_CNT = get_max_neighbor_cnt();
const int HUB_NEIGHTBOR_PEER_CNT = 3 + SUPERVISOR_CNT;

const int DEFAULT_BACK_FETCH_DURATION = 25 * 1000;
const int DEFAULT_DELAY_GUARANTEE = 5000;//Ĭ���ӳٱ�֤
const int MAX_PUSH_DELAY = 3500;//Ĭ����������ӳ�
예제 #15
0
void handle_motors() {
	if (step_state == 1)
		return;
	last_active = seconds();
	cli();
	uint8_t state = step_state;
	uint8_t cf = current_fragment;
	uint8_t cs = current_sample;
	sei();
	// Check probe.
	bool probed;
	if (settings[cf].flags & Settings::PROBING && probe_pin < NUM_DIGITAL_PINS) {
		if (state == 0) {
			if (GET(probe_pin) ^ bool(pin_flags & 2))
				stopping = active_motors;
			probed = true;
		}
		else
			probed = false;
	}
	else
		probed = true;	// If we didn't need to probe; don't block later on.
	if (stopping < 0) {
		// Check sensors.
		for (uint8_t m = 0; m < active_motors; ++m) {
			if (!(motor[m].intflags & Motor::ACTIVE))
				continue;
			//debug("check %d", m);
			// Check sense pins.
			if (motor[m].sense_pin < NUM_DIGITAL_PINS) {
				if (GET(motor[m].sense_pin) ^ bool(motor[m].flags & Motor::SENSE_STATE)) {
					//debug("sense %d %x", m, motor[m].flags);
					motor[m].flags ^= Motor::SENSE_STATE;
					motor[m].flags |= (motor[m].flags & Motor::SENSE_STATE ? Motor::SENSE1 : Motor::SENSE0);
					uint8_t sense_state = motor[m].flags & Motor::SENSE_STATE ? 1 : 0;
					cli();
					for (int mi = 0; mi < active_motors; ++mi)
						motor[mi].sense_pos[sense_state] = motor[mi].current_pos;
					sei();
				}
			}
			// Check limit switches.
			if (stopping < 0) {
				int8_t value = buffer[cf][m][cs];
				if (value == 0)
					continue;
				uint8_t limit_pin = value < 0 ? motor[m].limit_min_pin : motor[m].limit_max_pin;
				if (limit_pin < NUM_DIGITAL_PINS) {
					bool inverted = motor[m].flags & (value < 0 ? Motor::INVERT_LIMIT_MIN : Motor::INVERT_LIMIT_MAX);
					if (GET(limit_pin) ^ inverted) {
						debug("hit %d pos %d state %d sample %d", m, motor[m].current_pos, state, buffer[cf][m][cs]);
						stopping = m;
						motor[m].flags |= Motor::LIMIT;
						break;
					}
				}
			}
		}
	}
	if (stopping >= 0) {
		// Hit endstop or probe; disable timer interrupt.
		step_state = 1;
		//debug("hit limit %d curpos %ld cf %d ncf %d lf %d cfp %d", m, F(motor[m].current_pos), cf, notified_current_fragment, last_fragment, cs);
		// Notify host.
		limit_fragment_pos = cs;
		arch_set_speed(0);
		return;
	}
	if (homers > 0) {
		// Homing.
		if (state == 0) {
			probed = true;
			for (uint8_t m = 0; m < active_motors; ++m) {
				if (!(motor[m].intflags & Motor::ACTIVE))
					continue;
				// Get twe "wrong" limit pin for the given direction.
				uint8_t limit_pin = (buffer[cf][m][cs] < 0 ? motor[m].limit_max_pin : motor[m].limit_min_pin);
				bool inverted = motor[m].flags & (buffer[cf][m][cs] < 0 ? Motor::INVERT_LIMIT_MAX : Motor::INVERT_LIMIT_MIN);
				if (limit_pin >= NUM_DIGITAL_PINS || GET(limit_pin) ^ inverted) {
					// Limit pin still triggered; continue moving.
					continue;
				}
				// Limit pin no longer triggered.  Stop moving and possibly notify host.
				motor[m].intflags &= ~Motor::ACTIVE;
				if (!--homers) {
					arch_set_speed(0);
					return;
				}
			}
		}
		else
			probed = false;
	}
	if (state == 0 && probed) {
		if (homers > 0)
			current_sample = 0;	// Use only the first sample for homing.
		step_state = homers > 0 || (settings[cf].flags & Settings::PROBING) ? 2 : 3;
	}
}
예제 #16
0
bool PortMapping::UPnP::add(Protocol protocol, uint16_t internal, uint16_t &external)
{
	if(mControlUrl.empty()) return false;
	if(!external) external = 1024 + Random().readInt() % (49151 - 1024);

	unsigned duration = 3600;	// 1h
	unsigned attempts = 20;
	
	uint32_t gen = 0;
	for(int i=0; i<attempts; ++i)
	{
		Http::Request request(mControlUrl, "POST");
		
		String host;
		request.headers.get("Host", host);
		Socket sock(host, seconds(10.));
		Address localAddr = sock.getLocalAddress();
		
		String content = "<?xml version=\"1.0\"?>\r\n\
<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">\r\n\
<s:Body>\r\n\
<m:AddPortMapping xmlns:m=\"urn:schemas-upnp-org:service:WANIPConnection:1\">\r\n\
<NewRemoteHost></NewRemoteHost>\r\n\
<NewExternalPort>" + String::number(external) + "</NewExternalPort>\r\n\
<NewProtocol>"+(protocol == TCP ? String("TCP") : String("UDP"))+"</NewProtocol>\r\n\
<NewInternalPort>" + String::number(internal) + "</NewInternalPort>\r\n\
<NewInternalClient>"+Html::escape(localAddr.host())+"</NewInternalClient>\r\n\
<NewEnabled>1</NewEnabled>\r\n\
<NewPortMappingDescription>"+Html::escape(String(APPNAME))+"</NewPortMappingDescription>\r\n\
<NewLeaseDuration>"+String::number(duration)+"</NewLeaseDuration>\r\n\
</m:AddPortMapping>\r\n\
</s:Body>\r\n\
</s:Envelope>\r\n";

		request.headers["Content-Leng.hpp"] << content.size();
		request.headers["Content-Type"] = "text/xml; charset=\"utf-8\"";
		request.headers["Soapaction"] = "urn:schemas-upnp-org:service:WANIPConnection:1#AddPortMapping";

		request.send(&sock);
		sock.write(content);
		
		Http::Response response;
		response.recv(&sock);
		
		if(response.code == 200)
		{
			sock.clear();
			return true;
		}
		
		String result;
		Stream &stream = result;
		sock.read(stream);

		String strErrorCode = extract(result, "errorCode");
		if(strErrorCode.empty())
		{
			LogWarn("PortMapping::UPnP", String("AddPortMapping: Unknown error"));
			return false;
		}
		
		int errorCode = 0;
		strErrorCode.extract(errorCode);
	
		if(errorCode == 718)
		{
			// The port mapping entry specified conflicts with a object assigned previously to another client
			
			if(i == attempts-2)
			{
				// The device is probably bogus, and the object is actually assigned to us
				remove(protocol, internal, external); 
			}
			else {
				if(localAddr.isIpv4())
				{
					if(i == 0) gen = localAddr.host().dottedToInt(256) + external;	
					uint32_t rnd = gen = uint32_t(22695477*gen + 1); rnd = rnd >> 17;
					external = 1024 + rnd;
				}
				else {
					external = 1024 + Random().readInt() % (49151 - 1024);
				}
			}
			continue;
		}
		
		if(duration && errorCode == 725)
		{
			// The NAT implementation only supports permanent lease times on port mapping
			duration = 0;
			continue;
		}
		
		
		LogWarn("PortMapping::UPnP", String("AddPortMapping: Error code " + String::number(errorCode)));
		return false;
	}
예제 #17
0
 //! Function that converts a time_t into a ptime.
 inline
 ptime from_time_t(std::time_t t)
 {
   return ptime(gregorian::date(1970,1,1)) + seconds(static_cast<long>(t));
 }
예제 #18
0
Time SoundBuffer::getDuration() const
{
    return seconds(m_soundBuffer.getDuration().asSeconds());
}
예제 #19
0
std::string terrama2::core::DataStoragerTiff::replaceMask(const std::string& mask,
    std::shared_ptr<te::dt::DateTime> timestamp,
    terrama2::core::DataSetPtr dataSet) const
{
  if(!timestamp.get())
    return mask;

  long year = 0;
  long month = 0;
  long day = 0;
  long hour = 0;
  long minutes = 0;
  long seconds = 0;

  if(timestamp->getDateTimeType() == te::dt::TIME_INSTANT)
  {
    auto dateTime = std::dynamic_pointer_cast<te::dt::TimeInstant>(timestamp);
    //invalid date type
    if(dateTime->getTimeInstant().is_not_a_date_time())
      return mask;


    auto date = dateTime->getDate();
    year = date.getYear();
    month = date.getMonth().as_number();
    day = date.getDay().as_number();

    auto time = dateTime->getTime();
    hour = time.getHours();
    minutes = time.getMinutes();
    seconds = time.getSeconds();
  }
  else if(timestamp->getDateTimeType() == te::dt::TIME_INSTANT_TZ)
  {
    auto dateTime = std::dynamic_pointer_cast<te::dt::TimeInstantTZ>(timestamp);
    auto boostLocalTime = dateTime->getTimeInstantTZ();
    //invalid date type
    if(boostLocalTime.is_not_a_date_time())
      return mask;

    std::string timezone;
    try
    {
      //get dataset timezone
      timezone = getTimezone(dataSet);
    }
    catch(const terrama2::core::UndefinedTagException&)
    {
      //if no timezone is set use UTC
      timezone = "UTC+00";
    }

    boost::local_time::time_zone_ptr zone(new boost::local_time::posix_time_zone(timezone));
    auto localTime = boostLocalTime.local_time_in(zone);
    auto date = localTime.date();
    year = date.year();
    month = date.month().as_number();
    day = date.day();

    auto time = localTime.time_of_day();
    hour = time.hours();
    minutes = time.minutes();
    seconds = time.seconds();
  }
  else
  {
    //This method expects a valid Date/Time, other formats are not valid.
    QString errMsg = QObject::tr("Unknown date format.");
    TERRAMA2_LOG_ERROR() << errMsg;
    throw terrama2::core::DataAccessorException() << ErrorDescription(errMsg);
  }

  //replace wildcards in mask
  std::string fileName = mask;
  size_t pos = fileName.find("yyyy");
  if(pos != std::string::npos)
    fileName.replace(pos, 4, zeroPadNumber(year, 4));

  pos = fileName.find("yy");
  if(pos != std::string::npos)
    fileName.replace(pos, 2, zeroPadNumber(year, 2));

  pos = fileName.find("MM");
  if(pos != std::string::npos)
    fileName.replace(pos, 2, zeroPadNumber(month, 2));

  pos = fileName.find("dd");
  if(pos != std::string::npos)
    fileName.replace(pos, 2, zeroPadNumber(day, 2));

  pos = fileName.find("hh");
  if(pos != std::string::npos)
    fileName.replace(pos, 2, zeroPadNumber(hour, 2));

  pos = fileName.find("mm");
  if(pos != std::string::npos)
    fileName.replace(pos, 2, zeroPadNumber(minutes, 2));

  pos = fileName.find("ss");
  if(pos != std::string::npos)
    fileName.replace(pos, 2, zeroPadNumber(seconds, 2));

  //if no extension in the mask, add extension
  pos = fileName.find(".tif");
  if(pos != std::string::npos)
    fileName += ".tif";
  return fileName;
}
예제 #20
0
파일: minigate-1.c 프로젝트: rvcs/botball
int main()
{
	double start = 0.0;
	// initialize servo, camera, etc here?.
	// if you are using a Create you should uncomment the next line
	//create_connect();
	enable_servos ();
	set_servo_position(3, ARM_UP);
	
	int a1;
	int a2;
//goto START_DOWN_CAVE;
	
//lights
#if 0
	wait_for_light(2); // change the port number to match where your robot 

	shut_down_in(119); // shut off the motors and stop the Create after 119 seconds
	// note that shut_down_in should immediately follow wait_for_light!!

	printf("My program should score more points than this template!\n");
	// replace printf above with your code
#endif 
	//create_disconnect();
	
	
	
	
	//go forward to line follow
	motor(0,700);
	motor(2,700);
	msleep(1000);
	
	while ((a1 = analog(1)) <500 && (a2 = analog(3)) <500) {
		printf("%5d %5d\n",a1,a2);
		//msleep(5);
		if(seconds()-start>6.5){
			printf("time_out\n");
			break;
		}
	}
	printf("Found black %d\n", a1);

//
	//line follow
	start=seconds ();
	while(1){
		a1 =analog (1);
		a2 =analog (3);
		printf("cave%5d %5d\n",a1,a2);
		if(seconds()-start>4.5){
			break;
		}
		if ((a1<500 && a2<500) || (a1>500 && a2>500)) {
			motor(0,90 * factor);
			motor(2,56 * factor);
		} else if (a1<500) {
			motor(0,90 * 1.00 * factor);
			motor(2,75 * 0.80 * factor);
			
		}else {
			motor(0,90 * 0.80 * factor);
			motor(2,75 * 1.00 * factor);
		
		}
	}
	
	
	
	
	return 0;
}
예제 #21
0
/* Benchmark certain kernel operations */
void 
time_kernels (
    struct vtx_data **A,		/* matrix/graph being analyzed */
    int n,			/* number of rows/columns in matrix */
    double *vwsqrt		/* square roots of vertex weights */
)
{
    extern int DEBUG_PERTURB;	/* debug flag for matrix perturbation */
    extern int PERTURB;		/* randomly perturb to break symmetry? */
    extern int NPERTURB;	/* number of edges to perturb */
    extern int DEBUG_TRACE;	/* trace main execution path */
    extern double PERTURB_MAX;	/* maximum size of perturbation */
    int       i, beg, end;
    double   *dvec1, *dvec2, *dvec3;
    float    *svec1, *svec2, *svec3, *vwsqrt_float;
    double    norm_dvec, norm_svec;
    double    dot_dvec, dot_svec;
    double    time, time_dvec, time_svec;
    double    diff;
    double    factor, fac;
    float     factor_float, fac_float;
    int       loops;
    double    min_time, target_time;

    double   *mkvec();
    float    *mkvec_float();
    void      frvec(), frvec_float();
    void      vecran();
    double    ch_norm(), dot();
    double    norm_float(), dot_float();
    double    seconds();
    void      scadd(), scadd_float(), update(), update_float();
    void      splarax(), splarax_float();
    void      perturb_init(), perturb_clear();

    if (DEBUG_TRACE > 0) {
	printf("<Entering time_kernels>\n");
    }

    beg = 1;
    end = n;

    dvec1 = mkvec(beg, end);
    dvec2 = mkvec(beg, end);
    dvec3 = mkvec(beg - 1, end);
    svec1 = mkvec_float(beg, end);
    svec2 = mkvec_float(beg, end);
    svec3 = mkvec_float(beg - 1, end);

    if (vwsqrt == NULL) {
	vwsqrt_float = NULL;
    }
    else {
        vwsqrt_float = mkvec_float(beg - 1, end);
	for (i = beg - 1; i <= end; i++) {
	    vwsqrt_float[i] = vwsqrt[i];
	}
    }

    vecran(dvec1, beg, end);
    vecran(dvec2, beg, end);
    vecran(dvec3, beg, end);
    for (i = beg; i <= end; i++) {
	svec1[i] = dvec1[i];
	svec2[i] = dvec2[i];
	svec3[i] = dvec3[i];
    }

    /* Set number of loops so that ch_norm() takes about one second. This should
       insulate against inaccurate timings on faster machines. */

    loops = 1;
    time_dvec = 0;
    min_time = 0.5;
    target_time = 1.0;
    while (time_dvec < min_time) {
	time = seconds();
	for (i = loops; i; i--) {
	    norm_dvec = ch_norm(dvec1, beg, end);
	}
	time_dvec = seconds() - time;
	if (time_dvec < min_time) {
	    loops = 10 * loops;
	}
    }
    loops = (target_time / time_dvec) * loops;
    if (loops < 1)
	loops = 1;

    printf("                Kernel benchmarking\n");
    printf("Time (in seconds) for %d loops of each operation:\n\n", loops);

    printf("Routine      Double     Float      Discrepancy      Description\n");
    printf("-------      ------     -----      -----------      -----------\n");


    /* Norm operation */
    time = seconds();
    for (i = loops; i; i--) {
	norm_dvec = ch_norm(dvec1, beg, end);
    }
    time_dvec = seconds() - time;

    time = seconds();
    for (i = loops; i; i--) {
	norm_svec = norm_float(svec1, beg, end);
    }
    time_svec = seconds() - time;

    diff = norm_dvec - norm_svec;
    printf("norm        %6.2f    %6.2f    %14.5e", time_dvec, time_svec, diff);
    printf("      2 norm\n");


    /* Dot operation */
    time = seconds();
    for (i = loops; i; i--) {
	dot_dvec = dot(dvec1, beg, end, dvec2);
    }
    time_dvec = seconds() - time;

    time = seconds();
    for (i = loops; i; i--) {
	dot_svec = dot_float(svec1, beg, end, svec2);
    }
    time_svec = seconds() - time;

    diff = dot_dvec - dot_svec;
    printf("dot         %6.2f    %6.2f    %14.5e", time_dvec, time_svec, diff);
    printf("      scalar product\n");


    /* Scadd operation */
    factor = 1.01;
    factor_float = factor;

    fac = factor;
    time = seconds();
    for (i = loops; i; i--) {
	scadd(dvec1, beg, end, fac, dvec2);
	fac = -fac;		/* to keep things in scale */
    }
    time_dvec = seconds() - time;

    fac_float = factor_float;
    time = seconds();
    for (i = loops; i; i--) {
	scadd_float(svec1, beg, end, fac_float, svec2);
	fac_float = -fac_float;	/* to keep things in scale */
    }
    time_svec = seconds() - time;

    diff = checkvec(dvec1, beg, end, svec1);
    printf("scadd       %6.2f    %6.2f    %14.5e", time_dvec, time_svec, diff);
    printf("      vec1 <- vec1 + alpha*vec2\n");


    /* Update operation */
    time = seconds();
    for (i = loops; i; i--) {
	update(dvec1, beg, end, dvec2, factor, dvec3);
    }
    time_dvec = seconds() - time;

    time = seconds();
    for (i = loops; i; i--) {
	update_float(svec1, beg, end, svec2, factor_float, svec3);
    }
    time_svec = seconds() - time;

    diff = checkvec(dvec1, beg, end, svec1);
    printf("update      %6.2f    %6.2f    %14.2g", time_dvec, time_svec, diff);
    printf("      vec1 <- vec2 + alpha*vec3\n");

    /* splarax operation */
    if (PERTURB) {
	if (NPERTURB > 0 && PERTURB_MAX > 0.0) {
	    perturb_init(n);
	    if (DEBUG_PERTURB > 0) {
		printf("Matrix being perturbed with scale %e\n", PERTURB_MAX);
	    }
	}
	else if (DEBUG_PERTURB > 0) {
	    printf("Matrix not being perturbed\n");
	}
    }

    time = seconds();
    for (i = loops; i; i--) {
	splarax(dvec1, A, n, dvec2, vwsqrt, dvec3);
    }
    time_dvec = seconds() - time;

    time = seconds();
    for (i = loops; i; i--) {
	splarax_float(svec1, A, n, svec2, vwsqrt_float, svec3);
    }

    time_svec = seconds() - time;

    diff = checkvec(dvec1, beg, end, svec1);
    printf("splarax     %6.2f    %6.2f    %14.5e", time_dvec, time_svec, diff);
    printf("      sparse matrix vector multiply\n");

    if (PERTURB && NPERTURB > 0 && PERTURB_MAX > 0.0) {
	perturb_clear();
    }
    printf("\n");

    /* Free memory */
    frvec(dvec1, 1);
    frvec(dvec2, 1);
    frvec(dvec3, 0);
    frvec_float(svec1, 1);
    frvec_float(svec2, 1);
    frvec_float(svec3, 0);
    if (vwsqrt_float != NULL) {
        frvec_float(vwsqrt_float, beg - 1);
    }
}
예제 #22
0
파일: lego_v5.c 프로젝트: mvwicky/SBHS2013
int main()
{
	msleep(2500);
	set_analog_pullup(ET_s , 0); 
	extra_buttons_show(1); // show three extra buttons
	set_a_button_text("COORDS"); // set the text of various buttons
	set_b_button_text("POM SIZE");
	set_c_button_text("BOTGUY SIZE");
	set_x_button_text("CUBE SIZE"); 

	lego.left.port = 0; // set motor ports
	lego.right.port = 2;
	
	camera_open(LOW_RES);
	camera_update();
	while (a_button() == 0) // press the a button to set the coordinates
	{
		camera_update();
		target.green.x = get_object_center(0 , 0).x; // sets target coordinates (x)
		target.green.y = get_object_center(0 , 0).y; // sets target coordinates (y)
		printf("(%d , %d)\n" , target.green.x , target.green.y);
		msleep(10);
	}
	while (b_button() == 0)
	{
		camera_update();
		target.green.size = get_object_area(0 , 0);
		target.orange.size = get_object_area(1 , 0);
		printf("Orange Size = %d" , target.orange.size);
		printf(" Green Size = %d\n" , target.green.size);
	}
	enable_servo(arm_servo); 
	enable_servo(push_servo);
	enable_servo(basket_servo);
	set_servo_position(arm_servo , ARM_UP);
	set_servo_position(push_servo , P_DOWN);
	set_servo_position(basket_servo , B_UP);
	printf("(%d , %d)\n" , target.green.x , target.green.y);
	while(a_button() == 0)
	{
		printf("%d , %d , %d\n" , get_left() , get_middle() , get_right());
	}
	while (1) // line follow until poms are seen
	{
		blob_update();
		t_line_follow();
		if (current.orange.size > target.orange.size && current.green.size > target.green.size)
			break;
	}
	blob_update(); 
	get_pom(); // pick up a pom
	pom_push(); // push it into the basket
	while (1) // turn to next pom
	{
		blob_update();
		mav(lego.left.port , 300); 
		mav(lego.right.port , -300);
		msleep(10);
		if (current.green.size > target.green.size)
			break;
	}
	blob_update();
	get_pom(); // pick up pom
	pom_push(); // push it into the basket
	avoid_cubeguy(); // avoid the cube or botguy
	avoid_booster();
	while (1)
	{
		blob_update();
		t_line_follow();
		if (current.orange.size > target.orange.size && current.green.size > target.green.size)
			break;
	}
	blob_update();
	pom_push();
	while (1)
	{
		blob_update();
		mav(lego.left.port , 300);
		mav(lego.right.port , -300);
		msleep(10);
		if (current.green.size > target.green.size)
			break;
	}
	blob_update();
	get_pom();
	pom_push();
	avoid_cubeguy();
	int start_time = seconds();
	int t;
	while (1)
	{
		t_line_follow();
		if (seconds() < start_time + t)
			break;
	}
	while (1)
	{

	}
}
예제 #23
0
bool TimeWithDate::operator>= (const TimeWithDate& t) const
{
	return year >= t.year || month >= t.month ||
		day >= t.day || seconds() >= t.seconds();
}
예제 #24
0
 //! Function that converts a time_t into a ptime.
 inline
 ptime from_time_t(std::time_t t)
 {
   ptime start(gregorian::date(1970,1,1));
   return start + seconds(static_cast<long>(t));
 }
예제 #25
0
	void basic_http_connection_impl::__async_resolve_connect_coro(op_stamp_t stamp,
		coroutine coro,error_code err, resolver_iterator itr
		)
	{
		//all canceled operation will not be invoked
		if(is_canceled_op(stamp)||state_==CLOSED||!connection_)
			return;

		CORO_REENTER(coro)
		{
			state_=CONNECTING;
			//if qy is not null, we yield async resolve
			if (resolver_query_)
			{
				if (resolve_timer_)
					resolve_timer_->cancel();
				resolve_timer_=timer_type::create(get_io_service());
				resolve_timer_->set_obj_desc("basic_http_connection_impl::resolve_timer_");
				resolve_timer_->time_signal().bind(
					&this_type::__retry_async_resolve_connect_coro,this,stamp
					);
				resolve_timer_->async_wait(seconds(3));
				CORO_YIELD(
					resolver_.async_resolve(*resolver_query_,make_alloc_handler(
					boost::bind(&this_type::__async_resolve_connect_coro,
					SHARED_OBJ_FROM_THIS,stamp,coro,_1,_2))
					) 
					);
				if (resolve_timer_)
				{
					resolve_timer_->cancel();
					resolve_timer_.reset();
				}
				if (err||itr==resolver_iterator())
				{
					__retry_async_resolve_connect_coro(stamp);
					return;
				}
				remote_edp_.address(resolver_type::endpoint_type(*itr++).address());
				if (remote_edp_.port()==0)
					remote_edp_.port(80);
			}

			//yield async connect
			CORO_YIELD(socket_impl_->async_connect(remote_edp_,
				make_alloc_handler(
				boost::bind(&this_type::__async_resolve_connect_coro,
				SHARED_OBJ_FROM_THIS,stamp,coro,_1,itr))
				));

			while(err && itr != resolver_iterator())
			{
				//close socket that failed to connect, and open a new one
				socket_impl_->close(err);
				__open(local_edp_,err);
				if (err)
				{
					__retry_async_resolve_connect_coro(stamp);
					return;
				}
				remote_edp_.address(resolver_type::endpoint_type(*itr++).address());
				//yield async connect
				CORO_YIELD(socket_impl_->async_connect(remote_edp_,make_alloc_handler(
					boost::bind(&this_type::__async_resolve_connect_coro,
					SHARED_OBJ_FROM_THIS,stamp,coro,_1,itr)
					)));
			}
			if (err)
			{
				__retry_async_resolve_connect_coro(stamp);
				return;
			}

			//now lowlayer connected

			BOOST_ASSERT(!err);
			
			if (conn_timeout_timer_)
				conn_timeout_timer_->cancel();
			if (conn_retry_timer_)
				conn_retry_timer_->cancel();
			if(resolve_timer_)
				resolve_timer_->cancel();

			resolve_timer_.reset();
			resolver_query_.reset();

			state_=CONNECTED;
			keep_async_receiving();
			if (connection_)
				connection_->dispatch_connected(err);
			return;
		}
	}
예제 #26
0
파일: back up5.c 프로젝트: rvcs/botball
int main()
{
	double start = 0.0;
	// initialize servo, camera, etc here?.
	// if you are using a Create you should uncomment the next line
	//create_connect();
	enable_servos ();
	set_servo_position(3, ARM_UP);
	
//goto	GO_DOWN_CAVE;
	

	wait_for_light(2); // change the port number to match where your robot 

	shut_down_in(119); // shut off the motors and stop the Create after 119 seconds
	// note that shut_down_in should immediately follow wait_for_light!!

	printf("My program should score more points than this template!\n");
	// replace printf above with your code
 
	//create_disconnect();
	// Created on Mon March 2 2015
	int a1;
	int a2;
//turn on robot	
	motor(0,-700);
	motor(2,-700);
	msleep(700);
#if 0
//go forward	
	motor(0,400);
	motor(2,400); 
	msleep(1000);
//turn to aline 
	motor(0, -100);
	motor(2, 100);
	msleep(500);
//aline robot	
	motor(0,-100);
	motor(2,-100);
	msleep(2000);
	go(0, 0);
	msleep(1500);
#else
//go forward	
	motor(0,400);
	motor(2,400);
	msleep(400);
//turn to aline 
	motor(0,0);
	motor(2,200);
	msleep(1300);
//aline robot	
	motor(0,-100);
	motor(2,-100);
	msleep(2000);
#endif
//	ao(); return 0;

	
	  //go forwad 
	motor(0,85);
	motor(2,85);  //tweek if wheel goes sideways
	//msleep(6000);
	printf("before 3000 delay\n");
	msleep (1500); 
	set_servo_position(3, ARM_UP_PEG);
	printf("after 3000 delay\n");
	msleep(400);
	printf("%d\n",analog(1));
	start=seconds ();

	while ((a1 = analog(1)) <500) {
	//	printf("%d\n",a1);
		//msleep(5);
		if(seconds()-start>3.5){
		printf("time_out\n");
			break;
		}
	}
	printf("Found black %d\n", a1);

	//turn to go into middle
	turn_right();
	
		
//go forward	
	motor(0,60);
	motor(2,60);
	printf("go forward\n");
	//msleep(2000);
	while ((a1 = analog(1)) <600 || (a2 = analog(3)) <600) {
	//	printf("%4d %4d\n",a1, a2);
		//msleep(5);
		if (seconds()-start >10.5) {
			break;
		}
	}
	printf("%4d %4d\n",a1, a2);

	//turn in cave
	motor(0,0);
	motor(2,0);
	turn_right();
	
	set_servo_position(3, ARM_UP);
	//go to pick up cubes
	//motor(0,75);
	//motor(2,0);
	printf("turn right\n");
	//msleep(1500);
	
	
	//line follow
	start=seconds ();
	while(1){
		if(seconds()-start>4.9){
			break;
		}
		if (analog(1)>500) {
			motor(0,80);
			motor(2,100);
		}else if (analog(3)>500) {
			motor(0,100);
			motor(2,80);
		}else {
			motor(0,100);
			motor(2,100);
		}
	}
	
	//motor(0,85);
	//motor(2,85);
	//msleep(5500);
//put arm downto grab

GO_DOWN_CAVE:	
	go(0,0);
	set_servo_position(3, ARM_DOWN);	
	msleep(500);
	
	//begining of picking up poms
	
	go(75,75);
	msleep(2500);
	
	go_for(-50,-90, 1000);		// back up/turn/pull pom-poms
	
	go_for(90, -90, 500);
	
	go_for(-100, -90, 600);
	
	set_servo_position(3, ARM_UP);
	
	go_for(100, 100, 2000);
	
	go_for(-100, -100,2000);
	
	set_servo_position(3, ARM_DOWN);
	msleep(700);
	
	go_for(100,100,1000);
	
	go(-10, -10);
	set_servo_position(3, ARM_DOWN);
	msleep(100);
	
	set_servo_position(3, ARM_DOWN + 50);
	msleep(100);	

	set_servo_position(3, ARM_DOWN + 100);
	msleep(100);	

	set_servo_position(3, ARM_DOWN + 150);
	msleep(100);	

	set_servo_position(3, ARM_DOWN + 200);
	msleep(100);	

	//set_servo_position(3, ARM_DOWN + 250);
	//msleep(100);	

	//set_servo_position(3, ARM_DOWN + 400);
	//msleep(100);
	//push the poms over the top of the PVC
	go_for(20, 20, 1000);
	//StOp
	go(0,0);
    //wiggle the arm up and down so the poms fall off
	set_servo_position(3, ARM_DOWN+350);
	msleep(250); 
	set_servo_position(3, ARM_DOWN+300);
	msleep(250);
	set_servo_position(3, ARM_DOWN+350);
	msleep(250);
	
	// Raise the arm
	set_servo_position(3, ARM_UP);
	msleep(300);
	
	go_for(0, -100, 1000);
	
	//line follow
	start=seconds ();
	while(1){
		if(seconds()-start>1.5){
			break;
		}
		if (analog(1)>500) {
			motor(0,50);
			motor(2,80);
		}else if (analog(3)>500) {
			motor(0,80);
			motor(2,50);
		}else {
			motor(0,80);   //why is this 60 and 80
			motor(2,60);
		}
	}
		//line follow
	start=seconds ();
	while(1){
		if(seconds()-start>9.1){
			break;
		}
		if (analog(1)>500) {
			motor(0,80);
			motor(2,100);
		}else if (analog(3)>500) {
			motor(0,100);
			motor(2,80);
		}else {
			motor(0,100);
			motor(2,100);
		}
	}
	
	set_servo_position(3,ARM_DOWN);
	go_for(100, 100, 3500);			// Ram into PVC at the end of the cave
	
#if 1
	go_for(-50, -90, 1000);		// Back up with poms
	go_for(90, -90, 1000);
	set_servo_position(3, ARM_DOWNISH);
	
	// TODO: Run back across the cave to the good end
	start=seconds ();
	while(1){
		if(seconds()-start>1.5){
			break;
		}
		if (analog(1)>500) {
			motor(0,50);
			motor(2,80);
		}else if (analog(3)>500) {
			motor(0,80);
			motor(2,50);
		}else {
			motor(0,80);   //why is this 60 and 80
			motor(2,60);
		}
	}
	start=seconds ();
	while(1){
		if(seconds()-start>8.5){ // change from 8 sec
			break;
		}
		if (analog(1)>500) {
			motor(0,80);
			motor(2,100);
		}else if (analog(3)>500) {
			motor(0,100);
			motor(2,80);
		}else {
			motor(0,100);
			motor(2,100);
		}
	}
	set_servo_position(3, ARM_DOWN);
	go(75,75);
	msleep(2500);
	
	go_for(-50,-90, 1000);		// back up/turn/pull pom-poms
	
	go_for(90, -90, 500);
	
	go_for(-100, -90, 600);
	
	set_servo_position(3, ARM_UP);
	
	go_for(100, 100, 2000);
	
	go_for(-100, -100,2000);
	
	set_servo_position(3, ARM_DOWN);
	msleep(700);
	
	go_for(100,100,1000);
	
	go(-10, -10);
	set_servo_position(3, ARM_DOWN);
	msleep(100);
	
	set_servo_position(3, ARM_DOWN + 50);
	msleep(100);	

	set_servo_position(3, ARM_DOWN + 100);
	msleep(100);	

	set_servo_position(3, ARM_DOWN + 150);
	msleep(100);	

	set_servo_position(3, ARM_DOWN + 200);
	msleep(100);	

	//set_servo_position(3, ARM_DOWN + 250);
	//msleep(100);	

	//set_servo_position(3, ARM_DOWN + 400);
	//msleep(100);
	//push the poms over the top of the PVC
	go_for(20, 20, 1000);
	//StOp
	go(0,0);
    //wiggle the arm up and down so the poms fall off
	set_servo_position(3, ARM_DOWN+350);
	msleep(250); 
	set_servo_position(3, ARM_DOWN+300);
	msleep(250);
	set_servo_position(3, ARM_DOWN+350);
	msleep(250);
	//backs up to push poms second timeb
	set_servo_position(3, ARM_UP);
	go_for(-100, -100,2000);
//push poms second time
	go_for(100, 100, 2000);
	
	go_for(-100, -100,2000);
	
	set_servo_position(3, ARM_DOWN);
	msleep(700);
	
	go_for(100,100,1000);
	
	go(-10, -10);
	set_servo_position(3, ARM_DOWN);
	msleep(100);
	
	set_servo_position(3, ARM_DOWN + 50);
	msleep(100);	

	set_servo_position(3, ARM_DOWN + 100);
	msleep(100);	

	set_servo_position(3, ARM_DOWN + 150);
	msleep(100);	

	set_servo_position(3, ARM_DOWN + 200);
	msleep(100);	

	//set_servo_position(3, ARM_DOWN + 250);
	//msleep(100);	

	//set_servo_position(3, ARM_DOWN + 400);
	//msleep(100);
	//push the poms over the top of the PVC
	go_for(20, 20, 1000);
	//StOp
	go(0,0);
    //wiggle the arm up and down so the poms fall off
	set_servo_position(3, ARM_DOWN+350);
	msleep(250); 
	set_servo_position(3, ARM_DOWN+300);
	msleep(250);
	set_servo_position(3, ARM_DOWN+350);
	msleep(250);

	//motor(0,-75);
	//motor(2,-75);
	//msleep(8500);
	
//turn_left();
	
	//go_for(100, 100, 1800);
	//turn_left();
	//go_for(100, 100, 5000);
	
#endif 

	ao();
	return 0;
}
예제 #27
0
time_duration rpc_manager::tick()
{
	INVARIANT_CHECK;

	const static int short_timeout = 1;
	const static int timeout = 8;

	//	look for observers that have timed out

	if (m_transactions.empty()) return seconds(short_timeout);

	std::list<observer_ptr> timeouts;

	time_duration ret = seconds(short_timeout);
	ptime now = time_now();

#if defined TORRENT_DEBUG || TORRENT_RELEASE_ASSERTS
	ptime last = min_time();
	for (transactions_t::iterator i = m_transactions.begin();
		i != m_transactions.end(); ++i)
	{
		TORRENT_ASSERT((*i)->sent() >= last);
		last = (*i)->sent();
	}
#endif

	for (transactions_t::iterator i = m_transactions.begin();
		i != m_transactions.end();)
	{
		observer_ptr o = *i;

		// if we reach an observer that hasn't timed out
		// break, because every observer after this one will
		// also not have timed out yet
		time_duration diff = now - o->sent();
		if (diff < seconds(timeout))
		{
			ret = seconds(timeout) - diff;
			break;
		}
		
#ifdef TORRENT_DHT_VERBOSE_LOGGING
		TORRENT_LOG(rpc) << "[" << o->m_algorithm.get() << "] Timing out transaction id: " 
			<< (*i)->transaction_id() << " from " << o->target_ep();
#endif
		m_transactions.erase(i++);
		timeouts.push_back(o);
	}
	
	std::for_each(timeouts.begin(), timeouts.end(), boost::bind(&observer::timeout, _1));
	timeouts.clear();

	for (transactions_t::iterator i = m_transactions.begin();
		i != m_transactions.end(); ++i)
	{
		observer_ptr o = *i;

		// if we reach an observer that hasn't timed out
		// break, because every observer after this one will
		// also not have timed out yet
		time_duration diff = now - o->sent();
		if (diff < seconds(short_timeout))
		{
			ret = seconds(short_timeout) - diff;
			break;
		}
		
		if (o->has_short_timeout()) continue;

		// TODO: don't call short_timeout() again if we've
		// already called it once
		timeouts.push_back(o);
	}

	std::for_each(timeouts.begin(), timeouts.end(), boost::bind(&observer::short_timeout, _1));
	
	return ret;
}
예제 #28
0
void MoveForwardMillimeters(int mmToGo, int Speed)
{ 
	//Calculate the number of ticks to go
	float RightTicksToGo = TICKS_PER_REVOLUTION_RIGHT*(mmToGo/MILLIMETERS_PER_REVOLUTION);
	float LeftTicksToGo = TICKS_PER_REVOLUTION_LEFT*(mmToGo/MILLIMETERS_PER_REVOLUTION);
	
	//Calculate mm per tick
	float RightTicksPerMM = TICKS_PER_REVOLUTION_RIGHT/MILLIMETERS_PER_REVOLUTION;
	float LeftTicksPerMM = TICKS_PER_REVOLUTION_LEFT/MILLIMETERS_PER_REVOLUTION;
	
	//Set Motor Ticks position to zero
	clear_motor_position_counter(LEFT_PORT_WHEEL);
	clear_motor_position_counter(RIGHT_PORT_WHEEL);
	
	//Set Motor Positions to a variable .. should be zero here because we just cleared them
	int LeftMotorStartPosition = get_motor_position_counter(LEFT_PORT_WHEEL);
	int RightMotorStartPosition = get_motor_position_counter(RIGHT_PORT_WHEEL);
	
	//Calculate Motor Final Tick Position for MTP Command
	int LeftMotorFinalPosition = LeftMotorStartPosition + LeftTicksToGo;
	int RightMotorFinalPosition = RightMotorStartPosition + RightTicksToGo;
	
	
	//Get time of start movement
	//Not used yet.. for timeout functionality
	double StartMovementTime = seconds();
		
	//Loop until movment complete as measured by the left wheel
	while(get_motor_position_counter(LEFT_PORT_WHEEL) < LeftMotorFinalPosition) 
	{
		//Calculate Wheel Distance Moved each loop
		int LeftDistanceMoved = (get_motor_position_counter(LEFT_PORT_WHEEL)-LeftMotorStartPosition)/LeftTicksPerMM;
		int RightDistanceMoved = (get_motor_position_counter(RIGHT_PORT_WHEEL)-RightMotorStartPosition)/RightTicksPerMM;
		
		//Calculate Wheel Split
		//Positive Values Right Wheel is Ahead, Negative Values Left Wheel is ahead
		int WheelSplit = RightDistanceMoved - LeftDistanceMoved;
		
		//See if Wheel Split is exceeding the Correction Threshhold in either direction
		if(WheelSplit < CORRECTION_THRESHOLD && WheelSplit > -CORRECTION_THRESHOLD)
		{
			//Wheels are going straight
			motor(RIGHT_PORT_WHEEL, 100);
			motor(LEFT_PORT_WHEEL, 100);
			
			//move_to_position(RIGHT_PORT_WHEEL, Speed, RightMotorFinalPosition);
			//move_to_position(LEFT_PORT_WHEEL, Speed, LeftMotorFinalPosition);
			printf("STRAIGHT: left: %d right: %d split: %d\n", LeftDistanceMoved, RightDistanceMoved, WheelSplit);
		}
		else if(WheelSplit >= CORRECTION_THRESHOLD)
		{
			//Right wheel is ahead of left wheel
			//correction reduction applied to right wheel
			
			motor(RIGHT_PORT_WHEEL, 100*CORRECTION_REDUCTION);
			motor(LEFT_PORT_WHEEL, 100);
			
			//move_to_position(RIGHT_PORT_WHEEL, Speed * CORRECTION_REDUCTION, RightMotorFinalPosition);
			//move_to_position(LEFT_PORT_WHEEL, Speed, LeftMotorFinalPosition);
			printf("CORRECT RIGHT\n");
		}
		else if(WheelSplit <= -CORRECTION_THRESHOLD)
		{
			//Left wheel is ahead of right wheel
			//correction reduction applied to left wheel
			
			motor(RIGHT_PORT_WHEEL, 100);
			motor(LEFT_PORT_WHEEL, 100*CORRECTION_REDUCTION);
			//move_to_position(RIGHT_PORT_WHEEL, Speed, RightMotorFinalPosition);
			//move_to_position(LEFT_PORT_WHEEL, Speed * CORRECTION_REDUCTION, LeftMotorFinalPosition);
			printf("CORRECT LEFT\n");
		}
		msleep(150);
	}
	//Turn All Motors Off 
	ao();
}
예제 #29
0
int Timeval::operator>=(const Timeval& arg2) const {
    return seconds() > arg2.seconds()
           || (seconds() == arg2.seconds()
               && useconds() >= arg2.useconds());
}
예제 #30
0
	}

	std::stringstream ssm;
	std::string str_xml;
	boost::property_tree::write_xml(ssm, pt);
	str_xml = ssm.str();

	http::response res;
	res.status(http::header::HTTP_OK);
	res.content_length(str_xml.size());

	safe_buffer buf;
	safe_buffer_io bio(&buf);
	bio<<res<<str_xml;
	ppc_server_->close_connection(crack_adapters_[_adapter.lock()], buf);

	adapters_delay_destroy_.try_keep(_adapter.lock(), seconds(5));

	crack_adapters_.erase(_adapter.lock());

	URL_CRACK_DBG(
	std::cout<<"--------------url crack result start------------"<<std::endl;
	std::cout<<str_xml<<std::endl;
	std::cout<<"--------------url crack result end------------"<<std::endl;
	std::cout<<"-----has url crackcount----"<<crack_adapters_.size()<<std::endl;
	);
}


NAMESPACE_END(ppc);