//! reads foreign keys info from database void Table::loadForeignKeys() { if (foreignKeysLoadedM) return; foreignKeysM.clear(); DatabasePtr db = getDatabase(); wxMBConv* conv = db->getCharsetConverter(); MetadataLoader* loader = db->getMetadataLoader(); // first start a transaction for metadata loading, then lock the table // when objects go out of scope and are destroyed, table will be unlocked // before the transaction is committed - any update() calls on observers // can possibly use the same transaction MetadataLoaderTransaction tr(loader); SubjectLocker lock(this); IBPP::Statement& st1 = loader->getStatement( "select r.rdb$constraint_name, i.rdb$field_name, c.rdb$update_rule, " " c.rdb$delete_rule, c.RDB$CONST_NAME_UQ, r.rdb$index_name " "from rdb$relation_constraints r, rdb$index_segments i, rdb$ref_constraints c " "where r.rdb$relation_name=? and r.rdb$index_name=i.rdb$index_name " "and r.rdb$constraint_name = c.rdb$constraint_name " "and (r.rdb$constraint_type='FOREIGN KEY') order by 1, i.rdb$field_position" ); IBPP::Statement& st2 = loader->getStatement( "select r.rdb$relation_name, i.rdb$field_name" " from rdb$relation_constraints r" " join rdb$index_segments i on i.rdb$index_name = r.rdb$index_name " " where r.rdb$constraint_name = ?" " order by i.rdb$field_position " ); st1->Set(1, wx2std(getName_(), conv)); st1->Execute(); ForeignKey *fkp = 0; while (st1->Fetch()) { std::string s; st1->Get(1, s); wxString cname(std2wxIdentifier(s, conv)); st1->Get(2, s); wxString fname(std2wxIdentifier(s, conv)); st1->Get(3, s); wxString update_rule(std2wxIdentifier(s, conv)); st1->Get(4, s); wxString delete_rule(std2wxIdentifier(s, conv)); std::string ref_constraint; st1->Get(5, ref_constraint); st1->Get(6, s); wxString ixname(std2wxIdentifier(s, conv)); if (fkp && fkp->getName_() == cname) // add column fkp->columnsM.push_back(fname); else { ForeignKey fk; foreignKeysM.push_back(fk); fkp = &foreignKeysM.back(); fkp->setName_(cname); fkp->setParent(this); fkp->updateActionM = update_rule; fkp->deleteActionM = delete_rule; fkp->indexNameM = ixname; st2->Set(1, ref_constraint); st2->Execute(); std::string rtable; while (st2->Fetch()) { st2->Get(1, rtable); st2->Get(2, s); fkp->referencedColumnsM.push_back(std2wxIdentifier(s, conv)); } fkp->referencedTableM = std2wxIdentifier(rtable, conv); fkp->columnsM.push_back(fname); } } foreignKeysLoadedM = true; }
void FlashySlideShowStarterFrame::OnPathTextCtrlText(wxCommandEvent& event) { wxDir dir(PathTextCtrl->GetValue()); if ( !dir.IsOpened() ) { StatusBar1->SetStatusText(wxT("Dir does not exist..")); return ; //DIR does not exist.. } StatusBar1->SetStatusText(wxT("Please Wait while accessing filesystem..")); PictureFolder->SetPath(PathTextCtrl->GetValue()); wxFileName fname(PathTextCtrl->GetValue()); wxDateTime mod_time=fname.GetModificationTime(); wxDateTime now_time=wxDateTime::Now(); StatusBar1->SetStatusText(wxT(" ")); if ( mod_time.IsEarlierThan(now_time) ) { StatusBar1->SetStatusText(wxT("Please Wait while thumbnails are generated..")); unsigned int total_pictures = RefreshThumbnails(); StatusBar1->SetStatusText(wxT(" ")); wxTimeSpan difference = now_time.Subtract(mod_time); wxString value; value<<wxT("Modified "); //THIS IS KIND OF BAD CODE :P , NEEDS REVISION unsigned int days_difference_full = difference.GetDays(); unsigned int days_difference_subtracted = difference.GetDays(); unsigned int years_diff = (unsigned int) difference.GetDays()/365; days_difference_subtracted = days_difference_full-years_diff*365; unsigned int months_diff = (unsigned int) (days_difference_subtracted)/30 ; days_difference_subtracted -= months_diff*30; unsigned int days_diff = days_difference_subtracted; if (years_diff>0) { if (years_diff==1) { value << wxT("1 year "); } else { value << years_diff; value << wxT(" years "); } } if (months_diff>0) { if (months_diff==1) { value << wxT("1 month "); } else { value << months_diff; value << wxT(" months "); } } if (days_diff>0) { if (days_diff==1) { value << wxT("1 day "); } else { value << days_diff; value << wxT(" days "); } } if ( (years_diff>0)||(months_diff>0)||(days_diff>0) ) { value << wxT("ago - "); } value << mod_time.GetDay(); value << wxT("/"); value << mod_time.GetMonth(); value << wxT("/"); value << mod_time.GetYear(); if (total_pictures>0) { value << wxT(" - "); value << total_pictures; value << wxT(" picture"); if (total_pictures>1) { value << wxT("s"); } } DateText->SetLabel(value); } else { //This is weird , date appears to be in the future! wxString value; value << mod_time.GetDay(); value << wxT("/"); value << mod_time.GetMonth(); value << wxT("/"); value << mod_time.GetYear(); DateText->SetLabel(value); } }
void shopping_buy( char *arg, struct char_data *ch, struct char_data *keeper, int shop_nr) { char argm[100], buf[MAX_STRING_LENGTH], newarg[100]; int num = 1; struct obj_data *temp1; int i; float mult = 0; if(!(is_ok(keeper,ch,shop_nr))) return; if(keeper->generic != 0) for(i = 0; i <= MAX_TRADE; i++) { if(keeper->generic == FAMINE) if(shop_index[shop_nr].type[i] == ITEM_FOOD) { mult = shop_multiplier; /* we're in a famine, we sell food, so we */ break; /* our prices to hell ;-) -DM */ } if(keeper->generic == DWARVES_STRIKE) if((shop_index[shop_nr].type[i] == ITEM_ARMOR) || (shop_index[shop_nr].type[i] == ITEM_WEAPON)) { mult = shop_multiplier; break; } } only_argument(arg, argm); if(!(*argm)) { sprintf(buf, "%s what do you want to buy??" ,GET_NAME(ch)); do_tell(keeper,buf,19); return; }; if ((num = getabunch(argm,newarg))!=NULL) { strcpy(argm,newarg); } if (num == 0) num = 1; if(!( temp1 = get_obj_in_list_vis(ch,argm,keeper->carrying))) { sprintf(buf, shop_index[shop_nr].no_such_item1 ,GET_NAME(ch)); do_tell(keeper,buf,19); return; } if(temp1->obj_flags.cost <= 0) { sprintf(buf, shop_index[shop_nr].no_such_item1 ,GET_NAME(ch)); do_tell(keeper,buf,19); extract_obj(temp1); return; } if (GET_GOLD(ch) < (int) (num*(temp1->obj_flags.cost* shop_index[shop_nr].profit_buy - ((chr_apply[GET_CHR(ch)].reaction*temp1->obj_flags.cost)/100) + (mult * temp1->obj_flags.cost))) && GetMaxLevel(ch)<DEMIGOD) { sprintf(buf, shop_index[shop_nr].missing_cash2, GET_NAME(ch)); do_tell(keeper,buf,19); switch(shop_index[shop_nr].temper1) { case 0: do_action(keeper,GET_NAME(ch),30); return; case 1: do_emote(keeper,"grins happily",36); return; default: return; } } if ((IS_CARRYING_N(ch) + num) > (CAN_CARRY_N(ch))) { sprintf(buf,"%s : You can't carry that many items.\n\r", fname(temp1->name)); send_to_char(buf, ch); return; } if ((IS_CARRYING_W(ch) + (num * temp1->obj_flags.weight)) > CAN_CARRY_W(ch)) { sprintf(buf,"%s : You can't carry that much weight.\n\r", fname(temp1->name)); send_to_char(buf, ch); return; } act("$n buys $p.", FALSE, ch, temp1, 0, TO_ROOM); sprintf(buf, shop_index[shop_nr].message_buy, GET_NAME(ch), (int) (num * (temp1->obj_flags.cost* shop_index[shop_nr].profit_buy - ((chr_apply[GET_CHR(ch)].reaction*temp1->obj_flags.cost)/100) + (mult * temp1->obj_flags.cost)))); do_tell(keeper,buf,19); sprintf(buf,"You now have %s (*%d).\n\r", temp1->short_description,num); send_to_char(buf,ch); while (num-- > 0) { if (GetMaxLevel(ch)<DEMIGOD) GET_GOLD(ch) -= (int)(temp1->obj_flags.cost* shop_index[shop_nr].profit_buy - ((chr_apply[GET_CHR(ch)].reaction*temp1->obj_flags.cost)/100)+ (mult * temp1->obj_flags.cost)); GET_GOLD(keeper) += (int)(temp1->obj_flags.cost* shop_index[shop_nr].profit_buy - ((chr_apply[GET_CHR(ch)].reaction*temp1->obj_flags.cost)/100)+ (mult * temp1->obj_flags.cost)); /* Test if producing shop ! */ if (shop_producing(temp1,shop_nr)) temp1 = read_object(temp1->item_number, REAL); else { obj_from_char(temp1); if (temp1 == NULL) { send_to_char("Sorry, I just ran out of those.\n\r",ch); GET_GOLD(ch) += (int)(temp1->obj_flags.cost* shop_index[shop_nr].profit_buy - ((chr_apply[GET_CHR(ch)].reaction*temp1->obj_flags.cost)/100)+ (mult * temp1->obj_flags.cost)); return; } } obj_to_char(temp1,ch); } return; }
int CImageTestApp::Run(void) { CArgs args = GetArgs(); // // test image conversions // string base = args["base"].AsString(); const int max_fmts = 8; CImageIO::EType fmts[max_fmts] = { CImageIO::eBmp, CImageIO::eJpeg, CImageIO::ePng, CImageIO::eGif, CImageIO::eSgi, CImageIO::eTiff, CImageIO::eXpm, CImageIO::eRaw }; const char* extensions[max_fmts] = { ".bmp", ".jpg", ".png", ".gif", ".sgi", ".tiff", ".xpm", ".raw" }; vector<string> image_names; for (int i = 0; i < max_fmts; ++i) { image_names.push_back(base + extensions[i]); } cout << "testing image read/write..." << endl; ITERATE (vector<string>, iter, image_names) { cout << "image: " << *iter << endl; CRef<CImage> image(CImageIO::ReadImage(*iter)); if ( !image ) { continue; } cout << " width = " << image->GetWidth() << " height = " << image->GetHeight() << " depth = " << image->GetDepth() << endl; image->SetDepth(3); // write in a multitude of formats for (int i = 0; i < max_fmts; ++i) { string fname (*iter + extensions[i]); cout << "trying to write: " << fname << endl; if (CImageIO::WriteImage(*image, fname, fmts[i])) { cout << "wrote to file " << fname << endl; } } }
int main(int argc, char *argv[]) { #if 0 Stack *stack = Read_Stack("../data/fly_neuron.tif"); Stretch_Stack_Value_Q(stack, 0.99); Translate_Stack(stack, GREY, 1); Write_Stack("../data/test.tif", stack); Kill_Stack(stack); #endif #if 0 int idx1, idx2, width, height; idx1 = 33332; idx2 = 65535; width = 111; height = 112; printf("%g\n", Stack_Util_Voxel_Distance(idx1, idx2, width, height)); int x1, y1, z1, x2, y2, z2; Stack_Util_Coord(idx1, width, height, &x1, &y1, &z1); Stack_Util_Coord(idx2, width, height, &x2, &y2, &z2); printf("%d, %d, %d\n", x1 - x2, y1 - y2, z1 - z2); #endif #if 0 Stack *stack = Read_Stack("../data/fly_neuron.tif"); //Translate_Stack(stack, GREY16, 1); Image *image = Proj_Stack_Zmax(stack); Write_Image("../data/test.tif", image); #endif #if 0 Stack *stack = Read_Stack("../data/fly_neuron_a1_org.tif"); //stack = Crop_Stack(stack, 256, 256, 0, 512, 512, 170, NULL); int i; Stack stack2; stack2.width = stack->width; stack2.height = stack->height; stack2.kind = stack->kind; stack2.depth = 1; for (i = 0; i < stack->depth; i++) { stack2.array = stack->array + i * stack->width * stack->height; //Stack *locmax = Stack_Locmax_Region(&stack2, 8); Stack *locmax = Stack_Local_Max(&stack2, NULL, STACK_LOCMAX_SINGLE); int *hist = Stack_Hist_M(&stack2, locmax); int low, high; Int_Histogram_Range(hist, &low, &high); int thre = Int_Histogram_Triangle_Threshold(hist, low, high); printf("Threshold: %d\n", thre); Stack_Threshold_Binarize(&stack2, thre); Kill_Stack(locmax); free(hist); } //Stack_Bc_Autoadjust(result); /* Translate_Stack(stack, COLOR, 1); Stack_Blend_Mc(stack, result, 0.1); */ Write_Stack("../data/test.tif", stack); #endif #if 1 Stack *stack = Read_Stack("../data/fly_neuron_crop.tif"); Filter_3d *filter = Gaussian_Filter_3d(1.0, 1.0, 0.5); Stack *out = Filter_Stack(stack, filter); Kill_FMatrix(filter) Write_Stack("../data/test.tif", out); #endif #if 0 Stack *stack = Read_Stack("../data/fly_neuron_a2_org.tif"); Stack *locmax = Stack_Locmax_Region(stack, 18); Stack *mask = Read_Stack("../data/fly_neuron_a2_org/threshold_s.tif"); //Stack_And(locmax, mask, locmax); Object_3d_List *objs = Stack_Find_Object_N(locmax, NULL, 1, 0, 18); Zero_Stack(locmax); int objnum = 0; while (objs != NULL) { Object_3d *obj = objs->data; Voxel_t center; Object_3d_Central_Voxel(obj, center); Set_Stack_Pixel(locmax, center[0], center[1], center[2], 0, 1); objs = objs->next; objnum++; } Write_Stack("../data/fly_neuron_a2_org/locmax.tif", locmax); printf("objnum: %d\n", objnum); U8Matrix mat; mat.ndim = 3; mat.dim[0] = stack->width; mat.dim[1] = stack->height; mat.dim[2] = stack->depth; mat.array = locmax->array; dim_type bdim[3]; bdim[0] = 7; bdim[1] = 7; bdim[2] = 5; U8Matrix *mat2 = U8Matrix_Blocksum(&mat, bdim, NULL); int offset[3]; offset[0] = bdim[0] / 2; offset[1] = bdim[1] / 2; offset[2] = bdim[2] / 2; Crop_U8Matrix(mat2, offset, mat.dim, &mat); Write_Stack("../data/fly_neuron_a2_org/locmax_sum.tif", locmax); Stack_Threshold_Binarize(locmax, 6); Stack *clear_stack = Stack_Majority_Filter_R(locmax, NULL, 26, 4); Struct_Element *se = Make_Cuboid_Se(3, 3, 3); Stack *dilate_stack = Stack_Dilate(clear_stack, NULL, se); Stack *fill_stack = Stack_Fill_Hole_N(dilate_stack, NULL, 1, 4, NULL); Kill_Stack(dilate_stack); Stack_Not(fill_stack, fill_stack); Stack_And(fill_stack, mask, mask); Write_Stack("../data/test.tif", mask); #endif #if 0 Stack *stack = Read_Stack("../data/fly_neuron_t1.tif"); Stack *locmax = Stack_Locmax_Region(stack, 6); Stack_Label_Objects_Ns(locmax, NULL, 1, 2, 3, 6); int nvoxel = Stack_Voxel_Number(locmax); int i; int s[26]; for (i = 0; i < nvoxel; i++) { if (locmax->array[i] < 3) { locmax->array[i] = 0; } else { locmax->array[i] = 1; printf("%u\n", stack->array[i]); Stack_Neighbor_Sampling_I(stack, 6, i, -1, s); iarray_print2(s, 6, 1); } } //Stack *locmax = Stack_Local_Max(stack, NULL, STACK_LOCMAX_SINGLE); Write_Stack("../data/test.tif", locmax); #endif #if 0 Stack *stack = Read_Stack("../data/fly_neuron_n1.tif"); Stack *stack2 = Flip_Stack_Y(stack, NULL); Flip_Stack_Y(stack2, stack2); if (!Stack_Identical(stack, stack2)) { printf("bug found\n"); } Write_Stack("../data/test.tif", stack); #endif #if 0 Mc_Stack *stack = Read_Mc_Stack("../data/benchmark/L3_12bit.lsm", -1); Mc_Stack_Grey16_To_8(stack, 3); Write_Mc_Stack("../data/test.lsm", stack, "../data/benchmark/L3_12bit.lsm"); #endif #if 0 //Stack *stack = Read_Stack("../data/C2-Slice06_R1_GR1_B1_L18.tif"); Stack *stack = Read_Stack("../data/fly_neuron_n1/traced.tif"); Print_Stack_Info(stack); #endif #if 0 Mc_Stack *stack = Make_Mc_Stack(GREY, 1024, 1024, 1024, 5); /* stack.width = 1024; stack.height = 1024; stack.depth = 1024; stack.kind = GREY; stack.nchannel = 5; printf("%zd\n", ((size_t)stack.kind * stack.width * stack.height * stack.depth * stack.nchannel)); */ #endif #if 0 Stack *stack = Make_Stack(GREY, 1, 1, 1); printf("stack usage: %d\n", Stack_Usage()); uint8 *data = stack->array; stack->array = NULL; Kill_Stack(stack); stack = Read_Stack("../data/benchmark/line.tif"); free(data); printf("stack usage: %d\n", Stack_Usage()); #endif #if 0 Stack *stack = Read_Stack("../data/test.tif"); int *hist = Stack_Hist(stack); Print_Int_Histogram(hist); #endif #if 0 Stack *stack = Read_Stack("../data/benchmark/mouse_neuron_single/stack.tif"); Stack dst; dst.text = "\0"; dst.array = stack->array; Crop_Stack(stack, 0, 0, 0, stack->width - 100, stack->height - 100, stack->depth - 30, &dst); Write_Stack("../data/test.tif", &dst); #endif #if 0 Stack *stack = Make_Stack(GREY, 5, 5, 3); Zero_Stack(stack); Set_Stack_Pixel(stack, 2, 2, 1, 0, 1.0); Print_Stack_Value(stack); Stack *out = Stack_Running_Max(stack, 0, NULL); out = Stack_Running_Max(out, 1, out); out = Stack_Running_Max(out, 2, out); Print_Stack_Value(out); #endif #if 0 Stack *stack = Read_Stack("../data/benchmark/stack_graph/fork/fork.tif"); Stack *out = Stack_Running_Median(stack, 0, NULL); Stack_Running_Median(out, 1, out); //Stack_Running_Max(stack, 0, out); //Stack_Running_Max(out, 1, out); Write_Stack("../data/test.tif", out); Stack *out2 = Stack_Running_Median(stack, 0, NULL); Stack *out3 = Stack_Running_Median(out2, 1, NULL); if (Stack_Identical(out, out3)) { printf("Same in-place and out-place\n"); } #endif #if 0 Stack *stack = Read_Stack_U("../data/diadem_d1_147.xml"); printf("%d\n", Stack_Threshold_Quantile(stack, 0.9)); #endif #if 0 const char *filepath = "/Users/zhaot/Data/Julie/All_tiled_nsyb5_Sum.lsm"; char filename[100]; fname(filepath, filename); Mc_Stack *stack = Read_Mc_Stack(filepath, -1); Print_Mc_Stack_Info(stack); Mc_Stack *tmpstack = Make_Mc_Stack(stack->kind, stack->width, stack->height, stack->depth / 8, stack->nchannel); size_t channel_size = stack->kind * stack->width *stack->height * stack->depth; size_t channel_size2 = tmpstack->kind * tmpstack->width *tmpstack->height * tmpstack->depth; int i; int k; uint8_t *array = stack->array; for (k = 0; k < 8; k++) { int offset = 0; int offset2 = 0; for (i = 0; i < stack->nchannel; i++) { memcpy(tmpstack->array + offset2, array + offset, channel_size2); offset += channel_size; offset2 += channel_size2; } array += channel_size2; char outpath[500]; sprintf(outpath, "../data/test/%s_%03d.lsm", filename, k); Write_Mc_Stack(outpath, tmpstack, filepath); } #endif #if 0 Stack *stack = Index_Stack(GREY16, 5, 5, 1); Set_Stack_Pixel(stack, 1, 1, 0, 0, 0); Set_Stack_Pixel(stack, 1, 2, 0, 0, 0); Print_Stack_Value(stack); Stack *out = Stack_Neighbor_Median(stack, 8, NULL); Print_Stack_Value(out); #endif #if 0 Stack *stack = Make_Stack(GREY, 10, 10, 3); Zero_Stack(stack); Cuboid_I bound_box; Set_Stack_Pixel(stack, 1, 1, 1, 0, 1); Set_Stack_Pixel(stack, 1, 2, 1, 0, 1); Set_Stack_Pixel(stack, 3, 1, 2, 0, 1); Stack_Bound_Box(stack, &bound_box); Print_Cuboid_I(&bound_box); #endif #if 0 Stack_Document *doc = Xml_Read_Stack_Document("../data/test.xml"); File_List *list = (File_List*) doc->ci; Cuboid_I bound_box; Stack_Bound_Box_F(list, &bound_box); Print_Cuboid_I(&bound_box); #endif #if 0 Stack_Document *doc = Xml_Read_Stack_Document("../data/test.xml"); File_List *list = (File_List*) doc->ci; Print_File_List(list); Stack *stack = Read_Image_List_Bounded(list); Stack *out = stack; out = Stack_Region_Expand(stack, 8, 1, NULL); out = Downsample_Stack(out, 4, 4, 0); Write_Stack("../data/test.tif", out); #endif #if 0 Stack_Document *doc = Xml_Read_Stack_Document( "../data/ting_example_stack/test.xml"); File_List *list = (File_List*) doc->ci; Print_File_List(list); int i; for (i = 0; i < list->file_number; i++) { Stack *stack = Read_Stack_U(list->file_path[i]); Stack *ds = Downsample_Stack(stack, 39, 39, 0); char file_path[500]; sprintf(file_path, "../data/ting_example_stack/thumbnails/tb%05d.tif", i); Write_Stack(file_path, ds); Free_Stack(stack); } #endif #if 0 Stack *stack = Read_Stack("../data/test2.tif"); Stack_Threshold_Binarize(stack, 6); Objlabel_Workspace ow; STACK_OBJLABEL_OPEN_WORKSPACE(stack, (&ow)); Object_3d *obj = Stack_Find_Largest_Object_N(stack, ow.chord, 1, 26); //Print_Object_3d(obj); //printf("%llu\n", obj->size); double vec[3]; Object_3d_Orientation(obj, vec, MAJOR_AXIS); double center[3]; Object_3d_Centroid(obj, center); darray_print2(vec, 3, 1); double span[2] = {100000, -100000}; for (int i = 0; i < obj->size; i++) { double proj = Geo3d_Dot_Product(vec[0], vec[1], vec[2], (double) obj->voxels[i][0] - center[0], (double) obj->voxels[i][1] - center[1], (double) obj->voxels[i][2] - center[2]); if (proj < span[0]) { span[0] = proj; } if (proj > span[1]) { span[1] = proj; } } darray_print2(span, 2, 1); double vec2[3]; Object_3d_Orientation(obj, vec2, PLANE_NORMAL); darray_print2(vec2, 3, 1); double span2[2] = {100000, -100000}; for (int i = 0; i < obj->size; i++) { double proj = Geo3d_Dot_Product(vec2[0], vec2[1], vec2[2], (double) obj->voxels[i][0] - center[0], (double) obj->voxels[i][1] - center[1], (double) obj->voxels[i][2] - center[2]); if (proj < span2[0]) { span2[0] = proj; } if (proj > span2[1]) { span2[1] = proj; } } darray_print2(span2, 2, 1); double vec3[3]; Geo3d_Cross_Product(vec[0], vec[1], vec[2], vec2[0], vec2[1], vec2[2], vec3, vec3+1, vec3+2); double span3[2] = {100000, -100000}; int i; for (i = 0; i < obj->size; i++) { double proj = Geo3d_Dot_Product(vec3[0], vec3[1], vec3[2], (double) obj->voxels[i][0] - center[0], (double) obj->voxels[i][1] - center[1], (double) obj->voxels[i][2] - center[2]); if (proj < span3[0]) { span3[0] = proj; } if (proj > span3[1]) { span3[1] = proj; } } darray_print2(span3, 2, 1); coordinate_3d_t vertex[8]; for (i = 0; i < 8; i++) { Coordinate_3d_Copy(vertex[i], center); int j; for (j = 0; j < 3; j++) { vertex[i][j] += span[0] * vec[j] + span2[0] * vec2[j] + span3[0] * vec3[j]; } } for (i = 0; i < 3; i++) { vertex[1][i] += (span[1] - span[0]) * vec[i]; vertex[2][i] += (span2[1] - span2[0]) * vec2[i]; vertex[3][i] += (span3[1] - span3[0]) * vec3[i]; vertex[4][i] = vertex[1][i] + (span2[1] - span2[0]) * vec2[i]; vertex[5][i] = vertex[2][i] + (span3[1] - span3[0]) * vec3[i]; vertex[6][i] = vertex[3][i] + (span[1] - span[0]) * vec[i]; vertex[7][i] = vertex[5][i] + (span[1] - span[0]) * vec[i]; } FILE *fp = fopen("../data/test.swc", "w"); fprintf(fp, "%d %d %g %g %g %g %d\n", 1, 2, vertex[0][0], vertex[0][1], vertex[0][2], 3.0, -1); fprintf(fp, "%d %d %g %g %g %g %d\n", 2, 2, vertex[1][0], vertex[1][1], vertex[1][2], 3.0, 1); fprintf(fp, "%d %d %g %g %g %g %d\n", 3, 2, vertex[2][0], vertex[2][1], vertex[2][2], 3.0, 1); fprintf(fp, "%d %d %g %g %g %g %d\n", 4, 2, vertex[3][0], vertex[3][1], vertex[3][2], 3.0, 1); fprintf(fp, "%d %d %g %g %g %g %d\n", 5, 2, vertex[4][0], vertex[4][1], vertex[4][2], 3.0, 2); fprintf(fp, "%d %d %g %g %g %g %d\n", 6, 2, vertex[5][0], vertex[5][1], vertex[5][2], 3.0, 3); fprintf(fp, "%d %d %g %g %g %g %d\n", 7, 2, vertex[6][0], vertex[6][1], vertex[6][2], 3.0, 4); fprintf(fp, "%d %d %g %g %g %g %d\n", 8, 2, vertex[7][0], vertex[7][1], vertex[7][2], 3.0, 7); fprintf(fp, "%d %d %g %g %g %g %d\n", 9, 2, vertex[4][0], vertex[4][1], vertex[4][2], 3.0, 8); fprintf(fp, "%d %d %g %g %g %g %d\n", 10, 2, vertex[4][0], vertex[4][1], vertex[4][2], 3.0, 3); fprintf(fp, "%d %d %g %g %g %g %d\n", 11, 2, vertex[5][0], vertex[5][1], vertex[5][2], 3.0, 8); fprintf(fp, "%d %d %g %g %g %g %d\n", 12, 2, vertex[5][0], vertex[5][1], vertex[5][2], 3.0, 4); fprintf(fp, "%d %d %g %g %g %g %d\n", 13, 2, vertex[6][0], vertex[6][1], vertex[6][2], 3.0, 2); /* Geo3d_Scalar_Field *field = Make_Geo3d_Scalar_Field(6); field->points[0][0] = span[0] * vec[0] + center[0]; field->points[0][1] = span[0] * vec[1] + center[1]; field->points[0][2] = span[0] * vec[2] + center[2]; field->points[1][0] = span[1] * vec[0] + center[0]; field->points[1][1] = span[1] * vec[1] + center[1]; field->points[1][2] = span[1] * vec[2] + center[2]; field->points[2][0] = span2[0] * vec2[0] + center[0]; field->points[2][1] = span2[0] * vec2[1] + center[1]; field->points[2][2] = span2[0] * vec2[2] + center[2]; field->points[3][0] = span2[1] * vec2[0] + center[0]; field->points[3][1] = span2[1] * vec2[1] + center[1]; field->points[3][2] = span2[1] * vec2[2] + center[2]; field->points[4][0] = span3[0] * vec3[0] + center[0]; field->points[4][1] = span3[0] * vec3[1] + center[1]; field->points[4][2] = span3[0] * vec3[2] + center[2]; field->points[5][0] = span3[1] * vec3[0] + center[0]; field->points[5][1] = span3[1] * vec3[1] + center[1]; field->points[5][2] = span3[1] * vec3[2] + center[2]; coordinate_3d_t corner[2]; Geo3d_Scalar_Field_Boundbox(field, corner); darray_print2(corner[0], 3, 1); darray_print2(corner[1], 3, 1); fprintf(fp, "%d %d %g %g %g %g %d\n", 1, 2, corner[0][0], corner[0][1], corner[0][2], 3.0, -1); fprintf(fp, "%d %d %g %g %g %g %d\n", 2, 2, corner[1][0], corner[0][1], corner[0][2], 3.0, 1); fprintf(fp, "%d %d %g %g %g %g %d\n", 3, 2, corner[1][0], corner[1][1], corner[0][2], 3.0, 2); fprintf(fp, "%d %d %g %g %g %g %d\n", 4, 2, corner[0][0], corner[1][1], corner[0][2], 3.0, 3); fprintf(fp, "%d %d %g %g %g %g %d\n", 5, 2, corner[0][0], corner[0][1], corner[0][2], 3.0, 4); fprintf(fp, "%d %d %g %g %g %g %d\n", 6, 2, corner[0][0], corner[0][1], corner[1][2], 3.0, -1); fprintf(fp, "%d %d %g %g %g %g %d\n", 7, 2, corner[1][0], corner[0][1], corner[1][2], 3.0, 6); fprintf(fp, "%d %d %g %g %g %g %d\n", 8, 2, corner[1][0], corner[1][1], corner[1][2], 3.0, 7); fprintf(fp, "%d %d %g %g %g %g %d\n", 9, 2, corner[0][0], corner[1][1], corner[1][2], 3.0, 8); fprintf(fp, "%d %d %g %g %g %g %d\n", 10, 2, corner[0][0], corner[0][1], corner[1][2], 3.0, 9); fprintf(fp, "%d %d %g %g %g %g %d\n", 11, 2, corner[0][0], corner[0][1], corner[1][2], 3.0, 1); fprintf(fp, "%d %d %g %g %g %g %d\n", 12, 2, corner[1][0], corner[0][1], corner[1][2], 3.0, 2); fprintf(fp, "%d %d %g %g %g %g %d\n", 13, 2, corner[1][0], corner[1][1], corner[1][2], 3.0, 3); fprintf(fp, "%d %d %g %g %g %g %d\n", 14, 2, corner[0][0], corner[1][1], corner[1][2], 3.0, 4); */ /* fprintf(fp, "%d %d %g %g %g %g %d\n", 5, 2, corner[1][0], corner[1][1], corner[1][2], 3.0, -1); fprintf(fp, "%d %d %g %g %g %g %d\n", 6, 2, corner[0][0], corner[1][1], corner[1][2], 3.0, 6); fprintf(fp, "%d %d %g %g %g %g %d\n", 7, 2, corner[1][0], corner[0][1], corner[1][2], 3.0, 7); fprintf(fp, "%d %d %g %g %g %g %d\n", 8, 2, corner[1][0], corner[1][1], corner[0][2], 3.0, 7); fprintf(fp, "%d %d %g %g %g %g %d\n", 12, 2, corner[1][0], corner[1][1], corner[0][2], 3.0, 2); fprintf(fp, "%d %d %g %g %g %g %d\n", 9, 2, corner[1][0], corner[1][1], corner[1][2], 3.0, 6); fprintf(fp, "%d %d %g %g %g %g %d\n", 10, 2, corner[0][0], corner[1][1], corner[1][2], 3.0, 3); fprintf(fp, "%d %d %g %g %g %g %d\n", 11, 2, corner[1][0], corner[0][1], corner[1][2], 3.0, 4); fprintf(fp, "%d %d %g %g %g %g %d\n", 12, 2, corner[1][0], corner[1][1], corner[0][2], 3.0, -1); */ fprintf(fp, "%d %d %g %g %g %g %d\n", 21, 2, span[0] * vec[0] + center[0], span[0] * vec[1] + center[1], span[0] * vec[2] + center[2], 3.0, -1); fprintf(fp, "%d %d %g %g %g %g %d\n", 22, 2, span[1] * vec[0] + center[0], span[1] * vec[1] + center[1], span[1] * vec[2] + center[2], 3.0, 21); fprintf(fp, "%d %d %g %g %g %g %d\n", 23, 2, span2[0] * vec2[0] + center[0], span2[0] * vec2[1] + center[1], span2[0] * vec2[2] + center[2], 3.0, -1); fprintf(fp, "%d %d %g %g %g %g %d\n", 24, 2, span2[1] * vec2[0] + center[0], span2[1] * vec2[1] + center[1], span2[1] * vec2[2] + center[2], 3.0, 23); fprintf(fp, "%d %d %g %g %g %g %d\n", 25, 2, span3[0] * vec3[0] + center[0], span3[0] * vec3[1] + center[1], span3[0] * vec3[2] + center[2], 3.0, -1); fprintf(fp, "%d %d %g %g %g %g %d\n", 26, 2, span3[1] * vec3[0] + center[0], span3[1] * vec3[1] + center[1], span3[1] * vec3[2] + center[2], 3.0, 25); fclose(fp); //double corner[6]; /* FILE *fp = fopen("../data/test.swc", "w"); fprintf(fp, "%d %d %g %g %g %g %d\n", 1, 2, span[0] * vec[0] + center[0], span[0] * vec[1] + center[1], span[0] * vec[2] + center[2], 3.0, -1); fprintf(fp, "%d %d %g %g %g %g %d\n", 2, 2, span[1] * vec[0] + center[0], span[1] * vec[1] + center[1], span[1] * vec[2] + center[2], 3.0, 1); fprintf(fp, "%d %d %g %g %g %g %d\n", 3, 2, span2[0] * vec2[0] + center[0], span2[0] * vec2[1] + center[1], span2[0] * vec2[2] + center[2], 3.0, -1); fprintf(fp, "%d %d %g %g %g %g %d\n", 4, 2, span2[1] * vec2[0] + center[0], span2[1] * vec2[1] + center[1], span2[1] * vec2[2] + center[2], 3.0, 3); fprintf(fp, "%d %d %g %g %g %g %d\n", 5, 2, span3[0] * vec3[0] + center[0], span3[0] * vec3[1] + center[1], span3[0] * vec3[2] + center[2], 3.0, -1); fprintf(fp, "%d %d %g %g %g %g %d\n", 6, 2, span3[1] * vec3[0] + center[0], span3[1] * vec3[1] + center[1], span3[1] * vec3[2] + center[2], 3.0, 5); fclose(fp); */ //calculate corners //Draw the six line of the corners /* Stack *stack2 = Copy_Stack(stack); Zero_Stack(stack2); int i = 0; for (i = 0; i < obj->size; i++) { stack2->array[Stack_Util_Offset(obj->voxels[i][0], obj->voxels[i][1], obj->voxels[i][2], stack->width, stack->height, stack->depth)] = 1; } Write_Stack("../data/test.tif", stack2); */ #endif #if 0 Stack *stack = Read_Stack("../data/test2.tif"); Stack_Threshold_Binarize(stack, 6); Objlabel_Workspace ow; STACK_OBJLABEL_OPEN_WORKSPACE(stack, (&ow)); ow.conn = 26; ow.init_chord = TRUE; int obj_size = Stack_Label_Largest_Object_W(stack, 1, 2, &ow); Object_3d *obj = Make_Object_3d(obj_size, ow.conn); extract_object(ow.chord, ow.seed, obj); //Print_Object_3d(obj); /* STACK_OBJLABEL_CLOSE_WORKSPACE((&ow)); Objlabel_Workspace *ow = New_Objlabel_Workspace(); ow->conn = 26; ow->init_chord = TRUE; STACK_OBJLABEL_OPEN_WORKSPACE(stack, ow); Stack_Label_Largest_Object_W(stack, 1, 2, ow); */ Write_Stack("../data/test3.tif", stack); #endif #if 0 Mc_Stack *stack = Read_Mc_Stack("../data/test2.tif", -1); Print_Mc_Stack_Info(stack); size_t offset; size_t voxelNumber = Mc_Stack_Voxel_Number(stack); uint8_t* arrayc[3] = {NULL, NULL, NULL}; arrayc[0] = stack->array; arrayc[1] = stack->array + voxelNumber; arrayc[2] = stack->array + voxelNumber * 2; for (offset = 0; offset < voxelNumber; ++offset) { if ((arrayc[0][offset] != 128) || (arrayc[1][offset] != 6) || (arrayc[2][offset] != 0)) { arrayc[0][offset] = 0; arrayc[1][offset] = 0; arrayc[2][offset] = 0; } } Write_Mc_Stack("../data/test.tif", stack, NULL); Kill_Mc_Stack(stack); #endif #if 0 Mc_Stack *stack = Read_Mc_Stack("../data/flyem/TEM/slice_figure/segmentation/selected_body.tif", -1); Print_Mc_Stack_Info(stack); size_t offset; size_t voxelNumber = Mc_Stack_Voxel_Number(stack); Stack *mask = Make_Stack(GREY, stack->width, stack->height, stack->depth); uint8_t* arrayc[4] = {NULL, NULL, NULL, NULL}; int i; for (i = 0; i < 4; ++i) { arrayc[i] = stack->array + voxelNumber * i; } for (offset = 0; offset < voxelNumber; ++offset) { if ((arrayc[0][offset] > 0) || (arrayc[1][offset] > 0) || (arrayc[2][offset] > 0) || (arrayc[3][offset] > 0)) { mask->array[offset] = 1; } else { mask->array[offset] = 0; } } mask = Downsample_Stack_Max(mask, 7, 7, 0, NULL); Write_Stack("../data/test.tif", mask); #endif #if 0 Stack *stack = Read_Stack("../data/test2.tif"); size_t offset; size_t voxelNumber = Stack_Voxel_Number(stack); color_t *arrayc = (color_t*) stack->array; for (offset = 0; offset < voxelNumber; ++offset) { if ((arrayc[offset][0] != 128) || (arrayc[offset][1] != 6) || (arrayc[offset][2] != 0)) { arrayc[offset][0] = 0; arrayc[offset][1] = 0; arrayc[offset][2] = 0; } } Write_Stack("../data/test.tif", stack); #endif #if 0 Stack *stack = Read_Stack("../data/flyem/TEM/slice_figure/segmentation/selected_body_volume.tif"); Stack *out = Make_Stack(COLOR, stack->width, stack->height, stack->depth); Zero_Stack(out); Object_3d_List *objs = Stack_Find_Object_N(stack, NULL, 255, 0, 26); Print_Object_3d_List_Compact(objs); uint8_t color[] = {0, 200, 50, 200, 0, 0}; uint8_t *color2 = color; while (objs != NULL) { Object_3d *obj = objs->data; Stack_Draw_Object_C(out, obj, color2[0], color2[1], color2[2]); color2 += 3; objs = objs->next; break; } Write_Stack("../data/test.tif", out); #endif #if 0 //Stack *stack = Read_Stack("../data/benchmark/binary/2d/btrig2.tif"); Stack *stack = Make_Stack(GREY, 3, 3, 3); One_Stack(stack); //Zero_Stack(stack); //Set_Stack_Pixel(stack, 0, 1, 1, 1, 1); Set_Stack_Pixel(stack, 0, 1, 1, 1, 0); Set_Stack_Pixel(stack, 0, 1, 1, 0, 0); Set_Stack_Pixel(stack, 0, 0, 0, 0, 0); Set_Stack_Pixel(stack, 0, 0, 2, 0, 0); Set_Stack_Pixel(stack, 0, 2, 0, 0, 0); Set_Stack_Pixel(stack, 0, 2, 2, 0, 0); Set_Stack_Pixel(stack, 0, 0, 0, 2, 0); Set_Stack_Pixel(stack, 0, 0, 2, 2, 0); Set_Stack_Pixel(stack, 0, 2, 0, 2, 0); Set_Stack_Pixel(stack, 0, 2, 2, 2, 0); //Set_Stack_Pixel(stack, 0, 1, 1, 2, 0); Stack_Graph_Workspace *sgw = New_Stack_Graph_Workspace(); //Default_Stack_Graph_Workspace(sgw); sgw->signal_mask = stack; Graph *graph = Stack_Graph_W(stack, sgw); sgw->signal_mask = NULL; //Print_Graph(graph); //Graph_To_Dot_File(graph, "../data/test.dot"); if (Graph_Has_Hole(graph) == TRUE) { printf("The graph has a hole.\n"); } #endif #if 0 Stack *stack = Read_Stack("../data/flyem/skeletonization/session3/T1_207.tif"); size_t voxel_number = Stack_Voxel_Number(stack); size_t i; for (i = 0; i < voxel_number; ++i) { if (stack->array[i] == 1) { stack->array[i] = 255; } } Filter_3d *filter = Gaussian_Filter_3d(0.5, 0.5, 0.5); Stack *out = Filter_Stack(stack, filter); Write_Stack("../data/test2.tif", out); #endif #if 0 Stack *stack = Make_Stack(GREY, 3, 3, 3); Zero_Stack(stack); Cuboid_I cuboid; Cuboid_I_Set_S(&cuboid, 0, 0, 0, 4, 2, 3); Cuboid_I_Label_Stack(&cuboid, 1, stack); Print_Stack_Value(stack); #endif #if 0 Stack *stack = Make_Stack(GREY, 3, 3, 1); Zero_Stack(stack); Set_Stack_Pixel(stack, 1, 1, 0, 0, 1); Print_Stack_Value(stack); Stack *out = Downsample_Stack_Max(stack, 2, 2, 2, NULL); Print_Stack_Value(out); #endif #if 0 double t[3] = {1, 2 * 256 + 12, 255 * 256}; printf("%g\n", Stack_Voxel_Weight_C(t)); #endif #if 0 Stack *stack = Read_Stack_U("../data/vr/label.tif"); Stack_Binarize_Level(stack, 1); Stack_Label_Large_Objects_N(stack, NULL, 1, 2, 2000, 4); Stack_Threshold_Binarize(stack, 2); Write_Stack("../data/vr/label1.tif", stack); #endif #if 0 Stack *stack = Read_Stack_U("../data/vr/label.tif"); Stack_Binarize_Level(stack, 5); Stack_Label_Large_Objects_N(stack, NULL, 1, 2, 5000, 4); Stack_Threshold_Binarize(stack, 2); Write_Stack("../data/vr/label5.tif", stack); #endif #if 0 Stack *stack = Read_Stack_U("../data/vr/original.tif"); /* Make mask */ Stack *mask = Make_Stack(GREY, Stack_Width(stack), Stack_Height(stack), Stack_Depth(stack)); Zero_Stack(mask); Stack *overallLabel = Copy_Stack(mask); Stack *labelStack[5]; size_t voxelNumber = Stack_Voxel_Number(mask); size_t k; Struct_Element *se = Make_Disc_Se(5); int i; char filePath[100]; for (i = 0; i < 5; ++i) { sprintf(filePath, "../data/vr/label%d.tif", i + 1); labelStack[i] = Read_Stack_U(filePath); //labelStack[i] = Stack_Erode_Fast(labelStack[i], NULL, se); Stack_Or(mask, labelStack[i], mask); for (k = 0; k < voxelNumber; ++k) { if (labelStack[i]->array[k] == 1) { overallLabel->array[k] = i + 1; } } } for (k = 0; k < voxelNumber; ++k) { if (mask->array[k] == 1) { mask->array[k] = SP_GROW_SOURCE; } } Sp_Grow_Workspace *sgw = New_Sp_Grow_Workspace(); sgw->size = voxelNumber; Sp_Grow_Workspace_Set_Mask(sgw, mask->array); sgw->wf = Stack_Voxel_Weight_C; sgw->sp_option = 1; tic(); Int_Arraylist *path = Stack_Sp_Grow(stack, NULL, 0, NULL, 0, sgw); printf("time: %llu\n", toc()); Kill_Int_Arraylist(path); for (k = 0; k < voxelNumber; ++k) { if (mask->array[k] == 0) { int idx = (int) k; while (overallLabel->array[idx] == 0) { idx = sgw->path[idx]; } int label = overallLabel->array[idx]; idx = (int) k; while (overallLabel->array[idx] == 0) { overallLabel->array[idx] = label; idx = sgw->path[idx]; } } } for (k = 0; k < voxelNumber; ++k) { if (overallLabel->array[k] == 1 || overallLabel->array[k] == 5) { overallLabel->array[k] = 0; } } Write_Stack("../data/test.tif", overallLabel); Kill_Stack(stack); #endif return 0; }
bool MainWindow::sendFileStream() { const DRUIDString cancelStreaming("0"); uint8_t sendBuffer[MAINWINDOW_SENDSTREAM_BUFFER_SIZE]; std::map<wxString, wxString> wildcardMap; wxString extension, defaultDir, defaultFile, wildcards; // setup wildcards and defaults, partially based on last uploaded file. wildcardMap[_T("txt")] = wxT("Text (*.txt)|*.txt"); wildcardMap[_T("csv")] = wxT("CSV (*.csv)|*.csv"); wildcardMap[_T("wav")] = wxT("WAVE (*.wav)|*.wav"); wildcardMap[_T("html")] = wxT("HTML (*.html)|*.html"); if (last_uploaded_filepath.Length()) { wxFileName fname(last_uploaded_filepath); defaultDir = fname.GetPath(); defaultFile = fname.GetFullName(); extension = fname.GetExt().Lower(); if (extension.Length()) { // see if this extension is present std::map<wxString, wxString>::iterator findExtIter = wildcardMap.find(extension); if (findExtIter == wildcardMap.end()) { // nope, not here... add it wildcardMap[extension] = extension + wxT(" files (*.") + extension + _T(")|*.") + extension ; } } } for (std::map<wxString, wxString>::iterator wcIter = wildcardMap.begin(); wcIter != wildcardMap.end(); wcIter++) { wildcards += (*wcIter).second + _T("|"); } // add the all files option wildcards += wxT("All files|*.*"); DRUID_DEBUG2("WILDCARDS IS ", wildcards.mb_str()); DRUID::SerialUIUserPtr serial_user = connection->serialUser(); wxFileDialog * selectFileDialog = new wxFileDialog(this, wxT("Select file to use for upload"), defaultDir, defaultFile, wildcards, wxFD_OPEN | wxFD_FILE_MUST_EXIST); if (selectFileDialog->ShowModal() != wxID_OK) { serial_user->sendAndReceive(cancelStreaming, true); return false; } wxString fileName = selectFileDialog->GetPath(); configUpdateLastUploadedFilePath(fileName); wxFile fileHandle; if (!fileHandle.Open(fileName.c_str(), wxFile::read)) { wxString errMsg(wxT("Could not open file ")); errMsg += fileName; wxMessageDialog *dial = new wxMessageDialog(NULL, errMsg, wxT("Can't read file"), wxOK | wxICON_ERROR); dial->ShowModal(); serial_user->sendAndReceive(cancelStreaming, true); return false; } wxFileOffset fileLen = fileHandle.Length(); if (fileLen < 1) { // forget this serial_user->sendAndReceive(cancelStreaming, true); return false; } DRUIDString lenAsStr; try { lenAsStr = boost::lexical_cast<DRUIDString>(fileLen); } catch (boost::bad_lexical_cast & e) { // could not cast string?? serial_user->sendAndReceive(cancelStreaming, true); return false; } // seems it worked... send len: serial_user->send(lenAsStr, true); size_t curPos = 0; serial_user->setAutoReplaceLastMessage(false); serial_user->checkForLastMessage(); // outputTextCtrl->AppendText(DRUID_STDSTRING_TOWX(serial_user->lastMessage())); serial_user->flushReceiveBuffer(); bool curEOTChecks = serial_user->eotChecks(); serial_user->setEotChecks(false); serial_user->setAutoReplaceLastMessage(false); DRUID_DEBUG2("Reading file of len ", fileLen); // wait a while between each send, to allow for sending and processing // set a wait time, per byte, related to baud rate size_t waitTimePerByte = upload_rate_delay_factor * 8 * 1000000 / baud_rate ; DRUID_DEBUG2("Will wait between block sends (us/byte):", waitTimePerByte); wxString statusSuffixStr(_T("/") + DRUID_STDSTRING_TOWX(lenAsStr)); wxString statusPosStr; { wxBusyCursor wait; DRUIDString curPosStr; while (curPos < fileLen) { DRUID_DEBUG2("*** reading from pos ", curPos); size_t numToRead = (MAINWINDOW_SENDSTREAM_BUFFER_SIZE < (fileLen - curPos)) ? MAINWINDOW_SENDSTREAM_BUFFER_SIZE : (fileLen - curPos); size_t numRead = fileHandle.Read(sendBuffer, numToRead); if (numRead < 1) { break; } serial_user->send(sendBuffer, numRead); usleep(waitTimePerByte * numRead); curPos += numRead; try { curPosStr = boost::lexical_cast<DRUIDString>(curPos); statusPosStr = DRUID_STDSTRING_TOWX(curPosStr) + statusSuffixStr; SetStatusText(statusPosStr); } catch (boost::bad_lexical_cast & e) { } wxYield(); touchLastInteraction(); } } statusPosStr += _T(" Complete !"); SetStatusText(statusPosStr); fileHandle.Close(); serial_user->setEotChecks(curEOTChecks); // serial_user->sendAndReceive("", true); serial_user->checkForLastMessage(); outputTextCtrl->AppendText(DRUID_STDSTRING_TOWX(serial_user->lastMessage())); serial_user->setAutoReplaceLastMessage(true); return true; }
void TMVAClassificationCategory() { //--------------------------------------------------------------- // Example for usage of different event categories with classifiers std::cout << std::endl << "==> Start TMVAClassificationCategory" << std::endl; bool batchMode = false; // Create a new root output file. TString outfileName( "TMVA.root" ); TFile* outputFile = TFile::Open( outfileName, "RECREATE" ); // Create the factory object (see TMVAClassification.C for more information) std::string factoryOptions( "!V:!Silent:Transformations=I;D;P;G,D" ); if (batchMode) factoryOptions += ":!Color:!DrawProgressBar"; TMVA::Factory *factory = new TMVA::Factory( "TMVAClassificationCategory", outputFile, factoryOptions ); // Define the input variables used for the MVA training factory->AddVariable( "var1", 'F' ); factory->AddVariable( "var2", 'F' ); factory->AddVariable( "var3", 'F' ); factory->AddVariable( "var4", 'F' ); // You can add so-called "Spectator variables", which are not used in the MVA training, // but will appear in the final "TestTree" produced by TMVA. This TestTree will contain the // input variables, the response values of all trained MVAs, and the spectator variables factory->AddSpectator( "eta" ); // Load the signal and background event samples from ROOT trees TFile *input(0); TString fname( "" ); if (UseOffsetMethod) fname = "data/toy_sigbkg_categ_offset.root"; else fname = "data/toy_sigbkg_categ_varoff.root"; if (!gSystem->AccessPathName( fname )) { // first we try to find tmva_example.root in the local directory std::cout << "--- TMVAClassificationCategory: Accessing " << fname << std::endl; input = TFile::Open( fname ); } if (!input) { std::cout << "ERROR: could not open data file: " << fname << std::endl; exit(1); } TTree *signal = (TTree*)input->Get("TreeS"); TTree *background = (TTree*)input->Get("TreeB"); /// Global event weights per tree (see below for setting event-wise weights) Double_t signalWeight = 1.0; Double_t backgroundWeight = 1.0; /// You can add an arbitrary number of signal or background trees factory->AddSignalTree ( signal, signalWeight ); factory->AddBackgroundTree( background, backgroundWeight ); // Apply additional cuts on the signal and background samples (can be different) TCut mycuts = ""; // for example: TCut mycuts = "abs(var1)<0.5 && abs(var2-0.5)<1"; TCut mycutb = ""; // for example: TCut mycutb = "abs(var1)<0.5"; // Tell the factory how to use the training and testing events factory->PrepareTrainingAndTestTree( mycuts, mycutb, "nTrain_Signal=0:nTrain_Background=0:SplitMode=Random:NormMode=NumEvents:!V" ); // ---- Book MVA methods // Fisher discriminant factory->BookMethod( TMVA::Types::kFisher, "Fisher", "!H:!V:Fisher" ); // Likelihood factory->BookMethod( TMVA::Types::kLikelihood, "Likelihood", "!H:!V:TransformOutput:PDFInterpol=Spline2:NSmoothSig[0]=20:NSmoothBkg[0]=20:NSmoothBkg[1]=10:NSmooth=1:NAvEvtPerBin=50" ); // --- Categorised classifier TMVA::MethodCategory* mcat = 0; // The variable sets TString theCat1Vars = "var1:var2:var3:var4"; TString theCat2Vars = (UseOffsetMethod ? "var1:var2:var3:var4" : "var1:var2:var3"); // Fisher with categories TMVA::MethodBase* fiCat = factory->BookMethod( TMVA::Types::kCategory, "FisherCat","" ); mcat = dynamic_cast<TMVA::MethodCategory*>(fiCat); mcat->AddMethod( "abs(eta)<=1.3", theCat1Vars, TMVA::Types::kFisher, "Category_Fisher_1","!H:!V:Fisher" ); mcat->AddMethod( "abs(eta)>1.3", theCat2Vars, TMVA::Types::kFisher, "Category_Fisher_2","!H:!V:Fisher" ); // Likelihood with categories TMVA::MethodBase* liCat = factory->BookMethod( TMVA::Types::kCategory, "LikelihoodCat","" ); mcat = dynamic_cast<TMVA::MethodCategory*>(liCat); mcat->AddMethod( "abs(eta)<=1.3",theCat1Vars, TMVA::Types::kLikelihood, "Category_Likelihood_1","!H:!V:TransformOutput:PDFInterpol=Spline2:NSmoothSig[0]=20:NSmoothBkg[0]=20:NSmoothBkg[1]=10:NSmooth=1:NAvEvtPerBin=50" ); mcat->AddMethod( "abs(eta)>1.3", theCat2Vars, TMVA::Types::kLikelihood, "Category_Likelihood_2","!H:!V:TransformOutput:PDFInterpol=Spline2:NSmoothSig[0]=20:NSmoothBkg[0]=20:NSmoothBkg[1]=10:NSmooth=1:NAvEvtPerBin=50" ); // ---- Now you can tell the factory to train, test, and evaluate the MVAs // Train MVAs using the set of training events factory->TrainAllMethods(); // ---- Evaluate all MVAs using the set of test events factory->TestAllMethods(); // ----- Evaluate and compare performance of all configured MVAs factory->EvaluateAllMethods(); // -------------------------------------------------------------- // Save the output outputFile->Close(); std::cout << "==> Wrote root file: " << outputFile->GetName() << std::endl; std::cout << "==> TMVAClassificationCategory is done!" << std::endl; // Clean up delete factory; // Launch the GUI for the root macros if (!gROOT->IsBatch()) TMVAGui( outfileName ); }
void MeshLabXMLStdDialog::loadFrameContent( ) { assert(qf); qf->hide(); QLabel *ql; QGridLayout *gridLayout = new QGridLayout(qf); qf->setLayout(gridLayout); QString fname(curmfc->act->text()); setWindowTitle(fname); ql = new QLabel("<i>"+curmfc->xmlInfo->filterHelp(fname)+"</i>",qf); ql->setTextFormat(Qt::RichText); ql->setWordWrap(true); gridLayout->addWidget(ql,0,0,1,2,Qt::AlignTop); // this widgets spans over two columns. stdParFrame = new XMLStdParFrame(this,curgla); //connect(stdParFrame,SIGNAL(frameEvaluateExpression(const Expression&,Value**)),this,SIGNAL(dialogEvaluateExpression(const Expression&,Value**)),Qt::DirectConnection); MLXMLPluginInfo::XMLMapList mplist = curmfc->xmlInfo->filterParametersExtendedInfo(fname); EnvWrap wrap(env); stdParFrame->loadFrameContent(mplist,wrap); gridLayout->addWidget(stdParFrame,1,0,1,2); //int buttonRow = 2; // the row where the line of buttons start helpButton = new QPushButton("Help", qf); //helpButton->setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Minimum); closeButton = new QPushButton("Close", qf); //closeButton->setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Minimum); applyButton = new QPushButton("Apply", qf); //applyButton->setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Minimum); defaultButton = new QPushButton("Default", qf); //defaultButton->setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Minimum); applyButton->setFocus(); ExpandButtonWidget* exp = new ExpandButtonWidget(qf); connect(exp,SIGNAL(expandView(bool)),this,SLOT(extendedView(bool))); connect(this->parentWidget(),SIGNAL(filterExecuted()),this,SLOT(postFilterExecution())); #ifdef Q_WS_MAC // Hack needed on mac for correct sizes of button in the bottom of the dialog. helpButton->setMinimumSize(100, 25); closeButton->setMinimumSize(100,25); applyButton->setMinimumSize(100,25); defaultButton->setMinimumSize(100, 25); #endif QString postCond = curmfc->xmlInfo->filterAttribute(fname,MLXMLElNames::filterPostCond); QStringList postCondList = postCond.split(QRegExp("\\W+"), QString::SkipEmptyParts); curmask = MeshLabFilterInterface::convertStringListToMeshElementEnum(postCondList); if(isPreviewable()) { previewCB = new QCheckBox("Preview", qf); previewCB->setCheckState(Qt::Unchecked); gridLayout->addWidget(previewCB, gridLayout->rowCount(),0,Qt::AlignBottom); connect(previewCB,SIGNAL(toggled(bool)),this,SLOT( togglePreview() )); //buttonRow++; } connect(helpButton,SIGNAL(clicked()),this,SLOT(toggleHelp())); connect(closeButton,SIGNAL(clicked()),this,SLOT(closeClick())); connect(defaultButton,SIGNAL(clicked()),this,SLOT(resetExpressions())); connect(applyButton,SIGNAL(clicked()),this,SLOT(applyClick())); gridLayout->addWidget(exp,gridLayout->rowCount(),0,1,2,Qt::AlignJustify); int firstButLine = gridLayout->rowCount(); gridLayout->addWidget(helpButton, firstButLine,1,Qt::AlignBottom); gridLayout->addWidget(defaultButton,firstButLine,0,Qt::AlignBottom); int secButLine = gridLayout->rowCount(); gridLayout->addWidget(closeButton, secButLine,0,Qt::AlignBottom); gridLayout->addWidget(applyButton, secButLine,1,Qt::AlignBottom); qf->showNormal(); qf->adjustSize(); //set the minimum size so it will shrink down to the right size after the help is toggled //this->setMinimumSize(qf->sizeHint()); this->showNormal(); this->adjustSize(); //setSizePolicy(QSizePolicy::Minimum,QSizePolicy::MinimumExpanding); }
int main(int argc, char* argv []) { // Do some output std::cout << "========== Test Suite 1 ==========" << std::endl; std::cout << " Testing computational aspects " << std::endl; // create a variety of stopping power models to test std::vector<StopPow::StopPow*> models; // --------------------------------------- // Set up SRIM models // --------------------------------------- // Load all SRIM models from SRIM directory std::string dir_name("SRIM"); DIR *SRIM_dir = opendir(dir_name.c_str()); if(SRIM_dir) // dir is open { // loop over all files: dirent* result = readdir(SRIM_dir); while( (result=readdir(SRIM_dir)) != NULL ) { // try to load SRIM: try { // construct relative file path/name: std::string fname(dir_name); fname.append("/"); fname.append(result->d_name); // create model and add to the vector: StopPow::StopPow* s = new StopPow::StopPow_SRIM(fname); models.push_back(s); } // catch and ignore all exceptions catch(...){} } } std::cout << models.size() << " SRIM model(s) loaded" << std::endl; // test the SRIM models: bool SRIM_passed = run_tests(models,argc,argv); if(SRIM_passed) std::cout << "Passed!" << std::endl; else { std::cout << "FAILED!" << std::endl; return 1; } // clear the models: for( StopPow::StopPow* s : models ) delete s; models.clear(); // --------------------------------------- // Set up Li-Petrasso models // --------------------------------------- // plasma parameters read from file: std::string fname("test1/LiPetrasso.csv"); std::vector< std::vector<double> > file_data = read_model_file(fname); // construct the models: double mt = 1; double Zt = 1; for(int i=0; i<file_data.size()-3; i+=4) { StopPow::StopPow * s = new StopPow::StopPow_LP(mt,Zt, file_data[i],file_data[i+1], file_data[i+2],file_data[i+3] ); models.push_back(s); } std::cout << models.size() << " Li-Petrasso model(s) loaded" << std::endl; // test the L-P models: bool LP_passed = run_tests(models,argc,argv); if(LP_passed) std::cout << "Passed!" << std::endl; else { std::cout << "FAILED!" << std::endl; return 1; } // clear the models: for( StopPow::StopPow* s : models ) delete s; models.clear(); // --------------------------------------- // Set up Li-Petrasso models // --------------------------------------- // plasma parameters read from file: fname = "test1/BetheBloch.csv"; file_data = read_model_file(fname); // construct the models: mt = 1; Zt = 1; for(int i=0; i<file_data.size()-2; i+=4) { StopPow::StopPow * s = new StopPow::StopPow_BetheBloch(mt,Zt, file_data[i],file_data[i+1], file_data[i+2] ); models.push_back(s); } std::cout << models.size() << " Bethe-Bloch model(s) loaded" << std::endl; // test the L-P models: bool BB_passed = run_tests(models,argc,argv); if(BB_passed) std::cout << "Passed!" << std::endl; else { std::cout << "FAILED!" << std::endl; return 1; } std::cout << "All tests passed" << std::endl; return 0; }
void FileMemoryCard::Open() { for( int slot=0; slot<8; ++slot ) { if( FileMcd_IsMultitapSlot(slot) ) { if( !EmuConfig.MultitapPort0_Enabled && (FileMcd_GetMtapPort(slot) == 0) ) continue; if( !EmuConfig.MultitapPort1_Enabled && (FileMcd_GetMtapPort(slot) == 1) ) continue; } wxFileName fname( g_Conf->FullpathToMcd( slot ) ); wxString str( fname.GetFullPath() ); bool cont = false; if( fname.GetFullName().IsEmpty() ) { str = L"[empty filename]"; cont = true; } if( !g_Conf->Mcd[slot].Enabled ) { str = L"[disabled]"; cont = true; } if ( g_Conf->Mcd[slot].Type != MemoryCardType::MemoryCard_File ) { str = L"[is not memcard file]"; cont = true; } Console.WriteLn( cont ? Color_Gray : Color_Green, L"McdSlot %u [File]: " + str, slot ); if( cont ) continue; const wxULongLong fsz = fname.GetSize(); if( (fsz == 0) || (fsz == wxInvalidSize) ) { // FIXME : Ideally this should prompt the user for the size of the // memory card file they would like to create, instead of trying to // create one automatically. if( !Create( str, 8 ) ) { Msgbox::Alert( wxsFormat(_( "Could not create a memory card: \n\n%s\n\n" ), str.c_str()) + GetDisabledMessage( slot ) ); } } // [TODO] : Add memcard size detection and report it to the console log. // (8MB, 256Mb, formatted, unformatted, etc ...) #ifdef __WXMSW__ NTFS_CompressFile( str, g_Conf->McdCompressNTFS ); #endif if( !m_file[slot].Open( str.c_str(), L"r+b" ) ) { // Translation note: detailed description should mention that the memory card will be disabled // for the duration of this session. Msgbox::Alert( wxsFormat(_( "Access denied to memory card: \n\n%s\n\n" ), str.c_str()) + GetDisabledMessage( slot ) ); } else // Load checksum { m_ispsx[slot] = m_file[slot].Length() == 0x20000; m_chkaddr = 0x210; if(!m_ispsx[slot] && !!m_file[slot].Seek( m_chkaddr )) m_file[slot].Read( &m_chksum[slot], 8 ); } } }
int main(int argc, char** argv) { double ri = 0.0; double rf = 1.0; std::vector<int> npts(3); npts[0]=51;npts[1]=51;npts[2]=51; double xcut=0.23; double ycut=0.67; const int nk0=1; const int nk1=1; const int nk2=1; //Create one-dimensional grids for three orthogonal directions typedef LinearGrid<double> GridType; GridType gridX, gridY, gridZ; gridX.set(ri,rf,npts[0]); gridY.set(ri,rf,npts[1]); gridZ.set(ri,rf,npts[2]); //Create an analytic function for assignment ComboFunc infunc; infunc.push_back(0.5,new TestFunc(1,1,1)); //infunc.push_back(0.3,new TestFunc(1,1,2)); //infunc.push_back(0.1,new TestFunc(1,2,1)); //infunc.push_back(0.01,new TestFunc(2,1,1)); //infunc.push_back(0.01,new TestFunc(2,2,1)); //infunc.push_back(0.001,new TestFunc(2,1,2)); //infunc.push_back(0.001,new TestFunc(2,2,2)); //infunc.push_back(0.001,new TestFunc(5,5,5)); //infunc.push_back(-0.3,new TestFunc(7,2,3)); //infunc.push_back(0.01,new TestFunc(7,7,7)); //infunc.push_back(0.001,new TestFunc(5,5,5)); //Write to an array std::vector<double> inData(npts[0]*npts[1]*npts[2]); std::vector<double>::iterator it(inData.begin()); Pooma::Clock timer; timer.start(); //Assign the values for(int ix=0; ix<npts[0]; ix++) { double x(gridX(ix)); for(int iy=0; iy<npts[1]; iy++) { double y(gridY(iy)); for(int iz=0; iz<npts[2]; iz++) { (*it)=infunc.f(x,y,gridZ(iz));++it; } } } timer.stop(); cout << "Time to evaluate " << timer.cpu_time() << endl; //Test TriCubicSplineT function //Create XYZCubicGrid XYZCubicGrid<double> grid3(&gridX,&gridY,&gridZ); //Create a TriCubicSpline with PBC: have to think more about fixed-boundary conditions TriCubicSplineT<double> aorb(&grid3); //Reset the coefficients aorb.reset(inData.begin(), inData.end()); double lap,val; TinyVector<double,3> grad; //aorb.reset(); //Write for vtk ImageData string fname("spline3d.vti"); std::ofstream dfile(fname.c_str()); dfile.setf(ios::scientific, ios::floatfield); dfile.setf(ios::left,ios::adjustfield); dfile.precision(10); dfile << "<?xml version=\"1.0\"?>" << endl; dfile << "<VTKFile type=\"ImageData\" version=\"0.1\">" << endl; dfile << " <ImageData WholeExtent=\"0 " << npts[0]-2 << " 0 " << npts[1]-2 << " 0 " << npts[2]-2 << "\" Origin=\"0 0 0\" Spacing=\"1 1 1\">"<< endl; dfile << " <Piece Extent=\"0 " << npts[0]-2 << " 0 " << npts[1]-2 << " 0 " << npts[2]-2 << "\">" << endl; dfile << " <PointData Scalars=\"wfs\">" << endl; dfile << " <DataArray type=\"Float32\" Name=\"wfs\">" << endl; timer.start(); int ng=0; for(int ix=0; ix<npts[0]-1; ix++) { double x(gridX(ix)); for(int iy=0; iy<npts[1]-1; iy++) { double y(gridY(iy)); for(int iz=0; iz<npts[2]-1; iz++, ng++) { TinyVector<double,3> p(x,y,gridZ(iz)); //aorb.setgrid(p); //Timing with the ofstream is not correct. //Uncomment the line below and comment out the next two line. //double t=aorb.evaluate(p,grad,lap); dfile << setw(20) << aorb.evaluate(p,grad,lap); if(ng%5 == 4) dfile << endl; } } } timer.stop(); cout << "Time to evaluate with spline " << timer.cpu_time() << endl; dfile << " </DataArray>" << endl; dfile << " </PointData>" << endl; dfile << " </Piece>" << endl; dfile << " </ImageData>" << endl; dfile << "</VTKFile>" << endl; hid_t h_file = H5Fcreate("spline3d.h5",H5F_ACC_TRUNC,H5P_DEFAULT,H5P_DEFAULT); HDFAttribIO<std::vector<double> > dump(inData,npts); dump.write(h_file,"orb0000"); HDFAttribIO<TriCubicSplineT<double> > dump1(aorb); dump1.write(h_file,"spline0000"); H5Fclose(h_file); //double lap; //TinyVector<double,3> grad; //for(int k=0; k<nptY-1; k++) { // //TinyVector<double,3> p(xcut,ycut,gridZ(k)+0.11*gridZ.dr(k)); // TinyVector<double,3> p(xcut,gridY(k)+0.11*gridY.dr(k),ycut); // aorb.setgrid(p); // double y=aorb.evaluate(p,grad,lap); // dfile << setw(30) << p[1] << setw(30) << infunc.f(p) << setw(30) << y << setw(30) << infunc.d2f(p) << setw(30) << lap << endl; //} return 0; }
int main(int argc, char * argv[]) { // This ParsleyNode pointer will be the root for the xml document ParsleyNode* root; // The Parsley class parses the test.xml document. It has // two methods, parse() and save() and it stores neither // the filename nor the ParsleyNode, meaning you must take care // of calling the save() method before exiting your program // if you want to save the XML document back to a file. // It also means, however, that you can get rid of // the parser if you don't need it anymore after parsing // a document. Parsley parser; // Store the file name std::string fname("/Users/petergoldsborough/Documents/C++/Exercises/Exercises/test.xml"); // Call the parse() method to parse an xml document. It then // returns (if all went well) the root node of the document. root = parser.parse(fname); // We now have access to the entire tree. ParsleyNode* firstChild = root->getFirstChild(); //Lets change the first child's tag name. firstChild->setTag("changedTagName"); // It's also good to know where our food is from firstChild->addAttr("origin", "Belgium"); // We're also adding a 10% tax due to a critical ice cream // shortage in our region, forcing us to import it from // the north pole. firstChild->getElementsByTagName("price")[0]->setData("$4.29"); // We can create a new ParsleyNode. Its constructor takes the tag // name for the new XML node. ParsleyNode* child = new ParsleyNode("dish"); // We can give it an attribute child->addAttr("time", "lunch"); // Let's also put something between the tags child->setData("KFC with ketchup and caviar"); // Adding a new ParsleyNode to an existing one is very easy root->appendChild(child); // Did it work? std::cout << root->getLastChild()->getData() << std::endl << root->getNthChild(1)->getAttr("time") << std::endl; // This should output: // >>> KFC with ketchup and caviar // >>> lunch // Finally, if you want to save the XML document, call the parser's // save() method to store the XML tree back into a file. By default, // this also destroys the tree. If you want to keep on using the tree // or maybe save it into multiple files, set the third argument to false // as I have here. This means you must take care of deleting the tree // yourself afterwards. parser.save(root, fname, false); // Which would be done like so: delete root; // Note that as soon as you make a new node part of at tree like we // did here for "child", you only need to delete the root. Let recursion // take care of the rest. }
int main(int argc, char *argv[]) { LOGOG_INITIALIZE(); auto* logog_cout(new logog::Cout); auto* custom_format(new BaseLib::LogogSimpleFormatter); logog_cout->SetFormatter(*custom_format); TCLAP::CmdLine cmd("Simple mesh search test", ' ', "0.1"); // Define a value argument and add it to the command line. // A value arg defines a flag and a type of value that it expects, // such as "-m meshfile". TCLAP::ValueArg<std::string> mesh_arg("m","mesh","input mesh file",true,"test.msh","string"); // Add the argument mesh_arg to the CmdLine object. The CmdLine object // uses this Arg to parse the command line. cmd.add( mesh_arg ); TCLAP::ValueArg<unsigned> number_arg("n","number-of-test-points","the number of test points",true,10000,"positive number"); cmd.add( number_arg ); TCLAP::ValueArg<bool> contiguous_arg("c","use-contiguous-memory","use a contiguous memory for the test",false,true,"yes or no | 1 or 0"); cmd.add( contiguous_arg ); cmd.parse( argc, argv ); std::string fname (mesh_arg.getValue()); MeshLib::IO::Legacy::MeshIO mesh_io; #ifndef WIN32 BaseLib::MemWatch mem_watch; unsigned long mem_without_mesh (mem_watch.getVirtMemUsage()); #endif BaseLib::RunTime run_time; run_time.start(); MeshLib::Mesh* mesh (mesh_io.loadMeshFromFile(fname)); #ifndef WIN32 unsigned long mem_with_mesh (mem_watch.getVirtMemUsage()); INFO ("mem for mesh: %i MB", (mem_with_mesh - mem_without_mesh)/(1024*1024)); #endif INFO ("time for reading: %f s", run_time.elapsed()); // *** preparing test data std::vector<MeshLib::Node*> const& nodes(mesh->getNodes()); std::vector<GeoLib::Point*> pnts_for_search; unsigned n(std::min(static_cast<unsigned>(nodes.size()), number_arg.getValue())); for (std::size_t k(0); k<n; k++) { pnts_for_search.push_back(new GeoLib::Point(*(nodes[k]), k)); } std::vector<std::size_t> idx_found_nodes; testMeshGridAlgorithm(mesh, pnts_for_search, idx_found_nodes, contiguous_arg.getValue()); for (std::size_t k(0); k<n; k++) { delete pnts_for_search[k]; } delete mesh; delete custom_format; delete logog_cout; LOGOG_SHUTDOWN(); }
//! reads indices from database void Table::loadIndices() { if (indicesLoadedM) return; indicesM.clear(); DatabasePtr db = getDatabase(); wxMBConv* conv = db->getCharsetConverter(); MetadataLoader* loader = db->getMetadataLoader(); // first start a transaction for metadata loading, then lock the table // when objects go out of scope and are destroyed, table will be unlocked // before the transaction is committed - any update() calls on observers // can possibly use the same transaction MetadataLoaderTransaction tr(loader); SubjectLocker lock(this); IBPP::Statement& st1 = loader->getStatement( "SELECT i.rdb$index_name, i.rdb$unique_flag, i.rdb$index_inactive, " " i.rdb$index_type, i.rdb$statistics, " " s.rdb$field_name, rc.rdb$constraint_name, i.rdb$expression_source " " from rdb$indices i " " left join rdb$index_segments s on i.rdb$index_name = s.rdb$index_name " " left join rdb$relation_constraints rc " " on rc.rdb$index_name = i.rdb$index_name " " where i.rdb$relation_name = ? " " order by i.rdb$index_name, s.rdb$field_position " ); st1->Set(1, wx2std(getName_(), conv)); st1->Execute(); Index* i = 0; while (st1->Fetch()) { std::string s; st1->Get(1, s); wxString ixname(std2wxIdentifier(s, conv)); short unq, inactive, type; if (st1->IsNull(2)) // null = non-unique unq = 0; else st1->Get(2, unq); if (st1->IsNull(3)) // null = active inactive = 0; else st1->Get(3, inactive); if (st1->IsNull(4)) // null = ascending type = 0; else st1->Get(4, type); double statistics; if (st1->IsNull(5)) // this can happen, see bug #1825725 statistics = -1; else st1->Get(5, statistics); st1->Get(6, s); wxString fname(std2wxIdentifier(s, conv)); wxString expression; readBlob(st1, 8, expression, conv); if (i && i->getName_() == ixname) i->getSegments()->push_back(fname); else { Index x( unq == 1, inactive == 0, type == 0, statistics, !st1->IsNull(7), expression ); indicesM.push_back(x); i = &indicesM.back(); i->setName_(ixname); i->getSegments()->push_back(fname); i->setParent(this); } } indicesLoadedM = true; }
TEST_P(BroxOpticalFlow, Regression) { cv::Mat frame0 = readImageType("opticalflow/frame0.png", CV_32FC1); ASSERT_FALSE(frame0.empty()); cv::Mat frame1 = readImageType("opticalflow/frame1.png", CV_32FC1); ASSERT_FALSE(frame1.empty()); cv::gpu::BroxOpticalFlow brox(0.197f /*alpha*/, 50.0f /*gamma*/, 0.8f /*scale_factor*/, 10 /*inner_iterations*/, 77 /*outer_iterations*/, 10 /*solver_iterations*/); cv::gpu::GpuMat u; cv::gpu::GpuMat v; brox(loadMat(frame0), loadMat(frame1), u, v); #ifndef DUMP std::string fname(cvtest::TS::ptr()->get_data_path()); if (devInfo.majorVersion() >= 2) fname += BROX_OPTICAL_FLOW_DUMP_FILE_CC20; else fname += BROX_OPTICAL_FLOW_DUMP_FILE; std::ifstream f(fname.c_str(), std::ios_base::binary); int rows, cols; f.read((char*)&rows, sizeof(rows)); f.read((char*)&cols, sizeof(cols)); cv::Mat u_gold(rows, cols, CV_32FC1); for (int i = 0; i < u_gold.rows; ++i) f.read(u_gold.ptr<char>(i), u_gold.cols * sizeof(float)); cv::Mat v_gold(rows, cols, CV_32FC1); for (int i = 0; i < v_gold.rows; ++i) f.read(v_gold.ptr<char>(i), v_gold.cols * sizeof(float)); EXPECT_MAT_NEAR(u_gold, u, 0); EXPECT_MAT_NEAR(v_gold, v, 0); #else std::string fname(cvtest::TS::ptr()->get_data_path()); if (devInfo.majorVersion() >= 2) fname += BROX_OPTICAL_FLOW_DUMP_FILE_CC20; else fname += BROX_OPTICAL_FLOW_DUMP_FILE; std::ofstream f(fname.c_str(), std::ios_base::binary); f.write((char*)&u.rows, sizeof(u.rows)); f.write((char*)&u.cols, sizeof(u.cols)); cv::Mat h_u(u); cv::Mat h_v(v); for (int i = 0; i < u.rows; ++i) f.write(h_u.ptr<char>(i), u.cols * sizeof(float)); for (int i = 0; i < v.rows; ++i) f.write(h_v.ptr<char>(i), v.cols * sizeof(float)); #endif }
void each_thread(mg_connection* conn, struct Thread* r, char display_state, bool admin_view, const char* iid, const char* uid){ time_t now = time(NULL); string thread_post_time = cc_timestamp_to_time(r->date); int diff_day = cc_timestamp_diff_day(now, r->date); const char* content = unq_read_string(pDb, r->content); string thread_content(content); delete [] content; if((display_state & SEND_CUT_LONG_COMMENT) && thread_content.size() > 1024) thread_content = thread_content.substr(0, 1024) + templates.invoke("misc").toggle("more_contents").build_destory(); //+ "<font color='red'><b>👁" + STRING_MORE + "</b></font>"; HTMLTemplate *ht = templates.invoke_pointer("single_thread"); map<string, bool> stats; map<string, string> vars; ConfigManager c; stats["reply"] = display_state & SEND_IS_REPLY; stats["show_reply"] = display_state & SEND_SHOW_REPLY_LINK; stats["archive"] = c.global().get<bool>("archive"); stats["normal_display"] = r->state & NORMAL_DISPLAY || admin_view; stats["thread_poster_is_admin"] = (strcmp(r->ssid, "Admin") == 0); stats["thread_poster_is_sameone"] = (strcmp(r->ssid, iid) == 0); stats["is_sameone"] = (strcmp(r->ssid, uid) == 0); stats["sage"] = (r->state & SAGE_THREAD && !stats["reply"]); stats["lock"] = (r->state & LOCKED_THREAD); stats["delete"] = !(r->state & NORMAL_DISPLAY); stats["show_admin"] = admin_view; if (strlen(r->imgSrc) >= 4){ string fname(r->imgSrc); vars["THREAD_IMAGE"] = fname; if (!cc_valid_image_ext(fname).empty()){ stats["image_attached"] = true; if(display_state & SEND_CUT_IMAGE){ struct stat st; stat(("images/" + fname).c_str(), &st); stats["show_size_only"] = true; vars["THREAD_IMAGE_SIZE"] = to_string((int)(st.st_size / 1024)); } else{ stats["show_full_image"] = true; vars["THREAD_THUMB_PREFIX"] = c.global().get("image::thumb_prefix"); } }else{ stats["file_attached"] = true; } } if(r->childThread && !(display_state & SEND_CUT_REPLY_COUNT)){ struct Thread* c = unq_read_thread(pDb, r->childThread); const char *first_reply = unq_read_string(pDb, c->content); string display_reply = (c->state & NORMAL_DISPLAY) ? string(first_reply) : ""; stats["show_num_replies"] = true; vars["NUM_REPLIES"] = to_string(c->childCount); vars["FIRST_REPLY"] = cc_smart_shorten(display_reply);// display_reply.substr(0, display_reply.find_first_of("<")).substr(0,15); delete c; delete[] first_reply; } vars["THREAD_POSTER"] = string(r->ssid); vars["THREAD_NO"] = to_string(r->threadID); vars["THREAD_CONTENT"] = thread_content; // stats["show_title"] = !stats["reply"] || strcmp(r->author, STRING_UNTITLED) != 0; vars["THREAD_TITLE"] = string(r->author); vars["THREAD_IP"] = string(r->email); vars["THREAD_POST_TIME"] = thread_post_time; vars["THREAD_STATE"] = to_string(r->state); if(diff_day >= 0 && diff_day <= 2){ stats["show_easy_date"] = true; vars["THREAD_POST_DATE"] = to_string(diff_day); }else{ char timetmp[64]; struct tm post_date; localtime_r(&(r->date), &post_date); strftime(timetmp, 64, "%Y-%m-%d", &post_date); vars["THREAD_POST_DATE"] = string(timetmp); } map<string, queue<string>> loops; //nothing mg_printf_data(conn, "%s", ht->build(vars, stats, loops).c_str()); // if(content) delete [] content; delete ht; }
HRESULT Mesh::Create(ID3D11Device * pDevice, const char * path, const char * name, bool sdkmesh) { m_isSdkMesh = sdkmesh; if (sdkmesh) { char filename[256]; sprintf(filename, "%s%s", path, name); std::string fname(filename); std::wstring wfname(fname.begin(), fname.end()); return m_sdkMesh.Create(pDevice, wfname.c_str(), false); } #ifdef AMD_SDK_MINIMAL else { // the minimal-dependencies version of AMD_SDK // only supports sdkmesh return E_FAIL; } #else HRESULT hr = S_OK; Assimp::Importer importer; int num_vertices = 0; int num_faces = 0; std::string filename = std::string(path) + std::string(name); aiScene* scene = (aiScene*)importer.ReadFile(filename.c_str(), 0); if (!scene) { return E_FAIL; } _id = crcFast((const unsigned char *)filename.c_str(), (int)filename.length()); if (scene->HasMeshes() && scene->mNumMeshes > 0) { for (int i = 0; i < (int)scene->mNumMeshes; i++) { num_vertices += scene->mMeshes[i]->mNumVertices; num_faces += scene->mMeshes[i]->mNumFaces; } if (num_vertices == 0 || num_faces == 0) { return S_OK; } int current_vertex = 0; int current_face = 0; _material_group.resize(scene->mNumMeshes); _vertex.resize(num_vertices); _index.resize(num_faces * 3); ID3D11DeviceContext * pContext = NULL; pDevice->GetImmediateContext(&pContext); for (unsigned int i = 0; i < scene->mNumMeshes; i++) { ID3D11Texture2D * t2d = NULL; ID3D11ShaderResourceView * srv = NULL; aiMesh * mesh = scene->mMeshes[i]; aiMaterial * material = scene->mMaterials[mesh->mMaterialIndex]; aiString c_texture_filename; material->Get(AI_MATKEY_TEXTURE_DIFFUSE(0), c_texture_filename); std::string tex_filename = std::string(path) + std::string(c_texture_filename.C_Str()); { WCHAR wc_texture_filename[1024]; mbstowcs(wc_texture_filename, tex_filename.c_str(), tex_filename.length() + 1); unsigned int bind_flags = D3D11_BIND_SHADER_RESOURCE; hr = DirectX::CreateDDSTextureFromFileEx(pDevice, wc_texture_filename, 0, D3D11_USAGE_DEFAULT, bind_flags, 0, 0, true, (ID3D11Resource**)&t2d, &srv); } _material_group[i]._texture_index = (int)_t2d.size(); _t2d.push_back(t2d); _srv.push_back(srv); _material_group[i]._first_index = current_face; _material_group[i]._index_count = mesh->mNumFaces * 3; aiVector3D * position = mesh->HasPositions() ? mesh->mVertices : NULL; aiVector3D * normal = mesh->HasNormals() ? mesh->mNormals : NULL; aiVector3D * uv = mesh->HasTextureCoords(0) ? mesh->mTextureCoords[0] : NULL; for (unsigned int j = 0; j < mesh->mNumVertices; j++) { if (position != NULL) { memcpy( &_vertex[current_vertex + j].position, &position[j], sizeof( float ) * 3 ); } if (normal != NULL) { memcpy( &_vertex[current_vertex + j].normal, &normal[j], sizeof( float ) * 3 ); } if (uv != NULL) { memcpy( &_vertex[current_vertex + j].uv, &uv[j], sizeof( float ) * 2 ); } } if (mesh->HasFaces()) { aiFace * f = mesh->mFaces; for (unsigned int j = 0; j < mesh->mNumFaces; j++) { _index[current_face + j * 3 + 0] = current_vertex + f[j].mIndices[0]; _index[current_face + j * 3 + 1] = current_vertex + f[j].mIndices[1]; _index[current_face + j * 3 + 2] = current_vertex + f[j].mIndices[2]; } } current_face += mesh->mNumFaces * 3; current_vertex += mesh->mNumVertices; } AMD_SAFE_RELEASE(pContext); CD3D11_BUFFER_DESC vertexDesc, indexDesc; vertexDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER | D3D11_BIND_SHADER_RESOURCE; vertexDesc.ByteWidth = sizeof(Vertex) * num_vertices; vertexDesc.CPUAccessFlags = 0; vertexDesc.MiscFlags = 0; vertexDesc.StructureByteStride = 0; vertexDesc.Usage = D3D11_USAGE_IMMUTABLE; indexDesc.BindFlags = D3D11_BIND_INDEX_BUFFER; indexDesc.ByteWidth = sizeof(int) * num_faces * 3; indexDesc.CPUAccessFlags = 0; indexDesc.MiscFlags = 0; indexDesc.StructureByteStride = 0; indexDesc.Usage = D3D11_USAGE_IMMUTABLE; D3D11_SUBRESOURCE_DATA vertexData, indexData; memset(&vertexData, 0, sizeof(vertexData)); memset(&indexData, 0, sizeof(indexData)); vertexData.pSysMem = &_vertex[0]; indexData.pSysMem = &_index[0]; hr = pDevice->CreateBuffer(&vertexDesc, &vertexData, &_b1d_vertex); hr = pDevice->CreateBuffer(&indexDesc, &indexData, &_b1d_index); } return hr; #endif }
void KMerHamClusterer::cluster(const std::string &prefix, const KMerData &data, ConcurrentDSU &uf) { // First pass - split & sort the k-mers std::ostringstream tmp; tmp << prefix << ".first"; std::string fname(tmp.str()); std::ofstream ofs(fname, std::ios::out | std::ios::binary); VERIFY(ofs.good()); INFO("Serializing sub-kmers."); for (unsigned i = 0; i < tau_ + 1; ++i) { size_t from = (*Globals::subKMerPositions)[i]; size_t to = (*Globals::subKMerPositions)[i+1]; INFO("Serializing: [" << from << ", " << to << ")"); serialize(ofs, data, NULL, SubKMerPartSerializer(from, to)); } VERIFY(!ofs.fail()); ofs.close(); size_t big_blocks1 = 0; { INFO("Splitting sub-kmers, pass 1."); SubKMerSplitter Splitter(fname, fname + ".blocks"); std::pair<size_t, size_t> stat = Splitter.split(); INFO("Splitting done." " Processed " << stat.first << " blocks." " Produced " << stat.second << " blocks."); // Sanity check - there cannot be more blocks than tau + 1 times of total // kmer number. And on the first pass we have only tau + 1 input blocks! VERIFY(stat.first == tau_ + 1); VERIFY(stat.second <= (tau_ + 1) * data.size()); // Ok, now in the files we have everything grouped in blocks in the output files. std::vector<size_t> block; INFO("Merge sub-kmers, pass 1"); SubKMerBlockFile blocks(fname + ".blocks", /* unlink */ true); std::ostringstream tmp; tmp << prefix << ".second"; fname = tmp.str(); ofs.open(fname, std::ios::out | std::ios::binary); VERIFY(ofs.good()); while (blocks.get_block(block)) { unsigned block_thr = cfg::get().hamming_blocksize_quadratic_threshold; if (block.size() < block_thr) { // Merge small blocks. processBlockQuadratic(uf, block, data, tau_); } else { big_blocks1 += 1; // Otherwise - dump for next iteration. for (unsigned i = 0; i < tau_ + 1; ++i) { serialize(ofs, data, &block, SubKMerStridedSerializer(i, tau_ + 1)); } } } VERIFY(!ofs.fail()); ofs.close(); INFO("Merge done, total " << big_blocks1 << " new blocks generated."); } size_t big_blocks2 = 0; { INFO("Spliting sub-kmers, pass 2."); SubKMerSplitter Splitter(fname, fname + ".blocks"); std::pair<size_t, size_t> stat = Splitter.split(); INFO("Splitting done." " Processed " << stat.first << " blocks." " Produced " << stat.second << " blocks."); // Sanity check - there cannot be more blocks than tau + 1 times of total // kmer number. And there should be tau + 1 times big_blocks input blocks. VERIFY(stat.first == (tau_ + 1)*big_blocks1); VERIFY(stat.second <= (tau_ + 1) * (tau_ + 1) * data.size()); INFO("Merge sub-kmers, pass 2"); SubKMerBlockFile blocks(fname + ".blocks", /* unlink */ true); std::vector<size_t> block; size_t nblocks = 0; while (blocks.get_block(block)) { if (block.size() > 50) { big_blocks2 += 1; #if 0 for (size_t i = 0; i < block.size(); ++i) { std::string s(Globals::blob + data[block[i]], K); INFO("" << block[i] << ": " << s); } #endif } processBlockQuadratic(uf, block, data, tau_); nblocks += 1; } INFO("Merge done, saw " << big_blocks2 << " big blocks out of " << nblocks << " processed."); } }
int main() { // Create a messaging object Optizelle::Messaging msg; // Create some arbitrary vector in R^2 std::vector <Real> x = {1.2,2.3}; std::vector <Real> x0 = {2.3,1.2}; // Create an unconstrained state based on this vector //---State0--- Optizelle::Unconstrained <Real,XX>::State::t state(x); //---State1--- // Read in some parameters std::string fname("blank.json"); //---ReadJson0--- Optizelle::json::Unconstrained <Real,XX>::read(msg,fname,state); //---ReadJson1--- // Create a bundle of functions //---Functions0--- Optizelle::Unconstrained <Real,XX>::Functions::t fns; //---Functions1--- fns.f.reset(new F); // Do a null optimization //---Solver0--- Optizelle::Unconstrained<Real,XX>::Algorithms::getMin( msg,fns,state); //---Solver1--- // Do a null optimization with a state manipulator BlankManipulator <Optizelle::Unconstrained<Real,XX> > smanip; //---SmanipSolver0--- Optizelle::Unconstrained<Real,XX>::Algorithms::getMin( msg,fns,state,smanip); //---SmanipSolver1--- // Read and write the state to file fname = "restart.json"; //---WriteReadRestart0--- Optizelle::json::Unconstrained <Real,XX>::write_restart( msg,fname,state); Optizelle::json::Unconstrained <Real,XX>::read_restart( msg,fname,x,state); //---WriteReadRestart1--- // Do a release //---Release0--- Optizelle::Unconstrained <Real,XX>::Restart::X_Vectors xs; Optizelle::Unconstrained <Real,XX>::Restart::Reals reals; Optizelle::Unconstrained <Real,XX>::Restart::Naturals nats; Optizelle::Unconstrained <Real,XX>::Restart::Params params; Optizelle::Unconstrained <Real,XX>::Restart ::release(state,xs,reals,nats,params); //---Release1--- // Check that the state has empty slots for the variables CHECK(state.x.size()==0); CHECK(state.grad.size()==0); CHECK(state.dx.size()==0); CHECK(state.x_old.size()==0); CHECK(state.grad_old.size()==0); CHECK(state.dx_old.size()==0); CHECK(state.oldY.size()==0); CHECK(state.oldS.size()==0); // Check that we have the correct number of vectors CHECK(xs.size() == 6); // Modify some vectors xs.front().second = x0; // Capture the state //---Capture0--- Optizelle::Unconstrained <Real,XX>::Restart ::capture(msg,state,xs,reals,nats,params); //---Capture1--- // Check that we actually have memory in these slots CHECK(state.x.size()>0); CHECK(state.grad.size()>0); CHECK(state.dx.size()>0); CHECK(state.x_old.size()>0); CHECK(state.grad_old.size()>0); CHECK(state.dx_old.size()>0); // Check the relative error between the vector created above and the one // left in the state { std::vector <Real> residual(XX <Real>::init(x)); XX <Real>::copy(x0,residual); XX <Real>::axpy(-1.,state.x,residual); Real err=std::sqrt(XX <Real>::innr(residual,residual)) /(1.+sqrt(XX <Real>::innr(x0,x0))); CHECK(err < 1e-15); } // Make sure we know we're successful return EXIT_SUCCESS; }
bool KICADMODULE::ComposePCB( class PCBMODEL* aPCB, S3D_FILENAME_RESOLVER* resolver, DOUBLET aOrigin ) { // translate pads and curves to final position and append to PCB. double dlim = (double)std::numeric_limits< float >::epsilon(); double vsin = sin( m_rotation ); double vcos = cos( m_rotation ); bool hasdata = false; double posX = m_position.x - aOrigin.x; double posY = m_position.y - aOrigin.y; for( auto i : m_curves ) { if( i->m_layer != LAYER_EDGE || CURVE_NONE == i->m_form ) continue; KICADCURVE lcurve = *i; if( LAYER_TOP == m_side ) { lcurve.m_start.y = -lcurve.m_start.y; lcurve.m_end.y = -lcurve.m_end.y; lcurve.m_angle = -lcurve.m_angle; } if( m_rotation < -dlim || m_rotation > dlim ) { double x = lcurve.m_start.x * vcos - lcurve.m_start.y * vsin; double y = lcurve.m_start.x * vsin + lcurve.m_start.y * vcos; lcurve.m_start.x = x; lcurve.m_start.y = y; x = lcurve.m_end.x * vcos - lcurve.m_end.y * vsin; y = lcurve.m_end.x * vsin + lcurve.m_end.y * vcos; lcurve.m_end.x = x; lcurve.m_end.y = y; } lcurve.m_start.x += posX; lcurve.m_start.y -= posY; lcurve.m_end.x += posX; lcurve.m_end.y -= posY; if( aPCB->AddOutlineSegment( &lcurve ) ) hasdata = true; } for( auto i : m_pads ) { if( !i->IsThruHole() ) continue; KICADPAD lpad = *i; lpad.m_position.y = -lpad.m_position.y; if( m_rotation < -dlim || m_rotation > dlim ) { double x = lpad.m_position.x * vcos - lpad.m_position.y * vsin; double y = lpad.m_position.x * vsin + lpad.m_position.y * vcos; lpad.m_position.x = x; lpad.m_position.y = y; } lpad.m_position.x += posX; lpad.m_position.y -= posY; if( aPCB->AddPadHole( &lpad ) ) hasdata = true; } DOUBLET newpos( posX, posY ); for( auto i : m_models ) { std::string fname( resolver->ResolvePath( i->m_modelname.c_str() ).ToUTF8() ); if( aPCB->AddComponent( fname, m_refdes, LAYER_BOTTOM == m_side ? true : false, newpos, m_rotation, i->m_offset, i->m_rotation ) ) hasdata = true; } return hasdata; }
void CompileTargetBase::GenerateTargetFilename(wxString& filename) const { // nothing to do if no auto-generation if ( m_PrefixGenerationPolicy == tgfpNone && m_ExtensionGenerationPolicy == tgfpNone ) return; wxFileName fname(filename); filename.Clear(); // path with volume and separator filename << fname.GetPath(wxPATH_GET_VOLUME | wxPATH_GET_SEPARATOR); // prefix + name + extension switch (m_TargetType) { case ttConsoleOnly: case ttExecutable: { if (m_ExtensionGenerationPolicy == tgfpPlatformDefault) { filename << fname.GetName(); filename << FileFilters::EXECUTABLE_DOT_EXT; } else filename << fname.GetFullName(); break; } case ttDynamicLib: { if (m_PrefixGenerationPolicy == tgfpPlatformDefault) { wxString prefix = wxEmptyString; // On linux, "lib" is th common prefix for this platform if (platform::linux) prefix = wxT("lib"); // FIXME (mortenmacfly#5#): What about Mac (Windows is OK)?! // avoid adding the prefix, if there is no prefix, or already its there if (!prefix.IsEmpty() && !fname.GetName().StartsWith(prefix)) filename << prefix; } if (m_ExtensionGenerationPolicy == tgfpPlatformDefault) filename << fname.GetName() << FileFilters::DYNAMICLIB_DOT_EXT; else filename << fname.GetFullName(); break; } case ttNative: { if (m_ExtensionGenerationPolicy == tgfpPlatformDefault) filename << fname.GetName() << FileFilters::NATIVE_DOT_EXT; else filename << fname.GetFullName(); break; } case ttStaticLib: { if (m_PrefixGenerationPolicy == tgfpPlatformDefault) { Compiler* compiler = CompilerFactory::GetCompiler(m_CompilerId); wxString prefix = compiler ? compiler->GetSwitches().libPrefix : _T(""); // avoid adding the prefix, if already there if (!prefix.IsEmpty() && !fname.GetName().StartsWith(prefix)) filename << prefix; } if (m_ExtensionGenerationPolicy == tgfpPlatformDefault) { Compiler* compiler = CompilerFactory::GetCompiler(m_CompilerId); wxString Ext = compiler ? compiler->GetSwitches().libExtension : FileFilters::STATICLIB_EXT; filename << fname.GetName() << _T(".") << Ext; } else { filename << fname.GetFullName(); } break; } default: filename.Clear(); break; } #ifdef command_line_generation Manager::Get()->GetLogManager()->DebugLog(F(_T("CompileTargetBase::GenerateTargetFilename got %s and returns: '%s'"), fname.GetFullPath().wx_str(), filename.wx_str())); #endif }
int main(int argc, char * argv[]) { if (argc != 2) { std::cerr << "usage: " << argv[0] << " config.ini" << std::endl; return 1; } nntpchan::Mainloop loop; nntpchan::NNTPServer nntp(loop); std::string fname(argv[1]); std::ifstream i(fname); if(i.is_open()) { INI::Parser conf(i); std::vector<std::string> requiredSections = {"nntp", "storage"}; auto & level = conf.top(); for ( const auto & section : requiredSections ) { if(level.sections.find(section) == level.sections.end()) { std::cerr << "config file " << fname << " does not have required section: "; std::cerr << section << std::endl; return 1; } } auto & storeconf = level.sections["storage"].values; if (storeconf.find("path") == storeconf.end()) { std::cerr << "storage section does not have 'path' value" << std::endl; return 1; } nntp.SetStoragePath(storeconf["path"]); auto & nntpconf = level.sections["nntp"].values; if (nntpconf.find("bind") == nntpconf.end()) { std::cerr << "nntp section does not have 'bind' value" << std::endl; return 1; } if (nntpconf.find("authdb") != nntpconf.end()) { nntp.SetLoginDB(nntpconf["authdb"]); } if ( level.sections.find("frontend") != level.sections.end()) { // frontend enabled auto & frontconf = level.sections["frontend"].values; if (frontconf.find("type") == frontconf.end()) { std::cerr << "frontend section provided but 'type' value not provided" << std::endl; return 1; } auto ftype = frontconf["type"]; if (ftype == "exec") { if (frontconf.find("exec") == frontconf.end()) { std::cerr << "exec frontend specified but no 'exec' value provided" << std::endl; return 1; } nntp.SetFrontend(new nntpchan::ExecFrontend(frontconf["exec"])); } else { std::cerr << "unknown frontend type '" << ftype << "'" << std::endl; } } auto & a = nntpconf["bind"]; try { nntp.Bind(a); } catch ( std::exception & ex ) { std::cerr << "failed to bind: " << ex.what() << std::endl; return 1; } try { std::cerr << "run mainloop" << std::endl; loop.Run(); } catch ( std::exception & ex ) { std::cerr << "exception in mainloop: " << ex.what() << std::endl; return 2; } } else { std::cerr << "failed to open " << fname << std::endl; return 1; } }
static void buildRuntimeModule() { Logger::println("building runtime module"); M = new llvm::Module("ldc internal runtime", gIR->context()); Type *voidTy = Type::tvoid; Type *boolTy = Type::tbool; Type *ubyteTy = Type::tuns8; Type *intTy = Type::tint32; Type *uintTy = Type::tuns32; Type *ulongTy = Type::tuns64; Type *sizeTy = Type::tsize_t; Type *dcharTy = Type::tdchar; Type *voidPtrTy = Type::tvoidptr; Type *voidArrayTy = Type::tvoid->arrayOf(); Type *voidArrayPtrTy = voidArrayTy->pointerTo(); Type *stringTy = Type::tchar->arrayOf(); Type *wstringTy = Type::twchar->arrayOf(); Type *dstringTy = Type::tdchar->arrayOf(); // Ensure that the declarations exist before creating llvm types for them. ensureDecl(ClassDeclaration::object, "Object"); ensureDecl(Type::typeinfoclass, "TypeInfo_Class"); ensureDecl(Type::dtypeinfo, "DTypeInfo"); ensureDecl(Type::typeinfoassociativearray, "TypeInfo_AssociativeArray"); ensureDecl(Module::moduleinfo, "ModuleInfo"); Type *objectTy = ClassDeclaration::object->type; Type *classInfoTy = Type::typeinfoclass->type; Type *typeInfoTy = Type::dtypeinfo->type; Type *aaTypeInfoTy = Type::typeinfoassociativearray->type; Type *moduleInfoPtrTy = Module::moduleinfo->type->pointerTo(); // The AA type is a struct that only contains a ptr Type *aaTy = voidPtrTy; ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// // Construct some attribute lists used below (possibly multiple times) AttrSet NoAttrs, Attr_NoAlias(NoAttrs, llvm::AttributeSet::ReturnIndex, llvm::Attribute::NoAlias), Attr_NoUnwind(NoAttrs, llvm::AttributeSet::FunctionIndex, llvm::Attribute::NoUnwind), Attr_ReadOnly(NoAttrs, llvm::AttributeSet::FunctionIndex, llvm::Attribute::ReadOnly), Attr_Cold(NoAttrs, llvm::AttributeSet::FunctionIndex, llvm::Attribute::Cold), Attr_Cold_NoReturn(Attr_Cold, llvm::AttributeSet::FunctionIndex, llvm::Attribute::NoReturn), Attr_ReadOnly_NoUnwind(Attr_ReadOnly, llvm::AttributeSet::FunctionIndex, llvm::Attribute::NoUnwind), Attr_ReadOnly_1_NoCapture(Attr_ReadOnly, 1, llvm::Attribute::NoCapture), Attr_ReadOnly_1_3_NoCapture(Attr_ReadOnly_1_NoCapture, 3, llvm::Attribute::NoCapture), Attr_ReadOnly_NoUnwind_1_NoCapture(Attr_ReadOnly_1_NoCapture, ~0U, llvm::Attribute::NoUnwind), Attr_ReadNone(NoAttrs, ~0U, llvm::Attribute::ReadNone), Attr_1_NoCapture(NoAttrs, 1, llvm::Attribute::NoCapture), Attr_NoAlias_1_NoCapture(Attr_1_NoCapture, 0, llvm::Attribute::NoAlias), Attr_1_2_NoCapture(Attr_1_NoCapture, 2, llvm::Attribute::NoCapture), Attr_1_3_NoCapture(Attr_1_NoCapture, 3, llvm::Attribute::NoCapture), Attr_1_4_NoCapture(Attr_1_NoCapture, 4, llvm::Attribute::NoCapture); ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// // void _d_assert(string file, uint line) // void _d_arraybounds(string file, uint line) createFwdDecl(LINKc, Type::tvoid, {"_d_assert", "_d_arraybounds"}, {stringTy, uintTy}, {}, Attr_Cold_NoReturn); // void _d_assert_msg(string msg, string file, uint line) createFwdDecl(LINKc, voidTy, {"_d_assert_msg"}, {stringTy, stringTy, uintTy}, {}, Attr_Cold_NoReturn); // void _d_assertm(immutable(ModuleInfo)* m, uint line) // void _d_array_bounds(immutable(ModuleInfo)* m, uint line) // void _d_switch_error(immutable(ModuleInfo)* m, uint line) createFwdDecl( LINKc, voidTy, {"_d_assertm", "_d_array_bounds", "_d_switch_error"}, {moduleInfoPtrTy, uintTy}, {STCimmutable, 0}, Attr_Cold_NoReturn); ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// // void* _d_allocmemory(size_t sz) createFwdDecl(LINKc, voidPtrTy, {"_d_allocmemory"}, {sizeTy}, {}, Attr_NoAlias); // void* _d_allocmemoryT(TypeInfo ti) createFwdDecl(LINKc, voidPtrTy, {"_d_allocmemoryT"}, {typeInfoTy}, {}, Attr_NoAlias); // void[] _d_newarrayT (const TypeInfo ti, size_t length) // void[] _d_newarrayiT(const TypeInfo ti, size_t length) // void[] _d_newarrayU (const TypeInfo ti, size_t length) createFwdDecl(LINKc, voidArrayTy, {"_d_newarrayT", "_d_newarrayiT", "_d_newarrayU"}, {typeInfoTy, sizeTy}, {STCconst, 0}); // void[] _d_newarraymTX (const TypeInfo ti, size_t[] dims) // void[] _d_newarraymiTX(const TypeInfo ti, size_t[] dims) createFwdDecl(LINKc, voidArrayTy, {"_d_newarraymTX", "_d_newarraymiTX"}, {typeInfoTy, sizeTy->arrayOf()}, {STCconst, 0}); // void[] _d_arraysetlengthT (const TypeInfo ti, size_t newlength, void[]* p) // void[] _d_arraysetlengthiT(const TypeInfo ti, size_t newlength, void[]* p) createFwdDecl(LINKc, voidArrayTy, {"_d_arraysetlengthT", "_d_arraysetlengthiT"}, {typeInfoTy, sizeTy, voidArrayPtrTy}, {STCconst, 0, 0}); // byte[] _d_arrayappendcTX(const TypeInfo ti, ref byte[] px, size_t n) createFwdDecl(LINKc, voidArrayTy, {"_d_arrayappendcTX"}, {typeInfoTy, voidArrayTy, sizeTy}, {STCconst, STCref, 0}); // void[] _d_arrayappendT(const TypeInfo ti, ref byte[] x, byte[] y) createFwdDecl(LINKc, voidArrayTy, {"_d_arrayappendT"}, {typeInfoTy, voidArrayTy, voidArrayTy}, {STCconst, STCref, 0}); // void[] _d_arrayappendcd(ref byte[] x, dchar c) // void[] _d_arrayappendwd(ref byte[] x, dchar c) createFwdDecl(LINKc, voidArrayTy, {"_d_arrayappendcd", "_d_arrayappendwd"}, {voidArrayTy, dcharTy}, {STCref, 0}); // byte[] _d_arraycatT(const TypeInfo ti, byte[] x, byte[] y) createFwdDecl(LINKc, voidArrayTy, {"_d_arraycatT"}, {typeInfoTy, voidArrayTy, voidArrayTy}, {STCconst, 0, 0}); // void[] _d_arraycatnTX(const TypeInfo ti, byte[][] arrs) createFwdDecl(LINKc, voidArrayTy, {"_d_arraycatnTX"}, {typeInfoTy, voidArrayTy->arrayOf()}, {STCconst, 0}); // Object _d_newclass(const ClassInfo ci) createFwdDecl(LINKc, objectTy, {"_d_newclass"}, {classInfoTy}, {STCconst}, Attr_NoAlias); // void* _d_newitemT (TypeInfo ti) // void* _d_newitemiT(TypeInfo ti) createFwdDecl(LINKc, voidPtrTy, {"_d_newitemT", "_d_newitemiT"}, {typeInfoTy}, {0}, Attr_NoAlias); // void _d_delarray_t(void[]* p, const TypeInfo_Struct ti) createFwdDecl(LINKc, voidTy, {"_d_delarray_t"}, {voidArrayPtrTy, Type::typeinfostruct->type}, {0, STCconst}); // void _d_delmemory(void** p) // void _d_delinterface(void** p) createFwdDecl(LINKc, voidTy, {"_d_delmemory", "_d_delinterface"}, {voidPtrTy->pointerTo()}); // void _d_callfinalizer(void* p) createFwdDecl(LINKc, voidTy, {"_d_callfinalizer"}, {voidPtrTy}); // D2: void _d_delclass(Object* p) createFwdDecl(LINKc, voidTy, {"_d_delclass"}, {objectTy->pointerTo()}); // void _d_delstruct(void** p, TypeInfo_Struct inf) createFwdDecl(LINKc, voidTy, {"_d_delstruct"}, {voidPtrTy->pointerTo(), Type::typeinfostruct->type}); ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// // array slice copy when assertions are on! // void _d_array_slice_copy(void* dst, size_t dstlen, void* src, size_t // srclen) createFwdDecl(LINKc, voidTy, {"_d_array_slice_copy"}, {voidPtrTy, sizeTy, voidPtrTy, sizeTy}, {}, Attr_1_3_NoCapture); //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // int _aApplycd1(in char[] aa, dg_t dg) // int _aApplyRcd1(in char[] aa, dg_t dg) #define STR_APPLY1(TY, a, b) \ { \ const std::string prefix = "_aApply"; \ std::string fname1 = prefix + (a) + '1', fname2 = prefix + (b) + '1', \ fname3 = prefix + 'R' + (a) + '1', \ fname4 = prefix + 'R' + (b) + '1'; \ createFwdDecl(LINKc, sizeTy, {fname1, fname2, fname3, fname4}, \ {TY, rt_dg1()}); \ } STR_APPLY1(stringTy, "cw", "cd") STR_APPLY1(wstringTy, "wc", "wd") STR_APPLY1(dstringTy, "dc", "dw") #undef STR_APPLY1 // int _aApplycd2(in char[] aa, dg2_t dg) // int _aApplyRcd2(in char[] aa, dg2_t dg) #define STR_APPLY2(TY, a, b) \ { \ const std::string prefix = "_aApply"; \ std::string fname1 = prefix + (a) + '2', fname2 = prefix + (b) + '2', \ fname3 = prefix + 'R' + (a) + '2', \ fname4 = prefix + 'R' + (b) + '2'; \ createFwdDecl(LINKc, sizeTy, {fname1, fname2, fname3, fname4}, \ {TY, rt_dg2()}); \ } STR_APPLY2(stringTy, "cw", "cd") STR_APPLY2(wstringTy, "wc", "wd") STR_APPLY2(dstringTy, "dc", "dw") #undef STR_APPLY2 ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// // fixes the length for dynamic array casts // size_t _d_array_cast_len(size_t len, size_t elemsz, size_t newelemsz) createFwdDecl(LINKc, sizeTy, {"_d_array_cast_len"}, {sizeTy, sizeTy, sizeTy}, {}, Attr_ReadNone); ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// // void[] _d_arrayassign_l(TypeInfo ti, void[] src, void[] dst, void* ptmp) // void[] _d_arrayassign_r(TypeInfo ti, void[] src, void[] dst, void* ptmp) createFwdDecl(LINKc, voidArrayTy, {"_d_arrayassign_l", "_d_arrayassign_r"}, {typeInfoTy, voidArrayTy, voidArrayTy, voidPtrTy}); // void[] _d_arrayctor(TypeInfo ti, void[] from, void[] to) createFwdDecl(LINKc, voidArrayTy, {"_d_arrayctor"}, {typeInfoTy, voidArrayTy, voidArrayTy}); // void* _d_arraysetassign(void* p, void* value, int count, TypeInfo ti) // void* _d_arraysetctor(void* p, void* value, int count, TypeInfo ti) createFwdDecl(LINKc, voidPtrTy, {"_d_arraysetassign", "_d_arraysetctor"}, {voidPtrTy, voidPtrTy, intTy, typeInfoTy}, {}, Attr_NoAlias); ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// // cast interface // void* _d_interface_cast(void* p, ClassInfo c) createFwdDecl(LINKc, voidPtrTy, {"_d_interface_cast"}, {voidPtrTy, classInfoTy}, {}, Attr_ReadOnly_NoUnwind); // dynamic cast // void* _d_dynamic_cast(Object o, ClassInfo c) createFwdDecl(LINKc, voidPtrTy, {"_d_dynamic_cast"}, {objectTy, classInfoTy}, {}, Attr_ReadOnly_NoUnwind); ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// // char[] _adReverseChar(char[] a) // char[] _adSortChar(char[] a) createFwdDecl(LINKc, stringTy, {"_adReverseChar", "_adSortChar"}, {stringTy}); // wchar[] _adReverseWchar(wchar[] a) // wchar[] _adSortWchar(wchar[] a) createFwdDecl(LINKc, wstringTy, {"_adReverseWchar", "_adSortWchar"}, {wstringTy}); // void[] _adReverse(void[] a, size_t szelem) createFwdDecl(LINKc, wstringTy, {"_adReverse"}, {voidArrayTy, sizeTy}, {}, Attr_NoUnwind); // int _adEq2(void[] a1, void[] a2, TypeInfo ti) // int _adCmp2(void[] a1, void[] a2, TypeInfo ti) createFwdDecl(LINKc, intTy, {"_adEq2", "_adCmp2"}, {voidArrayTy, voidArrayTy, typeInfoTy}, {}, Attr_ReadOnly); // int _adCmpChar(void[] a1, void[] a2) createFwdDecl(LINKc, intTy, {"_adCmpChar"}, {voidArrayTy, voidArrayTy}, {}, Attr_ReadOnly_NoUnwind); // void[] _adSort(void[] a, TypeInfo ti) createFwdDecl(LINKc, voidArrayTy, {"_adSort"}, {voidArrayTy, typeInfoTy}); ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// // size_t _aaLen(in AA aa) createFwdDecl(LINKc, sizeTy, {"_aaLen"}, {aaTy}, {STCin}, Attr_ReadOnly_NoUnwind_1_NoCapture); // void* _aaGetY(AA* aa, const TypeInfo aati, in size_t valuesize, // in void* pkey) createFwdDecl(LINKc, voidPtrTy, {"_aaGetY"}, {aaTy->pointerTo(), aaTypeInfoTy, sizeTy, voidPtrTy}, {0, STCconst, STCin, STCin}, Attr_1_4_NoCapture); // inout(void)* _aaInX(inout AA aa, in TypeInfo keyti, in void* pkey) // FIXME: "inout" storageclass is not applied to return type createFwdDecl(LINKc, voidPtrTy, {"_aaInX"}, {aaTy, typeInfoTy, voidPtrTy}, {STCin | STCout, STCin, STCin}, Attr_ReadOnly_1_3_NoCapture); // bool _aaDelX(AA aa, in TypeInfo keyti, in void* pkey) createFwdDecl(LINKc, boolTy, {"_aaDelX"}, {aaTy, typeInfoTy, voidPtrTy}, {0, STCin, STCin}, Attr_1_3_NoCapture); // inout(void[]) _aaValues(inout AA aa, in size_t keysize, // in size_t valuesize, const TypeInfo tiValueArray) createFwdDecl( LINKc, voidArrayTy, {"_aaValues"}, {aaTy, sizeTy, sizeTy, typeInfoTy}, {STCin | STCout, STCin, STCin, STCconst}, Attr_ReadOnly_1_3_NoCapture); // void* _aaRehash(AA* paa, in TypeInfo keyti) createFwdDecl(LINKc, voidPtrTy, {"_aaRehash"}, {aaTy->pointerTo(), typeInfoTy}, {0, STCin}); // inout(void[]) _aaKeys(inout AA aa, in size_t keysize, // const TypeInfo tiKeyArray) createFwdDecl(LINKc, voidArrayTy, {"_aaKeys"}, {aaTy, sizeTy, typeInfoTy}, {STCin | STCout, STCin, STCconst}, Attr_NoAlias_1_NoCapture); // int _aaApply(AA aa, in size_t keysize, dg_t dg) createFwdDecl(LINKc, intTy, {"_aaApply"}, {aaTy, sizeTy, rt_dg1()}, {0, STCin, 0}, Attr_1_NoCapture); // int _aaApply2(AA aa, in size_t keysize, dg2_t dg) createFwdDecl(LINKc, intTy, {"_aaApply2"}, {aaTy, sizeTy, rt_dg2()}, {0, STCin, 0}, Attr_1_NoCapture); // int _aaEqual(in TypeInfo tiRaw, in AA e1, in AA e2) createFwdDecl(LINKc, intTy, {"_aaEqual"}, {typeInfoTy, aaTy, aaTy}, {STCin, STCin, STCin}, Attr_1_2_NoCapture); // AA _d_assocarrayliteralTX(const TypeInfo_AssociativeArray ti, // void[] keys, void[] values) createFwdDecl(LINKc, aaTy, {"_d_assocarrayliteralTX"}, {aaTypeInfoTy, voidArrayTy, voidArrayTy}, {STCconst, 0, 0}); ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// // void _moduleCtor() // void _moduleDtor() createFwdDecl(LINKc, voidTy, {"_moduleCtor", "_moduleDtor"}, {}); ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// // void _d_throw_exception(Object e) createFwdDecl(LINKc, voidTy, {"_d_throw_exception"}, {objectTy}); ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// // int _d_switch_string(char[][] table, char[] ca) createFwdDecl(LINKc, intTy, {"_d_switch_string"}, {stringTy->arrayOf(), stringTy}, {}, Attr_ReadOnly); // int _d_switch_ustring(wchar[][] table, wchar[] ca) createFwdDecl(LINKc, intTy, {"_d_switch_ustring"}, {wstringTy->arrayOf(), wstringTy}, {}, Attr_ReadOnly); // int _d_switch_dstring(dchar[][] table, dchar[] ca) createFwdDecl(LINKc, intTy, {"_d_switch_dstring"}, {dstringTy->arrayOf(), dstringTy}, {}, Attr_ReadOnly); ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// // int _d_eh_personality(...) { if (global.params.targetTriple->isWindowsMSVCEnvironment()) { const char *fname = useMSVCEH() ? "__CxxFrameHandler3" : "_d_eh_personality"; // (ptr ExceptionRecord, ptr EstablisherFrame, ptr ContextRecord, // ptr DispatcherContext) createFwdDecl(LINKc, intTy, {fname}, {voidPtrTy, voidPtrTy, voidPtrTy, voidPtrTy}); } else if (global.params.targetTriple->getArch() == llvm::Triple::arm) { // (int state, ptr ucb, ptr context) createFwdDecl(LINKc, intTy, {"_d_eh_personality"}, {intTy, voidPtrTy, voidPtrTy}); } else { // (int ver, int actions, ulong eh_class, ptr eh_info, ptr context) createFwdDecl(LINKc, intTy, {"_d_eh_personality"}, {intTy, intTy, ulongTy, voidPtrTy, voidPtrTy}); } } if (useMSVCEH()) { // _d_enter_cleanup(ptr frame) createFwdDecl(LINKc, boolTy, {"_d_enter_cleanup"}, {voidPtrTy}); // _d_leave_cleanup(ptr frame) createFwdDecl(LINKc, voidTy, {"_d_leave_cleanup"}, {voidPtrTy}); // Object _d_eh_enter_catch(ptr exception, ClassInfo catchType) createFwdDecl(LINKc, objectTy, {"_d_eh_enter_catch"}, {voidPtrTy, classInfoTy}, {}); } else { // void _d_eh_resume_unwind(ptr) createFwdDecl(LINKc, voidTy, {"_d_eh_resume_unwind"}, {voidPtrTy}); // Object _d_eh_enter_catch(ptr) createFwdDecl(LINKc, objectTy, {"_d_eh_enter_catch"}, {voidPtrTy}, {}, Attr_NoUnwind); } ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// // void invariant._d_invariant(Object o) createFwdDecl( LINKd, voidTy, {gABI->mangleFunctionForLLVM("_D9invariant12_d_invariantFC6ObjectZv", LINKd)}, {objectTy}); // void _d_dso_registry(CompilerDSOData* data) llvm::StringRef fname("_d_dso_registry"); LLType *LLvoidTy = LLType::getVoidTy(gIR->context()); LLType *LLvoidPtrPtrTy = getPtrToType(getPtrToType(LLvoidTy)); LLType *moduleInfoPtrPtrTy = getPtrToType(getPtrToType(DtoType(Module::moduleinfo->type))); llvm::StructType *dsoDataTy = llvm::StructType::get(DtoSize_t(), // version LLvoidPtrPtrTy, // slot moduleInfoPtrPtrTy, // _minfo_beg moduleInfoPtrPtrTy, // _minfo_end NULL); llvm::Type *types[] = {getPtrToType(dsoDataTy)}; llvm::FunctionType *fty = llvm::FunctionType::get(LLvoidTy, types, false); llvm::Function::Create(fty, llvm::GlobalValue::ExternalLinkage, fname, M); ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// // extern (C) void _d_cover_register2(string filename, size_t[] valid, // uint[] data, ubyte minPercent) if (global.params.cov) { createFwdDecl(LINKc, voidTy, {"_d_cover_register2"}, {stringTy, sizeTy->arrayOf(), uintTy->arrayOf(), ubyteTy}); } if (global.params.hasObjectiveC) { assert(global.params.targetTriple->isOSDarwin()); // The types of these functions don't really matter because they are always // bitcast to correct signature before calling. Type* objectPtrTy = voidPtrTy; Type* selectorPtrTy = voidPtrTy; Type* realTy = Type::tfloat80; // id objc_msgSend(id self, SEL op, ...) // Function called early and/or often, so lazy binding isn't worthwhile. createFwdDecl(LINKc, objectPtrTy, {"objc_msgSend"}, {objectPtrTy, selectorPtrTy}, {}, AttrSet(NoAttrs, ~0U, llvm::Attribute::NonLazyBind)); switch (global.params.targetTriple->getArch()) { case llvm::Triple::x86_64: // creal objc_msgSend_fp2ret(id self, SEL op, ...) createFwdDecl(LINKc, Type::tcomplex80, {"objc_msgSend_fp2ret"}, {objectPtrTy, selectorPtrTy}); // fall-thru case llvm::Triple::x86: // x86_64 real return only, x86 float, double, real return // real objc_msgSend_fpret(id self, SEL op, ...) createFwdDecl(LINKc, realTy, {"objc_msgSend_fpret"}, {objectPtrTy, selectorPtrTy}); // fall-thru case llvm::Triple::arm: case llvm::Triple::thumb: // used when return value is aggregate via a hidden sret arg // void objc_msgSend_stret(T *sret_arg, id self, SEL op, ...) createFwdDecl(LINKc, voidTy, {"objc_msgSend_stret"}, {objectPtrTy, selectorPtrTy}); break; default: break; } } }
int main(int argc, char **argv) { const bool release(argc >= 2 && std::string(argv[1]) == "--release"); // Get files.. std::vector<std::string> libfiles; getCppFiles(libfiles, "lib/", false); std::vector<std::string> extfiles; extfiles.push_back("externals/simplecpp/simplecpp.cpp"); extfiles.push_back("externals/tinyxml/tinyxml2.cpp"); std::vector<std::string> clifiles; getCppFiles(clifiles, "cli/", false); std::vector<std::string> testfiles; getCppFiles(testfiles, "test/", false); std::vector<std::string> toolsfiles; getCppFiles(toolsfiles, "tools/", false); if (libfiles.empty() && clifiles.empty() && testfiles.empty()) { std::cerr << "No files found. Are you in the correct directory?" << std::endl; return EXIT_FAILURE; } // QMAKE - lib/lib.pri { std::ofstream fout1("lib/lib.pri"); if (fout1.is_open()) { fout1 << "# no manual edits - this file is autogenerated by dmake\n\n"; fout1 << "include($$PWD/pcrerules.pri)\n"; fout1 << "include($$PWD/../externals/externals.pri)\n"; fout1 << "INCLUDEPATH += $$PWD\n"; fout1 << "HEADERS += $${PWD}/check.h \\\n"; for (unsigned int i = 0; i < libfiles.size(); ++i) { std::string fname(libfiles[i].substr(4)); if (fname.find(".cpp") == std::string::npos) continue; // shouldn't happen fname.erase(fname.find(".cpp")); fout1 << std::string(11, ' ') << "$${PWD}/" << fname << ".h"; if (i + 1 < testfiles.size()) fout1 << " \\\n"; } fout1 << "\n\nSOURCES += "; for (unsigned int i = 0; i < libfiles.size(); ++i) { fout1 << "$${PWD}/" << libfiles[i].substr(4); if (i < libfiles.size() - 1) fout1 << " \\\n" << std::string(11, ' '); } fout1 << "\n"; } } // QMAKE - test/testfiles.pri { std::ofstream fout1("test/testfiles.pri"); if (fout1.is_open()) { fout1 << "# no manual edits - this file is autogenerated by dmake\n\n"; fout1 << "INCLUDEPATH += ../externals/tinyxml\n"; fout1 << "\n\nSOURCES += "; for (unsigned int i = 0; i < testfiles.size(); ++i) { const std::string filename(testfiles[i].substr(5)); // Include only files containing tests in this listing. // I.e. filenames beginning with "test". if (filename.compare(0, 4, "test") == 0) { fout1 << "$${BASEPATH}/" << filename; if (i + 1 < testfiles.size()) fout1 << " \\\n" << std::string(11, ' '); } } fout1 << "\n"; } } static const char makefile[] = "Makefile"; std::ofstream fout(makefile, std::ios_base::trunc); if (!fout.is_open()) { std::cerr << "An error occurred while trying to open " << makefile << ".\n"; return EXIT_FAILURE; } fout << "# This file is generated by tools/dmake, do not edit.\n\n"; fout << "# To compile with rules, use 'make HAVE_RULES=yes'\n"; makeConditionalVariable(fout, "HAVE_RULES", "no"); // compiled patterns.. fout << "# folder where lib/*.cpp files are located\n"; makeConditionalVariable(fout, "SRCDIR", "lib"); fout << "ifeq ($(SRCDIR),build)\n" << " ifdef VERIFY\n" << " matchcompiler_S := $(shell python tools/matchcompiler.py --verify)\n" << " else\n" << " matchcompiler_S := $(shell python tools/matchcompiler.py)\n" << " endif\n" << "endif\n\n"; // explicit cfg dir.. fout << "ifdef CFGDIR\n" << " CFG=-DCFGDIR=\\\"$(CFGDIR)\\\"\n" << "else\n" << " CFG=\n" << "endif\n\n"; // enable backtrac fout << "RDYNAMIC=-rdynamic\n"; // The _GLIBCXX_DEBUG doesn't work in cygwin or other Win32 systems. fout << "# Set the CPPCHK_GLIBCXX_DEBUG flag. This flag is not used in release Makefiles.\n" << "# The _GLIBCXX_DEBUG define doesn't work in Cygwin or other Win32 systems.\n" << "ifndef COMSPEC\n" << " ifdef ComSpec\n" << " #### ComSpec is defined on some WIN32's.\n" << " COMSPEC=$(ComSpec)\n" << " endif # ComSpec\n" << "endif # COMSPEC\n" << "\n" << "ifdef COMSPEC\n" << " #### Maybe Windows\n" << " ifndef CPPCHK_GLIBCXX_DEBUG\n" << " CPPCHK_GLIBCXX_DEBUG=\n" << " endif # !CPPCHK_GLIBCXX_DEBUG\n" << "\n" << " ifeq ($(MSYSTEM),MINGW32)\n" << " LDFLAGS=-lshlwapi\n" << " else\n" << " RDYNAMIC=-lshlwapi\n" << " endif\n" << "else # !COMSPEC\n" << " uname_S := $(shell sh -c 'uname -s 2>/dev/null || echo not')\n" << "\n" << " ifeq ($(uname_S),Linux)\n" << " ifndef CPPCHK_GLIBCXX_DEBUG\n" << " CPPCHK_GLIBCXX_DEBUG=-D_GLIBCXX_DEBUG\n" << " endif # !CPPCHK_GLIBCXX_DEBUG\n" << " endif # Linux\n" << "\n" << " ifeq ($(uname_S),GNU/kFreeBSD)\n" << " ifndef CPPCHK_GLIBCXX_DEBUG\n" << " CPPCHK_GLIBCXX_DEBUG=-D_GLIBCXX_DEBUG\n" << " endif # !CPPCHK_GLIBCXX_DEBUG\n" << " endif # GNU/kFreeBSD\n" << "\n" << "endif # COMSPEC\n" << "\n"; // tinymxl2 requires __STRICT_ANSI__ to be undefined to compile under CYGWIN. fout << "# Set the UNDEF_STRICT_ANSI flag to address compile time warnings\n" << "# with tinyxml2 and Cygwin.\n" << "ifdef COMSPEC\n" << " uname_S := $(shell uname -s)\n" << "\n" << " ifneq (,$(findstring CYGWIN,$(uname_S)))\n" << " UNDEF_STRICT_ANSI=-U__STRICT_ANSI__\n" << " endif # CYGWIN\n" << "endif # COMSPEC\n" << "\n"; // skip "-D_GLIBCXX_DEBUG" if clang, since it breaks the build makeConditionalVariable(fout, "CXX", "g++"); fout << "ifeq ($(CXX), clang++)\n" << " CPPCHK_GLIBCXX_DEBUG=\n" << "endif\n"; // Makefile settings.. if (release) { makeConditionalVariable(fout, "CXXFLAGS", "-std=c++0x -O2 -include lib/cxx11emu.h -DNDEBUG -Wall -Wno-sign-compare"); } else { // TODO: add more compiler warnings. // -Wlogical-op : doesn't work on older GCC // -Wsign-conversion : too many warnings // -Wunreachable-code : some GCC versions report lots of warnings makeConditionalVariable(fout, "CXXFLAGS", "-include lib/cxx11emu.h " "-pedantic " "-Wall " "-Wextra " "-Wabi " "-Wcast-qual " // "-Wconversion " // danmar: gives fp. for instance: unsigned int sizeof_pointer = sizeof(void *); "-Wfloat-equal " // "-Wlogical-op " "-Wmissing-declarations " "-Wmissing-format-attribute " "-Wno-long-long " // "-Woverloaded-virtual " // danmar: we get fp when overloading analyseWholeProgram() "-Wpacked " "-Wredundant-decls " "-Wshadow " // "-Wsign-conversion " // "-Wsign-promo " "-Wno-missing-field-initializers " "-Wno-missing-braces " // "-Wunreachable-code " "-Wno-sign-compare " // danmar: I don't like this warning, it's very rarelly a bug "-Wno-multichar " "$(CPPCHK_GLIBCXX_DEBUG) " "-g"); } fout << "ifeq ($(CXX), g++)\n" << " override CXXFLAGS += -std=c++0x\n" << "else ifeq ($(CXX), clang++)\n" << " override CXXFLAGS += -std=c++0x\n" << "else ifeq ($(CXX), c++)\n" << " ifeq ($(shell uname -s), Darwin)\n" << " override CXXFLAGS += -std=c++0x\n" << " endif\n" << "endif\n" << "\n"; fout << "ifeq ($(HAVE_RULES),yes)\n" << " override CXXFLAGS += -DHAVE_RULES -DTIXML_USE_STL $(shell pcre-config --cflags)\n" << " ifdef LIBS\n" << " LIBS += $(shell pcre-config --libs)\n" << " else\n" << " LIBS=$(shell pcre-config --libs)\n" << " endif\n" << "endif\n\n"; makeConditionalVariable(fout, "PREFIX", "/usr"); makeConditionalVariable(fout, "INCLUDE_FOR_LIB", "-Ilib -Iexternals/simplecpp -Iexternals/tinyxml"); makeConditionalVariable(fout, "INCLUDE_FOR_CLI", "-Ilib -Iexternals/simplecpp -Iexternals/tinyxml"); makeConditionalVariable(fout, "INCLUDE_FOR_TEST", "-Ilib -Icli -Iexternals/simplecpp -Iexternals/tinyxml"); fout << "BIN=$(DESTDIR)$(PREFIX)/bin\n\n"; fout << "# For 'make man': sudo apt-get install xsltproc docbook-xsl docbook-xml on Linux\n"; fout << "DB2MAN?=/usr/share/sgml/docbook/stylesheet/xsl/nwalsh/manpages/docbook.xsl\n"; fout << "XP=xsltproc -''-nonet -''-param man.charmap.use.subset \"0\"\n"; fout << "MAN_SOURCE=man/cppcheck.1.xml\n\n"; fout << "\n###### Object Files\n\n"; fout << "LIBOBJ = " << objfile(libfiles[0]); for (size_t i = 1; i < libfiles.size(); ++i) fout << " \\\n" << std::string(14, ' ') << objfile(libfiles[i]); fout << "\n\n"; fout << "EXTOBJ = " << objfile(extfiles[0]); for (size_t i = 1; i < extfiles.size(); ++i) fout << " \\\n" << std::string(14, ' ') << objfile(extfiles[i]); fout << "\n\n"; fout << "CLIOBJ = " << objfile(clifiles[0]); for (size_t i = 1; i < clifiles.size(); ++i) fout << " \\\n" << std::string(14, ' ') << objfile(clifiles[i]); fout << "\n\n"; fout << "TESTOBJ = " << objfile(testfiles[0]); for (size_t i = 1; i < testfiles.size(); ++i) fout << " \\\n" << std::string(14, ' ') << objfile(testfiles[i]); fout << "\n\n"; fout << ".PHONY: run-dmake\n\n"; fout << "\n###### Targets\n\n"; fout << "cppcheck: $(LIBOBJ) $(CLIOBJ) $(EXTOBJ)\n"; fout << "\t$(CXX) $(CPPFLAGS) $(CXXFLAGS) -o cppcheck $(CLIOBJ) $(LIBOBJ) $(EXTOBJ) $(LIBS) $(LDFLAGS) $(RDYNAMIC)\n\n"; fout << "all:\tcppcheck testrunner\n\n"; fout << "testrunner: $(TESTOBJ) $(LIBOBJ) $(EXTOBJ) cli/threadexecutor.o cli/cmdlineparser.o cli/cppcheckexecutor.o cli/filelister.o\n"; fout << "\t$(CXX) $(CPPFLAGS) $(CXXFLAGS) -o testrunner $(TESTOBJ) $(LIBOBJ) cli/threadexecutor.o cli/cppcheckexecutor.o cli/cmdlineparser.o cli/filelister.o $(EXTOBJ) $(LIBS) $(LDFLAGS) $(RDYNAMIC)\n\n"; fout << "test:\tall\n"; fout << "\t./testrunner\n\n"; fout << "check:\tall\n"; fout << "\t./testrunner -g -q\n\n"; fout << "checkcfg:\tcppcheck\n"; fout << "\t./test/cfg/runtests.sh\n\n"; fout << "dmake:\ttools/dmake.o cli/filelister.o lib/pathmatch.o lib/path.o\n"; fout << "\t$(CXX) $(CXXFLAGS) -o dmake tools/dmake.o cli/filelister.o lib/pathmatch.o lib/path.o -Ilib $(LDFLAGS)\n\n"; fout << "run-dmake: dmake\n"; fout << "\t./dmake\n\n"; fout << "reduce:\ttools/reduce.o $(LIBOBJ) $(EXTOBJ)\n"; fout << "\t$(CXX) $(CPPFLAGS) $(CXXFLAGS) -g -o reduce tools/reduce.o $(INCLUDE_FOR_LIB) $(LIBOBJ) $(LIBS) $(EXTOBJ) $(LDFLAGS) $(RDYNAMIC)\n\n"; fout << "clean:\n"; fout << "\trm -f build/*.o lib/*.o cli/*.o test/*.o tools/*.o externals/*/*.o testrunner reduce dmake cppcheck cppcheck.1\n\n"; fout << "man:\tman/cppcheck.1\n\n"; fout << "man/cppcheck.1:\t$(MAN_SOURCE)\n\n"; fout << "\t$(XP) $(DB2MAN) $(MAN_SOURCE)\n\n"; fout << "tags:\n"; fout << "\tctags -R --exclude=doxyoutput --exclude=test/cfg cli externals gui lib test\n\n"; fout << "install: cppcheck\n"; fout << "\tinstall -d ${BIN}\n"; fout << "\tinstall cppcheck ${BIN}\n"; fout << "\tinstall addons/*.py ${BIN}\n"; fout << "\tinstall addons/*/*.py ${BIN}\n"; fout << "\tinstall htmlreport/cppcheck-htmlreport ${BIN}\n"; fout << "ifdef CFGDIR \n"; fout << "\tinstall -d ${DESTDIR}${CFGDIR}\n"; fout << "\tinstall -m 644 cfg/* ${DESTDIR}${CFGDIR}\n"; fout << "endif\n\n"; fout << "\n###### Build\n\n"; compilefiles(fout, libfiles, "${INCLUDE_FOR_LIB}"); compilefiles(fout, clifiles, "${INCLUDE_FOR_CLI}"); compilefiles(fout, testfiles, "${INCLUDE_FOR_TEST}"); compilefiles(fout, extfiles, ""); compilefiles(fout, toolsfiles, "${INCLUDE_FOR_LIB}"); return 0; }
bool extractItem( FILEINDEX_ENTRY &info, unsigned char method, char *strMrf, char *strName ) { TFileStream mrf( strMrf ); if( !( mrf.isOpen() ) ) { printf("ERROR: Could not open file (%s)\n", strMrf ); return false; } // Format the output filename std::string fname( fsRename( strMrf, strName ) ); #ifdef VERBOSE printf("Using filename: %s\n", fname.c_str()); #endif // UNFORCED EXTRACTION // If file already exists, ignore it if( TFileSize( fname.c_str() ) == info.size ) { mrf.Close(); return true; } unsigned char *buf( new unsigned char[ info.zsize ] ); #ifdef VERBOSE printf("Allocated %u bytes\n", info.zsize); #endif // Load MRF data into buffer mrf.Seek( info.offset, bufo_start ); mrf.Read( buf, info.zsize ); mrf.Close(); #ifdef VERBOSE printf("Read %u bytes at %u\n", info.zsize, info.offset ); #endif // Copy into TStream TMemoryStream fdata; fdata.LoadFromBuffer( buf, info.zsize ); delete buf; printf ( ( user_opt_allow_extraction ? "Saving %s.. " : "Checking %s.. " ), fname.substr( fname.rfind('/') +1 ).c_str() ); // Create path only when extraction is flagged if( user_opt_allow_extraction ) fsCreatePath( fname ); switch( method ) { // Compressed, most files case FILEINDEX_ENTRY_COMPRESSED : { fsXor( info, fdata ); #ifdef VERBOSE printf("Complete XOR routine\n"); #endif TMemoryStream fdata_raw; if( fsRle( fdata, fdata_raw ) ) { #ifdef VERBOSE printf("Completed RLE routine\n"); #endif if( user_opt_allow_extraction ) fdata_raw.SaveToFile( fname.c_str() ); printf("done!\n"); } // fsRle will display any errors fdata_raw.Close(); break; } // Encrypted and compressed, some system data (GunZ 2) case FILEINDEX_ENTRY_COMPRESSED2 : { TMemoryStream fdata_dec; z3Decrypt( z3CurrentKey, fdata, fdata_dec ); fdata.Close(); // Now same as FILEINDEX_ENTRY_COMPRESSED fsXor( info, fdata_dec ); TMemoryStream fdata_raw; if( fsRle( fdata_dec, fdata_raw ) ) { if( user_opt_allow_extraction ) fdata_raw.SaveToFile( fname.c_str() ); printf("done!\n"); } // fsRle will display any errors fdata_dec.Close(); fdata_raw.Close(); break; } // Large files, some FSB (GunZ 2) case FILEINDEX_ENTRY_UNCOMPRESSED : { if( user_opt_allow_extraction ) fdata.SaveToFile( fname.c_str() ); printf("done!\n"); break; } default: { fdata.Close(); printf("ERROR: Unknown compression type (%02X)\n", method); return false; } } fdata.Close(); return true; }
int Reaching::PerformTrajectories(string *infname, string *outfname){ ifstream istr(infname->c_str()); if(istr.fail()){ cout <<"can't open file "<<infname->c_str()<<endl; return 0; } else{ int timeOfJump, tar_ok,tar_spec; string fname(*outfname); string line; char nc[80]; joint_vec_t& pos, new_tar; int n=0; sprintf(nc,"%d",n); fname = *outfname + nc +".txt"; // appending the traj number to the filename ofstream out(fname.c_str()); getline(istr,line); if(4 != sscanf(line.c_str(),"%f %f %f %f \n", &(pos[0]),&(pos[1]),&(pos[2]),&(pos[3]))){ #ifndef SILENT cout << "line " << n << " not decripted"<<endl; #endif } else{ SetActualRobPosition(pos); } out << *this << endl; while(!istr.eof()){ getline(istr,line); tar_spec = sscanf(line.c_str(),"%d: %f %f %f %f\n", &timeOfJump, &(new_tar[0]),&(new_tar[1]),&(new_tar[2]), &(new_tar[3])); if ((tar_spec !=5) && (tar_spec != 4)){ #ifndef SILENT //cout << "line " << n << " not decripted"<<endl; #endif } else{ if (tar_spec ==4){ // a 3d cartesian end-effector is specified tar_ok = SetTarget(new_tar); // only the first 3 values } else{ tar_ok = SetArmConfigurationTarget(new_tar); // a 4d arm configuration is specified // coutvec4(new_tar); } if(tar_ok){ for (int i=0;i<timeOfJump && !TargetReached();i++){ ReachingStep(); #ifdef LEARNING LearningLocal(); #endif out << *this << endl; } #ifdef LEARNING LearningGlobal(); #endif } } } out.close(); if(TargetReached()){ return 1; } } return 0; }
int main(int argc, const char* argv[]){ gSystem->Load("libTree"); bool _syst = false; bool _tr_unc = false; bool _idiso_unc = false; const char * _output = 0; const char * _input = 0; const char * _dir = "/home/brochero/ttbar/TopTrees_CATuples/"; const char * _tr = 0; const char * _idiso = 0; // Arguments used //std::set<int> usedargs; //Parsing input options if(argc == 1){ display_usage(); return -1; } else{ //Argumet 1 must be a valid input fileName for (int i = 1; i < argc; i++){ if( strcmp(argv[i],"-i") == 0 ){ _input = argv[i+1]; i++; } if( strcmp(argv[i],"-d") == 0 ){ _dir = argv[i+1]; i++; } if( strcmp(argv[i],"-o") == 0 ){ _output= argv[i+1]; i++; } if( strcmp(argv[i],"-h") == 0 || strcmp(argv[i],"--help") == 0 ){ display_usage(); return 0; } } }//else if( _input ==0 ){ std::cerr << "\033[1;31mskimfile ERROR:\033[1;m The '-i' option is mandatory!" << std::endl; display_usage(); return -1; } // reassigning TString fname(_input); TString hname(_output); TString fdir(_dir); TChain theTree("ttbarSingleLepton/AnalysisTree"); std::cout << "-----------------------------------------" << std::endl; std::cout << "-----------------------------------------" << std::endl; std::cout << "Signal: "; std::cout << fname + ".root" << std::endl; theTree.Add(fdir + fname + ".root"); int Event,Channel,PV,GoodPV; float PUWeight; // Temporal float MET,MET_Phi; float Lep_px, Lep_py, Lep_pz, Lep_E; std::vector<float> *Jet_px=0, *Jet_py=0, *Jet_pz=0, *Jet_E=0; std::vector<bool> *Jet_LooseID=0; std::vector<float> *Jet_CSV=0; theTree.SetBranchAddress( "event", &Event ); theTree.SetBranchAddress( "PUWeight", &PUWeight ); theTree.SetBranchAddress( "channel", &Channel ); theTree.SetBranchAddress( "PV", &PV ); theTree.SetBranchAddress( "GoodPV", &GoodPV ); theTree.SetBranchAddress( "MET", &MET ); theTree.SetBranchAddress( "MET_phi", &MET_Phi ); theTree.SetBranchAddress( "lepton_px", &Lep_px ); theTree.SetBranchAddress( "lepton_py", &Lep_py ); theTree.SetBranchAddress( "lepton_pz", &Lep_pz ); theTree.SetBranchAddress( "lepton_E", &Lep_E ); theTree.SetBranchAddress( "jet_px", &Jet_px ); theTree.SetBranchAddress( "jet_py", &Jet_py ); theTree.SetBranchAddress( "jet_pz", &Jet_pz ); theTree.SetBranchAddress( "jet_E", &Jet_E ); theTree.SetBranchAddress( "jet_LooseID", &Jet_LooseID ); theTree.SetBranchAddress( "jet_CSV", &Jet_CSV ); /********************************* Histograms **********************************/ TH1F *hPV[4][2]; TH1F *hMET[4][2],*hMET_Phi[4][2]; TH1F *hLepPt[4][2],*hLepEta[4][2],*hLepPhi[4][2]; TH1F *hNJets[4][2],*hHT[4][2],*hNBtagJets[4][2]; TH1F *CSV[4][4][2]; TString namech[2]; namech[0]="mujets"; namech[1]="ejets"; TString namecut[4]; namecut[0]="lepton"; namecut[1]="4Jets"; namecut[2]="MET"; namecut[3]="2btag"; TString titlenamech[2]; titlenamech[0]="#mu+Jets"; titlenamech[1]="e+Jets"; for(int j=0; j<4; j++){ // Cut for(int i=0; i<2; i++){ // Channel hPV[j][i] = new TH1F("hPV_"+namech[i]+"_"+namecut[j],"PV Distribution " + titlenamech[i],30,0,30); hMET[j][i] = new TH1F("hMET_"+namech[i]+"_"+namecut[j],"#slash{E}_{T} " + titlenamech[i],40,0,200); hMET_Phi[j][i] = new TH1F("hMET_Phi_"+namech[i]+"_"+namecut[j],"#Phi_{#slash{E}_{T}} " + titlenamech[i],160,-4,4); hLepPt [j][i] = new TH1F("hLepPt_" +namech[i] + "_" + namecut[j], "Lepton p_{T} " + titlenamech[i],50,0.0,250.0); hLepEta[j][i] = new TH1F("hLepEta_" +namech[i] + "_" + namecut[j], "#eta_{Lep} " + titlenamech[i],50,-2.5,2.5); hLepPhi[j][i] = new TH1F("hLepPhi_" +namech[i] + "_" + namecut[j], "#phi_{Lep} " + titlenamech[i],100,-5,5); hNJets[j][i] = new TH1F("hNJets_"+namech[i]+"_"+namecut[j],"Jet multiplicity " + titlenamech[i],9,-0.5,8.5); hNBtagJets[j][i] = new TH1F("hNBtagJets_"+namech[i]+"_"+namecut[j],"b-tag jet multiplicity " + titlenamech[i],9,-0.5,8.5); hHT[j][i] = new TH1F("hHT_"+namech[i]+"_"+namecut[j],"H_{T} " + titlenamech[i],300,0,600); TString jetn[4]; jetn[0]= "Jet0"; jetn[1]= "Jet1"; jetn[2]= "Jet2"; jetn[3]= "Jet3"; for(int ij=0; ij<4; ij++){ CSV[ij][j][i] = new TH1F("hCSV_" + jetn[ij] + "_" + namech[i] + "_" + namecut[j],"CSV " + jetn[ij] + " " + titlenamech[i],80,0,1); } }//for(i) }//for(j) TStopwatch sw; sw.Start(kTRUE); // Number de events for <pT Reweight> // [Cut][Channel] float SF_pTweight[4][2]={0,0,0,0, 0,0,0,0}; // Number de events for acceptance // [Cut][Channel] int AccEvent[4][2]={0,0,0,0, 0,0,0,0}; // Number de events for acceptance // [Cut][Channel] float EffEvent[4][2]={0.0,0.0,0.0,0.0, 0.0,0.0,0.0,0.0}; std::cout << "--- Processing: " << theTree.GetEntries() << " events" << std::endl; for (Long64_t ievt=0; ievt<theTree.GetEntries();ievt++) { theTree.GetEntry( ievt ); ////////////////////////////////////////////////////// int step = theTree.GetEntries()/50; if (ievt%(step) == 0){ float progress=(ievt)/(theTree.GetEntries()*1.0); int barWidth = 50; std::cout << "["; int pos = barWidth * progress; for (int i = 0; i < barWidth; ++i) { if (i < pos) std::cout << "="; else if (i == pos) std::cout << ">"; else std::cout << " "; } std::cout << "] " << int(progress * 100.0) << " %\r"; std::cout.flush(); } //////////////////////////////////////////////////////// int NJets,NBtagJets; TLorentzVector Lep; std::vector<TLorentzVector> Jet; std::vector<TLorentzVector> bJet; Lep.SetPxPyPzE(Lep_px,Lep_py,Lep_pz,Lep_E); if(Lep.Pt()<30) continue; // Lep pT >30GeV // Jets NJets = 0; NBtagJets = 0; for(int ijet=0; ijet < Jet_px->size(); ijet++){ TLorentzVector jet; jet.SetPxPyPzE((*Jet_px)[ijet],(*Jet_py)[ijet],(*Jet_pz)[ijet],(*Jet_E)[ijet]); if(jet.Pt()>25 && // Jet pT > 25GeV !(*Jet_LooseID)[ijet]){ // Loose ID Jet.push_back(jet); NJets++; // Number of jets if((*Jet_CSV)[ijet] > 0.814){ // CSVM. Luca b-tagging code to apply SF? bJet.push_back(jet); NBtagJets++; // Number of b-tagged jets } // if(b-tag) } // if(Jet_pT) }// for(jets) /*************************** Selection ***************************/ int cut=0; // Single Lepton if(NJets>3) cut=1; // + 4Jets if(NJets>3 && MET>30.0) cut=2; // + MET if(NJets>3 && MET>30.0 && NBtagJets>1) cut=3; // + 2 Btag // /******************* // Fill Histograms // ******************/ float PUWeight_event=PUWeight; for(int icut=0; icut<cut+1; icut++){ // PUWeight reset for each cut PUWeight=PUWeight_event; /************************************************************ Scale Factors (Luminosity) *************************************************************/ // Number of events from https://cmsweb.cern.ch/das // Cross Sections at 13 TeV: // - ttbar from https://twiki.cern.ch/twiki/bin/view/Sandbox/FullNNLOcrossSections // https://twiki.cern.ch/twiki/bin/view/LHCPhysics/TtbarNNLO // - backgrounds from https://twiki.cern.ch/twiki/bin/view/CMS/StandardModelCrossSectionsat13TeV int Lumi=1000; //pb // PUWeight = PUWeight*Lumi*(1.0/N_Gen_events)*(Xsec)*(Br) if(fname.Contains("QCD")) PUWeight = PUWeight * Lumi * (1.0/4777926.0) * (866600000.0) * (0.00044); // [pb] (cross section) * (Filter Eff) if(fname.Contains("ZJets")) PUWeight = PUWeight * Lumi * (1.0/2829164.0) * (3591.6) * (0.03*3); // [pb] if(fname.Contains("WJets")) PUWeight = PUWeight * Lumi * (1.0/10017930) * (61526.7) * (0.1*3); // [pb] if(fname.Contains("tW")) PUWeight = PUWeight * Lumi * (1.0/986100.0) * (35.6); // [pb] if(fname.Contains("tbarW")) PUWeight = PUWeight * Lumi * (1.0/971800.0) * (35.6); // [pb] if(fname.Contains("ttbar")) PUWeight = PUWeight * Lumi * (1.0/25446993.0) * (827.1) * (0.108*3) * (0.67); // [pb] /*************************************************************/ /****************** Acceptace ******************/ AccEvent[icut][Channel]++; EffEvent[icut][Channel] = EffEvent[icut][Channel] + PUWeight; hPV[icut][Channel]->Fill(PV,PUWeight); hMET[icut][Channel]->Fill(MET,PUWeight); hMET_Phi[icut][Channel]->Fill(MET_Phi,PUWeight); hLepPt[icut][Channel]->Fill(Lep.Pt(),PUWeight); hLepEta[icut][Channel]->Fill(Lep.Eta(),PUWeight); hLepPhi[icut][Channel]->Fill(Lep.Phi(),PUWeight); hNJets[icut][Channel]->Fill(NJets,PUWeight); hNBtagJets[icut][Channel]->Fill(NBtagJets,PUWeight); for(int ijet=0; ijet < Jet_px->size(); ijet++){ if (ijet<4) CSV[ijet][icut][Channel]->Fill((*Jet_CSV)[ijet],PUWeight); } }//for(icuts) Jet.clear(); bJet.clear(); }//for(events) delete Jet_px; delete Jet_py; delete Jet_pz; delete Jet_E; delete Jet_CSV; // Get elapsed time sw.Stop(); std::cout << "==================================================] 100% " << std::endl; std::cout << "--- End of event loop: "; sw.Print(); //Acceptance-Efficiency std::cout << "-------- Acceptace --------" << std::endl; std::cout << "Number of RAW-mu+Jets events:" << std::endl; std::cout << "lepton: " << AccEvent[0][0] << std::endl; std::cout << "4 Jets: " << AccEvent[1][0] << std::endl; std::cout << "MET: " << AccEvent[2][0] << std::endl; std::cout << "2 btag: " << AccEvent[3][0] << std::endl; std::cout << "-------- Efficiency --------" << std::endl; std::cout << "Number of Weigthed-mu+Jets events:" << std::endl; std::cout << "lepton: " << EffEvent[0][0] << " +/- " << sqrt(AccEvent[0][0])*EffEvent[0][0]/AccEvent[0][0] << std::endl; std::cout << "4 Jets: " << EffEvent[1][0] << " +/- " << sqrt(AccEvent[1][0])*EffEvent[1][0]/AccEvent[1][0] << std::endl; std::cout << "MET: " << EffEvent[2][0] << " +/- " << sqrt(AccEvent[2][0])*EffEvent[2][0]/AccEvent[2][0] << std::endl; std::cout << "2 btag: " << EffEvent[3][0] << " +/- " << sqrt(AccEvent[3][0])*EffEvent[3][0]/AccEvent[3][0] << std::endl; std::cout << "-------- Acceptace --------" << std::endl; std::cout << "Number of RAW-e+Jets events:" << std::endl; std::cout << "lepton: " << AccEvent[0][1] << std::endl; std::cout << "4 Jets: " << AccEvent[1][1] << std::endl; std::cout << "MET: " << AccEvent[2][1] << std::endl; std::cout << "2 btag: " << AccEvent[3][1] << std::endl; std::cout << "-------- Efficiency --------" << std::endl; std::cout << "Number of Weigthed-e+Jets events: " << std::endl; std::cout << "lepton: " << EffEvent[0][1] << " +/- " << sqrt(AccEvent[0][1])*EffEvent[0][1]/AccEvent[0][1] << std::endl; std::cout << "4 Jets: " << EffEvent[1][1] << " +/- " << sqrt(AccEvent[1][1])*EffEvent[1][1]/AccEvent[1][1] << std::endl; std::cout << "MET: " << EffEvent[2][1] << " +/- " << sqrt(AccEvent[2][1])*EffEvent[2][1]/AccEvent[2][1] << std::endl; std::cout << "2 btag: " << EffEvent[3][1] << " +/- " << sqrt(AccEvent[3][1])*EffEvent[3][1]/AccEvent[3][1] << std::endl; //Output Dir TString dirname="TopResults"; // make a dir if it does not exist!! struct stat st; if(stat(dirname,&st) != 0) system("mkdir " + dirname); TString systname=""; bool matchname=false; TString temp_fname=fname + ".root"; for(int i=0;i<temp_fname.Sizeof();i++){ if (i>2){ if (temp_fname[i-3]=='-' && temp_fname[i-2]=='1' && temp_fname[i-1]=='_') matchname=true; } if (temp_fname[i]=='.') matchname=false; if (matchname) systname.Append(temp_fname[i]); } // Yields TString Yieldfile=dirname + "/Yields_" + hname + ".h"; FILE* fyields = fopen(Yieldfile, "a"); fprintf(fyields,"// %s Sample on %s \n", (fname + ".root").Data() , currentDateTime().Data()); fprintf(fyields,"// %s version \n", hname.Data()); fprintf(fyields,"float %s[2][4];//[channel][Cut] \n", systname.Data()); fprintf(fyields,"float err_%s[2][4]; //[channel][Cut] \n", systname.Data()); fprintf(fyields,"// Channel: [0]=mu+Jets [1]=e+Jets \n"); fprintf(fyields,"// Cut [0]=lepton [1]= Jets [2]=MET [3]=btag \n"); for(int ch=0;ch<2;ch++){ for(int cut=0;cut<4;cut++){ fprintf(fyields,"%s[%i][%i] = %.3f ; \n", systname.Data(), ch, cut, EffEvent[cut][ch]); if(AccEvent[cut][ch]!=0.0) fprintf(fyields,"err_%s[%i][%i] = %.3f ; \n", systname.Data(), ch, cut, sqrt(AccEvent[cut][ch])*EffEvent[cut][ch]/AccEvent[cut][ch]); else fprintf(fyields,"err_%s[%i][%i] = 0.0 ; \n", systname.Data(), ch, cut); } } fclose(fyields); std::cout << "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" << std::endl; std::cout << "Yields saved into " << Yieldfile << " file" << std::endl; std::cout << "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" << std::endl; // --- Write histograms TString outfname=dirname + "/hSF-" + hname + "_" + fname + ".root"; TFile *target = new TFile(outfname,"RECREATE" ); for(int j=0; j<4; j++){ for(int i=0; i<2; i++){ hPV[j][i]->Write(); hMET[j][i]->Write(); hMET_Phi[j][i]->Write(); hLepPt[j][i]->Write(); hLepEta[j][i]->Write(); hLepPhi[j][i]->Write(); hNJets[j][i]->Write(); hNBtagJets[j][i]->Write(); for(int ij=0; ij<4; ij++){ CSV[ij][j][i]->Write(); } }//for(i) }//for(j) std::cout << "File saved as " << outfname << std::endl; }
void EditPathDlg::OnBrowse(wxCommandEvent& /*event*/) { wxFileName path; wxArrayString multi; wxString val = XRCCTRL(*this, "txtPath", wxTextCtrl)->GetValue(); int idx = val.Find(DEFAULT_ARRAY_SEP); if (idx != -1) val.Remove(idx); wxFileName fname(val); if (m_WantDir) { // try to "decode" custom var wxString bkp = val; Manager::Get()->GetMacrosManager()->ReplaceEnvVars(val); fname = val; fname.MakeAbsolute(m_Basepath); m_Path = fname.GetFullPath(); path = ChooseDirectory(this, m_Message, (m_Path.IsEmpty() ? s_LastPath : m_Path), m_Basepath, false, m_ShowCreateDirButton); if (path.GetFullPath().IsEmpty()) return; // if it was a custom var, see if we can re-insert it if (bkp != val) { wxString tmp = path.GetFullPath(); if (tmp.Replace(val, bkp) != 0) { // done here XRCCTRL(*this, "txtPath", wxTextCtrl)->SetValue(tmp); return; } } } else { wxFileDialog dlg(this, m_Message, (fname.GetPath().IsEmpty() ? s_LastPath : fname.GetPath()), fname.GetFullName(), m_Filter, wxFD_CHANGE_DIR | (m_AllowMultiSel ? wxFD_MULTIPLE : 0) ); PlaceWindow(&dlg); if (dlg.ShowModal() == wxID_OK) { if (m_AllowMultiSel) dlg.GetPaths(multi); else path = dlg.GetPath(); } else return; } if (m_AllowMultiSel && multi.GetCount() != 0 && !multi[0].IsEmpty()) s_LastPath = multi[0]; else if (!path.GetFullPath().IsEmpty()) s_LastPath = path.GetFullPath(); wxString result; if (m_AskMakeRelative && !m_Basepath.IsEmpty()) { // ask the user if he wants it to be kept as relative if (cbMessageBox(_("Keep this as a relative path?"), _("Question"), wxICON_QUESTION | wxYES_NO, this) == wxID_YES) { if (m_AllowMultiSel) { for (unsigned int i = 0; i < multi.GetCount(); ++i) { path = multi[i]; path.MakeRelativeTo(m_Basepath); wxString tmp = path.GetFullPath(); if( !tmp.Contains(_T("\\")) && !tmp.Contains(_T("/"))) { tmp = _T("."); tmp << wxFileName::GetPathSeparator(); tmp += path.GetFullPath(); } multi[i] = tmp; } result = GetStringFromArray(multi); } else { path.MakeRelativeTo(m_Basepath); wxString tmp = path.GetFullPath(); if( !tmp.Contains(_T("\\")) && !tmp.Contains(_T("/"))) { tmp = _T("."); tmp << wxFileName::GetPathSeparator(); tmp += path.GetFullPath(); } result = tmp; } } else { if (m_AllowMultiSel) result = GetStringFromArray(multi); else result = path.GetFullPath(); } } else // always absolute path { if (m_AllowMultiSel) result = GetStringFromArray(multi); else result = path.GetFullPath(); } // finally set the path XRCCTRL(*this, "txtPath", wxTextCtrl)->SetValue(result); }
int main(int argc, char* argv []) { // check for verbosity flag: bool verbose = false; if( argc >= 2 ) { for(int i=1; i < argc; i++) { std::string flag(argv[i]); if(flag == "--verbose") verbose = true; } } bool pass = true; // Do some output std::cout << "========== Test Suite 2 ==========" << std::endl; std::cout << " Testing plot generators " << std::endl; // create a model to use for the test: std::string fname("SRIM/Hydrogen in Aluminum.txt"); //StopPow::StopPow_SRIM s(fname); std::vector<double> mf(2); mf[0] = 1.0; mf[1] = 1/1800.; std::vector<double> Zf(2); Zf[0] = 1.0; Zf[1] = -1.; std::vector<double> Tf(2); Tf[0] = 1.0; Tf[1] = 1.0; std::vector<double> nf(2); nf[0] = 1e24; nf[1] = 1e24; nf[0] = 1e24; nf[1] = 1e24; StopPow::StopPow_LP s(1,1,mf,Zf,Tf,nf); std::vector< std::vector<double> > dEdx_plot; bool ret = StopPow::get_dEdx_vs_E( s , dEdx_plot ); if(ret) std::cout << "dE/dx plot generated successfully" << std::endl; else std::cout << "ERROR: could not generate dE/dx plot" << std::endl; pass &= ret; std::vector< std::vector<double> > Range_plot; ret = StopPow::get_Range_vs_E( s , Range_plot ); if(ret) std::cout << "Range plot generated successfully" << std::endl; else std::cout << "ERROR: could not generate Range plot" << std::endl; pass &= ret; double thickness = 100; // um std::vector< std::vector<double> > Eout_plot_1; ret = StopPow::get_Eout_vs_Ein( s , thickness , Eout_plot_1 ); if(ret) std::cout << "Eout vs Ein plot generated successfully" << std::endl; else std::cout << "ERROR: could not generate Eout vs Ein plot" << std::endl; pass &= ret; double Ein = 15; // MeV std::vector< std::vector<double> > Eout_plot_2; ret = StopPow::get_Eout_vs_Thickness( s , Ein , Eout_plot_2 ); if(ret) std::cout << "Eout vs Thickness plot generated successfully" << std::endl; else std::cout << "ERROR: could not generate Eout vs Thickness plot" << std::endl; pass &= ret; thickness = 100; // um std::vector< std::vector<double> > Ein_plot_1; ret = StopPow::get_Ein_vs_Eout( s , thickness , Ein_plot_1 ); if(ret) std::cout << "Ein vs Eout plot generated successfully" << std::endl; else std::cout << "ERROR: could not generate Ein vs Eout plot" << std::endl; pass &= ret; double Eout = 15; // MeV std::vector< std::vector<double> > Ein_plot_2; ret = StopPow::get_Ein_vs_Thickness( s , Eout , Ein_plot_2 ); if(ret) std::cout << "Ein vs Thickness plot generated successfully" << std::endl; else std::cout << "ERROR: could not generate Ein vs Thickness plot" << std::endl; pass &= ret; Ein = 15; std::vector< std::vector<double> > Thickness_plot_1; ret = StopPow::get_Thickness_vs_Eout( s , Ein , Thickness_plot_1 ); if(ret) std::cout << "Thickness vs Eout plot generated successfully" << std::endl; else std::cout << "ERROR: could not generate Thickness vs Eout plot" << std::endl; pass &= ret; Eout = 5; std::vector< std::vector<double> > Thickness_plot_2; ret = StopPow::get_Thickness_vs_Ein( s , Eout , Thickness_plot_2 ); if(ret) std::cout << "Thickness vs Ein plot generated successfully" << std::endl; else std::cout << "ERROR: could not generate Thickness vs Ein plot" << std::endl; pass &= ret; // print if requested if( verbose) { std::cout << "E (MeV) , dE/dx" << std::endl; for(int j=0; j<dEdx_plot[0].size(); j++) { std::cout << dEdx_plot[0][j] << "," << dEdx_plot[1][j] << std::endl; } std::cout << "--------------------------------" << std::endl; std::cout << "E (MeV) , Range" << std::endl; for(int j=0; j<Range_plot[0].size(); j++) { std::cout << Range_plot[0][j] << "," << Range_plot[1][j] << std::endl; } std::cout << "--------------------------------" << std::endl; std::cout << "Ein (MeV) , Eout (MeV)" << std::endl; for(int j=0; j<Eout_plot_1[0].size(); j++) { std::cout << Eout_plot_1[0][j] << "," << Eout_plot_1[1][j] << std::endl; } std::cout << "--------------------------------" << std::endl; std::cout << "Thickness , Eout (MeV)" << std::endl; for(int j=0; j<Eout_plot_2[0].size(); j++) { std::cout << Eout_plot_2[0][j] << "," << Eout_plot_2[1][j] << std::endl; } std::cout << "--------------------------------" << std::endl; std::cout << "Eout (MeV) , Ein (MeV)" << std::endl; for(int j=0; j<Ein_plot_1[0].size(); j++) { std::cout << Ein_plot_1[0][j] << "," << Ein_plot_1[1][j] << std::endl; } std::cout << "--------------------------------" << std::endl; std::cout << "Thickness , Ein (MeV)" << std::endl; for(int j=0; j<Ein_plot_2[0].size(); j++) { std::cout << Ein_plot_2[0][j] << "," << Ein_plot_2[1][j] << std::endl; } std::cout << "--------------------------------" << std::endl; std::cout << "Eout (MeV) , Thickness" << std::endl; for(int j=0; j<Thickness_plot_1[0].size(); j++) { std::cout << Thickness_plot_1[0][j] << "," << Thickness_plot_1[1][j] << std::endl; } std::cout << "--------------------------------" << std::endl; std::cout << "Ein (MeV) , Thickness" << std::endl; for(int j=0; j<Thickness_plot_2[0].size(); j++) { std::cout << Thickness_plot_2[0][j] << "," << Thickness_plot_2[1][j] << std::endl; } std::cout << "--------------------------------" << std::endl; } // --------------------------------------- // Speed tests // --------------------------------------- std::cout << "Speed tests (ms / generation):" << std::endl; int n = 10; std::clock_t start; double duration; start = std::clock(); for(int i=0; i<n; i++) ret = StopPow::get_dEdx_vs_E( s , dEdx_plot ); // duration per call in ms: duration = (1000./n)*(std::clock()-start) / (double) CLOCKS_PER_SEC; std::cout << "dE/dx vs E = " << duration << " ms" << std::endl; start = std::clock(); for(int i=0; i<n; i++) ret = StopPow::get_Range_vs_E( s , Range_plot ); // duration per call in ms: duration = (1000./n)*(std::clock()-start) / (double) CLOCKS_PER_SEC; std::cout << "Range vs E = " << duration << " ms" << std::endl; start = std::clock(); for(int i=0; i<n; i++) ret = StopPow::get_Eout_vs_Ein( s , thickness , Eout_plot_1 ); // duration per call in ms: duration = (1000./n)*(std::clock()-start) / (double) CLOCKS_PER_SEC; std::cout << "Eout vs Ein = " << duration << " ms" << std::endl; start = std::clock(); for(int i=0; i<n; i++) ret = StopPow::get_Eout_vs_Thickness( s , Ein , Eout_plot_2 ); // duration per call in ms: duration = (1000./n)*(std::clock()-start) / (double) CLOCKS_PER_SEC; std::cout << "Eout vs Thickness = " << duration << " ms" << std::endl; start = std::clock(); for(int i=0; i<n; i++) ret = StopPow::get_Ein_vs_Eout( s , thickness , Ein_plot_1 ); // duration per call in ms: duration = (1000./n)*(std::clock()-start) / (double) CLOCKS_PER_SEC; std::cout << "Ein vs Eout = " << duration << " ms" << std::endl; start = std::clock(); for(int i=0; i<n; i++) ret = StopPow::get_Ein_vs_Thickness( s , Eout , Ein_plot_2 ); // duration per call in ms: duration = (1000./n)*(std::clock()-start) / (double) CLOCKS_PER_SEC; std::cout << "Ein vs Thickness = " << duration << " ms" << std::endl; start = std::clock(); for(int i=0; i<n; i++) ret = StopPow::get_Thickness_vs_Eout( s , Ein , Thickness_plot_1 ); // duration per call in ms: duration = (1000./n)*(std::clock()-start) / (double) CLOCKS_PER_SEC; std::cout << "Thickness vs Eout = " << duration << " ms" << std::endl; start = std::clock(); for(int i=0; i<n; i++) ret = StopPow::get_Thickness_vs_Ein( s , Eout , Thickness_plot_2 ); // duration per call in ms: duration = (1000./n)*(std::clock()-start) / (double) CLOCKS_PER_SEC; std::cout << "Thickness vs Ein = " << duration << " ms" << std::endl; if(pass) { std::cout << "PASS" << std::endl; return 0; } std::cout << "FAIL!" << std::endl; return 1; }
/// This is to be used *only* for files not belonging to a project!!! wxArrayString DirectCommands::GetCompileSingleFileCommand(const wxString& filename) const { wxArrayString ret; // lookup file's type FileType ft = FileTypeOf(filename); // is it compilable? if (ft != ftSource) return ret; wxFileName fname(filename); fname.SetExt(m_pCompiler->GetSwitches().objectExtension); wxString o_filename = fname.GetFullPath(); wxString srcExt = fname.GetExt(); fname.SetExt(FileFilters::EXECUTABLE_EXT); wxString exe_filename = fname.GetFullPath(); wxString s_filename = filename; QuoteStringIfNeeded(s_filename); QuoteStringIfNeeded(o_filename); Compiler* compiler = CompilerFactory::GetDefaultCompiler(); if (!compiler) return ret; // please leave this check here for convenience: single file compilation is "special" if (!m_pGenerator) cbThrow(_T("Command generator not initialised through ctor!")); wxString compilerCmd = compiler->GetCommand(ctCompileObjectCmd, srcExt); m_pGenerator->GenerateCommandLine(compilerCmd, 0, 0, s_filename, o_filename, o_filename, wxEmptyString); wxString linkerCmd = compiler->GetCommand(ctLinkConsoleExeCmd, fname.GetExt()); m_pGenerator->GenerateCommandLine(linkerCmd, 0, 0, wxEmptyString, o_filename, o_filename, wxEmptyString); if (!compilerCmd.IsEmpty()) { switch (m_pCompiler->GetSwitches().logging) { case clogFull: ret.Add(wxString(COMPILER_SIMPLE_LOG) + compilerCmd); break; case clogSimple: ret.Add(wxString(COMPILER_SIMPLE_LOG) + _("Compiling: ") + filename); break; case clogNone: // fall-through default: break; } AddCommandsToArray(compilerCmd, ret); } else ret.Add(wxString(COMPILER_SIMPLE_LOG) + _("Skipping file (no compiler program set): ") + filename); if (!linkerCmd.IsEmpty()) { switch (m_pCompiler->GetSwitches().logging) { case clogFull: ret.Add(wxString(COMPILER_SIMPLE_LOG) + linkerCmd); break; case clogSimple: // fall-through case clogNone: // fall-through default: // linker always simple log (if not full) ret.Add(wxString(COMPILER_SIMPLE_LOG) + _("Linking console executable: ") + exe_filename); break; } AddCommandsToArray(linkerCmd, ret, true); } else ret.Add(wxString(COMPILER_SIMPLE_LOG) + _("Skipping linking (no linker program set): ") + exe_filename); return ret; }