void TestUseCoarsePdeMesh() throw(Exception) { EXIT_IF_PARALLEL; // Create a cell population HoneycombMeshGenerator generator(4, 4, 0); MutableMesh<2,2>* p_generating_mesh = generator.GetMesh(); NodesOnlyMesh<2> mesh; mesh.ConstructNodesWithoutMesh(*p_generating_mesh, 1.5); std::vector<CellPtr> cells; CellsGenerator<FixedDurationGenerationBasedCellCycleModel, 2> cells_generator; cells_generator.GenerateBasic(cells, mesh.GetNumNodes()); NodeBasedCellPopulation<2> cell_population(mesh, cells); // Create a PDE handler object using this cell population CellBasedPdeHandler<2> pde_handler(&cell_population); // Test that UseCoarsePdeMesh() throws an exception if no PDEs are specified ChastePoint<2> lower(0.0, 0.0); ChastePoint<2> upper(9.0, 9.0); ChasteCuboid<2> cuboid(lower, upper); TS_ASSERT_THROWS_THIS(pde_handler.UseCoarsePdeMesh(3.0, cuboid, true), "mPdeAndBcCollection should be populated prior to calling UseCoarsePdeMesh()."); // Set up PDE and pass to handler AveragedSourcePde<2> pde(cell_population, -0.1); ConstBoundaryCondition<2> bc(1.0); PdeAndBoundaryConditions<2> pde_and_bc(&pde, &bc, false); pde_handler.AddPdeAndBc(&pde_and_bc); // Test UseCoarsePdeMesh() again pde_handler.UseCoarsePdeMesh(3.0, cuboid, true); // Test that the coarse mesh has the correct number of nodes and elements TetrahedralMesh<2,2>* p_coarse_mesh = pde_handler.GetCoarsePdeMesh(); TS_ASSERT_EQUALS(p_coarse_mesh->GetNumNodes(), 16u); TS_ASSERT_EQUALS(p_coarse_mesh->GetNumElements(), 18u); // Find centre of cell population c_vector<double,2> centre_of_cell_population = cell_population.GetCentroidOfCellPopulation(); // Find centre of coarse PDE mesh c_vector<double,2> centre_of_coarse_pde_mesh = zero_vector<double>(2); for (unsigned i=0; i<p_coarse_mesh->GetNumNodes(); i++) { centre_of_coarse_pde_mesh += p_coarse_mesh->GetNode(i)->rGetLocation(); } centre_of_coarse_pde_mesh /= p_coarse_mesh->GetNumNodes(); // Test that the two centres match c_vector<double,2> centre_difference = centre_of_cell_population - centre_of_coarse_pde_mesh; TS_ASSERT_DELTA(norm_2(centre_difference), 0.0, 1e-4); // Test that UseCoarsePdeMesh() throws an exception if the wrong type of PDE is specified SimpleUniformSourcePde<2> pde2(-0.1); ConstBoundaryCondition<2> bc2(1.0); PdeAndBoundaryConditions<2> pde_and_bc2(&pde2, &bc2, false); pde_and_bc2.SetDependentVariableName("second variable"); pde_handler.AddPdeAndBc(&pde_and_bc2); TS_ASSERT_THROWS_THIS(pde_handler.UseCoarsePdeMesh(3.0, cuboid, true), "UseCoarsePdeMesh() should only be called if averaged-source PDEs are specified."); // Now test the 1D case std::vector<Node<1>*> nodes_1d; nodes_1d.push_back(new Node<1>(0, true, 0.0)); NodesOnlyMesh<1> mesh_1d; mesh_1d.ConstructNodesWithoutMesh(nodes_1d, 1.5); std::vector<CellPtr> cells_1d; CellsGenerator<FixedDurationGenerationBasedCellCycleModel, 1> cells_generator_1d; cells_generator_1d.GenerateBasic(cells_1d, mesh_1d.GetNumNodes()); NodeBasedCellPopulation<1> cell_population_1d(mesh_1d, cells_1d); CellBasedPdeHandler<1> pde_handler_1d(&cell_population_1d); AveragedSourcePde<1> pde_1d(cell_population_1d, -0.1); ConstBoundaryCondition<1> bc_1d(1.0); PdeAndBoundaryConditions<1> pde_and_bc_1d(&pde_1d, &bc_1d, false); pde_handler_1d.AddPdeAndBc(&pde_and_bc_1d); ChastePoint<1> lower1(0.0); ChastePoint<1> upper1(9.0); ChasteCuboid<1> cuboid1(lower1, upper1); pde_handler_1d.UseCoarsePdeMesh(3.0, cuboid1, true); // Test that the coarse mesh has the correct number of nodes and elements TetrahedralMesh<1,1>* p_coarse_mesh_1d = pde_handler_1d.GetCoarsePdeMesh(); TS_ASSERT_EQUALS(p_coarse_mesh_1d->GetNumNodes(), 4u); TS_ASSERT_EQUALS(p_coarse_mesh_1d->GetNumElements(), 3u); // Now test the 3D case std::vector<Node<3>*> nodes_3d; nodes_3d.push_back(new Node<3>(0, true, 0.0)); NodesOnlyMesh<3> mesh_3d; mesh_3d.ConstructNodesWithoutMesh(nodes_3d, 1.5); std::vector<CellPtr> cells_3d; CellsGenerator<FixedDurationGenerationBasedCellCycleModel, 3> cells_generator_3d; cells_generator_3d.GenerateBasic(cells_3d, mesh_3d.GetNumNodes()); NodeBasedCellPopulation<3> cell_population_3d(mesh_3d, cells_3d); CellBasedPdeHandler<3> pde_handler_3d(&cell_population_3d); AveragedSourcePde<3> pde_3d(cell_population_3d, -0.1); ConstBoundaryCondition<3> bc_3d(1.0); PdeAndBoundaryConditions<3> pde_and_bc_3d(&pde_3d, &bc_3d, false); pde_handler_3d.AddPdeAndBc(&pde_and_bc_3d); ChastePoint<3> lower3(0.0, 0.0, 0.0); ChastePoint<3> upper3(9.0, 9.0, 9.0); ChasteCuboid<3> cuboid3(lower3, upper3); pde_handler_3d.UseCoarsePdeMesh(3.0, cuboid3, true); // Test that the coarse mesh has the correct number of nodes and elements TetrahedralMesh<3,3>* p_coarse_mesh_3d = pde_handler_3d.GetCoarsePdeMesh(); TS_ASSERT_EQUALS(p_coarse_mesh_3d->GetNumNodes(), 64u); TS_ASSERT_EQUALS(p_coarse_mesh_3d->GetNumElements(), 162u); // Avoid memory leak for (unsigned i=0; i<nodes_1d.size(); i++) { delete nodes_1d[i]; delete nodes_3d[i]; } }
int popmatch(char *nome, int i){ /*função que abre o arquivo de pop lê e mostra a música a ser adivinhada, lê e armazena o titulo da musica*/ FILE *arq; char c = 'a', tit_mus[200], resp[200]; int n, j; int p; printf("Qual é a música?\n\n"); if((arq = fopen("mus_pop.txt","r"))==NULL){ printf("O arquivo nao pode ser aberto\n"); } printf("\n"); n = -1; do{ if(c!='$'){ fscanf(arq, "%c", &c); } else{ fscanf(arq, "%c", &c); n++; } }while(c!='$' || n<(i-1)); while(c!='@'){ fscanf(arq, "%c", &c); if(c!='@'){ printf("%c", c); } } fclose(arq); if((arq = fopen("mus_pop.txt","r"))==NULL){ printf("O arquivo nao pode ser aberto\n"); } n = -1; j = 0; do{ if(c!='&'){ fscanf(arq, "%c", &c); } else{ fscanf(arq, "%c", &c); n++; } }while(c!='&' || n<(i-1)); while(c!='#'){ fscanf(arq, "%c", &c); if(c!='#'){ tit_mus[j] = c; } else{ tit_mus[j]='\0'; } j++; } fclose(arq); printf("\n\nDigite o nome da música:"); scanf("%[^\n]s", resp); while(getchar()!='\n'); lower(resp); if(compare(tit_mus,resp)==0){ /*primeira chance*/ printf("\nParabéns! Você acertou! +10 pontos!\n\n"); printf("Aperte ENTER para continuar."); while(getchar()!='\n'); clear(); p = 10; } else{ /*segunda chance*/ printf("Você errou e perdeu 1 ponto, mas ainda tem 1 chance.\nQual é o nome da música? "); scanf("%[^\n]s", resp); lower(resp); if(compare(tit_mus,resp)==0){ printf("\nParabéns! Você acertou! +10 pontos!\n\n"); printf("Aperte ENTER para continuar."); while(getchar()!='\n'); while(getchar()!='\n'); clear(); p = 9; } else{ printf("\nQue pena, você errou e perdeu mais 1 ponto. Suas chances acabaram.\n\n"); printf("Aperte ENTER para continuar."); while(getchar()!='\n'); while(getchar()!='\n'); clear(); p = -2; } } return(p); }
void TestArchiveParabolicBoxDomainPdeModifier() { // Create a file for archiving OutputFileHandler handler("archive", false); handler.SetArchiveDirectory(); std::string archive_filename = handler.GetOutputDirectoryFullPath() + "ParabolicBoxDomainPdeModifier.arch"; // Separate scope to write the archive { // Create PDE and boundary condition objects MAKE_PTR_ARGS(UniformSourceParabolicPde<2>, p_pde, (-0.1)); MAKE_PTR_ARGS(ConstBoundaryCondition<2>, p_bc, (1.0)); // Create a ChasteCuboid on which to base the finite element mesh used to solve the PDE ChastePoint<2> lower(-10.0, -10.0); ChastePoint<2> upper(10.0, 10.0); MAKE_PTR_ARGS(ChasteCuboid<2>, p_cuboid, (lower, upper)); // Create a PDE modifier and set the name of the dependent variable in the PDE std::vector<double> data(10); for (unsigned i=0; i<10; i++) { data[i] = i + 0.45; } Vec vector = PetscTools::CreateVec(data); ParabolicBoxDomainPdeModifier<2> modifier(p_pde, p_bc, false, p_cuboid, 2.0, vector); modifier.SetDependentVariableName("averaged quantity"); // Create an output archive std::ofstream ofs(archive_filename.c_str()); boost::archive::text_oarchive output_arch(ofs); // Serialize via pointer AbstractCellBasedSimulationModifier<2,2>* const p_modifier = &modifier; output_arch << p_modifier; } // Separate scope to read the archive { AbstractCellBasedSimulationModifier<2,2>* p_modifier2; // Restore the modifier std::ifstream ifs(archive_filename.c_str()); boost::archive::text_iarchive input_arch(ifs); input_arch >> p_modifier2; // Test that member variables are correct TS_ASSERT_EQUALS((static_cast<ParabolicBoxDomainPdeModifier<2>*>(p_modifier2))->rGetDependentVariableName(), "averaged quantity"); TS_ASSERT_DELTA((static_cast<ParabolicBoxDomainPdeModifier<2>*>(p_modifier2))->GetStepSize(), 2.0, 1e-5); TS_ASSERT_EQUALS((static_cast<ParabolicBoxDomainPdeModifier<2>*>(p_modifier2))->AreBcsSetOnBoxBoundary(), true); Vec solution = (static_cast<ParabolicBoxDomainPdeModifier<2>*>(p_modifier2))->GetSolution(); ReplicatableVector solution_repl(solution); TS_ASSERT_EQUALS(solution_repl.GetSize(), 10u); for (unsigned i=0; i<10; i++) { TS_ASSERT_DELTA(solution_repl[i], i + 0.45, 1e-6); } delete p_modifier2; } }
void b2VoronoiDiagram::Generate(float32 radius) { b2Assert(m_diagram == NULL); float32 inverseRadius = 1 / radius; b2Vec2 lower(+b2_maxFloat, +b2_maxFloat); b2Vec2 upper(-b2_maxFloat, -b2_maxFloat); for (int32 k = 0; k < m_generatorCount; k++) { Generator& g = m_generatorBuffer[k]; lower = b2Min(lower, g.center); upper = b2Max(upper, g.center); } m_countX = 1 + (int32) (inverseRadius * (upper.x - lower.x)); m_countY = 1 + (int32) (inverseRadius * (upper.y - lower.y)); m_diagram = (Generator**) m_allocator->Allocate(sizeof(Generator*) * m_countX * m_countY); for (int32 i = 0; i < m_countX * m_countY; i++) { m_diagram[i] = NULL; } b2StackQueue<b2VoronoiDiagramTask> queue( m_allocator, 4 * m_countX * m_countX); for (int32 k = 0; k < m_generatorCount; k++) { Generator& g = m_generatorBuffer[k]; g.center = inverseRadius * (g.center - lower); int32 x = b2Max(0, b2Min((int32) g.center.x, m_countX - 1)); int32 y = b2Max(0, b2Min((int32) g.center.y, m_countY - 1)); queue.Push(b2VoronoiDiagramTask(x, y, x + y * m_countX, &g)); } while (!queue.Empty()) { int32 x = queue.Front().m_x; int32 y = queue.Front().m_y; int32 i = queue.Front().m_i; Generator* g = queue.Front().m_generator; queue.Pop(); if (!m_diagram[i]) { m_diagram[i] = g; if (x > 0) { queue.Push(b2VoronoiDiagramTask(x - 1, y, i - 1, g)); } if (y > 0) { queue.Push(b2VoronoiDiagramTask(x, y - 1, i - m_countX, g)); } if (x < m_countX - 1) { queue.Push(b2VoronoiDiagramTask(x + 1, y, i + 1, g)); } if (y < m_countY - 1) { queue.Push(b2VoronoiDiagramTask(x, y + 1, i + m_countX, g)); } } } int32 maxIteration = m_countX + m_countY; for (int32 iteration = 0; iteration < maxIteration; iteration++) { for (int32 y = 0; y < m_countY; y++) { for (int32 x = 0; x < m_countX - 1; x++) { int32 i = x + y * m_countX; Generator* a = m_diagram[i]; Generator* b = m_diagram[i + 1]; if (a != b) { queue.Push(b2VoronoiDiagramTask(x, y, i, b)); queue.Push(b2VoronoiDiagramTask(x + 1, y, i + 1, a)); } } } for (int32 y = 0; y < m_countY - 1; y++) { for (int32 x = 0; x < m_countX; x++) { int32 i = x + y * m_countX; Generator* a = m_diagram[i]; Generator* b = m_diagram[i + m_countX]; if (a != b) { queue.Push(b2VoronoiDiagramTask(x, y, i, b)); queue.Push(b2VoronoiDiagramTask(x, y + 1, i + m_countX, a)); } } } bool updated = false; while (!queue.Empty()) { int32 x = queue.Front().m_x; int32 y = queue.Front().m_y; int32 i = queue.Front().m_i; Generator* k = queue.Front().m_generator; queue.Pop(); Generator* a = m_diagram[i]; Generator* b = k; if (a != b) { float32 ax = a->center.x - x; float32 ay = a->center.y - y; float32 bx = b->center.x - x; float32 by = b->center.y - y; float32 a2 = ax * ax + ay * ay; float32 b2 = bx * bx + by * by; if (a2 > b2) { m_diagram[i] = b; if (x > 0) { queue.Push(b2VoronoiDiagramTask(x - 1, y, i - 1, b)); } if (y > 0) { queue.Push(b2VoronoiDiagramTask(x, y - 1, i - m_countX, b)); } if (x < m_countX - 1) { queue.Push(b2VoronoiDiagramTask(x + 1, y, i + 1, b)); } if (y < m_countY - 1) { queue.Push(b2VoronoiDiagramTask(x, y + 1, i + m_countX, b)); } updated = true; } } } if (!updated) { break; } } }
void p2p_go_mode(struct p2p *p) { FILE *pf = NULL; int count = 0, ret = 0, i = -1; char addr_lower[18]; p2p_ifaddr(p); p->p2p_get=1; memset( p->print_line, 0x00, CMD_SZ ); strcpy( p->print_line, "Start hostapd"); ui_screen(p); if(p->ap_open != 1) { memset( p->cmd, 0x00, CMD_SZ ); sprintf( p->cmd, "%s -B %s > temp.txt",p->ap_path, p->ap_conf); system( p->cmd ); usleep( HOSTAPD_INIT_TIME ); } if(p->wps_info==1 || p->wps_info==2) { do { memset( p->cmd, 0x00, CMD_SZ ); sprintf( p->cmd, "%s wps_pin any %d > supp_status.txt", p->apcli_path, p->pin); system( p->cmd ); pf = fopen( "./supp_status.txt", "r" ); if ( pf ) { while( !feof( pf ) ){ memset(p->parse, 0x00, CMD_SZ); fgets(p->parse, CMD_SZ, pf); if(strncmp(p->parse, "", 2) == 0) { ret = 1; p->wpsing = 1; } } fclose( pf ); } if( ret == 0 ) usleep( HOSTAPD_INIT_TIME ); } while( ret == 0 ); } else if(p->wps_info==3) { do { memset( p->cmd, 0x00, CMD_SZ ); sprintf( p->cmd, "%s wps_pbc any > supp_status.txt", p->apcli_path); system( p->cmd ); pf = fopen( "./supp_status.txt", "r" ); if ( pf ) { while( !feof( pf ) ){ memset(p->parse, 0x00, CMD_SZ); fgets(p->parse, CMD_SZ, pf); if(strncmp(p->parse, "OK", 2) == 0) { ret = 1; p->wpsing = 1; } } fclose( pf ); } if( ret == 0 ) usleep( HOSTAPD_INIT_TIME ); } while( ret == 0 ); } usleep( HOSTAPD_INTERVAL ); while( count < WPS_RETRY ) //query status { memset( p->cmd, 0x00, CMD_SZ ); sprintf( p->cmd, "%s all_sta > supp_status.txt", p->apcli_path); system( p->cmd ); pf = fopen( "./supp_status.txt", "r" ); if ( pf ) { for(i=0;i<17;i++) { if( p->ap_open != 1 ) addr_lower[i] = lower(p->peer_ifaddr[i]); else addr_lower[i] = lower(p->peer_devaddr[i]); } addr_lower[17]='\0'; while( !feof( pf ) ){ memset( p->parse, 0x00, CMD_SZ ); fgets( p->parse, CMD_SZ, pf ); if( strncmp( p->parse, "dot11RSNAStatsSTAAddress=", 25) == 0 ) { if( strncmp( p->parse+25, addr_lower, 17) == 0 ) { count = WPS_RETRY; p->wpsing = 0; p->p2p_get=1; memset(p->print_line, 0x00, CMD_SZ); for(i=0; i<CMD_SZ; i++){ if(p->parse[i] == '\n'){ p->parse[i] = ' '; } } sprintf(p->print_line, "%s", p->parse); ui_screen(p); #ifdef DHCP memset( p->cmd, 0x00, CMD_SZ ); sprintf( p->cmd, "ifconfig %s 192.168.1.254", p->ifname); system( p->cmd ); usleep(50000); system( "/etc/rc.d/init.d/dhcpd start" ); system( "clear" ); #endif //DHCP //After starting hostapd and doing WPS connection successful, //We create a thread to query driver if some other p2p devices connected. p2p_status(p, 0); usleep(50000); #ifdef P2P_AUTO p->res_go = pthread_create(&p->pthread_go, NULL, &polling_client, (void *)p); if( p->res_go != 0 ) { p->p2p_get=1; memset( p->print_line, 0x00, CMD_SZ ); sprintf( p->print_line, "Thread creation failed" ); } #endif break; } } } fclose( pf ); } if( count == WPS_RETRY) break; count++; usleep( HOSTAPD_INTERVAL ); p->p2p_get=1; memset( p->print_line, 0x00, CMD_SZ ); sprintf( p->print_line, "hostapd open, count:%d", count); ui_screen(p); } if(p->ap_open != 1) p->ap_open = 1; }
BOOST_AUTO_TEST_CASE_TEMPLATE ( test_mapping_upper_bound, Tp, quad_maps ) { { // find the smallest element that is greater than key Tp fix(100, randomize(-2, 2)); quad lower (-3, -3, -3, -3); quad in (-1, -1, -1, -1); quad upper (1, 1, 1, 1); for (dimension_type mapping_dim = 0; mapping_dim < 4; ++mapping_dim) { mapping_iterator<typename Tp::container_type> iter (mapping_upper_bound(fix.container, mapping_dim, in)); BOOST_CHECK(iter == mapping_end(fix.container, mapping_dim) || quad_less()(mapping_dim, in, iter->first)); BOOST_CHECK(iter == mapping_begin(fix.container, mapping_dim) || !quad_less()(mapping_dim, (--iter)->first, in)); iter = mapping_upper_bound(fix.container, mapping_dim, lower); BOOST_CHECK(iter == mapping_begin(fix.container, mapping_dim)); iter = mapping_upper_bound(fix.container, mapping_dim, upper); BOOST_CHECK(iter == mapping_end(fix.container, mapping_dim)); } } { // same test with a tree filled with similar values Tp fix(100, same()); quad lower (99, 99, 99, 99); quad in (100, 100, 100, 100); quad upper (101, 101, 101, 101); for (dimension_type mapping_dim = 0; mapping_dim < 4; ++mapping_dim) { mapping_iterator<typename Tp::container_type> iter (mapping_upper_bound(fix.container, mapping_dim, lower)); BOOST_CHECK(iter == mapping_begin(fix.container, mapping_dim)); iter = mapping_upper_bound(fix.container, mapping_dim, in); BOOST_CHECK(iter == mapping_end(fix.container, mapping_dim)); iter = mapping_upper_bound(fix.container, mapping_dim, upper); BOOST_CHECK(iter == mapping_end(fix.container, mapping_dim)); } } { // test at the limit: tree with 1 value Tp fix(1, same()); quad lower (0, 0, 0, 0); quad in (1, 1, 1, 1); quad upper (2, 2, 2, 2); for (dimension_type mapping_dim = 0; mapping_dim < 4; ++mapping_dim) { mapping_iterator<const typename Tp::container_type> iter (mapping_cupper_bound(fix.container, mapping_dim, lower)); BOOST_CHECK(iter == mapping_cbegin(fix.container, mapping_dim)); iter = mapping_cupper_bound(fix.container, mapping_dim, in); BOOST_CHECK(iter == mapping_cend(fix.container, mapping_dim)); iter = mapping_cupper_bound(fix.container, mapping_dim, upper); BOOST_CHECK(iter == mapping_cend(fix.container, mapping_dim)); } } { // test at the limit: tree filled with decreasing values Tp fix(100, decrease()); // first (100, 100, 100, 100), last (1, 1, 1, 1) quad lower(0, 0, 0, 0); quad in (99, 99, 99, 99); quad upper(100, 100, 100, 100); for (dimension_type mapping_dim = 0; mapping_dim < 4; ++mapping_dim) { mapping_iterator<typename Tp::container_type> iter (mapping_upper_bound(fix.container, mapping_dim, lower)); BOOST_CHECK(iter == mapping_begin(fix.container, mapping_dim)); iter = mapping_upper_bound(fix.container, mapping_dim, in); BOOST_CHECK(iter != mapping_end(fix.container, mapping_dim) && ++iter == mapping_end(fix.container, mapping_dim)); iter = mapping_upper_bound(fix.container, mapping_dim, upper); BOOST_CHECK(iter == mapping_end(fix.container, mapping_dim)); } } { // test at the limit: tree filled with increasing values Tp fix(100, increase()); // first (0, 0, 0, 0), last (99, 99, 99, 99) quad lower(-1, -1, -1, -1); quad in(98, 98, 98, 98); quad upper (99, 99, 99, 99); for (dimension_type mapping_dim = 0; mapping_dim < 4; ++mapping_dim) { mapping_iterator<typename Tp::container_type> iter (mapping_upper_bound(fix.container, mapping_dim, lower)); BOOST_CHECK(iter == mapping_begin(fix.container, mapping_dim)); iter = mapping_upper_bound(fix.container, mapping_dim, in); BOOST_CHECK(iter != mapping_end(fix.container, mapping_dim) && ++iter == mapping_end(fix.container, mapping_dim)); iter = mapping_upper_bound(fix.container, mapping_dim, upper); BOOST_CHECK(iter == mapping_end(fix.container, mapping_dim)); } } }
void IconCanvas::menu(const QPoint&) { Q3PopupMenu m(0); m.insertItem(new MenuTitle(browser_node->get_name() + TR("\nshort cut"), m.font()), -1); m.insertSeparator(); m.insertItem(TR("Upper"), 0); m.insertItem(TR("Lower"), 1); m.insertItem(TR("Go up"), 6); m.insertItem(TR("Go down"), 7); m.insertSeparator(); if (! browser_node->deletedp()) { m.insertItem(TR("Open"), 2); m.insertSeparator(); } m.insertItem(TR("Select diagram in browser"), 3); m.insertItem(TR("Select linked items"), 4); m.insertSeparator(); m.insertItem(TR("Remove from diagram"),5); switch (m.exec(QCursor::pos())) { case 0: upper(); // force son reaffichage hide(); show(); canvas()->update(); break; case 1: lower(); // force son reaffichage hide(); show(); canvas()->update(); break; case 6: z_up(); // force son reaffichage hide(); show(); canvas()->update(); break; case 7: z_down(); // force son reaffichage hide(); show(); canvas()->update(); break; case 2: browser_node->open(FALSE); return; case 3: browser_node->select_in_browser(); return; case 4: the_canvas()->unselect_all(); select_associated(); return; case 5: // delete delete_it(); break; default: return; } package_modified(); }
void b2VoronoiDiagram::Generate(float32 radius, float32 margin) { b2Assert(m_diagram == NULL); float32 inverseRadius = 1 / radius; b2Vec2 lower(+b2_maxFloat, +b2_maxFloat); b2Vec2 upper(-b2_maxFloat, -b2_maxFloat); for (int32 k = 0; k < m_generatorCount; k++) { Generator& g = m_generatorBuffer[k]; if (g.necessary) { lower = b2Min(lower, g.center); upper = b2Max(upper, g.center); } } lower.x -= margin; lower.y -= margin; upper.x += margin; upper.y += margin; m_countX = 1 + (int32) (inverseRadius * (upper.x - lower.x)); m_countY = 1 + (int32) (inverseRadius * (upper.y - lower.y)); m_diagram = (Generator**) m_allocator->Allocate(sizeof(Generator*) * m_countX * m_countY); for (int32 i = 0; i < m_countX * m_countY; i++) { m_diagram[i] = NULL; } // (4 * m_countX * m_countY) is the queue capacity that is experimentally // known to be necessary and sufficient for general particle distributions. b2StackQueue<b2VoronoiDiagramTask> queue( m_allocator, 4 * m_countX * m_countY); for (int32 k = 0; k < m_generatorCount; k++) { Generator& g = m_generatorBuffer[k]; g.center = inverseRadius * (g.center - lower); int32 x = (int32) g.center.x; int32 y = (int32) g.center.y; if (x >=0 && y >= 0 && x < m_countX && y < m_countY) { queue.Push(b2VoronoiDiagramTask(x, y, x + y * m_countX, &g)); } } while (!queue.Empty()) { int32 x = queue.Front().m_x; int32 y = queue.Front().m_y; int32 i = queue.Front().m_i; Generator* g = queue.Front().m_generator; queue.Pop(); if (!m_diagram[i]) { m_diagram[i] = g; if (x > 0) { queue.Push(b2VoronoiDiagramTask(x - 1, y, i - 1, g)); } if (y > 0) { queue.Push(b2VoronoiDiagramTask(x, y - 1, i - m_countX, g)); } if (x < m_countX - 1) { queue.Push(b2VoronoiDiagramTask(x + 1, y, i + 1, g)); } if (y < m_countY - 1) { queue.Push(b2VoronoiDiagramTask(x, y + 1, i + m_countX, g)); } } } for (int32 y = 0; y < m_countY; y++) { for (int32 x = 0; x < m_countX - 1; x++) { int32 i = x + y * m_countX; Generator* a = m_diagram[i]; Generator* b = m_diagram[i + 1]; if (a != b) { queue.Push(b2VoronoiDiagramTask(x, y, i, b)); queue.Push(b2VoronoiDiagramTask(x + 1, y, i + 1, a)); } } } for (int32 y = 0; y < m_countY - 1; y++) { for (int32 x = 0; x < m_countX; x++) { int32 i = x + y * m_countX; Generator* a = m_diagram[i]; Generator* b = m_diagram[i + m_countX]; if (a != b) { queue.Push(b2VoronoiDiagramTask(x, y, i, b)); queue.Push(b2VoronoiDiagramTask(x, y + 1, i + m_countX, a)); } } } while (!queue.Empty()) { const b2VoronoiDiagramTask& task = queue.Front(); int32 x = task.m_x; int32 y = task.m_y; int32 i = task.m_i; Generator* k = task.m_generator; queue.Pop(); Generator* a = m_diagram[i]; Generator* b = k; if (a != b) { float32 ax = a->center.x - x; float32 ay = a->center.y - y; float32 bx = b->center.x - x; float32 by = b->center.y - y; float32 a2 = ax * ax + ay * ay; float32 b2 = bx * bx + by * by; if (a2 > b2) { m_diagram[i] = b; if (x > 0) { queue.Push(b2VoronoiDiagramTask(x - 1, y, i - 1, b)); } if (y > 0) { queue.Push(b2VoronoiDiagramTask(x, y - 1, i - m_countX, b)); } if (x < m_countX - 1) { queue.Push(b2VoronoiDiagramTask(x + 1, y, i + 1, b)); } if (y < m_countY - 1) { queue.Push(b2VoronoiDiagramTask(x, y + 1, i + m_countX, b)); } } } } }
/* * Prompts the user for a move with getinput, sanitizes it, and makes * the move. It stores the move in *move, you can specify the maximum * length l of the move to take, this should be at most the length of * move. If mill is less than three or more than five, move should * hold at least 5 characters. Returns pointer to the move. */ char * getmove(scrgame *sg, char *move, int l) { int length, pieces, index, twmm = 0; /* Do we only have 3 pieces, i.e. are we in skipping mode? */ pieces = sg->game->pieces[(int) sg->game->state]; if (l < 3 || 5 < l) { if (sg->game->type == TWMM) { /* We need to add one to our length to make up for the * possibility of ne/nw/se/sw over n/e/s/w */ twmm = 1; } switch (sg->game->phase) { case 1: /* In piece placing mode */ length = 3; break; case 2: /* Of form d3s or d3sw */ length = 4 + twmm; break; case 3: if (pieces == 3) { /* Of form d3a1 */ length = 5; } else { /* Of form d3s or d3sw */ length = 4 + twmm; } break; default: length = 0; /* NOTREACHED */ } } else { length = l; } move = getinput(sg, move, length); move = lower(move); if (!validcoords(sg->game, move) || /* Check the length to make sure we're not in mill mode */ (pieces == 3 && length != 3 && !validcoords(sg->game, &move[2]))) { update_msgbox(sg->msg_w, "Invalid coordinates"); return getmove(sg, move, length); } /* If we'e in piece sliding stage. The length check makes sure we're not in mill mode. */ if (sg->game->phase != 1 && pieces != 3 && length != 3) { index = dirtoindex(&move[2]); if (index == -1) { update_msgbox(sg->msg_w, "Invalid direction"); return getmove(sg, move, length); } else if (!(getpoint(sg->game, /* We already checked that move[2] is safe */ move)->n[index])) { update_msgbox(sg->msg_w, "Impossible to move in that direction"); return getmove(sg, move, length); } } move[length - 1] = '\0'; return move; }
IFloat cospi (const IFloat &ifloat) { if (ifloat.isempty) return ifloat; IFloat range = fmod(ifloat, 2); if (width(range) >= 2) return IFloat(-1, 1); bool up; bool set = false; if (ifloat.contains_zero()) { set = true; up = true; } if (range.contains(1) != false) { if (set) return IFloat(-1, 1); set = true; up = false; } if (range.contains(2) != false) { if (set) return IFloat(-1, 1); set = true; up = true; } /* This can be more precise */ if (range.contains(3) != false) return IFloat(-1, 1); UnprotectRounding upr; if (!set) { if (upper(range) < lower(1)) return IFloat(cospi_rd(upper(range)), cospi_ru(lower(range))); if (upper(range) < lower(2)) return IFloat(cospi_rd(lower(range)), cospi_ru(upper(range))); return IFloat(cospi_rd(upper(range)), cospi_ru(lower(range))); } /* Probably this part can be more fast, whit only a cosine */ if (up) return IFloat(std::min(cospi_rd(lower(range)), cospi_rd(upper(range))), 1); return IFloat(-1, std::max(cospi_ru(lower(range)), cospi_ru(upper(range)))); }
void LocalImageLoaderPrivate::prepareImages() { QString file, filename, mime; int32 filesize = 0; QImage img; QByteArray data; PeerId peer; uint64 id, jpeg_id = 0; ToPrepareMediaType type; { QMutexLocker lock(loader->toPrepareMutex()); ToPrepareMedias &list(loader->toPrepareMedias()); if (list.isEmpty()) return; file = list.front().file; img = list.front().img; data = list.front().data; peer = list.front().peer; id = list.front().id; type = list.front().type; } if (img.isNull()) { if (!file.isEmpty()) { QFileInfo info(file); if (type == ToPrepareAuto) { QString lower(file.toLower()); const QStringList &photoExtensions(cPhotoExtensions()); for (QStringList::const_iterator i = photoExtensions.cbegin(), e = photoExtensions.cend(); i != e; ++i) { if (lower.lastIndexOf(*i) == lower.size() - i->size()) { if (info.size() < MaxUploadPhotoSize) { type = ToPreparePhoto; break; } } } if (type == ToPrepareAuto && info.size() < MaxUploadDocumentSize) { type = ToPrepareDocument; } } if (type != ToPrepareAuto && info.size() < MaxUploadPhotoSize) { img = App::readImage(file); } if (type == ToPrepareDocument) { mime = QMimeDatabase().mimeTypeForFile(info).name(); } filename = info.fileName(); filesize = info.size(); } else if (!data.isEmpty()) { img = App::readImage(data); if (type == ToPrepareAuto) { if (!img.isNull() && data.size() < MaxUploadPhotoSize) { type = ToPreparePhoto; } else if (data.size() < MaxUploadDocumentSize) { type = ToPrepareDocument; } else { img = QImage(); } } QMimeType mimeType = QMimeDatabase().mimeTypeForData(data); if (type == ToPrepareDocument) { mime = mimeType.name(); } filename = qsl("Document"); QStringList patterns = mimeType.globPatterns(); if (!patterns.isEmpty()) { filename = patterns.front().replace('*', filename); } filesize = data.size(); } } else { if (type == ToPrepareDocument) { filename = filedialogDefaultName(qsl("image"), qsl(".png"), QString(), true); QMimeType mimeType = QMimeDatabase().mimeTypeForName("image/png"); data = QByteArray(); { QBuffer b(&data); img.save(&b, "PNG"); } filesize = data.size(); } else { type = ToPreparePhoto; // only photo from QImage filename = qsl("Untitled.jpg"); filesize = 0; } } if ((img.isNull() && (type != ToPrepareDocument || !filesize)) || type == ToPrepareAuto || (img.isNull() && file.isEmpty() && data.isEmpty())) { // if could not decide what type { QMutexLocker lock(loader->toPrepareMutex()); ToPrepareMedias &list(loader->toPrepareMedias()); list.pop_front(); } QTimer::singleShot(1, this, SLOT(prepareImages())); emit imageFailed(id); } else { PreparedPhotoThumbs photoThumbs; QVector<MTPPhotoSize> photoSizes; MTPPhotoSize thumb(MTP_photoSizeEmpty(MTP_string(""))); MTPPhoto photo(MTP_photoEmpty(MTP_long(0))); MTPDocument document(MTP_documentEmpty(MTP_long(0))); QByteArray jpeg; if (type == ToPreparePhoto) { int32 w = img.width(), h = img.height(); QPixmap thumb = (w > 100 || h > 100) ? QPixmap::fromImage(img.scaled(100, 100, Qt::KeepAspectRatio, Qt::SmoothTransformation)) : QPixmap::fromImage(img); photoThumbs.insert('s', thumb); photoSizes.push_back(MTP_photoSize(MTP_string("s"), MTP_fileLocationUnavailable(MTP_long(0), MTP_int(0), MTP_long(0)), MTP_int(thumb.width()), MTP_int(thumb.height()), MTP_int(0))); QPixmap medium = (w > 320 || h > 320) ? QPixmap::fromImage(img.scaled(320, 320, Qt::KeepAspectRatio, Qt::SmoothTransformation)) : QPixmap::fromImage(img); photoThumbs.insert('m', medium); photoSizes.push_back(MTP_photoSize(MTP_string("m"), MTP_fileLocationUnavailable(MTP_long(0), MTP_int(0), MTP_long(0)), MTP_int(medium.width()), MTP_int(medium.height()), MTP_int(0))); QPixmap full = (w > 800 || h > 800) ? QPixmap::fromImage(img.scaled(800, 800, Qt::KeepAspectRatio, Qt::SmoothTransformation)) : QPixmap::fromImage(img); photoThumbs.insert('x', full); photoSizes.push_back(MTP_photoSize(MTP_string("x"), MTP_fileLocationUnavailable(MTP_long(0), MTP_int(0), MTP_long(0)), MTP_int(full.width()), MTP_int(full.height()), MTP_int(0))); { QBuffer jpegBuffer(&jpeg); full.save(&jpegBuffer, "JPG", 87); } if (!filesize) filesize = jpeg.size(); photo = MTP_photo(MTP_long(id), MTP_long(0), MTP_int(user), MTP_int(unixtime()), MTP_string(""), MTP_geoPointEmpty(), MTP_vector<MTPPhotoSize>(photoSizes)); jpeg_id = id; } else if ((type == ToPrepareVideo || type == ToPrepareDocument) && !img.isNull()) { int32 w = img.width(), h = img.height(); QPixmap full = (w > 90 || h > 90) ? QPixmap::fromImage(img.scaled(90, 90, Qt::KeepAspectRatio, Qt::SmoothTransformation)) : QPixmap::fromImage(img); { QBuffer jpegBuffer(&jpeg); full.save(&jpegBuffer, "JPG", 87); } photoThumbs.insert('0', full); thumb = MTP_photoSize(MTP_string(""), MTP_fileLocationUnavailable(MTP_long(0), MTP_int(0), MTP_long(0)), MTP_int(full.width()), MTP_int(full.height()), MTP_int(0)); jpeg_id = MTP::nonce<uint64>(); } if (type == ToPrepareDocument) { document = MTP_document(MTP_long(id), MTP_long(0), MTP_int(MTP::authedId()), MTP_int(unixtime()), MTP_string(filename), MTP_string(mime), MTP_int(filesize), thumb, MTP_int(MTP::maindc())); } { QMutexLocker lock(loader->readyMutex()); loader->readyList().push_back(ReadyLocalMedia(type, file, filename, filesize, data, id, jpeg_id, peer, photo, photoThumbs, document, jpeg)); } { QMutexLocker lock(loader->toPrepareMutex()); ToPrepareMedias &list(loader->toPrepareMedias()); list.pop_front(); } QTimer::singleShot(1, this, SLOT(prepareImages())); emit imageReady(); } }
double new_lower(MC *expr) { double ans = lower(expr); return ans; }
void TestSolvePdeAndWriteResultsToFileCoarsePdeMeshNeumann() throw(Exception) { EXIT_IF_PARALLEL; // Set up SimulationTime SimulationTime::Instance()->SetEndTimeAndNumberOfTimeSteps(0.05, 6); // Create a cigar-shaped mesh TrianglesMeshReader<2,2> mesh_reader("mesh/test/data/disk_522_elements"); MutableMesh<2,2> mesh; mesh.ConstructFromMeshReader(mesh_reader); mesh.Scale(5.0, 1.0); // Create a cell population std::vector<CellPtr> cells; CellsGenerator<FixedDurationGenerationBasedCellCycleModel, 2> cells_generator; cells_generator.GenerateBasic(cells, mesh.GetNumNodes()); MeshBasedCellPopulation<2> cell_population(mesh, cells); // Create a PDE handler object using this cell population CellBasedPdeHandler<2> pde_handler(&cell_population); // Set up PDE and pass to handler AveragedSourcePde<2> pde(cell_population, -0.01); ConstBoundaryCondition<2> bc(0.0); PdeAndBoundaryConditions<2> pde_and_bc(&pde, &bc, true); // Last boolean specifies Neuman conditions pde_and_bc.SetDependentVariableName("variable"); pde_handler.AddPdeAndBc(&pde_and_bc); // Solve PDEs on a coarse mesh ChastePoint<2> lower(0.0, 0.0); ChastePoint<2> upper(50.0, 50.0); ChasteCuboid<2> cuboid(lower, upper); pde_handler.UseCoarsePdeMesh(10.0, cuboid, true); pde_handler.SetImposeBcsOnCoarseBoundary(false); // For coverage, provide an initial guess for the solution std::vector<double> data(pde_handler.mpCoarsePdeMesh->GetNumNodes()); for (unsigned i=0; i<pde_handler.mpCoarsePdeMesh->GetNumNodes(); i++) { data[i] = 1.0; } Vec vector = PetscTools::CreateVec(data); pde_and_bc.SetSolution(vector); // Open result file ourselves OutputFileHandler output_file_handler("TestWritePdeSolution", false); pde_handler.mpVizPdeSolutionResultsFile = output_file_handler.OpenOutputFile("results.vizpdesolution"); // Solve PDE (set sampling timestep multiple to be large doesn't do anything as always output on 1st timestep) pde_handler.SolvePdeAndWriteResultsToFile(10); // Close result file ourselves pde_handler.mpVizPdeSolutionResultsFile->close(); // Test that boundary cells experience the right boundary condition for (AbstractCellPopulation<2>::Iterator cell_iter = cell_population.Begin(); cell_iter != cell_population.End(); ++cell_iter) { if (cell_population.GetNodeCorrespondingToCell(*cell_iter)->IsBoundaryNode()) { TS_ASSERT_DELTA(cell_iter->GetCellData()->GetItem("variable"), 0.0, 1e-1); } } }
void TestWritingToFile() throw(Exception) { EXIT_IF_PARALLEL; std::string output_directory = "TestCellBasedPdeHandlerWritingToFile"; // Create a cell population HoneycombMeshGenerator generator(4, 4, 0); MutableMesh<2,2>* p_generating_mesh = generator.GetMesh(); NodesOnlyMesh<2> mesh; mesh.ConstructNodesWithoutMesh(*p_generating_mesh, 1.5); std::vector<CellPtr> cells; CellsGenerator<FixedDurationGenerationBasedCellCycleModel, 2> cells_generator; cells_generator.GenerateBasic(cells, mesh.GetNumNodes()); TS_ASSERT_EQUALS(cells.size(), mesh.GetNumNodes()); NodeBasedCellPopulation<2> cell_population(mesh, cells); cell_population.SetDataOnAllCells("variable", 1.0); // Create a PDE handler object using this cell population CellBasedPdeHandler<2> pde_handler(&cell_population); TS_ASSERT_THROWS_THIS(pde_handler.OpenResultsFiles(output_directory), "Trying to solve a PDE on a cell population that doesn't have a mesh. Try calling UseCoarsePdeMesh()."); // Use a coarse PDE mesh since we are using a node-based cell population AveragedSourcePde<2> pde(cell_population, -0.1); ConstBoundaryCondition<2> bc(1.0); PdeAndBoundaryConditions<2> pde_and_bc(&pde, &bc, false); pde_and_bc.SetDependentVariableName("variable"); pde_handler.AddPdeAndBc(&pde_and_bc); ChastePoint<2> lower(0.0, 0.0); ChastePoint<2> upper(9.0, 9.0); ChasteCuboid<2> cuboid(lower, upper); pde_handler.UseCoarsePdeMesh(3.0, cuboid, true); // For coverage, call SetWriteAverageRadialPdeSolution() prior to output pde_handler.SetWriteAverageRadialPdeSolution("variable", 5, true); // Test that output files are opened correctly pde_handler.OpenResultsFiles(output_directory); FileFinder file_finder(output_directory + "/results.vizcoarsepdesolution", RelativeTo::ChasteTestOutput); TS_ASSERT(file_finder.Exists()); TS_ASSERT(file_finder.IsFile()); FileFinder file_finder2(output_directory + "/radial_dist.dat", RelativeTo::ChasteTestOutput); TS_ASSERT(file_finder2.Exists()); TS_ASSERT(file_finder2.IsFile()); TS_ASSERT_THROWS_NOTHING(pde_handler.CloseResultsFiles()); // For coverage, also test that output files are opened correctly when not using a coarse PDE mesh HoneycombMeshGenerator generator2(5, 5, 0); MutableMesh<2,2>* p_mesh2 = generator2.GetMesh(); std::vector<CellPtr> cells2; CellsGenerator<FixedDurationGenerationBasedCellCycleModel, 2> cells_generator2; cells_generator2.GenerateBasic(cells2, p_mesh2->GetNumNodes()); MeshBasedCellPopulation<2> cell_population2(*p_mesh2, cells2); cell_population2.SetDataOnAllCells("another variable", 1.0); CellBasedPdeHandler<2> pde_handler2(&cell_population2); pde_handler2.OpenResultsFiles(output_directory); FileFinder file_finder3(output_directory + "/results.vizpdesolution", RelativeTo::ChasteTestOutput); TS_ASSERT(file_finder3.Exists()); TS_ASSERT(file_finder3.IsFile()); pde_handler2.CloseResultsFiles(); }
vector<int> searchRange(vector<int> &A, int target) { return {lower(A, target), upper(A, target)}; }
void Manager::createTitle() { leftButtonList_.clear(); rightButtonList_.clear(); TQString buttons; if (options()->customButtonPositions()) buttons = options()->titleButtonsLeft() + "|" + options()->titleButtonsRight(); else buttons = "XSH|IA"; TQPtrList<Button> *buttonList = &leftButtonList_; for (unsigned int i = 0; i < buttons.length(); ++i) { Button * tb = NULL; switch (buttons[i].latin1()) { case 'S': // Sticky tb = new StickyButton(widget()); connect(this, TQT_SIGNAL(stickyChanged(bool)), tb, TQT_SLOT(setOn(bool))); connect(tb, TQT_SIGNAL(toggleSticky()), this, TQT_SLOT(slotToggleSticky())); emit(stickyChanged(isOnAllDesktops())); break; case 'H': // Help if (providesContextHelp()) { tb = new HelpButton(widget()); connect(tb, TQT_SIGNAL(help()), this, TQT_SLOT(showContextHelp())); } break; case 'I': // Minimize if (isMinimizable()) { tb = new IconifyButton(widget()); connect(tb, TQT_SIGNAL(iconify()), this, TQT_SLOT(minimize())); } break; case 'A': // Maximize if (isMaximizable()) { tb = new MaximiseButton(widget()); connect(tb, TQT_SIGNAL(maximizeClicked(ButtonState)), this, TQT_SLOT(slotMaximizeClicked(ButtonState))); connect(this, TQT_SIGNAL(maximizeChanged(bool)), tb, TQT_SLOT(setOn(bool))); emit(maximizeChanged(maximizeMode() == MaximizeFull)); } break; case 'F': // Above tb = new AboveButton(widget()); connect(tb, TQT_SIGNAL(above()), this, TQT_SLOT(slotAbove())); break; case 'B': // Lower tb = new LowerButton(widget()); connect(tb, TQT_SIGNAL(lower()), this, TQT_SLOT(slotLower())); break; case 'X': // Close if (isCloseable()) { tb = new CloseButton(widget()); connect(tb, TQT_SIGNAL(closeWindow()), this, TQT_SLOT(closeWindow())); } break; case '|': buttonList = &rightButtonList_; break; } if (tb != NULL) { connect(this, TQT_SIGNAL(activeChanged(bool)), tb, TQT_SLOT(setActive(bool))); buttonList->append(tb); } }
void call21h() { /* * 对21h 中的功能号进行测试 */ while(1) { cls(); print("\r\n Now, you can run some commands to test the 21h:\n\n\r"); print(" 1.ouch -- to ouch 2.upper -- change the letter to upper\n\r"); print(" 3.lower -- change the letter to lower\n\r"); print(" 4.to_digit -- change the string to digit\r\n"); print(" 5.to_string -- change the digit to string\r\n"); print(" 6.display_where -- you can assign where to display\r\n"); print(" 7.to_deci -- change the Hex to a decimal digit\r\n"); print(" 8.reverse -- to reverse your string\r\n"); print(" 9.strlen -- get the length of your string\r\n"); print(" 10.quit -- just to quit\r\n\r\n"); print("Please input your choice:"); getline(input,20); if(strcmp(input,"1") || strcmp(input,"ouch")) { /* * 测试 0 号功能 */ to_OUCH(); } else if(strcmp(input,"2") || strcmp(input,"upper")) { /* * 测试 1 号功能 */ while(1) { print("\r\nPlease input a sentence or quit to back:"); getline(input,30); if(strcmp(input,"quit")) break; upper(input); print("\r\nThe upper case is:"); print(input); print("\r\n"); } } else if(strcmp(input,"3") || strcmp(input,"lower")) { /* * 测试 2 号功能 */ while(1) { print("\r\nPlease input a sentence or quit to back:"); getline(input,30); if(strcmp(input,"quit")) break; lower(input); print("\r\nThe lower case is:"); print(input); print("\r\n"); } } else if(strcmp(input,"4") || strcmp(input,"to_digit")) { /* * 测试 3 号功能 */ print("\r\nDo you want to continue? Y | N :"); getline(input,2); while(1) { int t1,t2,t3; t1 = 0;t2 = 0; if(strcmp(input,"n") || strcmp(input,"N")) break; print("\r\nPlease input the first digit:"); getline(input,4); if(isDigit(input)) { t1 = digital(input); } else { print("\r\nInvalid digit!We assume it is 12\n\r"); t1 = 12; } print("\r\nPlease input the second digit:"); getline(input,4); if(isDigit(input)) { t2 = digital(input); } else { print("\r\nInvalid digit!We assume it is 21\n\r"); t2 = 21; } print("\r\nThe sum of the them is:"); t3 = t1 + t2; printInt(t3); print("\r\n"); print("\r\nDo you want to continue? Y | N :"); getline(input,2); } } else if(strcmp(input,"5") || strcmp(input,"to_string")) { /* * 测试 4 号功能 */ print("\r\nDo you want to continue? Y | N: "); getline(input,2); while(1) { char *cht; int tt = rand(); if(strcmp(input,"n") || strcmp(input,"N")) break; cht = convertToString(tt); print("\r\nI am a string: "); print(cht); print("\r\n"); print("\r\nDo you want to continue? Y | N: "); getline(input,2); } } else if(strcmp(input,"6") || strcmp(input,"display_where")) { /* * 测试 5 号功能 */ int row,col; print("\r\nPlease input the row:"); getline(input,3); if(isDigit(input)) { row = digital(input); } else { print("\r\nInvalid digit!We assume it is 12\n\r"); row = 12; } print("\r\nPlease input column:"); getline(input,3); if(isDigit(input)) { col = digital(input); } else { print("\r\nInvalid digit!We assume it is 40\n\r"); col = 40; } print("\r\nPlease input the string:"); getline(input,30); display(row,col,input); } else if(strcmp(input,"7") || strcmp(input,"to_dec")) { /* * 测试 6 号功能 */ print("\r\nDo you want to continue? Y | N :"); getline(input,2); while(1) { int t1; t1 = 0; if(strcmp(input,"n") || strcmp(input,"N")) break; print("\r\nPlease input the hex digit:"); getline(input,3); if(isHex(input)) { t1 = convertHexToDec(input); } else { print("\r\nInvalid Hex!We assume it is 12\n\r"); t1 = 12; } print("\r\nThe decimal form is:"); printInt(t1); print("\r\n"); print("\r\nDo you want to continue? Y | N :"); getline(input,2); } } else if(strcmp(input,"8") || strcmp(input,"reverse")) { /* * 测试 7 号功能 */ print("\r\nDo you want to continue? Y | N :"); getline(input,2); while(1) { if(strcmp(input,"n") || strcmp(input,"N")) break; print("\r\nPlease input the your string:"); getline(input,30); reverse(input,strlen(input)); print("\r\nThe string after reverse is:"); print(input); print("\r\n"); print("\r\nDo you want to continue? Y | N :"); getline(input,2); } } else if(strcmp(input,"9") || strcmp(input,"strlen")) { /* * 测试 8 号功能 */ print("\r\nDo you want to continue? Y | N :"); getline(input,2); while(1) { int t; if(strcmp(input,"n") || strcmp(input,"N")) break; print("\r\nPlease input the your string:"); getline(input,30); t = strlen(input); print("\r\nThe length of the string is:"); printInt(t); print("\r\n"); print("\r\nDo you want to continue? Y | N :"); getline(input,2); } } else if(strcmp(input,"10") || strcmp(input,"quit")) { /* * 退出 */ break; } } }
void Foam::BlockLduMatrix<Type>::segregateB ( TypeField& sMul, const TypeField& x ) const { typedef typename TypeCoeffField::linearType linearType; typedef typename TypeCoeffField::squareType squareType; typedef typename TypeCoeffField::linearTypeField linearTypeField; typedef typename TypeCoeffField::squareTypeField squareTypeField; const unallocLabelList& u = lduAddr().upperAddr(); const unallocLabelList& l = lduAddr().lowerAddr(); // Diagonal multiplication if (thereIsDiag()) { if (diag().activeType() == blockCoeffBase::SQUARE) { const squareTypeField& activeDiag = this->diag().asSquare(); linearTypeField lf(activeDiag.size()); squareTypeField sf(activeDiag.size()); // Expand and contract contractLinear(lf, activeDiag); expandLinear(sf, lf); sMul -= (activeDiag - sf) & x; } } // Lower multiplication if (thereIsLower()) { if (lower().activeType() == blockCoeffBase::SQUARE) { const squareTypeField& activeLower = this->lower().asSquare(); // Auxiliary variables used in expand/contract linearType lt; squareType st; for (register label coeffI = 0; coeffI < u.size(); coeffI++) { contractLinear(lt, activeLower[coeffI]); expandLinear(st, lt); sMul[u[coeffI]] -= (activeLower[coeffI] - st) & x[l[coeffI]]; } } } // Upper multiplication if (thereIsUpper()) { if (upper().activeType() == blockCoeffBase::SQUARE) { const squareTypeField& activeUpper = this->upper().asSquare(); // Auxiliary variables used in expand/contract linearType lt; squareType st; for (register label coeffI = 0; coeffI < u.size(); coeffI++) { contractLinear(lt, activeUpper[coeffI]); expandLinear(st, lt); sMul[l[coeffI]] -= (activeUpper[coeffI] - st) & x[u[coeffI]]; } // If the matrix is symmetric, the lower triangular product // is also needed if (symmetric()) { for (register label coeffI = 0; coeffI < u.size(); coeffI++) { // Use transpose upper coefficient contractLinear(lt, activeUpper[coeffI]); expandLinear(st, lt); sMul[u[coeffI]] -= (activeUpper[coeffI].T() - st) & x[l[coeffI]]; } } } } }
RasterRenderPrivate::Widget::Widget(RasterRenderPrivate *render) : QWidget(lApp->mainWidget()), render(render) { setAttribute(Qt::WA_TransparentForMouseEvents); lower(); }
void KexiSimplePrintPreviewWindow::slotPageSetup() { lower(); emit pageSetupRequested(); }
void LocalImageLoaderPrivate::prepareImages() { QString file, filename, mime, stickerMime = qsl("image/webp"); int32 filesize = 0; QImage img; QByteArray data; PeerId peer; uint64 id, thumbId = 0; int32 duration = 0; QString thumbExt = "jpg"; ToPrepareMediaType type; bool animated = false; bool ctrlShiftEnter = false; MsgId replyTo = 0; { QMutexLocker lock(loader->toPrepareMutex()); ToPrepareMedias &list(loader->toPrepareMedias()); if (list.isEmpty()) return; file = list.front().file; img = list.front().img; data = list.front().data; peer = list.front().peer; id = list.front().id; type = list.front().type; duration = list.front().duration; ctrlShiftEnter = list.front().ctrlShiftEnter; replyTo = list.front().replyTo; } if (img.isNull()) { if (!file.isEmpty()) { QFileInfo info(file); if (type == ToPrepareAuto) { QString lower(file.toLower()); const QStringList &photoExtensions(cPhotoExtensions()); for (QStringList::const_iterator i = photoExtensions.cbegin(), e = photoExtensions.cend(); i != e; ++i) { if (lower.lastIndexOf(*i) == lower.size() - i->size()) { if (info.size() < MaxUploadPhotoSize) { type = ToPreparePhoto; break; } } } if (type == ToPrepareAuto && info.size() < MaxUploadDocumentSize) { type = ToPrepareDocument; } } if (type == ToPrepareDocument) { mime = mimeTypeForFile(info).name(); } if (type != ToPrepareAuto && info.size() < MaxUploadPhotoSize) { bool opaque = (mime != stickerMime); img = App::readImage(file, 0, opaque, &animated); } filename = info.fileName(); filesize = info.size(); } else if (!data.isEmpty()) { if (type != ToPrepareAudio) { img = App::readImage(data, 0, true, &animated); if (type == ToPrepareAuto) { if (!img.isNull() && data.size() < MaxUploadPhotoSize) { type = ToPreparePhoto; } else if (data.size() < MaxUploadDocumentSize) { type = ToPrepareDocument; } else { img = QImage(); } } } MimeType mimeType = mimeTypeForData(data); if (type == ToPrepareDocument || type == ToPrepareAudio) { mime = mimeType.name(); } if (mime == "image/jpeg") { filename = filedialogDefaultName(qsl("image"), qsl(".jpg"), QString(), true); } else if (type == ToPrepareAudio) { filename = filedialogDefaultName(qsl("audio"), qsl(".ogg"), QString(), true); mime = "audio/ogg"; } else { QString ext; QStringList patterns = mimeType.globPatterns(); if (!patterns.isEmpty()) { ext = patterns.front().replace('*', QString()); } filename = filedialogDefaultName((type == ToPrepareAudio) ? qsl("audio") : qsl("doc"), ext, QString(), true); } filesize = data.size(); } } else { if (type == ToPrepareDocument) { filename = filedialogDefaultName(qsl("image"), qsl(".png"), QString(), true); mime = mimeTypeForName("image/png").name(); data = QByteArray(); { QBuffer b(&data); img.save(&b, "PNG"); } filesize = data.size(); } else { if (img.hasAlphaChannel()) { QImage solid(img.width(), img.height(), QImage::Format_ARGB32_Premultiplied); solid.fill(st::white->c); { QPainter(&solid).drawImage(0, 0, img); } img = solid; } type = ToPreparePhoto; filename = qsl("Untitled.jpg"); filesize = 0; } } if ((img.isNull() && ((type != ToPrepareDocument && type != ToPrepareAudio) || !filesize)) || type == ToPrepareAuto || (img.isNull() && file.isEmpty() && data.isEmpty())) { // if could not decide what type { QMutexLocker lock(loader->toPrepareMutex()); ToPrepareMedias &list(loader->toPrepareMedias()); list.pop_front(); } QTimer::singleShot(1, this, SLOT(prepareImages())); emit imageFailed(id); } else { PreparedPhotoThumbs photoThumbs; QVector<MTPPhotoSize> photoSizes; QVector<MTPDocumentAttribute> attributes(1, MTP_documentAttributeFilename(MTP_string(filename))); MTPPhotoSize thumb(MTP_photoSizeEmpty(MTP_string(""))); MTPPhoto photo(MTP_photoEmpty(MTP_long(0))); MTPDocument document(MTP_documentEmpty(MTP_long(0))); MTPAudio audio(MTP_audioEmpty(MTP_long(0))); QByteArray jpeg; if (type == ToPreparePhoto) { int32 w = img.width(), h = img.height(); QPixmap thumb = (w > 100 || h > 100) ? QPixmap::fromImage(img.scaled(100, 100, Qt::KeepAspectRatio, Qt::SmoothTransformation), Qt::ColorOnly) : QPixmap::fromImage(img); photoThumbs.insert('s', thumb); photoSizes.push_back(MTP_photoSize(MTP_string("s"), MTP_fileLocationUnavailable(MTP_long(0), MTP_int(0), MTP_long(0)), MTP_int(thumb.width()), MTP_int(thumb.height()), MTP_int(0))); QPixmap medium = (w > 320 || h > 320) ? QPixmap::fromImage(img.scaled(320, 320, Qt::KeepAspectRatio, Qt::SmoothTransformation), Qt::ColorOnly) : QPixmap::fromImage(img); photoThumbs.insert('m', medium); photoSizes.push_back(MTP_photoSize(MTP_string("m"), MTP_fileLocationUnavailable(MTP_long(0), MTP_int(0), MTP_long(0)), MTP_int(medium.width()), MTP_int(medium.height()), MTP_int(0))); QPixmap full = (w > 1280 || h > 1280) ? QPixmap::fromImage(img.scaled(1280, 1280, Qt::KeepAspectRatio, Qt::SmoothTransformation), Qt::ColorOnly) : QPixmap::fromImage(img); photoThumbs.insert('y', full); photoSizes.push_back(MTP_photoSize(MTP_string("y"), MTP_fileLocationUnavailable(MTP_long(0), MTP_int(0), MTP_long(0)), MTP_int(full.width()), MTP_int(full.height()), MTP_int(0))); { QBuffer jpegBuffer(&jpeg); full.save(&jpegBuffer, "JPG", 77); } if (!filesize) filesize = jpeg.size(); photo = MTP_photo(MTP_long(id), MTP_long(0), MTP_int(user), MTP_int(unixtime()), MTP_geoPointEmpty(), MTP_vector<MTPPhotoSize>(photoSizes)); thumbId = id; } else if ((type == ToPrepareVideo || type == ToPrepareDocument) && !img.isNull()) { int32 w = img.width(), h = img.height(); QByteArray thumbFormat = "JPG"; int32 thumbQuality = 87; if (animated) { attributes.push_back(MTP_documentAttributeAnimated()); } else if (mime == stickerMime && w > 0 && h > 0 && w <= StickerMaxSize && h <= StickerMaxSize && filesize < StickerInMemory) { attributes.push_back(MTP_documentAttributeSticker(MTP_string(""), MTP_inputStickerSetEmpty())); thumbFormat = "webp"; thumbExt = qsl("webp"); } attributes.push_back(MTP_documentAttributeImageSize(MTP_int(w), MTP_int(h))); if (w < 20 * h && h < 20 * w) { QPixmap full = (w > 90 || h > 90) ? QPixmap::fromImage(img.scaled(90, 90, Qt::KeepAspectRatio, Qt::SmoothTransformation), Qt::ColorOnly) : QPixmap::fromImage(img, Qt::ColorOnly); { QBuffer jpegBuffer(&jpeg); full.save(&jpegBuffer, thumbFormat, thumbQuality); } photoThumbs.insert('0', full); thumb = MTP_photoSize(MTP_string(""), MTP_fileLocationUnavailable(MTP_long(0), MTP_int(0), MTP_long(0)), MTP_int(full.width()), MTP_int(full.height()), MTP_int(0)); thumbId = MTP::nonce<uint64>(); } } if (type == ToPrepareDocument) { document = MTP_document(MTP_long(id), MTP_long(0), MTP_int(unixtime()), MTP_string(mime), MTP_int(filesize), thumb, MTP_int(MTP::maindc()), MTP_vector<MTPDocumentAttribute>(attributes)); } else if (type == ToPrepareAudio) { audio = MTP_audio(MTP_long(id), MTP_long(0), MTP_int(user), MTP_int(unixtime()), MTP_int(duration), MTP_string(mime), MTP_int(filesize), MTP_int(MTP::maindc())); } { QMutexLocker lock(loader->readyMutex()); loader->readyList().push_back(ReadyLocalMedia(type, file, filename, filesize, data, id, thumbId, thumbExt, peer, photo, audio, photoThumbs, document, jpeg, ctrlShiftEnter, replyTo)); } { QMutexLocker lock(loader->toPrepareMutex()); ToPrepareMedias &list(loader->toPrepareMedias()); list.pop_front(); } QTimer::singleShot(1, this, SLOT(prepareImages())); emit imageReady(); } }
void Foam::lduMatrix::operator-=(const lduMatrix& A) { if (A.diagPtr_) { diag() -= A.diag(); } if (symmetric() && A.symmetric()) { upper() -= A.upper(); } else if (symmetric() && A.asymmetric()) { if (upperPtr_) { lower(); } else { upper(); } upper() -= A.upper(); lower() -= A.lower(); } else if (asymmetric() && A.symmetric()) { if (A.upperPtr_) { lower() -= A.upper(); upper() -= A.upper(); } else { lower() -= A.lower(); upper() -= A.lower(); } } else if (asymmetric() && A.asymmetric()) { lower() -= A.lower(); upper() -= A.upper(); } else if (diagonal()) { if (A.upperPtr_) { upper() = -A.upper(); } if (A.lowerPtr_) { lower() = -A.lower(); } } else if (A.diagonal()) { } else { if (debug > 1) { WarningIn("lduMatrix::operator-=(const lduMatrix& A)") << "Unknown matrix type combination" << nl << " this :" << " diagonal:" << diagonal() << " symmetric:" << symmetric() << " asymmetric:" << asymmetric() << nl << " A :" << " diagonal:" << A.diagonal() << " symmetric:" << A.symmetric() << " asymmetric:" << A.asymmetric() << endl; } } }
void Stokes::V_Coarsen_Patch_Strategy::postprocessCoarsen_2D (SAMRAI::hier::Patch& coarse, const SAMRAI::hier::Patch& fine, const SAMRAI::hier::Box& , const SAMRAI::hier::IntVector& ) { /* Fix up the boundary elements by iterating through the boundary boxes */ /* We only care about edges, not corners, so we only iterate over edge boundary boxes. */ const std::vector<SAMRAI::hier::BoundaryBox> &boundaries=coarse_fine[fine.getPatchLevelNumber()]->getEdgeBoundaries(coarse.getGlobalId()); boost::shared_ptr<SAMRAI::pdat::SideData<double> > v_fine = boost::dynamic_pointer_cast<SAMRAI::pdat::SideData<double> > (fine.getPatchData(v_id)); boost::shared_ptr<SAMRAI::pdat::SideData<double> > v = boost::dynamic_pointer_cast<SAMRAI::pdat::SideData<double> > (coarse.getPatchData(v_id)); TBOX_ASSERT(v); TBOX_ASSERT(v_fine); TBOX_ASSERT(v_fine->getDepth() == v->getDepth()); TBOX_ASSERT(v->getDepth() == 1); SAMRAI::hier::Box gbox(v_fine->getGhostBox()); SAMRAI::hier::Index ip(1,0), jp(0,1); for(size_t mm=0; mm<boundaries.size(); ++mm) { SAMRAI::hier::Box bbox=boundaries[mm].getBox(); int location_index=boundaries[mm].getLocationIndex(); SAMRAI::hier::Index lower=SAMRAI::hier::Index::coarsen(bbox.lower(), SAMRAI::hier::Index(2,2)), upper=SAMRAI::hier::Index::coarsen(bbox.upper(), SAMRAI::hier::Index(2,2)); for(int j=lower(1); j<=upper(1); ++j) for(int i=lower(0); i<=upper(0); ++i) { /* Fix vx */ if(location_index==0) { SAMRAI::pdat::SideIndex coarse(SAMRAI::hier::Index(i,j),0, SAMRAI::pdat::SideIndex::Upper); SAMRAI::pdat::SideIndex center(coarse*2); if(center[1]>=gbox.lower(1) && center[1]<gbox.upper(1)) { (*v)(coarse)=((*v_fine)(center) + (*v_fine)(center+jp))/2; } } else if(location_index==1) { SAMRAI::pdat::SideIndex coarse(SAMRAI::hier::Index(i,j),0, SAMRAI::pdat::SideIndex::Lower); SAMRAI::pdat::SideIndex center(coarse*2); if(center[1]>=gbox.lower(1) && center[1]<gbox.upper(1)) { (*v)(coarse)=((*v_fine)(center) + (*v_fine)(center+jp))/2; } } /* Fix vy */ else if(location_index==2) { SAMRAI::pdat::SideIndex coarse(SAMRAI::hier::Index(i,j),1, SAMRAI::pdat::SideIndex::Upper); SAMRAI::pdat::SideIndex center(coarse*2); if(center[0]>=gbox.lower(0) && center[0]<gbox.upper(0)) { (*v)(coarse)=((*v_fine)(center) + (*v_fine)(center+ip))/2; } } else if(location_index==3) { SAMRAI::pdat::SideIndex coarse(SAMRAI::hier::Index(i,j),1, SAMRAI::pdat::SideIndex::Lower); SAMRAI::pdat::SideIndex center(coarse*2); if(center[0]>=gbox.lower(0) && center[0]<gbox.upper(0)) { (*v)(coarse)=((*v_fine)(center) + (*v_fine)(center+ip))/2; } } else { abort(); } } } }
void ActivityPartitionCanvas::menu(const QPoint&) { QPopupMenu m(0); QPopupMenu toolm(0); int index; m.insertItem(new MenuTitle(browser_node->get_data()->definition(FALSE, TRUE), m.font()), -1); m.insertSeparator(); m.insertItem(TR("Upper"), 0); m.insertItem(TR("Lower"), 1); m.insertItem(TR("Go up"), 13); m.insertItem(TR("Go down"), 14); m.insertSeparator(); m.insertItem((horiz) ? TR("draw vertically") : TR("draw horizontally"), 10); m.insertSeparator(); m.insertItem(TR("Edit drawing settings"), 2); m.insertSeparator(); m.insertItem(TR("Edit activity partition"), 3); m.insertSeparator(); m.insertItem(TR("Select in browser"), 4); if (linked()) m.insertItem(TR("Select linked items"), 5); m.insertSeparator(); if (browser_node->is_writable()) { if (browser_node->get_associated() != (BrowserNode *) the_canvas()->browser_diagram()) m.insertItem(TR("Set associated diagram"),6); if (browser_node->get_associated()) m.insertItem(TR("Remove diagram association"),9); } m.insertSeparator(); m.insertItem(TR("Remove from diagram"), 7); if (browser_node->is_writable()) m.insertItem(TR("Delete from model"), 8); m.insertSeparator(); if (Tool::menu_insert(&toolm, UmlActivityPartition, 20)) m.insertItem(TR("Tool"), &toolm); switch (index = m.exec(QCursor::pos())) { case 0: upper(); modified(); // call package_modified() return; case 1: lower(); modified(); // call package_modified() return; case 13: z_up(); modified(); // call package_modified() return; case 14: z_down(); modified(); // call package_modified() return; case 2: edit_drawing_settings(); return; case 3: browser_node->open(TRUE); return; case 4: browser_node->select_in_browser(); return; case 5: the_canvas()->unselect_all(); select_associated(); return; case 6: ((BrowserActivityPartition *) browser_node) ->set_associated_diagram((BrowserActivityDiagram *) the_canvas()->browser_diagram()); return; case 7: //remove from diagram delete_it(); break; case 8: //delete from model browser_node->delete_it(); // will delete the canvas break; case 9: ((BrowserActivityPartition *) browser_node) ->set_associated_diagram(0); return; case 10: turn(-1000, -1000); break; default: if (index >= 20) ToolCom::run(Tool::command(index - 20), browser_node); return; } package_modified(); }
int main (void) { while ((character=getchar()) != EOF) { lower(character); putchar (lowerchar); } }
int power_config_gpio_bias(void) { char gpio_bias[32], gpio_name[32]; char *gpio_name_const="pa_bias"; char port_index; char *axp=NULL, *supply=NULL, *vol=NULL; uint main_hd; uint bias_vol_set; int index, ret, i; uint port_bias_addr; uint vol_index, config_type; int pmu_vol; struct bias_set bias_vol_config[8] = { {1800, 0}, {2500, 6}, {2800, 9}, {3000, 0xa}, {3300, 0xd}, {0, 0} }; main_hd = script_parser_fetch_subkey_start("gpio_bias"); index = 0; while(1) { memset(gpio_bias, 0, 32); memset(gpio_name, 0, 32); ret = script_parser_fetch_subkey_next(main_hd, gpio_name, (int *)gpio_bias, &index); if(!ret) { lower(gpio_name); lower(gpio_bias); port_index = gpio_name[1]; gpio_name[1] = 'a'; if(strcmp(gpio_name_const, gpio_name)) { printf("invalid gpio bias name %s\n", gpio_name); continue; } gpio_name[1] = port_index; i=0; axp = gpio_bias; while( (gpio_bias[i]!=':') && (gpio_bias[i]!='\0') ) { i++; } gpio_bias[i++]='\0'; if(!strcmp(axp, "constant")) { config_type = 1; } else if(!strcmp(axp, "floating")) { printf("ignore %s bias config\n", gpio_name); continue; } else { config_type = 0; } if(config_type == 0) { supply = gpio_bias + i; while( (gpio_bias[i]!=':') && (gpio_bias[i]!='\0') ) { i++; } gpio_bias[i++]='\0'; } printf("supply=%s\n", supply); vol = gpio_bias + i; while( (gpio_bias[i]!=':') && (gpio_bias[i]!='\0') ) { i++; } bias_vol_set = simple_strtoul(vol, NULL, 10); for(i=0;i<5;i++) { if(bias_vol_config[i].vol == bias_vol_set) { break; } } if(i==5) { printf("invalid gpio bias set vol %d, at name %s\n", bias_vol_set, gpio_name); break; } vol_index = bias_vol_config[i].index; if((port_index >= 'a') && (port_index <= 'h')) { //获取寄存器地址 port_bias_addr = SUNXI_PIO_BASE + 0x300 + 0x4 * (port_index - 'a'); } else if(port_index == 'j') { //获取寄存器地址 port_bias_addr = SUNXI_PIO_BASE + 0x300 + 0x4 * (port_index - 'a'); } else if((port_index == 'l') || (port_index == 'm')) { //获取寄存器地址 port_bias_addr = SUNXI_R_PIO_BASE + 0x300 + 0x4 * (port_index - 'l'); } else { printf("invalid gpio port at name %s\n", gpio_name); continue; } printf("axp=%s, supply=%s, vol=%d\n", axp, supply, bias_vol_set); if(config_type == 1) { smc_writel(vol_index, port_bias_addr); } else { pmu_vol = axp_probe_supply_status_byname(axp, supply); if(pmu_vol < 0) { printf("sunxi board read %s %s failed\n", axp, supply); continue; } if(pmu_vol > bias_vol_set) //pmu实际电压超过需要设置的电压 { //电压降低到需要电压 axp_set_supply_status_byname(axp, supply, bias_vol_set, 1); //设置寄存器 smc_writel(vol_index, port_bias_addr); } else if(pmu_vol < bias_vol_set) //pmu实际电压低于需要设置的电压 { //设置寄存器 smc_writel(vol_index, port_bias_addr); //把pmu电压调整到需要的电压 axp_set_supply_status_byname(axp, supply, bias_vol_set, 1); } else { //如果实际电压等于需要设置电压,直接设置即可 smc_writel(vol_index, port_bias_addr); } } printf("reg addr=0x%x, value=0x%x, pmu_vol=%d\n", port_bias_addr, smc_readl(port_bias_addr), bias_vol_set); } else { printf("config gpio bias voltage finish\n"); break; } } return 0; }
environment_list* insert_table(Node* node, environment_list* env, environment_list* previous, environment_list *outter_table){ Node *aux; Node *aux2; table_element *temp; table_element *nodeFunc; switch (node->type){ case VarDecl: ; aux=node; while(aux!=NULL){ aux2=aux->childs; Node *value=get_type(aux2); while(aux2->next!=NULL){ check_duplicates(aux2,env->locals); lower(aux2->value.s); env->locals=insert_line(env->locals,aux2->value.s,check_type(value,env),"",_NULL_); aux2=aux2->next; } aux=aux->next; } return env; case FuncDecl: case FuncDef2: case FuncDef: ; aux=node; while(aux!=NULL){ if(aux->type==FuncDef) nodeFunc=insert_func(1,aux->childs,env,outter_table); else if(aux->type==FuncDef2) nodeFunc=insert_funcdef2(aux->childs,env,outter_table); else if(aux->type==FuncDecl) nodeFunc=insert_func(0,aux->childs,env,outter_table); if(env->locals==NULL){ env->locals=nodeFunc; } else if(aux->type==FuncDef2){ if(nodeFunc!=NULL){ for(temp=env->locals;temp->next!=NULL;temp=temp->next){ if(strcmp(temp->name,nodeFunc->name)==0){ temp=nodeFunc; break; } } } } else{ for(temp=env->locals;temp->next!=NULL;temp=temp->next); temp->next=nodeFunc; } aux=aux->next; } return env; case Params: case VarParams: ; aux=node; while(aux!=NULL){ aux2=aux->childs; char *flag; if(aux->type==Params) flag="param"; else flag="varparam"; Node *value=get_type(aux2); while(aux2->next!=NULL){ check_duplicates(aux2,env->locals); lower(aux2->value.s); env->number_of_arguments++; env->locals=insert_line(env->locals,aux2->value.s,check_type(value,env),flag,_NULL_); aux2=aux2->next; } aux=aux->next; } return env; case IfElse: ; //check_statements(node->childs,"if",env); break; case While: ; //check_statements(node->childs,"while",env); break; case ValParam: ; //check_statements(node->childs,"val-paramstr",env); break; case Repeat: ; //check_statements(node->childs->next,"repeat-until",env); break; case Assign: ; //check_expressions(); break; case WriteLn: ; //check_writeln(node); break; case Call: ; check_number_of_arguments(node->childs,env); break; default: break; } if(node->childs){ env = insert_table(node->childs,env,previous,outter_table); } if(node->next) env = insert_table(node->next, env,previous,outter_table); return env; }
Aabb(const Point<> &llo, const Point<> &uup) { lower(llo); upper(uup); }
// Only difference from above test is the use of Neuman BCs here void TestMeshBasedSquareMonolayerWithNeumanBcs() { HoneycombMeshGenerator generator(10,10,0); MutableMesh<2,2>* p_mesh = generator.GetMesh(); std::vector<CellPtr> cells; MAKE_PTR(DifferentiatedCellProliferativeType, p_differentiated_type); CellsGenerator<UniformCellCycleModel, 2> cells_generator; cells_generator.GenerateBasicRandom(cells, p_mesh->GetNumNodes(), p_differentiated_type); // Make cells with x<5.0 apoptotic (so no source term) boost::shared_ptr<AbstractCellProperty> p_apoptotic_property = cells[0]->rGetCellPropertyCollection().GetCellPropertyRegistry()->Get<ApoptoticCellProperty>(); for (unsigned i=0; i<cells.size(); i++) { c_vector<double,2> cell_location; cell_location = p_mesh->GetNode(i)->rGetLocation(); if (cell_location(0) < 5.0) { cells[i]->AddCellProperty(p_apoptotic_property); } // Set initial condition for PDE cells[i]->GetCellData()->SetItem("variable",1.0); } TS_ASSERT_EQUALS(p_apoptotic_property->GetCellCount(), 50u); MeshBasedCellPopulation<2> cell_population(*p_mesh, cells); // Set up simulation time for file output SimulationTime::Instance()->SetEndTimeAndNumberOfTimeSteps(1.0, 10); // Create PDE and boundary condition objects MAKE_PTR_ARGS(AveragedSourceParabolicPde<2>, p_pde, (cell_population, 0.1, 1.0, -1.0)); MAKE_PTR_ARGS(ConstBoundaryCondition<2>, p_bc, (1.0)); // Create a ChasteCuboid on which to base the finite element mesh used to solve the PDE ChastePoint<2> lower(-5.0, -5.0); ChastePoint<2> upper(15.0, 15.0); MAKE_PTR_ARGS(ChasteCuboid<2>, p_cuboid, (lower, upper)); // Create a PDE modifier and set the name of the dependent variable in the PDE MAKE_PTR_ARGS(ParabolicBoxDomainPdeModifier<2>, p_pde_modifier, (p_pde, p_bc, true, p_cuboid)); p_pde_modifier->SetDependentVariableName("variable"); // For coverage, output the solution gradient p_pde_modifier->SetOutputGradient(true); p_pde_modifier->SetupSolve(cell_population,"TestAveragedParabolicPdeWithNeumannWithMeshOnSquare"); // Run for 10 time steps for (unsigned i=0; i<10; i++) { SimulationTime::Instance()->IncrementTimeOneStep(); p_pde_modifier->UpdateAtEndOfTimeStep(cell_population); p_pde_modifier->UpdateAtEndOfOutputTimeStep(cell_population); } // Test the solution at some fixed points to compare with other cell populations CellPtr p_cell_0 = cell_population.GetCellUsingLocationIndex(0); TS_ASSERT_DELTA(cell_population.GetLocationOfCellCentre(p_cell_0)[0], 0, 1e-4); TS_ASSERT_DELTA(cell_population.GetLocationOfCellCentre(p_cell_0)[1], 0.0, 1e-4); TS_ASSERT_DELTA( p_cell_0->GetCellData()->GetItem("variable"), 2.0029, 1e-4); TS_ASSERT_DELTA( p_cell_0->GetCellData()->GetItem("variable_grad_x"), -0.3783, 1e-4); TS_ASSERT_DELTA( p_cell_0->GetCellData()->GetItem("variable_grad_y"), -0.2981, 1e-4); }
void TestArchivingOfPdeHandlerOnCuboid() throw(Exception) { EXIT_IF_PARALLEL; FileFinder archive_dir("archive", RelativeTo::ChasteTestOutput); std::string archive_file = "CellBasedPdeHandlerOnCuboid.arch"; ArchiveLocationInfo::SetMeshFilename("pde_handler_mesh"); { // Create a cell population HoneycombMeshGenerator generator(2, 2, 0); MutableMesh<2,2>* p_generating_mesh = generator.GetMesh(); NodesOnlyMesh<2> mesh; mesh.ConstructNodesWithoutMesh(*p_generating_mesh, 1.5); std::vector<CellPtr> cells; CellsGenerator<FixedDurationGenerationBasedCellCycleModel, 2> cells_generator; cells_generator.GenerateBasic(cells, mesh.GetNumNodes()); NodeBasedCellPopulation<2> cell_population(mesh, cells); // Create a PDE handler object using this cell population CellBasedPdeHandlerOnCuboid<2>* const p_pde_handler = new CellBasedPdeHandlerOnCuboid<2>(&cell_population); // Set member variables for testing p_pde_handler->SetWriteAverageRadialPdeSolution("averaged quantity", 5, true); p_pde_handler->SetImposeBcsOnCoarseBoundary(false); // Set up PDE and pass to handler AveragedSourcePde<2> pde(cell_population, -0.1); ConstBoundaryCondition<2> bc(1.0); PdeAndBoundaryConditions<2> pde_and_bc(&pde, &bc, false); pde_and_bc.SetDependentVariableName("averaged quantity"); p_pde_handler->AddPdeAndBc(&pde_and_bc); // Test UseCoarsePdeMesh() again ChastePoint<2> lower(0.0, 0.0); ChastePoint<2> upper(9.0, 9.0); ChasteCuboid<2> cuboid(lower, upper); p_pde_handler->UseCoarsePdeMesh(3.0, cuboid, true); // Create an output archive ArchiveOpener<boost::archive::text_oarchive, std::ofstream> arch_opener(archive_dir, archive_file); boost::archive::text_oarchive* p_arch = arch_opener.GetCommonArchive(); // Archive object SimulationTime* p_simulation_time = SimulationTime::Instance(); p_simulation_time->SetEndTimeAndNumberOfTimeSteps(1.0, 11); (*p_arch) << static_cast<const SimulationTime&>(*p_simulation_time); (*p_arch) << p_pde_handler; // Tidy up SimulationTime::Destroy(); delete p_pde_handler; } { CellBasedPdeHandlerOnCuboid<2>* p_pde_handler; // Create an input archive ArchiveOpener<boost::archive::text_iarchive, std::ifstream> arch_opener(archive_dir, archive_file); boost::archive::text_iarchive* p_arch = arch_opener.GetCommonArchive(); // Restore object from the archive SimulationTime* p_simulation_time = SimulationTime::Instance(); (*p_arch) >> *p_simulation_time; (*p_arch) >> p_pde_handler; // Test that the member variables were archived correctly TS_ASSERT_EQUALS(p_pde_handler->mpCellPopulation->GetNumRealCells(), 4u); TS_ASSERT_EQUALS(p_pde_handler->GetWriteAverageRadialPdeSolution(), true); TS_ASSERT_EQUALS(p_pde_handler->GetWriteDailyAverageRadialPdeSolution(), true); TS_ASSERT_EQUALS(p_pde_handler->GetImposeBcsOnCoarseBoundary(), false); TS_ASSERT_EQUALS(p_pde_handler->GetNumRadialIntervals(), 5u); TS_ASSERT_EQUALS(p_pde_handler->mAverageRadialSolutionVariableName, "averaged quantity"); ///\todo we currently do not archive mpCoarsePdeMesh - consider doing this (#1891) TS_ASSERT(p_pde_handler->GetCoarsePdeMesh() == NULL); TS_ASSERT_EQUALS(p_pde_handler->mPdeAndBcCollection.size(), 1u); TS_ASSERT_EQUALS(p_pde_handler->mPdeAndBcCollection[0]->IsNeumannBoundaryCondition(), false); // Tidy up delete p_pde_handler->mpCellPopulation; delete p_pde_handler; } }