text
stringlengths
8
6.88M
#include <iostream> #include <queue> #include <algorithm> using namespace std; int M, N, H; int nMap[100][100][100]; int nCheck[100][100][100]; int dz[6] = { -1, 1, 0, 0, 0, 0 }; int dy[6] = { 0, 0, -1, 1, 0, 0 }; int dx[6] = { 0, 0, 0, 0, -1, 1 }; int nResult; int main(void) { queue < pair<int, pair<int, int>>> q; cin >> M >> N >> H; for (int k = 0; k < H; k++) { for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { cin >> nMap[k][i][j]; nCheck[k][i][j] = -1; if (nMap[k][i][j] == 1) { q.push(make_pair(k, make_pair(i, j))); nCheck[k][i][j] = 0; } } } } while (!q.empty()) { int z = q.front().first; int y = q.front().second.first; int x = q.front().second.second; q.pop(); for (int i = 0; i < 6; i++) { int nz = z + dz[i]; int ny = y + dy[i]; int nx = x + dx[i]; if (0 <= nz && nz < H && 0 <= ny && ny < N && 0 <= nx && nx < M) { if ((nMap[nz][ny][nx] == 0) && (nCheck[nz][ny][nx] == -1)) { nCheck[nz][ny][nx] = nCheck[z][y][x] + 1; q.push(make_pair(nz, make_pair(ny, nx))); } } } } int nResult = 0; for (int k = 0; k < H; k++) { for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { nResult = max(nResult, nCheck[k][i][j]); } } } for (int k = 0; k < H; k++) { for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { if ((nMap[k][i][j] == 0) && (nCheck[k][i][j] == -1)) { nResult = -1; break; } } } } cout << nResult << endl; return 0; }
/* * Copyright 2019 Nagoya University * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _DMP_DATA_H_ #define _DMP_DATA_H_ #include <string> #include <vector> #include <set> #include <map> /**************************************** * 定数定義 ****************************************/ /**************************************** * インデックス定義 ****************************************/ // 地物カテゴリ(Feature category)定義コード typedef enum { CAT_NONE = 0, // なし CAT_Point = 1, // 点地物 CAT_Line = 2, // 線地物 CAT_Area = 3, // 面地物 CAT_Complex = 4 // 複合地物 } DmpFtrCat_e; // 地物(Feature)定義コード typedef enum { F_NONE = 0, // 0: NONE FL4110_RoadElement, // 1:リンクレベル地物 FL4115_Pathway, // 2:歩道中心線 FP4120_Junction, // 3:○ジャンクション(子) FC4140_Road, // 4:リンクレベル地物 FC4145_Intersection, // 5:交差点(親) FP7210_Signpost, // 6:(使用しない) FP7220_TrafficSign, // 7:標識(親/子) FP7230_TrafficLight, // 8:(使用しない) FP7240_PedestrianCrossing, // 9:(使用しない) FC7245_ComplexPedestrianCrossing, // 10: FP7251_EnvironmentalEquipment, //11: FP7252_Lighting, // 12:街灯(子) FP7254_RoadMarkings, // 13:路面マーク中心点(子) FC8110_Lane, // 14:○レーン本体(親) FA8120_LaneArea, // 15:○レーン走行可能領域(子) FL8130_LaneLine, // 16:○レーン中心線/走行目安線(子) FC8140_ExtendedPedestrian, // 17:歩道(親) FC8145_ExtendedPedestrianCrossing, // 18:横断歩道(親) FA8150_PedestrianArea, // 19:歩道/横断歩道(縞模様の外形)形状(子) FL8160_PedestrianLine, // 20:歩道/横断歩道中心線(子) FA8170_IntersectionAreaShape, // 21:交差点領域(親/子) FP8210_Pole, // 22:○ポール(親/子) FC8220_ExtendedTrafficSign, // 23:○標識(親) FC8230_ExtendedTrafficLight, // 24:○信号(親) FP8231_TrafficLightLamp, // 25:○信号ランプ(子) FC8240_ExtendedLighting, // 26:街灯(親) FL8241_LightingLamp, // 27:街灯ランプ(子) FC8250_ExtendedRoadMarkings, // 28:路面マーク(親) FA8251_RoadMarkingsShape, // 29:路面マーク形状(子) FA8252_PedestrianCrossingMarkingShape, // 30:横断歩道形状(縞模様毎)(子) FL8260_StopLine, // 31:○停止線(親) FL8310_RoadEdge, // 32:道路縁(親) FL8311_Curb, // 33:縁石(親) FA8312_Gutter, // 34:側溝(親) FA8313_GuardRail, // 35:ガードレール(親) FA8314_ZebraZone, // 36:ゼブラゾーン(親) FP8410_ShapeDescriptionPoint // 37:形状記述点(子) } DmpFtrClass_e; // 関連(Relation)タイプ定義コード typedef enum { R_NONE = 0, // 0: NONE R2110_Connectivity, R9110_Crossing, R9120_Adjacency, R9130_Branch, R9210_TrafficLightRegulationForLane, R9220_TrafficSignRegulationForLane, R9230_FeatureAlongWithLane } DmpRelType_e; // 属性(Attribute)種別定義コード typedef enum { A_NONE = 0, // 0: NONE A_CT, // 1:other textual content of traffic sign A_DA, // 2:Diameter (数値, メートル) A_DH, // 3:Divider Height (数値) A_DM, // 4:Divider Marking (1:no line, 1:dashed line, ...) A_DT, // 5:Divider Type (3:legal, 4:physical) A_DW, // 6:Divider Width (数値) A_DX, // 7:Divider Impact (1:双方向, 2:右から, 3:左から) A_DZ, // 8:Divider Colour (1:white, 2:yellow) A_EV, // 9:Lane Type (0:normal lane, 1:emergency lane, ...) A_GR, // 10:Guard Rail type (0:板羽根, 1:パイプ) A_GU, // 11:Gutter type (0:蓋なし, 1:フタあり, 2:グレーチング) A_HT, // 12:Height (数値, メートル) A_LD, // 13:Lane Dependent validity (L:左から車線をカウント, R:右から) A_LI, // 14:Traffic Light Type (信号種別, 1:車両, 2:歩行者, 3:車両歩行者兼用, 9:その他) A_LM, // 15:Measured Length (数値, メートル) A_LR, // 16:Length of Road Element (数値) A_LY, // 17:Lamp Type (ランプ種別, 1: 赤, 2:青, 3:黄, 4: 左矢印, 5: 直進矢印, 6:右矢印, 9:その他) A_NL, // 18:Number of Lane (レーン数(交差点内は0)) A_OY, // 19:レーンの走行方向(0:順方向, 1:逆方向) 基本的には. A_PN, // 20:pitch angle (数値 [deg]) A_SP, // 21:Speed (走行時の想定速度(本来の意味は速度制限)) A_SY, // 22:Symbol on Traffic Sign A_TR, // 23:Toll Road (0:False, True) A_TS, // 24:Traffic sign class (50:優先権, 51:方向, 55:停車禁止, 56:警告, ...) A_TT, // 25:Travel time (数値) A_VT, // 26:Vehicle Type (0:all, 11:Passenger cars, 15:emergency vehicle, 16:taxi, 24:bicycle, 25:pedestrian, ...) A_WI, // 27:Width (数値) A_WL, // 28:Width of Leftside (左幅員, 数値 [m]) A_WR, // 29:Width of Rightside (右幅員, 数値 [m]) A_XM, // 30:Pedestrian crossing marking type (0:外枠, 1:縞模様, 2:自転車通行帯) A_YN // 31:yaw angle (数値 [deg]) } DmpAtrCode_e; /**************************************** * 構造体定義 ****************************************/ // 点(Point)データ定義 typedef struct { double x; // 平面直角座標系 Y座標(Ly) (東方向正) [m] (X,Yの入れ替わりに注意) double y; // 平面直角座標系 X座標(Bx) (北方向正) [m] (X,Yの入れ替わりに注意) double z; // 平面直角座標系 標高(H) [m] int sno; // 平面直角座標系 系番号 (1-19) double xLon; // 経度 [deg] double yLat; // 緯度 [deg] } StDmpPoint_t; typedef std::vector<StDmpPoint_t> VcDmpPoint_t; //----------------------------- // データベーステーブル読み込みバッファ定義 //----------------------------- // attribute_composition typedef struct { int attribute_id; // key int scope_level; int composition_number; int sequence_number; int parent_scope_level; int parent_comp_number; int parent_seq_number; std::string av_attr_value; DmpAtrCode_e av_type_code; } StAttributeComposition_t; // map<attribute_id, vector<struct>> typedef std::vector<StAttributeComposition_t> VcAttributeComposition_t; typedef std::map<int, VcAttributeComposition_t> MpVcAttributeComposition_t; // attribute_group (使用方法不明) typedef struct { int attribute_id; } StAttributeGroup_t; // vector<struct> typedef std::vector<StAttributeGroup_t> VcAttributeGroup_t; // cmp_feat_part_attr (未使用) typedef struct { int feat_category_num; // index int feature_id; // key int sequence_number; int attribute_id; } StCmpFeatPartAttr_t; // vector[feature_category_num-1].map<feature_id, vector<struct>> typedef std::vector<std::map<int, std::vector<StCmpFeatPartAttr_t> > > VcMpVcCmpFeatPartAttr_t; // feature_attr typedef struct { int feature_category_num; // index int feature_id; // key int attribute_id; } StFeatureAttr_t; // vector[feature_category_num-1].map<feature_id, struct> typedef std::vector<std::map<int, StFeatureAttr_t> > VcMpFeatureAttr_t; // feature_category (使わない) typedef struct { int feat_category_num; // key std::string feat_category_name; } StFeatureCategory_t; // map<feat_category_num, struct> typedef std::map<int, StFeatureCategory_t> MpFeatureCategory_t; // feature_class_code (使えない) typedef struct { DmpFtrClass_e feature_class_code; // key std::string description; } StFeatureClassCode_t; // map<feature_class_code, struct> typedef std::map<int, StFeatureClassCode_t> MpFeatureClassCode_t; // pf_area_feature typedef struct { int feat_category_num; // =3 int feature_id; // key DmpFtrClass_e feature_class_code; } StPfAreaFeature_t; // map<feature_id, struct> typedef std::map<int, StPfAreaFeature_t> MpPfAreaFeature_t; // pf_area_topo_prim typedef struct { int feat_category_num; // =3 int feature_id; // key int face_id; } StPfAreaTopoPrim_t; // map<feature_id, struct> typedef std::map<int, StPfAreaTopoPrim_t> MpPfAreaTopoPrim_t; // pf_comp_feat_part typedef struct { int comp_feat_category; // =4 int comp_feature_id; // key int feature_number; int feature_category_num; int feature_id; } StPfCompFeatPart_t; // map<comp_feature_id, vector<struct>> typedef std::map<int, std::vector<StPfCompFeatPart_t> > MpVcPfCompFeatPart_t; // pf_comp_feature typedef struct { int feat_category_num; // =4 int feature_id; // key DmpFtrClass_e feature_class_code; int from_feat_category; int from_feature_id; int to_feat_category; int to_feature_id; } StPfCompFeature_t; // map<feature_id, struct> typedef std::map<int, StPfCompFeature_t> MpPfCompFeature_t; // pf_line_feature typedef struct { int feat_category_num; // =2 int feature_id; // key DmpFtrClass_e feature_class_code; int end_elevation; int from_feat_category; int from_feat_id; int to_feat_category; int to_feat_id; } StPfLineFeature_t; // map<feature_id, struct> typedef std::map<int, StPfLineFeature_t> MpPfLineFeature_t; // pf_line_topo_prim typedef struct { int feat_category_num; // =2 int feature_id; // key int sequence_number; int edge_id; int edge_orientation; int start_elevation; int intermitted_elevation; } StPfLineTopoPrim_t; // map<feature_id, vector<struct>> typedef std::map<int, std::vector<StPfLineTopoPrim_t> > MpVcPfLineTopoPrim_t; // pf_point_feature typedef struct { int feat_category_num; // =1 int feature_id; // key DmpFtrClass_e feature_class_code; int node_id; } StPfPointFeature_t; // map<feature_id, struct> typedef std::map<int, StPfPointFeature_t> MpPfPointFeature_t; // relation_feat_attr (未使用) typedef struct { int relationship_id; // key int role_number; int feature_number; int attribute_id; } StRelationFeatAttr_t; // map<relationship_id, vector<struct>> typedef std::map<int, std::vector<StRelationFeatAttr_t> > MpVcRelationFeatAttr_t; // relation_role (使わない) typedef struct { DmpRelType_e rel_type_code; int role_number; std::string role_name; bool repeatable; bool mandatory; } StRelationRole_t; // map<rel_type_code, vector<struct>> typedef std::map<int, std::vector<StRelationRole_t> > MpVcRelationRole_t; // relation_type_code (使えない) typedef struct { DmpRelType_e rel_type_code; std::string description; } StRelationTypeCode_t; // map<rel_type_code, struct> typedef std::map<int, StRelationTypeCode_t> MpRelationTypeCode_t; // relationship typedef struct { int relationship_id; DmpRelType_e rel_type; } StRelationship_t; // map<relationship_id, struct> typedef std::map<int, StRelationship_t> MpRelationship_t; // relationship_attr typedef struct { int relationship_id; int attribute_id; } StRelationshipAttr_t; // map<relationship_id, vector<struct>> typedef std::map<int, std::vector<StRelationshipAttr_t> > MpVcRelationshipAttr_t; // relationship_feat typedef struct { int relationship_id; int role_number; int feature_number; int feat_category_num; int feature_id; DmpRelType_e rel_type; // relationshipからコピーする } StRelationshipFeat_t; // map<relationship_id, vector<struct>> typedef std::vector<StRelationshipFeat_t> VcRelationshipFeat_t; typedef std::map<int, VcRelationshipFeat_t> MpVcRelationshipFeat_t; // st_edge typedef struct { int edge_id; int start_node; int end_node; int next_left_edge; int next_right_edge; int left_face; int right_face; VcDmpPoint_t geometry; // geometry(LineStringZ,2449) } StStEdge_t; // map<edge_id, struct> typedef std::map<int, StStEdge_t> MpStEdge_t; // st_face typedef struct { int face_id; VcDmpPoint_t mbr; // geometry(PolygonZ,2449), double slope; int aspect; int light_value; bool extended_geom_flag; } StStFace_t; // map<face_id, struct> typedef std::map<int, StStFace_t> MpStFace_t; // st_node typedef struct { int node_id; StDmpPoint_t geometry; // geometry(PointZ,2449), int containing_face; } StStNode_t; // map<node_id, struct> typedef std::map<int, StStNode_t> MpStNode_t; //----------------------------- // 地物データ再構築バッファ定義 //----------------------------- //●[FP4120]ジャンクション(Junction)定義 typedef struct { // pf_point_feature //int feat_category_num; // 地物カテゴリ =1:Point int feature_id; // 地物ID (キー) //DmpFtrClass_e feature_class_code; // 地物クラス ='4120' int node_id; // st_nodeへの参照キー // st_node StDmpPoint_t sn_geometry; // 座標情報 // attribute } StDmpJunction_t; // map<feature_id, struct> typedef std::map<int, StDmpJunction_t> MpDmpJunction_t; //●[FC8110]レーン(Lane)定義 typedef struct { // pf_comp_feature //int feat_category_num; // 地物カテゴリ =4:Complex int feature_id; // 地物ID (キー) //DmpFtrClass_e feature_class_code; // 地物クラス ='8110' //int from_feat_category; // この地物を構成する最初の地物カテゴリ =2:Line //int from_feature_id; // この地物を構成する最初の地物ID //int to_feat_category; // この地物を構成する最後の地物カテゴリ =3:Area //int to_feature_id; // この地物を構成する最後の地物ID // pf_comp_feat_part - LaneLine //int pcfp1_comp_feat_category; // = 本体(親)地物カテゴリ =4:Complex //int pcfp1_comp_feature_id; // = 本体(親) 地物ID //int pcfp1_feature_number; // 何番目の部品かを表す //int pcfp1_feature_category_num; // 部品(子)地物カテゴリ =2:Line int pcfp1_feature_id; // 部品(子)地物ID // pf_line_feature - LaneLine //int plf1_feat_category_num; // 部品(子)地物カテゴリ =2:Line //int plf1_feature_id; // 部品(子)地物ID //DmpFtrClass_e plf1_feature_class_code; // 地物クラス ='8130' //int plf1_end_elevation; // 標高 //int plf1_from_feat_category; // 始点の地物カテゴリ =1:Point //int plf1_from_feat_id; // 始点の地物ID //int plf1_to_feat_category; // 終点の地物カテゴリ =1:Point //int plf1_to_feat_id; // 終点の地物ID // pf_line_topo_prim - LaneLine //int pltp1_feat_category_num; // 部品(子)地物カテゴリ =2:Line //int pltp1_feature_id; // 部品(子)地物ID //int pltp1_sequence_number; // 複数edgeがある場合用 =1 int pltp1_edge_id; // st_edgeへの参照キー //int pltp1_edge_orientation; // 0:CW,1:CCW =0 //int pltp1_start_elevation; // 標高 //int pltp1_intermitted_elevation; // 標高 // st_edge - LaneLine //int se1_edge_id; // ID //int se1_start_node; // 始点node_id //int se1_end_node; // 終点node_id //int se1_next_left_edge; // 隣接する左エッジID //int se1_next_right_edge; // 隣接する右エッジID //int se1_left_face; // 左面ID //int se1_right_face; // 右面ID VcDmpPoint_t se1_geometry; // 点の系列 // pf_comp_feat_part - LaneArea //int pcfp2_comp_feat_category; // = 本体(親)地物カテゴリ =4:Complex //int pcfp2_comp_feature_id; // = 本体(親) 地物ID //int pcfp2_feature_number; // 何番目の部品かを表す //int pcfp2_feature_category_num; // 部品(子)地物カテゴリ =3:Area int pcfp2_feature_id; // 部品(子)地物ID // pf_area_feature - LaneArea //int paf2_feat_category_num; // 部品(子)地物カテゴリ =3:Area //int paf2_feature_id; // 部品(子)地物ID //DmpFtrClass_e paf2_feature_class_code; // 地物クラス ='8120' // pf_area_topo_prim - LaneArea //int patp2_feat_category_num; // 部品(子)地物カテゴリ =3:Area //int patp2_feature_id; // 部品(子)地物ID int patp2_face_id; // st_faceへの参照キー // st_face - LaneArea VcDmpPoint_t sf2_mbr; // 領域を表す多角形 // attribute int iA_EV; // Lane Type double dA_LR; // Length of Road Element int iA_NL; // Number of Lane int iA_OY; // レーンの走行方向(0:順方向, 1:逆方向) double dA_PN; // pitch angle int iA_SP; // Speed int iA_TR; // Toll Road int iA_VT; // Vehicle Type double dA_WI; // Width double dA_WL; // Width of Leftside double dA_WR; // Width of Rightside double dA_YN; // yaw angle } StDmpLane_t; // map<feature_id, struct> typedef std::map<int, StDmpLane_t> MpDmpLane_t; //●[FA8150]歩道領域(PedestrianArea)定義 typedef struct { // pf_area_feature //int feat_category_num; // 地物カテゴリ =3:Area int feature_id; // 地物ID //DmpFtrClass_e feature_class_code; // 地物クラス ='8150' // pf_area_topo_prim //int patp_feat_category_num; // 地物カテゴリ =3:Area //int patp_feature_id; // 地物ID int patp_face_id; // st_faceへの参照キー // st_face VcDmpPoint_t sf_mbr; // 領域を表す多角形 // attribute } StDmpPedestrianArea_t; typedef std::vector<StDmpPedestrianArea_t> VcDmpPedestrianArea_t; //●[FL8160]歩道中心線(PedestrianLine)定義 typedef struct { // pf_line_feature //int feat_category_num; // 地物カテゴリ =2:Line int feature_id; // 地物ID (キー) //DmpFtrClass_e feature_class_code; // 地物クラス ='8160' //int end_elevation; //int from_feat_category; //int from_feat_id; //int to_feat_category; //int to_feat_id; // pf_line_topo_prim //int feat_category_num; // 地物カテゴリ =2:Line //int feature_id; // 地物ID (キー) //int pltp_sequence_number; // 複数edgeがある場合用 =1 int pltp_edge_id; // st_edgeへの参照キー //int pltp_edge_orientation; // 0:CW,1:CCW =0 //int pltp_start_elevation; // 標高 //int pltp_intermitted_elevation; // 標高 // st_edge //int se_edge_id; // ID //int se_start_node; // 始点node_id //int se_end_node; // 終点node_id //int se_next_left_edge; // 隣接する左エッジID //int se_next_right_edge; // 隣接する右エッジID //int se_left_face; // 左面ID //int se_right_face; // 右面ID VcDmpPoint_t se_geometry; // 点の系列 // attribute } StDmpPedestrianLine_t; typedef std::vector<StDmpPedestrianLine_t> VcDmpPedestrianLine_t; //●[FC8140]歩道(ExtendedPedestrian)定義 typedef struct { // pf_comp_feature //int feat_category_num; // 地物カテゴリ =4:Complex int feature_id; // 地物ID (キー) //DmpFtrClass_e feature_class_code; // 地物クラス ='8140' //int from_feat_category; // この地物を構成する最初の地物カテゴリ =2:Line //int from_feature_id; // この地物を構成する最初の地物ID //int to_feat_category; // この地物を構成する最後の地物カテゴリ =3:Area //int to_feature_id; // この地物を構成する最後の地物ID // pf_comp_feat_part以下 - PedestrianLine VcDmpPedestrianLine_t mVcDmpPedestrianLine; // [FL8160]歩道中心線 // pf_comp_feat_part以下 - PedestrianArea VcDmpPedestrianArea_t mVcDmpPedestrianArea; // [FA8150]歩道領域 // attribute } StDmpExtendedPedestrian_t; // map<feature_id, struct> typedef std::map<int, StDmpExtendedPedestrian_t> MpDmpExtendedPedestrian_t; //●[FA8252]横断歩道模様(PedestrianCrossingMarkingsShape)定義 typedef struct { // pf_area_feature //int feat_category_num; // 地物カテゴリ =3:Area int feature_id; // 地物ID //DmpFtrClass_e feature_class_code; // 地物クラス ='8252' // pf_area_topo_prim //int patp_feat_category_num; // 地物カテゴリ =3:Area //int patp_feature_id; // 地物ID int patp_face_id; // st_faceへの参照キー // st_face VcDmpPoint_t sf_mbr; // 領域を表す多角形 // attribute int iA_XM; // Pedestrian crossing marking type } StDmpPedestrianCrossingMarkingsShape_t; typedef std::vector<StDmpPedestrianCrossingMarkingsShape_t> VcDmpPedestrianCrossingMarkingsShape_t; //●[FC8145]横断歩道(ExtendedPedestrianCrossing)定義 typedef struct { // pf_comp_feature //int feat_category_num; // 地物カテゴリ =4:Complex int feature_id; // 地物ID (キー) //DmpFtrClass_e feature_class_code; // 地物クラス ='8145' //int from_feat_category; // この地物を構成する最初の地物カテゴリ =2:Line //int from_feature_id; // この地物を構成する最初の地物ID //int to_feat_category; // この地物を構成する最後の地物カテゴリ =3:Area //int to_feature_id; // この地物を構成する最後の地物ID // pf_comp_feat_part以下 - PedestrianLine VcDmpPedestrianLine_t mVcDmpPedestrianLine; // [FL8160]歩道中心線 // pf_comp_feat_part以下 - PedestrianArea VcDmpPedestrianArea_t mVcDmpPedestrianArea; // [FA8150]歩道領域 // pf_comp_feat_part以下 - PedestrianCrossingMarkingsShape VcDmpPedestrianCrossingMarkingsShape_t mVcDmpPedestrianCrossingMarkingsShape; // [FA8252]横断歩道模様 // attribute } StDmpExtendedPedestrianCrossing_t; // map<feature_id, struct> typedef std::map<int, StDmpExtendedPedestrianCrossing_t> MpDmpExtendedPedestrianCrossing_t; //●[FA8170]交差点領域(IntersectionAreaShape)定義 typedef struct { // pf_area_feature //int feat_category_num; // 地物カテゴリ =3:Area int feature_id; // 地物ID //DmpFtrClass_e feature_class_code; // 地物クラス ='8170' // pf_area_topo_prim //int patp_feat_category_num; // 地物カテゴリ =3:Area //int patp_feature_id; // 地物ID int patp_face_id; // st_faceへの参照キー // st_face VcDmpPoint_t sf_mbr; // 領域を表す多角形 // attribute } StDmpIntersectionAreaShape_t; // map<feature_id, struct> typedef std::map<int, StDmpIntersectionAreaShape_t> MpDmpIntersectionAreaShape_t; //●[FP8210]ポール(Pole)定義 typedef struct { // pf_point_feature //int feat_category_num; // 地物カテゴリ =1:Point int feature_id; // 地物ID (キー) //DmpFtrClass_e feature_class_code; // 地物クラス ='8210' int node_id; // st_nodeへの参照キー // st_node StDmpPoint_t sn_geometry; // 座標情報 // attribute double dA_DA; // Diameter double dA_LM; // Measured Length double dA_PN; // pitch angle double dA_YN; // yaw angle } StDmpPole_t; typedef std::vector<StDmpPole_t> VcDmpPole_t; // map<feature_id, struct> typedef std::map<int, StDmpPole_t> MpDmpPole_t; //●[FC8220]標識(ExtendedTrafficSign)定義 typedef struct { // pf_comp_feature //int feat_category_num; // 地物カテゴリ =4:Complex int feature_id; // 地物ID (キー) //DmpFtrClass_e feature_class_code; // 地物クラス ='8230' //int from_feat_category; // この地物を構成する最初の地物カテゴリ =2:Line //int from_feature_id; // この地物を構成する最初の地物ID //int to_feat_category; // この地物を構成する最後の地物カテゴリ =3:Area //int to_feature_id; // この地物を構成する最後の地物ID // pf_comp_feat_part以下 - Pole VcDmpPole_t mVcDmpPole; // [FP8210]ポール // pf_comp_feat_part - Traffic Sign //int pcfp2_comp_feat_category; // = 本体(親)地物カテゴリ =4:Complex //int pcfp2_comp_feature_id; // = 本体(親) 地物ID //int pcfp2_feature_number; // 何番目の部品かを表す //int pcfp2_feature_category_num; // 部品(子)地物カテゴリ =1:Point int pcfp2_feature_id; // 部品(子)地物ID // pf_point_feature - Traffic Sign //int ppf2_feat_category_num; // 地物カテゴリ =1:Point //int ppf2_feature_id; // 地物ID (キー) //DmpFtrClass_e ppf2_feature_class_code; // 地物クラス ='7220' int ppf2_node_id; // st_nodeへの参照キー // st_node - Traffic Sign StDmpPoint_t sn2_geometry; // 座標情報 // attribute int iA_CT; // other textual content of traffic sign double dA_PN; // pitch angle int iA_SY; // Symbol on Traffic Sign int iA_TS; // Traffic sign class double dA_YN; // yaw angle } StDmpExtendedTrafficSign_t; // map<feature_id, struct> typedef std::map<int, StDmpExtendedTrafficSign_t> MpDmpExtendedTrafficSign_t; //●[FP8231]信号ランプ(TrafficLightLamp)定義 typedef struct { // pf_point_feature //int feat_category_num; // 地物カテゴリ =1:Point int feature_id; // 地物ID (キー) //DmpFtrClass_e feature_class_code; // 地物クラス ='8231' int node_id; // st_nodeへの参照キー // st_node StDmpPoint_t sn_geometry; // 座標情報 // Attrubute int iA_LY; // ランプ種別 } StDmpTrafficLightLamp_t; typedef std::vector<StDmpTrafficLightLamp_t> VcDmpTrafficLightLamp_t; //●[FC8230]信号(ExtendedTrafficLight)定義 typedef struct { // pf_comp_feature //int feat_category_num; // 地物カテゴリ =4:Complex int feature_id; // 地物ID (キー) //DmpFtrClass_e feature_class_code; // 地物クラス ='8230' //int from_feat_category; // この地物を構成する最初の地物カテゴリ =2:Line //int from_feature_id; // この地物を構成する最初の地物ID //int to_feat_category; // この地物を構成する最後の地物カテゴリ =3:Area //int to_feature_id; // この地物を構成する最後の地物ID //○pf_comp_feat_part以下 - Pole VcDmpPole_t mVcDmpPole; // [FP8210]ポール //○pf_comp_feat_part以下 - TrafficLightLamp VcDmpTrafficLightLamp_t mVcTrafficLightLamp; // [FP8231]信号ランプ // attribute int iA_LI; // Traffic Light Type double dA_PN; // pitch angle double dA_YN; // yaw angle } StDmpExtendedTrafficLight_t; // map<feature_id, struct> typedef std::map<int, StDmpExtendedTrafficLight_t> MpDmpExtendedTrafficLight_t; //●[FC8240]街灯(ExtendedLighting)定義 typedef struct { // pf_comp_feature //int feat_category_num; // 地物カテゴリ =4:Complex int feature_id; // 地物ID (キー) //DmpFtrClass_e feature_class_code; // 地物クラス ='8240' //int from_feat_category; // この地物を構成する最初の地物カテゴリ =2:Line //int from_feature_id; // この地物を構成する最初の地物ID //int to_feat_category; // この地物を構成する最後の地物カテゴリ =3:Area //int to_feature_id; // この地物を構成する最後の地物ID //○pf_comp_feat_part - Lighting //int pcfp1_comp_feat_category; // = 本体(親)地物カテゴリ =4:Complex //int pcfp1_comp_feature_id; // = 本体(親) 地物ID //int pcfp1_feature_number; // 何番目の部品かを表す //int pcfp1_feature_category_num; // 部品(子)地物カテゴリ =1:Point int pcfp1_feature_id; // 部品(子)地物ID // pf_point_feature - Lighting //int ppf1_feat_category_num; // 地物カテゴリ =1:Point //int ppf1_feature_id; // 地物ID (キー) //DmpFtrClass_e ppf1_feature_class_code; // 地物クラス ='7252' int ppf1_node_id; // st_nodeへの参照キー // st_node - Lighting StDmpPoint_t sn1_geometry; // 座標情報 //○pf_comp_feat_part - Lighting Lamp //int pcfp2_comp_feat_category; // = 本体(親)地物カテゴリ =4:Complex //int pcfp2_comp_feature_id; // = 本体(親) 地物ID //int pcfp2_feature_number; // 何番目の部品かを表す //int pcfp2_feature_category_num; // 部品(子)地物カテゴリ =2:Line int pcfp2_feature_id; // 部品(子)地物ID // pf_line_feature - Lighting Lamp //int plf2_feat_category_num; // 地物カテゴリ =2:Line //int plf2_feature_id; // 地物ID (キー) //DmpFtrClass_e plf2_feature_class_code; // 地物クラス ='8241' //int plf2_end_elevation; //int plf2_from_feat_category; //int plf2_from_feat_id; //int plf2_to_feat_category; //int plf2_to_feat_id; // pf_line_topo_prim - Lighting Lamp //int pltp2_feat_category_num; // 地物カテゴリ =2:Line //int pltp2_feature_id; // 地物ID (キー) //int pltp2_sequence_number; // 複数edgeがある場合用 =1 int pltp2_edge_id; // st_edgeへの参照キー //int pltp2_edge_orientation; // 0:CW,1:CCW =0 //int pltp2_start_elevation; // 標高 //int pltp2_intermitted_elevation; // 標高 // st_edge - Lighting Lamp //int se2_edge_id; // ID //int se2_start_node; // 始点node_id //int se2_end_node; // 終点node_id //int se2_next_left_edge; // 隣接する左エッジID //int se2_next_right_edge; // 隣接する右エッジID //int se2_left_face; // 左面ID //int se2_right_face; // 右面ID VcDmpPoint_t se2_geometry; // 点の系列 //○pf_comp_feat_part - Pole //int pcfp3_comp_feat_category; // = 本体(親)地物カテゴリ =4:Complex //int pcfp3_comp_feature_id; // = 本体(親) 地物ID //int pcfp3_feature_number; // 何番目の部品かを表す //int pcfp3_feature_category_num; // 部品(子)地物カテゴリ =1:Point int pcfp3_feature_id; // 部品(子)地物ID // pf_point_feature - Pole //int ppf3_feat_category_num; // 地物カテゴリ =1:Point //int ppf3_feature_id; // 地物ID (キー) //DmpFtrClass_e ppf3_feature_class_code; // 地物クラス ='8210' int ppf3_node_id; // st_nodeへの参照キー // st_node - Pole StDmpPoint_t sn3_geometry; // 座標情報 // attribute - Pole double dA3_DA; // Diameter double dA3_LM; // Measured Length double dA3_PN; // pitch angle double dA3_YN; // yaw angle // attribute } StDmpExtendedLighting_t; // map<feature_id, struct> typedef std::map<int, StDmpExtendedLighting_t> MpDmpExtendedLighting_t; //●[FA8251]路面マーク模様(RoadMarkingsShape)定義 typedef struct { // pf_area_feature //int feat_category_num; // 地物カテゴリ =3:Area int feature_id; // 地物ID //DmpFtrClass_e feature_class_code; // 地物クラス ='8251' // pf_area_topo_prim //int patp_feat_category_num; // 地物カテゴリ =3:Area //int patp_feature_id; // 地物ID int patp_face_id; // st_faceへの参照キー // st_face VcDmpPoint_t sf_mbr; // 領域を表す多角形 // attribute } StDmpRoadMarkingsShape_t; typedef std::vector<StDmpRoadMarkingsShape_t> VcDmpRoadMarkingsShape_t; //●[FC8250]路面マーク(ExtendedRoadMarkings)定義 typedef struct { // pf_comp_feature //int feat_category_num; // 地物カテゴリ =4:Complex int feature_id; // 地物ID (キー) //DmpFtrClass_e feature_class_code; // 地物クラス ='8250' //int from_feat_category; // この地物を構成する最初の地物カテゴリ =1:Point //int from_feature_id; // この地物を構成する最初の地物ID //int to_feat_category; // この地物を構成する最後の地物カテゴリ =3:Area //int to_feature_id; // この地物を構成する最後の地物ID //○pf_comp_feat_part - RoadMarkings //int pcfp1_comp_feat_category; // = 本体(親)地物カテゴリ =4:Complex //int pcfp1_comp_feature_id; // = 本体(親) 地物ID //int pcfp1_feature_number; // 何番目の部品かを表す //int pcfp1_feature_category_num; // 部品(子)地物カテゴリ =1:Point int pcfp1_feature_id; // 部品(子)地物ID // pf_point_feature - RoadMarkings //int ppf1_feat_category_num; // 地物カテゴリ =1:Point //int ppf1_feature_id; // 地物ID (キー) //DmpFtrClass_e ppf1_feature_class_code; // 地物クラス ='7254' int ppf1_node_id; // st_nodeへの参照キー // st_node - RoadMarkings StDmpPoint_t sn1_geometry; // 座標情報 //○pf_comp_feat_part以下 - RoadMarkingsShape VcDmpRoadMarkingsShape_t mVcDmpRoadMarkingsShape; // [FA8251]路面マーク模様 // attribute } StDmpExtendedRoadMarkings_t; // map<feature_id, struct> typedef std::map<int, StDmpExtendedRoadMarkings_t> MpDmpExtendedRoadMarkings_t; //●[FL8260]停止線(StopLine)定義 typedef struct { // pf_line_feature //int feat_category_num; // 地物カテゴリ =2:Line int feature_id; // 地物ID (キー) //DmpFtrClass_e feature_class_code; // 地物クラス ='8260' //int end_elevation; //int from_feat_category; //int from_feat_id; //int to_feat_category; //int to_feat_id; // pf_line_topo_prim //int feat_category_num; // 地物カテゴリ =2:Line //int feature_id; // 地物ID (キー) //int pltp_sequence_number; // 複数edgeがある場合用 =1 int pltp_edge_id; // st_edgeへの参照キー //int pltp_edge_orientation; // 0:CW,1:CCW =0 //int pltp_start_elevation; // 標高 //int pltp_intermitted_elevation; // 標高 // st_edge //int se_edge_id; // ID //int se_start_node; // 始点node_id //int se_end_node; // 終点node_id //int se_next_left_edge; // 隣接する左エッジID //int se_next_right_edge; // 隣接する右エッジID //int se_left_face; // 左面ID //int se_right_face; // 右面ID VcDmpPoint_t se_geometry; // 点の系列 // attribute } StDmpStopLine_t; // map<feature_id, struct> typedef std::map<int, StDmpStopLine_t> MpDmpStopLine_t; //●[FL8310]道路縁(RoadEdge)定義 typedef struct { // pf_line_feature //int feat_category_num; // 地物カテゴリ =2:Line int feature_id; // 地物ID (キー) //DmpFtrClass_e feature_class_code; // 地物クラス ='8310' //int end_elevation; //int from_feat_category; //int from_feat_id; //int to_feat_category; //int to_feat_id; // pf_line_topo_prim //int feat_category_num; // 地物カテゴリ =2:Line //int feature_id; // 地物ID (キー) //int pltp_sequence_number; // 複数edgeがある場合用 =1 int pltp_edge_id; // st_edgeへの参照キー //int pltp_edge_orientation; // 0:CW,1:CCW =0 //int pltp_start_elevation; // 標高 //int pltp_intermitted_elevation; // 標高 // st_edge //int se_edge_id; // ID //int se_start_node; // 始点node_id //int se_end_node; // 終点node_id //int se_next_left_edge; // 隣接する左エッジID //int se_next_right_edge; // 隣接する右エッジID //int se_left_face; // 左面ID //int se_right_face; // 右面ID VcDmpPoint_t se_geometry; // 点の系列 // attribute } StDmpRoadEdge_t; // map<feature_id, struct> typedef std::map<int, StDmpRoadEdge_t> MpDmpRoadEdge_t; //●[FL8311]縁石(Curb)定義 typedef struct { // pf_line_feature //int feat_category_num; // 地物カテゴリ =2:Line int feature_id; // 地物ID (キー) //DmpFtrClass_e feature_class_code; // 地物クラス ='8311' //int end_elevation; //int from_feat_category; //int from_feat_id; //int to_feat_category; //int to_feat_id; // pf_line_topo_prim //int feat_category_num; // 地物カテゴリ =2:Line //int feature_id; // 地物ID (キー) //int pltp_sequence_number; // 複数edgeがある場合用 =1 int pltp_edge_id; // st_edgeへの参照キー //int pltp_edge_orientation; // 0:CW,1:CCW =0 //int pltp_start_elevation; // 標高 //int pltp_intermitted_elevation; // 標高 // st_edge //int se_edge_id; // ID //int se_start_node; // 始点node_id //int se_end_node; // 終点node_id //int se_next_left_edge; // 隣接する左エッジID //int se_next_right_edge; // 隣接する右エッジID //int se_left_face; // 左面ID //int se_right_face; // 右面ID VcDmpPoint_t se_geometry; // 点の系列 // attribute double dA_HT; // Height double dA_WI; // Width } StDmpCurb_t; // map<feature_id, struct> typedef std::map<int, StDmpCurb_t> MpDmpCurb_t; //●[FA8312]側溝(Gutter)定義 typedef struct { // pf_area_feature //int feat_category_num; // 地物カテゴリ =3:Area int feature_id; // 地物ID //DmpFtrClass_e feature_class_code; // 地物クラス ='8312' // pf_area_topo_prim //int patp_feat_category_num; // 地物カテゴリ =3:Area //int patp_feature_id; // 地物ID int patp_face_id; // st_faceへの参照キー // st_face VcDmpPoint_t sf_mbr; // 領域を表す多角形 // attribute int iA_GU; // Gutter type } StDmpGutter_t; // map<feature_id, struct> typedef std::map<int, StDmpGutter_t> MpDmpGutter_t; //●[FA8313]ガードレール(GuardRail)定義 typedef struct { // pf_area_feature //int feat_category_num; // 地物カテゴリ =3:Area int feature_id; // 地物ID //DmpFtrClass_e feature_class_code; // 地物クラス ='8313' // pf_area_topo_prim //int patp_feat_category_num; // 地物カテゴリ =3:Area //int patp_feature_id; // 地物ID int patp_face_id; // st_faceへの参照キー // st_face VcDmpPoint_t sf_mbr; // 領域を表す多角形 // attribute int iA_GR; // Guard Rail type } StDmpGuardRail_t; // map<feature_id, struct> typedef std::map<int, StDmpGuardRail_t> MpDmpGuardRail_t; //●[FA8314]ゼブラゾーン(ZebraZone)定義 typedef struct { // pf_area_feature //int feat_category_num; // 地物カテゴリ =3:Area int feature_id; // 地物ID //DmpFtrClass_e feature_class_code; // 地物クラス ='8314' // pf_area_topo_prim //int patp_feat_category_num; // 地物カテゴリ =3:Area //int patp_feature_id; // 地物ID int patp_face_id; // st_faceへの参照キー // st_face VcDmpPoint_t sf_mbr; // 領域を表す多角形 // attribute } StDmpZebraZone_t; // map<feature_id, struct> typedef std::map<int, StDmpZebraZone_t> MpDmpZebraZone_t; //----------------------------- // 関連データ再構築バッファ定義 //----------------------------- typedef struct { int role_number; int feat_category_num; int feature_id; } StDmpRebRelationshipFeat_t; typedef std::vector<StDmpRebRelationshipFeat_t> VcDmpRebRelationshipFeat_t; typedef struct { int relationship_id; DmpRelType_e rel_type; VcDmpRebRelationshipFeat_t mVcDmpRebRelationshipFeat; } StDmpRebRelationship_t; typedef std::vector<StDmpRebRelationship_t> VcDmpRebRelationship_t; #endif // _DMP_DATA_H_
// orthelloGame.cpp : 此檔案包含 'main' 函式。程式會於該處開始執行及結束執行。 // #include "pch.h" #include <iostream> #include <fstream> #include <string> #include <sstream> #include <vector> #include <iomanip> #include <windows.h> #include <wchar.h> using namespace std; //---------------------------------------------------- struct team { int who; int A[8][8]; }; struct point { int x; int y; }; //----------------------------------------------------- class filetool { public: static void checkupload() { system("dir .\\1082_IC192_A_ID_8 >list.txt"); string tmp; ifstream file; file.open("list.txt"); const int N = 1024; char aaa[N]; int i; for (i = 0; i < 7; i++) file.getline(aaa, N); for (i = 0; i < 57; i++) { file.getline(aaa, N); tmp = aaa; size_t n = tmp.find("<DIR>"); tmp = tmp.substr(n + 15); size_t m = tmp.find("_"); if (tmp.compare(m + 1, tmp.length() - 1, "0") == 0) continue; //tmp = tmp.substr(0, m); cout << tmp << endl; } file.close(); } }; //----------------------------------------------------- class Player { private: int order; string id; string name; HINSTANCE hDLL; struct point(*battle)(struct team t); static std::wstring charToWString(const char* text) { const size_t size = std::strlen(text); const size_t size2 = 64; size_t ReturnValue; wchar_t wcstr[64]; wstring wstr; if (size > 0) { wstr.resize(size); mbstowcs_s(&ReturnValue, wcstr, size2, text, size); wstr = wcstr; } return wstr; } public: Player() { hDLL = NULL; battle = NULL; order = 0; } ~Player() { detatchDLL(); } string getId() { return id; } wstring dllFileName() { wstring filename; filename = L"yzu"; wstring wname = charToWString(id.c_str()); filename.append(wname); filename.append(L".dll"); return filename; } bool attachDLL() { wstring file; file = dllFileName(); hDLL = LoadLibrary(file.c_str()); if (hDLL) { (FARPROC&)battle = GetProcAddress(hDLL, "play"); if (NULL == battle) { cout << "get fail" << endl; return false; } else return true; } else { cout << "load fail:" << id << endl; return false; } } bool detatchDLL() { if (hDLL) { FreeLibrary(hDLL); return true; } else return false; } bool hasDLL() { if (hDLL == NULL) return false; else return true; } //------------------------------------- struct point go(struct team t) { return battle(t); } friend istream& operator>>(istream& is, Player& player) { is >> player.order; is >> player.id; is >> player.name; return is; } friend ostream& operator<<(ostream& os, Player& player) { os << player.order; os << player.id; os << player.name; return os; } }; //----------------------------------------------------- class RecordTable { private: vector<vector<int>> record; public: void init(int amountPlayer) { record.resize(amountPlayer); int i; for (i = 0; i < amountPlayer; i++) record[i].resize(amountPlayer); reset(); } void reset() { int i, j; size_t N = record.size(); for (i = 0; i < N; i++) for (j = 0; j < N; j++) record[i][j] = 0; } void set(int m, int n, int status) { record[m][n] = status; } void setlose(int m, int n) { record[m][n]--; } int get(int m, int n) { return record[m][n]; } //----------------------------------------------------- friend ostream& operator<<(ostream& os, RecordTable& recordtable) { int i, j; size_t N; N = recordtable.record.size(); for (i = 0; i < N; i++) { for (j = 0; j < N; j++) os << setw(4) << recordtable.record[i][j]; os << endl; } return os; } }; //----------------------------------------------------- struct threaddata { struct team* t; struct point p; Player* player; }; DWORD WINAPI thread(LPVOID data) { cout << "ttt" << (((threaddata*)data)->t)->who << endl; (((struct threaddata*)data)->p) = ((struct threaddata*)data)->player->go(*(((threaddata*)data)->t)); return 0; } class Game { private: int amountPlayer; vector<Player> list; RecordTable recordTable; struct team t; void init(struct team& t) { int i, j; for (i = 0; i < 8; i++) for (j = 0; j < 8; j++) t.A[i][j] = 0; t.A[3][3] = 1; t.A[4][4] = 1; t.A[3][4] = 2; t.A[4][3] = 2; t.who = 1; } void showTable(struct team& t) { int i, j; for (i = 0; i < 8; i++) { for (j = 0; j < 8; j++) cout << setw(2) << t.A[i][j]; cout << endl; } } void setPlayPosition(struct point p) { t.A[p.x][p.y] = t.who; static struct point delta[] = { {1,0},{-1,0},{0,-1},{0,1},{-1,-1},{1,1},{-1,1},{1,-1} }; int i; struct point current; for (i = 0; i < 8; i++) { current = p; current.x += delta[i].x; current.y += delta[i].y; t.A[current.x][current.y] = t.who; /* while ((t.A[current.x][current.y] != t.who) && current.x >= 0 && current.x < 8 && current.y >= 0 || current.y < 8 ) { t.A[current.x][current.y] = t.who; current.x += delta[i].x; current.y += delta[i].y; } */ } } bool checkValid(struct point p) { return true; static struct point delta[] = { {1,0},{-1,0},{0,-1},{0,1},{-1,-1},{1,1},{-1,1},{1,-1} }; bool ret = false; if (t.A[p.x][p.y] == 0) { for (int i = 0; i < 8; i++) if (t.A[p.x + delta[i].x][p.y + delta[i].y] != t.who) ret = true; return ret; } else return false; } bool checkwin(struct point p) { static int debug = 0; debug++; if (debug > 64) return true; int i, j; for (i = 0; i < 8; i++) for (j = 0; j < 8; j++) if (t.A[i][j] == 0) return false; return true; } bool playRound(int m, int n) { bool result = true; int pp[2]; pp[0] = m; pp[1] = n; init(t); HANDLE hThread; struct threaddata d; d.t = &t; string teamname = list[pp[0]].getId(); teamname.append("vs"); teamname.append(list[pp[1]].getId()); cout << teamname << endl; cout << "---------------------------" << endl; bool ret = true; while (result) { //---- 以下請檢查邏輯 ---- d.player = &(list[pp[t.who - 1]]); hThread = CreateThread(NULL, 0, thread, &d, 0, NULL); if (WAIT_TIMEOUT == WaitForSingleObject(hThread, 10000)) { recordTable.setlose(pp[(t.who ^ 3) - 1], pp[(t.who) - 1]); ret = false; cout << "time out" << endl; break; } cout << "player" << d.player->getId() << ":" << d.p.x << "," << d.p.y << endl; if (checkValid(d.p)) { setPlayPosition(d.p); } else { recordTable.setlose(pp[t.who - 1], pp[(t.who ^ 3) - 1]); ret = false; break; } if (checkwin(d.p)) { int aa = (t.who ^ 3) - 1; int bb = (t.who) - 1; recordTable.setlose(pp[aa], pp[bb]); break; } t.who ^= 3; showTable(t); cout << endl; ofstream file; file.open(teamname + ".txt", std::ios_base::app); file << d.p.x << " " << d.p.y << endl; file.close(); } return ret; } public: Game() { amountPlayer = 0; } void loadGameTable(string filename) { ifstream file; file.open(filename); file >> amountPlayer; recordTable.init(amountPlayer); list.resize(amountPlayer); int i; for (i = 0; i < amountPlayer; i++) file >> list[i]; file.close(); //---------- debug ------- for (i = 0; i < amountPlayer; i++) cout << list[i] << endl; } void playAll() { int i; int j; for (i = 0; i < amountPlayer; i++) { if (!list[i].attachDLL()) recordTable.set(i, i, -1); } for (i = 0; i < amountPlayer; i++) for (j = 0; j < amountPlayer; j++) if (i != j && recordTable.get(i, i) != -1 && recordTable.get(j, j) != -1) { playRound(i, j); } cout << recordTable << endl; ofstream recordfile; TCHAR buf[64]; wsprintf(buf, L"recordTable%d.csv", time(0)); recordfile.open(buf); recordfile << recordTable; recordfile.close(); for (i = 0; i < amountPlayer; i++) list[i].detatchDLL(); } }; class App { public: void run() { Game game; game.loadGameTable("playerlist.txt"); game.playAll(); } }; int main() { //filetool::checkupload(); App app; app.run(); return 1; }
#include "timingMode.h" #include <chrono> namespace lab { using namespace std::chrono_literals; constexpr std::chrono::nanoseconds timestep(16ms); event<void(std::chrono::steady_clock::time_point&)> evt_timing_update; void TimingMode::update(lab::GraphicsRootWindow&) { using clock = std::chrono::high_resolution_clock; static auto time_start = clock::now(); static std::chrono::nanoseconds lag(0ns); auto delta_time = clock::now() - time_start; time_start = clock::now(); lag += std::chrono::duration_cast<std::chrono::nanoseconds>(delta_time); while (lag >= timestep) { lag -= timestep; evt_timing_update(time_start); time_start += timestep; } // calculate residual fraction //auto alpha = (float) lag.count / timestep.count; } } // lab
#include <iostream> using namespace std; int a[10010]; bool sumNum(int sum, int i, int k, int n) { if (sum == k) return true; if (i == n) return false; return sumNum(sum + a[i], i + 1, k, n) || sumNum(sum, i + 1, k, n); } int main() { int n; cin >> n; for (int i = 0; i < n; i++) cin >> a[i]; int k; cin >> k; cout << (sumNum(0, 0, k, n) ? "Yes" : "No") << endl; return 0; }
#include <bits/stdc++.h> #include <fstream> #include<string> #define M 5 #define N 7 //#define MAX 5 using namespace std; int coordinate; vector<int> final_x, final_y; // Function returns true if the // move taken is valid else // it will return false. int isSafe(int x, int y, char arr[M][N], bool visited[M][N]){ return (x >= 0 && x < M && y >= 0 && y < N && visited[x][y] == false && arr[x][y] == '.'); } int isAvailable(int x, int y, char arr[M][N], bool visited[M][N]){ return (isSafe(x+1, y, arr, visited) || isSafe(x-1, y, arr, visited) || isSafe(x, y+1, arr, visited) || isSafe(x, y-1, arr, visited)); } // Function to print all the possible // paths from (0, 0) to (n-1, n-1). void printPathUtil(int row, int col, char arr[M][N], int n, string& path, vector<string>& possiblePaths, bool visited[M][N]){ if(isSafe(row , col, arr, visited)){ if(!isAvailable(row, col, arr, visited)){ possiblePaths.push_back(path); final_x.push_back(row); final_y.push_back(col); return; } // Mark the cell as visited visited[row][col] = true; // Try for all the 4 directions (down, left, // right, up) in the given order to get the // paths in lexicographical order // Check if downward move is valid if (isSafe(row + 1, col, arr, visited)) { path.push_back('D'); printPathUtil(row + 1, col, arr, n, path, possiblePaths, visited); path.pop_back(); } // Check if the left move is valid if (isSafe(row, col - 1, arr, visited)) { path.push_back('L'); printPathUtil(row, col - 1, arr, n, path, possiblePaths, visited); path.pop_back(); } // Check if the right move is valid if (isSafe(row, col + 1, arr, visited)) { path.push_back('R'); printPathUtil(row, col + 1, arr, n, path, possiblePaths, visited); path.pop_back(); } // Check if the upper move is valid if (isSafe(row - 1, col, arr, visited)) { path.push_back('U'); printPathUtil(row - 1, col, arr, n, path, possiblePaths, visited); path.pop_back(); } // Mark the cell as unvisited for // other possible paths visited[row][col] = false; } } void replace(int pos, int size, char arr[M][N], int n, vector<int> final_x,vector<int> final_y, vector<string>& possiblePaths, string new_arr[M][N]){ int x = final_x[pos]; int y = final_y[pos]; string c; for(int i = size;i>=0;i--){ c = to_string(i); new_arr[x][y] = c; if(possiblePaths[pos][i-1] == 'D'){ x--; } else if(possiblePaths[pos][i-1] == 'L'){ y++; } else if(possiblePaths[pos][i-1] == 'R'){ y--; } else if(possiblePaths[pos][i-1] == 'U'){ x++; } } } // Function to store and print // all the valid paths void printPath(char arr[M][N], int n) { // vector to store all the possible paths int max_len = 0, pos = 0; int size = 0; int i = 0,j = 0; vector<string> possiblePaths; string path; string new_arr[M][N]; for(i = 0;i<M;i++){ for(j = 0;j<N;j++){ new_arr[i][j] = arr[i][j]; } } //string line; bool visited[M][N]; memset(visited, false, sizeof(visited)); // Call the utility function to // find the valid paths for(i = 0;i<M;i++){ for(j = 0;j<N;j++){ printPathUtil(i, j, arr, n, path, possiblePaths, visited); } } // Print all possible paths for (int i = 0; i < possiblePaths.size(); i++){ //cout << possiblePaths[i] << " " << possiblePaths[i].size() << " "; //cout << final_x[i] << final_y[i] << endl; if(possiblePaths[i].size() > max_len){ max_len = possiblePaths[i].size(); pos = i; } } size = possiblePaths[pos].size(); replace(pos,size, arr, n, final_x, final_y, possiblePaths, new_arr); cout << "Input" << endl ; for(i = 0;i<M;i++){ for(j = 0;j<N;j++){ cout << arr[i][j] << " "; } cout << endl; } cout << endl << "Output" << endl; for(i = 0;i<M;i++){ for(j = 0;j<N;j++){ cout << new_arr[i][j] << " "; } cout << endl; } } // Driver code int main() { int i=0,j = 0; char arr[M][N]; char ch; fstream fin("ip1.txt", fstream::in); while (fin >> noskipws >> ch) { if(ch != '\n'){ arr[i][j] = ch; j++; } else if(ch == '\n'){ //N = j; i++; j = 0; } } int n = sizeof(arr) / sizeof(arr[0]); printPath(arr, n); return 0; }
#include "SwirlDeformer.h" #include <maya/MItGeometry.h> #include <maya/MPoint.h> #define _USE_MATH_DEFINES #include <math.h> #include <maya/MFnUnitAttribute.h> #include <maya/MDistance.h> MTypeId SwirlDeformer::typeId(0x0033A); MString SwirlDeformer::typeName("swirl"); MObject SwirlDeformer::startDist; MObject SwirlDeformer::endDist; MStatus SwirlDeformer::initialize() { MFnUnitAttribute unitFn; startDist = unitFn.create("startDist", "sd", MFnUnitAttribute::kDistance); unitFn.setDefault(MDistance(0.0, MDistance::uiUnit())); unitFn.setMin(MDistance(0.0, MDistance::uiUnit())); unitFn.setKeyable(true); endDist = unitFn.create("endDist", "ed", MFnUnitAttribute::kDistance); unitFn.setDefault(MDistance(3.0, MDistance::uiUnit())); unitFn.setMin(MDistance(0.0, MDistance::uiUnit())); unitFn.setKeyable(true); addAttribute(startDist); addAttribute(endDist); attributeAffects(startDist, outputGeom); attributeAffects(endDist, outputGeom); return MS::kSuccess; } MStatus SwirlDeformer::deform(MDataBlock &data, MItGeometry &iter, const MMatrix &localToWorld, unsigned int geomIndex) { MStatus stat; MDataHandle envData = data.inputValue(envelope); float env = envData.asFloat(); if (env == 0.0) { return MS::kSuccess; } MDataHandle startDistHnd = data.inputValue(startDist); double startDist = startDistHnd.asDouble(); MDataHandle endDistHnd = data.inputValue(endDist); double endDist = endDistHnd.asDouble(); float weight; MPoint pt; double dist; double distFactor; double ang; double cosAng, sinAng; double x; for (iter.reset(); !iter.isDone(); iter.next()) { weight = weightValue(data, geomIndex, iter.index()); if (weight == 0.0) { continue; } pt = iter.position(); dist = sqrt(pt.x * pt.x + pt.z * pt.z); if (dist < startDist || dist > endDist) { continue; } distFactor = 1 - ((dist - startDist) / (endDist - startDist)); ang = distFactor * M_PI * 2.0 * env * weight; if (ang == 0.0) {; continue; } cosAng = cos(ang); sinAng = sin(ang); x = pt.x * cosAng - pt.z * sinAng; pt.z = pt.x * sinAng + pt.z * cosAng; pt.x = x; iter.setPosition(pt); } return stat; }
/* -*- Mode: c++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2; -*- * * Copyright (C) Opera Software ASA 2002 - 2012 */ #include "core/pch.h" #include "modules/ecmascript/carakan/src/es_pch.h" #include "modules/ecmascript/carakan/src/compiler/es_parser.h" #include "modules/ecmascript/carakan/src/compiler/es_compiler_expr.h" #include "modules/ecmascript/carakan/src/compiler/es_parser_inlines.h" #ifdef _DEBUG static bool DebugFalse() { return false; } #define DEBUG_FALSE DebugFalse() #else // _DEBUG #define DEBUG_FALSE false #endif // _DEBUG #define PARSE_FAILED(code) do { automatic_error_code = code; return FALSE; } while (0) static JString * ValueAsString (ES_Context *context, ES_Value_Internal &value) { if (value.IsString ()) return value.GetString (); else if (value.IsNumber ()) return tostring (context, value.GetNumAsDouble ()); else if (value.IsBoolean ()) return value.GetBoolean () ? context->rt_data->strings[STRING_true] : context->rt_data->strings[STRING_false]; else if (value.IsNull ()) return context->rt_data->strings[STRING_null]; else return context->rt_data->strings[STRING_undefined]; } #ifdef USE_CUSTOM_DOUBLE_OPS # define ADD_DOUBLES(a, b) AddDoubles(a, b) # define SUB_DOUBLES(a, b) SubtractDoubles(a, b) # define MUL_DOUBLES(a, b) MultiplyDoubles(a, b) # define DIV_DOUBLES(a, b) DivideDoubles(a, b) #else // USE_CUSTOM_DOUBLE_OPS # define ADD_DOUBLES(a, b) ((a) + (b)) # define SUB_DOUBLES(a, b) ((a) - (b)) # define MUL_DOUBLES(a, b) ((a) * (b)) # define DIV_DOUBLES(a, b) ((a) / (b)) #endif // USE_CUSTOM_DOUBLE_OPS bool ES_Parser::EvaluateConstantBinaryExpression (unsigned type, ES_Expression *left, ES_Expression *right) { if (left->GetType () == ES_Expression::TYPE_LITERAL && right->GetType () == ES_Expression::TYPE_LITERAL) { ES_Value_Internal vleft = static_cast<ES_LiteralExpr *> (left)->GetValue (); ES_Value_Internal vright = static_cast<ES_LiteralExpr *> (right)->GetValue (); if (type >= ES_Expression::TYPE_SHIFT_LEFT && type <= ES_Expression::TYPE_SHIFT_SIGNED_RIGHT || type >= ES_Expression::TYPE_BITWISE_AND && type <= ES_Expression::TYPE_BITWISE_OR) { int ileft = vleft.AsNumber (context).GetNumAsInt32 (); int iright = vright.AsNumber (context).GetNumAsInt32 (); int result; switch (type) { case ES_Expression::TYPE_SHIFT_LEFT: result = ileft << (iright & 31); break; case ES_Expression::TYPE_SHIFT_SIGNED_RIGHT: result = ileft >> (iright & 31); break; case ES_Expression::TYPE_BITWISE_AND: result = ileft & iright; break; case ES_Expression::TYPE_BITWISE_XOR: result = ileft ^ iright; break; case ES_Expression::TYPE_BITWISE_OR: result = ileft | iright; break; default: OP_ASSERT(FALSE); result = 0; } PushExpression (OP_NEWGRO_L (ES_LiteralExpr, (result), Arena ())); return true; } else if (type == ES_Expression::TYPE_SHIFT_UNSIGNED_RIGHT) { ES_Value_Internal result; result.SetUInt32 (vleft.AsNumber (context).GetNumAsUInt32 () >> (vright.AsNumber (context).GetNumAsUInt32 () & 31u)); PushExpression (OP_NEWGRO_L (ES_LiteralExpr, (result), Arena ())); return true; } else if (type >= ES_Expression::TYPE_MULTIPLY && type <= ES_Expression::TYPE_SUBTRACT) { numeric: double dleft = vleft.AsNumber (context).GetNumAsDouble (); double dright = vright.AsNumber (context).GetNumAsDouble (); double result; switch (type) { case ES_Expression::TYPE_MULTIPLY: result = MUL_DOUBLES (dleft, dright); break; case ES_Expression::TYPE_DIVIDE: result = DIV_DOUBLES (dleft, dright); break; case ES_Expression::TYPE_REMAINDER: if (op_isnan (dleft) || op_isnan (dright) || op_isinf (dleft) || dright == 0) result = op_nan (NULL); else if (dleft == 0 || op_isinf (dright)) result = dleft; else result = op_fmod (dleft, dright); break; case ES_Expression::TYPE_SUBTRACT: result = SUB_DOUBLES (dleft, dright); break; case ES_Expression::TYPE_ADD: result = ADD_DOUBLES (dleft, dright); break; default: OP_ASSERT(FALSE); result = 0; } PushExpression (OP_NEWGRO_L (ES_LiteralExpr, (result), Arena ())); return true; } else if (type == ES_Expression::TYPE_ADD) if (vleft.IsString() || vright.IsString()) { JString *sleft = ValueAsString (context, vleft); JString *sright = ValueAsString (context, vright); JString *result; if (Length (sleft) == 0) result = sright; else if (Length (sright) == 0) result = sleft; else { result = Share (context, sleft); Append (context, result, sright); } PushExpression (OP_NEWGRO_L (ES_LiteralExpr, (result), Arena ())); return true; } else goto numeric; } if (left->GetType () == ES_Expression::TYPE_LITERAL && (type == ES_Expression::TYPE_LOGICAL_OR || type == ES_Expression::TYPE_LOGICAL_AND)) { if (static_cast<ES_LiteralExpr *> (left)->GetValue ().AsBoolean ().GetBoolean () ? type == ES_Expression::TYPE_LOGICAL_OR : type == ES_Expression::TYPE_LOGICAL_AND) PushExpression (left); else PushExpression (right); return true; } return false; } static ES_LogicalExpr * MakeLogicalExpr (unsigned type, ES_Expression *left, ES_Expression *right, OpMemGroup *arena) { if (right->GetType() == static_cast<ES_Expression::Type> (type)) { left = MakeLogicalExpr (type, left, static_cast<ES_LogicalExpr *> (right)->GetLeft (), arena); right = static_cast<ES_LogicalExpr *> (right)->GetRight (); } return OP_NEWGRO_L (ES_LogicalExpr, (static_cast<ES_LogicalExpr::Type> (type), left, right), arena); } bool ES_Parser::ParseLogicalExpr (unsigned &depth, unsigned rhs_production, bool allow_in, unsigned type) { ES_Expression *left; ES_Expression *right; if (!ParseExpression (depth, rhs_production, allow_in, expression_stack_used)) return DEBUG_FALSE; right = PopExpression (); left = PopExpression (); if (in_typeof || !EvaluateConstantBinaryExpression (type, left, right)) PushExpression (MakeLogicalExpr (type, left, right, Arena ())); else if (!in_typeof) depth--; return true; } bool ES_Parser::ParseBitwiseExpr (unsigned &depth, unsigned rhs_production, bool allow_in, unsigned type) { ES_Expression *left; ES_Expression *right; if (!ParseExpression (depth, rhs_production, allow_in, expression_stack_used)) return DEBUG_FALSE; right = PopExpression (); left = PopExpression (); if (!EvaluateConstantBinaryExpression (type, left, right)) { /* Convert literal operands into int32, since we expect int32 operands and would otherwise just convert them runtime every time the expression is evaluated. */ if (left->GetType () == ES_Expression::TYPE_LITERAL && left->GetValueType () != ESTYPE_INT32) static_cast<ES_LiteralExpr *> (left)->GetValue ().SetInt32 (static_cast<ES_LiteralExpr *> (left)->GetValue ().AsNumber (context).GetNumAsInt32 ()); if (right->GetType () == ES_Expression::TYPE_LITERAL && right->GetValueType () != ESTYPE_INT32) static_cast<ES_LiteralExpr *> (right)->GetValue ().SetInt32 (static_cast<ES_LiteralExpr *> (right)->GetValue ().AsNumber (context).GetNumAsInt32 ()); PushExpression (OP_NEWGRO_L (ES_BitwiseExpr, (static_cast<ES_Expression::Type> (type), left, right), Arena ())); } else depth--; return true; } #define STORE_TOKEN_START() \ unsigned index = last_token.start; \ unsigned line = last_token.line; #define LOCATION() , ES_SourceLocation(index, line, last_token.end - index) #define LOCATION_FROM(expr) , ES_SourceLocation (expr->GetSourceLocation ().Index (), expr->GetSourceLocation ().Line (), last_token.end - expr->GetSourceLocation ().Index ()) bool ES_Parser::ParseAccessor (AccessorType type, JString *name, unsigned check_count, unsigned index, unsigned line, unsigned column) { #ifdef ES_LEXER_SOURCE_LOCATION_SUPPORT ES_SourceLocation name_location = last_token.GetSourceLocation(); # define NAME_LOCATION , name_location #else // ES_LEXER_SOURCE_LOCATION_SUPPORT # define NAME_LOCATION #endif // ES_LEXER_SOURCE_LOCATION_SUPPORT unsigned identifiers_before = identifier_stack_used; unsigned functions_before = function_stack_used; unsigned function_data_before = function_data_stack_used; unsigned statements_before = statement_stack_used; unsigned old_function_data_index = function_data_index; ES_SourceLocation start_location, end_location; function_data_index = 0; in_function++; if (!ParsePunctuator (ES_Token::LEFT_PAREN) || type == ACCESSOR_SET && !ParseFormalParameterList () || !ParsePunctuator (ES_Token::RIGHT_PAREN) || !ParseSourceElements (true, &start_location) || !ParsePunctuator (ES_Token::RIGHT_BRACE, end_location)) return DEBUG_FALSE; in_function--; unsigned parameter_names_count = identifier_stack_used - identifiers_before; unsigned functions_count = function_stack_used - functions_before; unsigned function_data_count = function_data_stack_used - function_data_before; unsigned statements_count = statement_stack_used - statements_before; function_data_index = old_function_data_index; is_simple_eval = FALSE; if (!CompileFunction (NULL, parameter_names_count, es_maxu (functions_count, function_data_count), statements_count, index, line, column, last_token.end, start_location, end_location, NULL, true)) return DEBUG_FALSE; if (in_function || is_strict_eval) { if (!PushProperty (check_count, name NAME_LOCATION, OP_NEWGRO_L (ES_FunctionExpr, (function_data_index - 1), Arena ()), type == ACCESSOR_GET, type == ACCESSOR_SET)) return DEBUG_FALSE; } else { if (!PushProperty (check_count, name NAME_LOCATION, OP_NEWGRO_L (ES_FunctionExpr, (function_stack[function_stack_used - 1]), Arena ()), type == ACCESSOR_GET, type == ACCESSOR_SET)) return DEBUG_FALSE; } #undef NAME_LOCATION return true; } bool ES_Parser::ParseExpression (unsigned depth, unsigned production, bool allow_in, unsigned expr_stack_base, bool opt) { recurse: if (++depth > ES_MAXIMUM_SYNTAX_TREE_DEPTH) PARSE_FAILED(INPUT_TOO_COMPLEX); unsigned expression_stack_length = expression_stack_used - expr_stack_base; JString *identifier; ES_Value_Internal value; ES_Expression *left; ES_Expression *right; /* These are always allowed and always unambigious. */ if (expression_stack_length == 0) { if (ParseKeyword (ES_Token::KEYWORD_THIS)) { PushExpression (OP_NEWGRO_L (ES_ThisExpr, (), Arena ())); goto recurse; } if (ParseIdentifier (identifier)) { if (in_function && identifier == ident_arguments) uses_arguments = TRUE; else if (identifier == ident_eval) uses_eval = TRUE; PushExpression (OP_NEWGRO_L (ES_IdentifierExpr, (identifier), Arena ())); goto recurse; } bool regexp; if (ParseLiteral (value, regexp)) { if (regexp) { ES_Expression *expr = OP_NEWGRO_L (ES_RegExpLiteralExpr, (token.regexp, token.regexp_source), Arena ()); token.regexp = NULL; PushExpression (expr); } else PushExpression (OP_NEWGRO_L (ES_LiteralExpr, (value), Arena ())); goto recurse; } if (ParsePunctuator (ES_Token::LEFT_PAREN)) { if (!ParseExpression (depth, ES_Expression::PROD_EXPRESSION, true, expression_stack_used) || !ParsePunctuator (ES_Token::RIGHT_PAREN)) return DEBUG_FALSE; goto recurse; } } ES_Expression::Production p = static_cast<ES_Expression::Production>(production); if (expression_stack_length == 0 && p < ES_Expression::PROD_UNARY_EXPR) p = ES_Expression::PROD_UNARY_EXPR; if (!HandleLinebreak ()) return DEBUG_FALSE; switch (p) { case ES_Expression::PROD_EXPRESSION: if (ParsePunctuator (ES_Token::COMMA)) { do if (!ParseExpression (depth, ES_Expression::PROD_ASSIGNMENT_EXPR, allow_in, expression_stack_used)) return DEBUG_FALSE; while (ParsePunctuator (ES_Token::COMMA)); unsigned expressions_count = expression_stack_used - expr_stack_base; ES_Expression **expressions = PopExpressions (expressions_count); PushExpression (OP_NEWGRO_L (ES_CommaExpr, (expressions, expressions_count), Arena ())); goto recurse; } case ES_Expression::PROD_ASSIGNMENT_EXPR: if (token.type == ES_Token::PUNCTUATOR) { bool is_assign = true; bool is_compound_assign = true; bool is_binary_number = false; bool is_additive = false; bool is_shift = false; ES_Expression::Type type = ES_Expression::TYPE_THIS; switch (token.punctuator) { case ES_Token::ASSIGN: is_compound_assign = false; break; case ES_Token::ADD_ASSIGN: is_additive = true; break; case ES_Token::MULTIPLY_ASSIGN: is_binary_number = true; type = ES_BinaryNumberExpr::TYPE_MULTIPLY; break; case ES_Token::DIVIDE_ASSIGN: is_binary_number = true; type = ES_BinaryNumberExpr::TYPE_DIVIDE; break; case ES_Token::REMAINDER_ASSIGN: is_binary_number = true; type = ES_BinaryNumberExpr::TYPE_REMAINDER; break; case ES_Token::SUBTRACT_ASSIGN: is_binary_number = true; type = ES_BinaryNumberExpr::TYPE_SUBTRACT; break; case ES_Token::SHIFT_LEFT_ASSIGN: is_shift = true; type = ES_ShiftExpr::TYPE_SHIFT_LEFT; break; case ES_Token::SHIFT_SIGNED_RIGHT_ASSIGN: is_shift = true; type = ES_ShiftExpr::TYPE_SHIFT_SIGNED_RIGHT; break; case ES_Token::SHIFT_UNSIGNED_RIGHT_ASSIGN: is_shift = true; type = ES_ShiftExpr::TYPE_SHIFT_UNSIGNED_RIGHT; break; case ES_Token::BITWISE_AND_ASSIGN: type = ES_BitwiseExpr::TYPE_BITWISE_AND; break; case ES_Token::BITWISE_OR_ASSIGN: type = ES_BitwiseExpr::TYPE_BITWISE_OR; break; case ES_Token::BITWISE_XOR_ASSIGN: type = ES_BitwiseExpr::TYPE_BITWISE_XOR; break; default: is_assign = false; } if (is_assign) { ES_Expression *target; ES_Expression *source; ES_BinaryExpr *compound_source; if (!NextToken ()) return DEBUG_FALSE; target = PopExpression (); JString *name; if (target->IsIdentifier (name)) if (!ValidateIdentifier (name, &target->GetSourceLocation ())) return DEBUG_FALSE; JString *old_debug_name = current_debug_name; ES_Expression *old_debug_name_expr = current_debug_name_expr; current_debug_name = NULL; current_debug_name_expr = NULL; if (token.type == ES_Token::KEYWORD && token.keyword == ES_Token::KEYWORD_FUNCTION) if (target->GetType () == ES_Expression::TYPE_IDENTIFIER || target->GetType () == ES_Expression::TYPE_PROPERTY_REFERENCE) current_debug_name_expr = target; if (!ParseExpression (depth, ES_Expression::PROD_ASSIGNMENT_EXPR, allow_in, expression_stack_used)) return DEBUG_FALSE; current_debug_name = old_debug_name; current_debug_name_expr = old_debug_name_expr; source = PopExpression (); /* It's apparently wrong to report this error compile time, although the specification explicitly allows it. */ #if 0 if (!target->IsLValue ()) { error_index = target->GetSourceLocation ().Index (); error_line = target->GetSourceLocation ().Line (); PARSE_FAILED (EXPECTED_LVALUE); } #endif // 0 if (!is_compound_assign) { PushExpression (OP_NEWGRO_L (ES_AssignExpr, (target, source), Arena ())); goto recurse; } else if (is_binary_number) compound_source = OP_NEWGRO_L (ES_BinaryNumberExpr, (type, target, source), Arena ()); else if (is_additive) compound_source = OP_NEWGRO_L (ES_AddExpr, (ES_AddExpr::UNKNOWN, target, source), Arena ()); else if (is_shift) compound_source = OP_NEWGRO_L (ES_ShiftExpr, (type, target, source), Arena ()); else compound_source = OP_NEWGRO_L (ES_BitwiseExpr, (type, target, source), Arena ()); compound_source->SetIsCompoundAssign (); PushExpression (OP_NEWGRO_L (ES_AssignExpr, (0, compound_source), Arena ())); goto recurse; } } case ES_Expression::PROD_CONDITIONAL_EXPR: if (ParsePunctuator (ES_Token::CONDITIONAL_TRUE)) { ES_Expression *condition; ES_Expression *first; ES_Expression *second; if (!ParseExpression (depth, ES_Expression::PROD_ASSIGNMENT_EXPR, true, expression_stack_used) || !ParsePunctuator (ES_Token::CONDITIONAL_FALSE) || !ParseExpression (depth, ES_Expression::PROD_ASSIGNMENT_EXPR, allow_in, expression_stack_used)) return DEBUG_FALSE; second = PopExpression (); first = PopExpression (); condition = PopExpression (); PushExpression (OP_NEWGRO_L (ES_ConditionalExpr, (condition, first, second), Arena ())); goto recurse; } case ES_Expression::PROD_LOGICAL_OR_EXPR: if (ParsePunctuator (ES_Token::LOGICAL_OR)) if (ParseLogicalExpr (depth, ES_Expression::PROD_LOGICAL_AND_EXPR, allow_in, ES_LogicalExpr::TYPE_LOGICAL_OR)) goto recurse; else return DEBUG_FALSE; case ES_Expression::PROD_LOGICAL_AND_EXPR: if (ParsePunctuator (ES_Token::LOGICAL_AND)) if (ParseLogicalExpr (depth, ES_Expression::PROD_BITWISE_OR_EXPR, allow_in, ES_LogicalExpr::TYPE_LOGICAL_AND)) goto recurse; else return DEBUG_FALSE; case ES_Expression::PROD_BITWISE_OR_EXPR: if (ParsePunctuator (ES_Token::BITWISE_OR)) if (ParseBitwiseExpr (depth, ES_Expression::PROD_BITWISE_XOR_EXPR, allow_in, ES_BitwiseExpr::TYPE_BITWISE_OR)) goto recurse; else return DEBUG_FALSE; case ES_Expression::PROD_BITWISE_XOR_EXPR: if (ParsePunctuator (ES_Token::BITWISE_XOR)) if (ParseBitwiseExpr (depth, ES_Expression::PROD_BITWISE_AND_EXPR, allow_in, ES_BitwiseExpr::TYPE_BITWISE_XOR)) goto recurse; else return DEBUG_FALSE; case ES_Expression::PROD_BITWISE_AND_EXPR: if (ParsePunctuator (ES_Token::BITWISE_AND)) if (ParseBitwiseExpr (depth, ES_Expression::PROD_EQUALITY_EXPR, allow_in, ES_BitwiseExpr::TYPE_BITWISE_AND)) goto recurse; else return DEBUG_FALSE; case ES_Expression::PROD_EQUALITY_EXPR: if (token.type == ES_Token::PUNCTUATOR) { ES_EqualityExpr::Type type; switch (token.punctuator) { case ES_Token::EQUAL: type = ES_EqualityExpr::TYPE_EQUAL; break; case ES_Token::NOT_EQUAL: type = ES_EqualityExpr::TYPE_NOT_EQUAL; break; case ES_Token::STRICT_EQUAL: type = ES_EqualityExpr::TYPE_STRICT_EQUAL; break; case ES_Token::STRICT_NOT_EQUAL: type = ES_EqualityExpr::TYPE_STRICT_NOT_EQUAL; break; default: /* Abuse TYPE_THIS to mean "not equality" */ type = ES_Expression::TYPE_THIS; } if (type != ES_Expression::TYPE_THIS) { if (!NextToken ()) PARSE_FAILED (GENERIC_ERROR); if (!ParseExpression (depth, ES_Expression::PROD_RELATIONAL_EXPR, allow_in, expression_stack_used)) return DEBUG_FALSE; right = PopExpression (); left = PopExpression (); PushExpression (OP_NEWGRO_L (ES_EqualityExpr, (type, left, right), Arena ())); goto recurse; } } case ES_Expression::PROD_RELATIONAL_EXPR: if (token.type == ES_Token::PUNCTUATOR || token.type == ES_Token::KEYWORD) { bool is_relational = false; bool is_instanceof_or_in = false; ES_RelationalExpr::Type relational_type = ES_Expression::TYPE_THIS; ES_InstanceofOrInExpr::Type instanceof_or_in_type = ES_Expression::TYPE_THIS; if (token.type == ES_Token::PUNCTUATOR) { is_relational = true; switch (token.punctuator) { case ES_Token::LESS_THAN: relational_type = ES_RelationalExpr::TYPE_LESS_THAN; break; case ES_Token::GREATER_THAN: relational_type = ES_RelationalExpr::TYPE_GREATER_THAN; break; case ES_Token::LESS_THAN_OR_EQUAL: relational_type = ES_RelationalExpr::TYPE_LESS_THAN_OR_EQUAL; break; case ES_Token::GREATER_THAN_OR_EQUAL: relational_type = ES_RelationalExpr::TYPE_GREATER_THAN_OR_EQUAL; break; default: is_relational = false; } } else if (token.keyword == ES_Token::KEYWORD_INSTANCEOF) { is_instanceof_or_in = true; instanceof_or_in_type = ES_InstanceofOrInExpr::TYPE_INSTANCEOF; } else if (token.keyword == ES_Token::KEYWORD_IN && allow_in) { is_instanceof_or_in = true; instanceof_or_in_type = ES_InstanceofOrInExpr::TYPE_IN; } if (is_relational || is_instanceof_or_in) { if (!NextToken ()) PARSE_FAILED (GENERIC_ERROR); if (!ParseExpression (depth, ES_Expression::PROD_SHIFT_EXPR, true, expression_stack_used)) return DEBUG_FALSE; right = PopExpression (); left = PopExpression (); if (is_relational) PushExpression (OP_NEWGRO_L (ES_RelationalExpr, (relational_type, left, right), Arena ())); else PushExpression (OP_NEWGRO_L (ES_InstanceofOrInExpr, (instanceof_or_in_type, left, right), Arena ())); goto recurse; } } case ES_Expression::PROD_SHIFT_EXPR: if (token.type == ES_Token::PUNCTUATOR) { ES_ShiftExpr::Type type; switch (token.punctuator) { case ES_Token::SHIFT_LEFT: type = ES_ShiftExpr::TYPE_SHIFT_LEFT; break; case ES_Token::SHIFT_SIGNED_RIGHT: type = ES_ShiftExpr::TYPE_SHIFT_SIGNED_RIGHT; break; case ES_Token::SHIFT_UNSIGNED_RIGHT: type = ES_ShiftExpr::TYPE_SHIFT_UNSIGNED_RIGHT; break; default: /* Abuse TYPE_THIS to mean "not shift" */ type = ES_Expression::TYPE_THIS; } if (type != ES_Expression::TYPE_THIS) { if (!NextToken ()) PARSE_FAILED (GENERIC_ERROR); if (!ParseExpression (depth, ES_Expression::PROD_ADDITIVE_EXPR, true, expression_stack_used)) return DEBUG_FALSE; right = PopExpression (); left = PopExpression (); if (!EvaluateConstantBinaryExpression (type, left, right)) PushExpression (OP_NEWGRO_L (ES_ShiftExpr, (type, left, right), Arena ())); else depth--; goto recurse; } } case ES_Expression::PROD_ADDITIVE_EXPR: if (token.type == ES_Token::PUNCTUATOR) { bool is_add = false; bool is_subtract = false; if (token.punctuator == ES_Token::ADD) is_add = true; else if (token.punctuator == ES_Token::SUBTRACT) is_subtract = true; if (is_add || is_subtract) { if (!NextToken ()) PARSE_FAILED (GENERIC_ERROR); if (!ParseExpression (depth, ES_Expression::PROD_MULTIPLICATIVE_EXPR, true, expression_stack_used)) return DEBUG_FALSE; right = PopExpression (); left = PopExpression (); if (is_add) if (right->GetType () == ES_Expression::TYPE_LITERAL) if (left->GetType () == ES_Expression::TYPE_ADD) { ES_Expression *left_right = static_cast<ES_BinaryExpr *> (left)->GetRight (); if (left_right->GetType () == ES_Expression::TYPE_LITERAL && left_right->GetValueType () == ESTYPE_STRING) { left = static_cast<ES_BinaryExpr *> (left)->GetLeft (); EvaluateConstantBinaryExpression (ES_Expression::TYPE_ADD, left_right, right); depth--; right = PopExpression (); } } if (!EvaluateConstantBinaryExpression (is_add ? ES_Expression::TYPE_ADD : ES_Expression::TYPE_SUBTRACT, left, right)) if (is_add) /* Should check if either left or right is a string literal and use ES_AddExpr::STRINGS if so. */ PushExpression (OP_NEWGRO_L (ES_AddExpr, (ES_AddExpr::UNKNOWN, left, right), Arena ())); else PushExpression (OP_NEWGRO_L (ES_BinaryNumberExpr, (ES_BinaryNumberExpr::TYPE_SUBTRACT, left, right), Arena ())); else depth--; goto recurse; } } case ES_Expression::PROD_MULTIPLICATIVE_EXPR: if (token.type == ES_Token::PUNCTUATOR) { ES_BinaryNumberExpr::Type type; switch (token.punctuator) { case ES_Token::MULTIPLY: type = ES_BinaryNumberExpr::TYPE_MULTIPLY; break; case ES_Token::DIVIDE: type = ES_BinaryNumberExpr::TYPE_DIVIDE; break; case ES_Token::REMAINDER: type = ES_BinaryNumberExpr::TYPE_REMAINDER; break; default: /* Abuse TYPE_THIS to mean "not multiplicative" */ type = ES_Expression::TYPE_THIS; } if (type != ES_Expression::TYPE_THIS) { if (!NextToken ()) PARSE_FAILED (GENERIC_ERROR); if (!ParseExpression (depth, ES_Expression::PROD_UNARY_EXPR, true, expression_stack_used)) return DEBUG_FALSE; right = PopExpression (); left = PopExpression (); if (!EvaluateConstantBinaryExpression (type, left, right)) PushExpression (OP_NEWGRO_L (ES_BinaryNumberExpr, (type, left, right), Arena ())); else depth--; goto recurse; } } case ES_Expression::PROD_UNARY_EXPR: if (expression_stack_length == 0) { if (ParseKeyword (ES_Token::KEYWORD_DELETE)) { STORE_TOKEN_START (); ES_Expression *expr; if (!ParseExpression (depth, ES_Expression::PROD_UNARY_EXPR, true, expression_stack_used)) return DEBUG_FALSE; expr = PopExpression (); if (is_strict_mode && expr->GetType () == ES_Expression::TYPE_IDENTIFIER) { error_code = INVALID_USE_OF_DELETE; return DEBUG_FALSE; } PushExpression (OP_NEWGRO_L (ES_DeleteExpr, (expr), Arena ()) LOCATION ()); goto recurse; } bool is_unary = true; bool is_inc_or_dec = false; ES_UnaryExpr::Type unary_type = ES_UnaryExpr::TYPE_THIS; ES_IncrementOrDecrementExpr::Type inc_or_dec_type = ES_IncrementOrDecrementExpr::POST_INCREMENT; if (token.type == ES_Token::KEYWORD) switch (token.keyword) { case ES_Token::KEYWORD_VOID: unary_type = ES_UnaryExpr::TYPE_VOID; break; case ES_Token::KEYWORD_TYPEOF: unary_type = ES_UnaryExpr::TYPE_TYPEOF; break; default: is_unary = false; } else if (token.type == ES_Token::PUNCTUATOR) switch (token.punctuator) { case ES_Token::INCREMENT: is_inc_or_dec = true; is_unary = false; inc_or_dec_type = ES_IncrementOrDecrementExpr::PRE_INCREMENT; break; case ES_Token::DECREMENT: is_inc_or_dec = true; is_unary = false; inc_or_dec_type = ES_IncrementOrDecrementExpr::PRE_DECREMENT; break; case ES_Token::ADD: unary_type = ES_UnaryExpr::TYPE_PLUS; break; case ES_Token::SUBTRACT: unary_type = ES_UnaryExpr::TYPE_MINUS; break; case ES_Token::BITWISE_NOT: unary_type = ES_UnaryExpr::TYPE_BITWISE_NOT; break; case ES_Token::LOGICAL_NOT: unary_type = ES_UnaryExpr::TYPE_LOGICAL_NOT; break; default: is_unary = false; } else is_unary = false; if (is_unary || is_inc_or_dec) { ES_Expression *expr; if (!NextToken ()) PARSE_FAILED (GENERIC_ERROR); STORE_TOKEN_START (); if (is_unary && unary_type == ES_UnaryExpr::TYPE_TYPEOF) ++in_typeof; if (!ParseExpression (depth, ES_Expression::PROD_UNARY_EXPR, true, expression_stack_used)) return DEBUG_FALSE; if (is_unary && unary_type == ES_UnaryExpr::TYPE_TYPEOF) --in_typeof; expr = PopExpression (); if (is_unary) { if (expr->GetType () == ES_Expression::TYPE_LITERAL) { ES_LiteralExpr *literal = static_cast<ES_LiteralExpr *>(expr); if (unary_type == ES_UnaryExpr::TYPE_PLUS || unary_type == ES_UnaryExpr::TYPE_MINUS) { double value = literal->GetValue ().AsNumber (context).GetNumAsDouble (); if (unary_type == ES_UnaryExpr::TYPE_MINUS) value = -value; PushExpression (OP_NEWGRO_L (ES_LiteralExpr, (value), Arena ())); goto recurse; } else if (unary_type == ES_UnaryExpr::TYPE_BITWISE_NOT) { int value = literal->GetValue ().AsNumber (context).GetNumAsInt32 (); PushExpression (OP_NEWGRO_L (ES_LiteralExpr, (~value), Arena ())); goto recurse; } else if (unary_type == ES_UnaryExpr::TYPE_LOGICAL_NOT) { value.SetBoolean (!literal->GetValue ().AsBoolean ().GetBoolean ()); PushExpression (OP_NEWGRO_L (ES_LiteralExpr, (value), Arena ())); goto recurse; } } PushExpression (OP_NEWGRO_L (ES_UnaryExpr, (unary_type, expr), Arena ()) LOCATION ()); } else { JString *name; if (expr->IsIdentifier (name)) if (!ValidateIdentifier (name, &expr->GetSourceLocation ())) return DEBUG_FALSE; PushExpression (OP_NEWGRO_L (ES_IncrementOrDecrementExpr, (inc_or_dec_type, expr), Arena ()) LOCATION ()); } goto recurse; } } case ES_Expression::PROD_POSTFIX_EXPR: if (expression_stack_length > 0) { bool previous_allow_linebreak = SetAllowLinebreak (false); ES_IncrementOrDecrementExpr::Type type; /* Abuse PRE_INCREMENT to mean "not postfix" */ if (last_token.type == ES_Token::LINEBREAK) type = ES_IncrementOrDecrementExpr::PRE_INCREMENT; else if (ParsePunctuator (ES_Token::INCREMENT)) type = ES_IncrementOrDecrementExpr::POST_INCREMENT; else if (ParsePunctuator (ES_Token::DECREMENT)) type = ES_IncrementOrDecrementExpr::POST_DECREMENT; else type = ES_IncrementOrDecrementExpr::PRE_INCREMENT; SetAllowLinebreak (previous_allow_linebreak); if (type != ES_IncrementOrDecrementExpr::PRE_INCREMENT) { ES_Expression *expr; expr = PopExpression (); JString *name; if (expr->IsIdentifier (name)) if (!ValidateIdentifier (name, &expr->GetSourceLocation ())) return DEBUG_FALSE; PushExpression (OP_NEWGRO_L (ES_IncrementOrDecrementExpr, (type, expr), Arena ()) LOCATION_FROM (expr)); goto recurse; } } case ES_Expression::PROD_LEFT_HAND_SIDE_EXPR: case ES_Expression::PROD_CALL_EXPR: if (expression_stack_length > 0) { unsigned exprs_before = expression_stack_used; if (ParsePunctuator (ES_Token::LEFT_PAREN)) if (ParseArguments (depth)) { ES_Expression *func; unsigned args_count; ES_Expression **args; args_count = expression_stack_used - exprs_before; args = PopExpressions (args_count); func = PopExpression (); PushExpression (OP_NEWGRO_L (ES_CallExpr, (func, args_count, args), Arena ()) LOCATION_FROM (func)); goto recurse; } else return DEBUG_FALSE; } case ES_Expression::PROD_NEW_EXPR: case ES_Expression::PROD_MEMBER_EXPR: if (expression_stack_length > 0) { switch (ParsePunctuator1 (ES_Token::LEFT_BRACKET)) { case INVALID_TOKEN: automatic_error_code = EXPECTED_EXPRESSION; return DEBUG_FALSE; case FOUND: ES_Expression *base; ES_Expression *index; if (!ParseExpression (depth, ES_Expression::PROD_EXPRESSION, true, expression_stack_used) || !ParsePunctuator (ES_Token::RIGHT_BRACKET)) return DEBUG_FALSE; index = PopExpression (); base = PopExpression (); if (index->GetType () == ES_Expression::TYPE_LITERAL && index->GetValueType () == ESTYPE_STRING) { JString *name = static_cast<ES_LiteralExpr *> (index)->GetValue ().GetString (); unsigned idx; if (convertindex (Storage (context, name), Length (name), idx)) static_cast<ES_LiteralExpr *> (index)->GetValue ().SetNumber (idx); else { PushExpression (OP_NEWGRO_L (ES_PropertyReferenceExpr, (base, name), Arena ()) LOCATION_FROM (base)); goto recurse; } } PushExpression (OP_NEWGRO_L (ES_ArrayReferenceExpr, (base, index), Arena ()) LOCATION_FROM (base)); goto recurse; } switch (ParsePunctuator1 (ES_Token::PERIOD)) { case INVALID_TOKEN: automatic_error_code = EXPECTED_IDENTIFIER; return DEBUG_FALSE; case FOUND: ES_Expression *base; JString *name; if (!ParseIdentifier (name, false, true)) return DEBUG_FALSE; base = PopExpression (); PushExpression (OP_NEWGRO_L (ES_PropertyReferenceExpr, (base, name), Arena ()) LOCATION_FROM (base)); goto recurse; } } if (expression_stack_length == 0) if (ParseKeyword (ES_Token::KEYWORD_NEW)) { STORE_TOKEN_START (); ES_Expression *ctor; unsigned args_count; ES_Expression **args; if (expression_stack_length > 0) PARSE_FAILED (GENERIC_ERROR); if (!ParseExpression (depth, ES_Expression::PROD_NEW_EXPR, true, expression_stack_used)) return DEBUG_FALSE; unsigned exprs_before = expression_stack_used; if (ParsePunctuator (ES_Token::LEFT_PAREN)) if (ParseArguments (depth)) { args_count = expression_stack_used - exprs_before; args = PopExpressions (args_count); } else return DEBUG_FALSE; else if (production < ES_Expression::PROD_MEMBER_EXPR) { args_count = 0; args = 0; } else PARSE_FAILED (GENERIC_ERROR); ctor = PopExpression (); PushExpression (OP_NEWGRO_L (ES_NewExpr, (ctor, args_count, args), Arena ()) LOCATION ()); goto recurse; } else if (ParseKeyword (ES_Token::KEYWORD_FUNCTION)) { if (!ParseFunctionExpr ()) return DEBUG_FALSE; goto recurse; } case ES_Expression::PROD_PRIMARY_EXPR: if (expression_stack_length == 0) { if (ParsePunctuator (ES_Token::LEFT_BRACKET)) { STORE_TOKEN_START (); unsigned exprs_count; ES_Expression **exprs; unsigned expressions_before = expression_stack_used; while (!ParsePunctuator (ES_Token::RIGHT_BRACKET)) if (ParseExpression (depth, ES_Expression::PROD_ASSIGNMENT_EXPR, true, expression_stack_used)) { if (!ParsePunctuator (ES_Token::COMMA)) if (ParsePunctuator (ES_Token::RIGHT_BRACKET)) break; else PARSE_FAILED (GENERIC_ERROR); } else if (ParsePunctuator (ES_Token::COMMA)) PushExpression (NULL); else PARSE_FAILED (GENERIC_ERROR); exprs_count = expression_stack_used - expressions_before; exprs = PopExpressions (exprs_count); PushExpression (OP_NEWGRO_L (ES_ArrayLiteralExpr, (exprs_count, exprs), Arena ()) LOCATION ()); goto recurse; } if (ParsePunctuator (ES_Token::LEFT_BRACE)) { unsigned index = last_token.start; unsigned line = last_token.line; unsigned props_count, properties_before = property_stack_used; while (1) { JString *name; if (!ParseProperty (name, false)) if (ParsePunctuator (ES_Token::RIGHT_BRACE)) break; else return DEBUG_FALSE; if (name) { JString *actual_name; unsigned check_count = property_stack_used - properties_before; #ifdef ES_LEXER_SOURCE_LOCATION_SUPPORT unsigned index = last_token.start; unsigned line = last_token.line; unsigned column = last_token.column; #endif // ES_LEXER_SOURCE_LOCATION_SUPPORT if (name->Equals (UNI_L ("get"), 3)) if (ParseProperty (actual_name, false)) { if (!ParseAccessor (ACCESSOR_GET, actual_name, check_count, index, line, column)) return DEBUG_FALSE; } else goto regular_property; else if (name->Equals (UNI_L ("set"), 3)) if (ParseProperty (actual_name, false)) { if (!ParseAccessor (ACCESSOR_SET, actual_name, check_count, index, line, column)) return DEBUG_FALSE; } else goto regular_property; else { regular_property: #ifdef ES_LEXER_SOURCE_LOCATION_SUPPORT ES_SourceLocation name_location = last_token.GetSourceLocation(); # define NAME_LOCATION , name_location #else // ES_LEXER_SOURCE_LOCATION_SUPPORT # define NAME_LOCATION #endif // ES_LEXER_SOURCE_LOCATION_SUPPORT JString *old_debug_name = current_debug_name; ES_Expression *old_debug_name_expr = current_debug_name_expr; current_debug_name = name; current_debug_name_expr = NULL; if (!ParsePunctuator (ES_Token::CONDITIONAL_FALSE) || !ParseExpression (depth, ES_Expression::PROD_ASSIGNMENT_EXPR, true, expression_stack_used)) return DEBUG_FALSE; current_debug_name = old_debug_name; current_debug_name_expr = old_debug_name_expr; if (!PushProperty (check_count, name NAME_LOCATION, PopExpression ())) return DEBUG_FALSE; } } if (!ParsePunctuator (ES_Token::COMMA)) if (!ParsePunctuator (ES_Token::RIGHT_BRACE)) return DEBUG_FALSE; else break; } #undef NAME_LOCATION props_count = property_stack_used - properties_before; ES_ObjectLiteralExpr::Property *properties = static_cast<ES_ObjectLiteralExpr::Property *>(PopProperties (props_count)); PushExpression (OP_NEWGRO_L (ES_ObjectLiteralExpr, (props_count, properties), Arena ()) LOCATION ()); goto recurse; } } if (expression_stack_length == 1 || (expression_stack_length == 0 && opt)) return true; else { automatic_error_code = ES_Parser::EXPECTED_EXPRESSION; return DEBUG_FALSE; } } /* Never reached. */ return DEBUG_FALSE; }
/* XMRig * Copyright 2010 Jeff Garzik <jgarzik@pobox.com> * Copyright 2012-2014 pooler <pooler@litecoinpool.org> * Copyright 2014 Lucas Jones <https://github.com/lucasjones> * Copyright 2014-2016 Wolf9466 <https://github.com/OhGodAPet> * Copyright 2016 Jay D Dee <jayddee246@gmail.com> * Copyright 2017-2018 XMR-Stak <https://github.com/fireice-uk>, <https://github.com/psychocrypt> * Copyright 2018-2020 SChernykh <https://github.com/SChernykh> * Copyright 2016-2020 XMRig <https://github.com/xmrig>, <support@xmrig.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "backend/cuda/wrappers/CudaDevice.h" #include "3rdparty/rapidjson/document.h" #include "backend/cuda/CudaThreads.h" #include "backend/cuda/wrappers/CudaLib.h" #include "base/crypto/Algorithm.h" #include "base/io/log/Log.h" #ifdef XMRIG_FEATURE_NVML # include "backend/cuda/wrappers/NvmlLib.h" #endif #include <algorithm> xmrig::CudaDevice::CudaDevice(uint32_t index, int32_t bfactor, int32_t bsleep) : m_index(index) { auto ctx = CudaLib::alloc(index, bfactor, bsleep); if (!CudaLib::deviceInfo(ctx, 0, 0, Algorithm::INVALID)) { CudaLib::release(ctx); return; } m_ctx = ctx; m_name = CudaLib::deviceName(ctx); m_topology = PciTopology(CudaLib::deviceUint(ctx, CudaLib::DevicePciBusID), CudaLib::deviceUint(ctx, CudaLib::DevicePciDeviceID), 0); } xmrig::CudaDevice::CudaDevice(CudaDevice &&other) noexcept : m_index(other.m_index), m_ctx(other.m_ctx), m_topology(other.m_topology), m_name(std::move(other.m_name)) { other.m_ctx = nullptr; } xmrig::CudaDevice::~CudaDevice() { CudaLib::release(m_ctx); } size_t xmrig::CudaDevice::freeMemSize() const { return CudaLib::deviceUlong(m_ctx, CudaLib::DeviceMemoryFree); } size_t xmrig::CudaDevice::globalMemSize() const { return CudaLib::deviceUlong(m_ctx, CudaLib::DeviceMemoryTotal); } uint32_t xmrig::CudaDevice::clock() const { return CudaLib::deviceUint(m_ctx, CudaLib::DeviceClockRate) / 1000; } uint32_t xmrig::CudaDevice::computeCapability(bool major) const { return CudaLib::deviceUint(m_ctx, major ? CudaLib::DeviceArchMajor : CudaLib::DeviceArchMinor); } uint32_t xmrig::CudaDevice::memoryClock() const { return CudaLib::deviceUint(m_ctx, CudaLib::DeviceMemoryClockRate) / 1000; } uint32_t xmrig::CudaDevice::smx() const { return CudaLib::deviceUint(m_ctx, CudaLib::DeviceSmx); } void xmrig::CudaDevice::generate(const Algorithm &algorithm, CudaThreads &threads) const { if (!CudaLib::deviceInfo(m_ctx, -1, -1, algorithm)) { return; } threads.add(CudaThread(m_index, m_ctx)); } #ifdef XMRIG_FEATURE_API void xmrig::CudaDevice::toJSON(rapidjson::Value &out, rapidjson::Document &doc) const { using namespace rapidjson; auto &allocator = doc.GetAllocator(); out.AddMember("name", name().toJSON(doc), allocator); out.AddMember("bus_id", topology().toString().toJSON(doc), allocator); out.AddMember("smx", smx(), allocator); out.AddMember("arch", arch(), allocator); out.AddMember("global_mem", static_cast<uint64_t>(globalMemSize()), allocator); out.AddMember("clock", clock(), allocator); out.AddMember("memory_clock", memoryClock(), allocator); # ifdef XMRIG_FEATURE_NVML if (m_nvmlDevice) { auto data = NvmlLib::health(m_nvmlDevice); Value health(kObjectType); health.AddMember("temperature", data.temperature, allocator); health.AddMember("power", data.power, allocator); health.AddMember("clock", data.clock, allocator); health.AddMember("mem_clock", data.memClock, allocator); Value fanSpeed(kArrayType); for (auto speed : data.fanSpeed) { fanSpeed.PushBack(speed, allocator); } health.AddMember("fan_speed", fanSpeed, allocator); out.AddMember("health", health, allocator); } # endif } #endif
#ifndef BASE_THREADING_SIMPLE_THREAD_H_ #define BASE_THREADING_SIMPLE_THREAD_H_ #include <memory> #include <tuple> #include <utility> #include "base/callback.h" #include "base/threading/thread.h" namespace base { class TaskRunner; class SimpleThread : public Thread { public: class SimpleThreadDelegate : public Thread::Delegate { public: explicit SimpleThreadDelegate(std::function<void()> f) : f_(f) {} // Thread::Delegate implementation. void BindToCurrentThread(ThreadType) override {} void Run() override { f_(); } std::shared_ptr<TaskRunner> GetTaskRunner() override { NOTREACHED(); } void Quit() override {} void QuitWhenIdle() override {} private: std::function<void()> f_; }; template <typename F, typename... Ts> SimpleThread(F func, Ts... args) : Thread() { std::function<void()> f{std::bind(func, args...)}; delegate_.reset(new SimpleThreadDelegate(f)); // Start the thread with the overridden delegate. Start(); } }; } // namespace base #endif // BASE_THREADING_SIMPLE_THREAD_H_
#include <iostream> #include <algorithm> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <memory.h> #include <math.h> #include <string> #include <sstream> #include <string.h> #include <queue> #include <vector> #include <set> #include <map> typedef long long LL; typedef unsigned long long ULL; #define PI 3.1415926535897932384626433832795 #define sqr(x) ((x)*(x)) using namespace std; struct Tp { int t1, t2, l, r; bool operator<(const Tp& B)const{ return t1 < B.t1; } } a[2222]; struct Tb { int t, l; bool operator<(const Tb& B)const{ return t < B.t || t==B.t && l < B.l; } } b[2222]; int n, x, dt, bn, can[2222]; int Process(int t, int x, int id) { if (!can[id]) return 0; for (int i = 0; i < n; i++) { if (t >= a[i].t1 && t <= a[i].t2 && x > a[i].l && x < a[i].r) return 0; } int hi = ((i&1)==0) ? (a[(id - 1)>>1].t2 - a[(id - 1)>>1].t1 + 1) : 0; int lo = 0; for (int i = 0; i < n; i++) { if (a[i].t1 > t) { if (a[i].l >= x) { if ( (a[i].l - x) + hi <= a[i].t1 - t) { can[i + i + 1] = true; } } else { if ( (x - a[i].l)) } } } } int main() { freopen(".in", "r", stdin); freopen(".out", "w", stdout); cin >> n >> x; for (int i = 0; i < n ;i++) { cin >> a[i].t1 >> dt >> a[i].l >> a[i].r; a[i].t2 = a[i].t1 + dt - 1; b[bn].t = a[i].t1; b[bn].l = a[i].l; bn++; b[bn].t = a[i].t2; b[bn].l = a[i].l; bn++; } sort(a, a + n); sort(b, b + bn); int t; can[0] = true; if (t = Process(0, 0, 0)) { cout << t << endl; } for (int i = 0; i < bn; i++) { if (t = Process(b[i].t, b[i].l, i + 1)) { cout << t << endl; } } return 0; }
#include "FourierPrinterSystem.h" #include "EverydayTools/Preprocessor/ExpotImport.h" extern "C" { void EXPORT __cdecl CreateSystem(void** result) { *result = new simple_quad_sample::FourierPrinterSystem(); } }
#include "PhysicsComponent.h" #include "TransformComponent.h" #include "MeshComponent.h" namespace Game { PhysicsComponent::PhysicsComponent() { } PhysicsComponent::~PhysicsComponent() { } void PhysicsComponent::update() { if (mConfigured) { Transform transform = mPhysicsObject->transform().fromPhysics(); entity->getComponent<TransformComponent>().setTransform(transform); } } void PhysicsComponent::draw() { } void PhysicsComponent::start() { } void PhysicsComponent::stop() { } void PhysicsComponent::configure() { } void PhysicsComponent::cleanup() { mConfigured = false; } void PhysicsComponent::setShape(CollisionShapes shape) { mPhysicsObject->setShape(shape); } void PhysicsComponent::setMass(float mass) { mPhysicsObject->setMass(mass); } void PhysicsComponent::onCreate() { mConfigured = true; mPhysicsObject = GameCore::get().getModule<PhysicsModule>() ->createPhysicsObject(entity->getComponent<TransformComponent>().getTransform()); mPhysicsObject->setMesh(&entity->getComponent<MeshComponent>().getMeshData()); } }
#include "StdAfx.h" #include "BallPhysics.h" #include "Config.h" BallPhysics::BallPhysics(GameLogic* gameLogic) :gameLogic(gameLogic) { gravity = Ogre::Vector3(0.0f, -9.81f, 0.0f); position = Ogre::Vector3(0.0f, 0.6f, 0.0f); speed = Ogre::Vector3::ZERO; spin = Ogre::Vector3::ZERO; out = true; } BallPhysics::~BallPhysics() { } void BallPhysics::update(float deltaT) { if (out == true) return; // Gravity speed += gravity * deltaT; // Spin speed += spin.crossProduct(speed) * g_SpinFactor * deltaT; // Air resistance Ogre::Vector3 speedNorm = speed; speedNorm.normalise(); speed += speedNorm * -speed.squaredLength() * g_AirResistance * deltaT; position += speed * deltaT; // If the ball is over the table if (isOverTable()) { // Check collision with net if (abs(position.z) < g_BallRadius && position.y < g_TableY + g_NetOverhang + g_BallRadius && (speed.z > 0 && position.z < 0 || speed.z < 0 && position.z > 0) && position.y >= g_TableY + g_BallRadius) { // If the ball hits the upper part of the net if (position.y > g_TableY + g_NetOverhang + g_BallRadius - 0.01f) { // If you draw some examples how to top of the net should reflect the ball, you'll see // you have to invert the reflected vector if the speed and the hit direction closes an // angle greater than 90 grad Ogre::Vector3 hitPoint(position.x, g_TableY + g_NetOverhang, 0.0f); Ogre::Vector3 hitDirection = position - hitPoint; if (speed.dotProduct(hitDirection) > 0.0f) speed = speed.reflect(hitDirection); else speed = speed.reflect(hitDirection) * -1.0f; } // If the ball hits the side of the net else { speed.z = -speed.z; } gameLogic->onTouchNet(); } // Check collision with table if (position.y < g_TableY + g_BallRadius && speed.y < 0.0f) { position.y = g_TableY + g_BallRadius; speed.y = -speed.y; gameLogic->onTouchTable(position.z > 0 ? 0 : 1); } } else { // If the ball touches the floor, out if (position.y < g_GroundY + g_BallRadius) { position.y = g_GroundY + g_BallRadius; out = true; gameLogic->onTouchGround(); } } } void BallPhysics::setSpeed(Ogre::Vector3 speed) { this->speed = speed; } void BallPhysics::setPosition(Ogre::Vector3 position) { this->position = position; out = false; } void BallPhysics::setSpin(Ogre::Vector3 spin) { this->spin = spin; } Ogre::Vector3 BallPhysics::getPosition() { return position; } Ogre::Vector3 BallPhysics::getSpeed() { return speed; } bool BallPhysics::isOverTable() { return abs(position.x) < g_TableX + g_BallRadius && abs(position.z) < g_TableZ + g_BallRadius; }
#include <gtest/gtest.h> #include <string> #include "../include/conveyor.h" class ConveyorSimple : public ::testing::Test { protected: virtual void SetUp() override { } virtual void TearDown() override { } }; // rec1 is 26 bytes, rec2 is 284 bytes const std::string rec1 = "abcdefghijklmnopqrstuvwxyz"; const std::string rec2 = "{ \"action\": \"added\", \"columns\": { \"name\": \"osqueryd\", \"path\": \"/usr/local/bin/osqueryd\", \"pid\": \"97830\" }, \"name\": \"processes\", \"hostname\": \"hostname.local\", \"calendarTime\": \"Tue Sep 30 17:37:30 2014\", \"unixTime\": \"1412123850\", \"epoch\": \"314159265\", \"counter\": \"1\"}"; const ConveyorSettings gSettings1 = { ".", "test_events", 3, 12, 1, 8192 }; struct TestConveyorListener : public ConveyorListener { void onRecord(void *context, const std::string &value, std::time_t ts, uint32_t id) override { numBytes += value.size(); numRecords++; } uint64_t numBytes {0}; uint64_t numRecords {0}; }; //-------------------------------------------------------------- // fill to limit + 1, should have a drop //-------------------------------------------------------------- TEST_F(ConveyorSimple, fill_and_drop) { int rv = 0; auto settings = gSettings1; std::time_t ts = time(NULL); SPConveyor conveyor = ConveyorNew(settings); conveyor->deleteAndStartFresh(); for (int i=0; i < settings.maxRecords; i++) { rv = conveyor->addRecord(i % 2 == 0 ? rec2 : rec1, ts); ASSERT_EQ(0, rv); } rv = conveyor->addRecord(rec1, ts); ASSERT_EQ(1, rv); // drop ASSERT_EQ(1, conveyor->getNumDrops()); } //-------------------------------------------------------------- // Fill and read back //-------------------------------------------------------------- TEST_F(ConveyorSimple, fill_and_read) { int rv = 0; auto settings = gSettings1; std::time_t ts = time(NULL); SPConveyor conveyor = ConveyorNew(settings); conveyor->deleteAndStartFresh(); int expBytes = 0; for (int i=0; i < settings.maxRecords; i++) { rv = conveyor->addRecord(i % 2 == 0 ? rec2 : rec1, ts); expBytes += (i % 2 == 0 ? rec2 : rec1).size(); ASSERT_EQ(0, rv); } TestConveyorListener listener; auto cursor = conveyor->openCursor(); conveyor->enumerateRecords(listener, nullptr, cursor, ts); EXPECT_EQ(settings.maxRecords, listener.numRecords); EXPECT_EQ(expBytes, listener.numBytes); EXPECT_EQ(settings.maxRecords, conveyor->getNumRecords()); EXPECT_EQ(0, conveyor->getNumDrops()); } //-------------------------------------------------------------- // Once a (non-autoAdvance) cursor has enumerateRecords(), it will have its // end position set. Consecutive reads should always stop at the same record, // even if new records are added between reads. Calling advanceCursor() will // clear the cursor's end position so that new records can be read. //-------------------------------------------------------------- TEST_F(ConveyorSimple, consec_reads_same_stop) { int rv = 0; auto settings = gSettings1; std::time_t ts = time(NULL); SPConveyor conveyor = ConveyorNew(settings); conveyor->deleteAndStartFresh(); int expBytes = 0; for (int i=0; i < settings.maxRecords / 2; i++) { rv = conveyor->addRecord(i % 2 == 0 ? rec2 : rec1, ts); expBytes += (i % 2 == 0 ? rec2 : rec1).size(); ASSERT_EQ(0, rv); } EXPECT_EQ(settings.maxRecords / 2, conveyor->getNumRecords()); TestConveyorListener listener; auto cursor = conveyor->openCursor(); conveyor->enumerateRecords(listener, nullptr, cursor, ts); EXPECT_EQ(settings.maxRecords / 2, listener.numRecords); EXPECT_EQ(expBytes, listener.numBytes); // add 2 more records rv = conveyor->addRecord(rec2, ts); ASSERT_EQ(0, rv); rv = conveyor->addRecord(rec2, ts); ASSERT_EQ(0, rv); EXPECT_EQ(settings.maxRecords / 2 + 2, conveyor->getNumRecords()); // read again. should not read the two new ones listener = TestConveyorListener(); conveyor->enumerateRecords(listener, nullptr, cursor, ts); EXPECT_EQ(settings.maxRecords / 2, listener.numRecords); conveyor->advanceCursor(cursor); EXPECT_EQ(2, conveyor->getNumRecords()); // now we should pick up the last two listener = TestConveyorListener(); conveyor->enumerateRecords(listener, nullptr, cursor, ts); EXPECT_EQ(2, listener.numRecords); conveyor->enumerateRecords(listener, nullptr, cursor, ts); EXPECT_EQ(4, listener.numRecords); // advance again, should be empty conveyor->advanceCursor(cursor); EXPECT_EQ(0, conveyor->getNumRecords()); } //-------------------------------------------------------------- // fill, read, advance, //-------------------------------------------------------------- TEST_F(ConveyorSimple, fill_and_read_advance_cursor) { int rv = 0; auto settings = gSettings1; std::time_t ts = time(NULL); SPConveyor conveyor = ConveyorNew(settings); conveyor->deleteAndStartFresh(); int expBytes = 0; for (int i=0; i < settings.maxRecords; i++) { rv = conveyor->addRecord(i % 2 == 0 ? rec2 : rec1, ts); expBytes += (i % 2 == 0 ? rec2 : rec1).size(); ASSERT_EQ(0, rv); } TestConveyorListener listener; auto cursor = conveyor->openCursor(); // read conveyor->enumerateRecords(listener, nullptr, cursor, ts); EXPECT_EQ(settings.maxRecords, conveyor->getNumRecords()); EXPECT_EQ(settings.maxRecords, listener.numRecords); EXPECT_EQ(expBytes, listener.numBytes); // advance. should discard all records conveyor->advanceCursor(cursor); EXPECT_EQ(0, conveyor->getNumRecords()); // without any new records added, listener stats should be same listener = TestConveyorListener(); conveyor->enumerateRecords(listener, nullptr, cursor, ts); conveyor->closeCursor(cursor); EXPECT_EQ(0, listener.numRecords); } //-------------------------------------------------------------- // test state //-------------------------------------------------------------- TEST_F(ConveyorSimple, fill_check_state) { int rv = 0; auto settings = gSettings1; std::time_t ts = time(NULL) - 10; SPConveyor conveyor = ConveyorNew(settings); conveyor->deleteAndStartFresh(); int expBytes = 0; for (int i=0; i < settings.maxRecords; i++) { rv = conveyor->addRecord(i % 2 == 0 ? rec2 : rec1, ts + i); expBytes += (i % 2 == 0 ? rec2 : rec1).size(); ASSERT_EQ(0, rv); } std::vector<ConveyorFile> state = conveyor->testGetFileState(); ASSERT_EQ(settings.numChunks, state.size()); EXPECT_EQ(0, state[0].startId); EXPECT_EQ(4, state[1].startId); EXPECT_EQ(8, state[2].startId); EXPECT_EQ(4, state[0].numRecords); EXPECT_EQ(4, state[1].numRecords); EXPECT_EQ(4, state[2].numRecords); EXPECT_EQ(true, state[0].isActive); EXPECT_EQ(true, state[1].isActive); EXPECT_EQ(true, state[2].isActive); } //-------------------------------------------------------------- // fill, advance to discard, fill again //-------------------------------------------------------------- TEST_F(ConveyorSimple, fill_twice) { int rv = 0; auto settings = gSettings1; std::time_t ts = time(NULL); SPConveyor conveyor = ConveyorNew(settings); conveyor->deleteAndStartFresh(); // fill int expBytes = 0; for (int i=0; i < settings.maxRecords; i++) { rv = conveyor->addRecord(i % 2 == 0 ? rec2 : rec1, ts); expBytes += (i % 2 == 0 ? rec2 : rec1).size(); ASSERT_EQ(0, rv); } EXPECT_EQ(settings.maxRecords, conveyor->getNumRecords()); TestConveyorListener listener; // read, advancing cursor auto cursor = conveyor->openCursor(); conveyor->enumerateRecords(listener, nullptr, cursor, ts); conveyor->advanceCursor(cursor); EXPECT_EQ(0, conveyor->getNumRecords()); // fill again for (int i=0; i < settings.maxRecords; i++) { rv = conveyor->addRecord(i % 2 == 0 ? rec2 : rec1, ts); ASSERT_EQ(0, rv); } EXPECT_EQ(settings.maxRecords, conveyor->getNumRecords()); // read again conveyor->enumerateRecords(listener, nullptr, cursor, ts); conveyor->advanceCursor(cursor); EXPECT_EQ(0, conveyor->getNumRecords()); EXPECT_EQ(settings.maxRecords*2, listener.numRecords); } //-------------------------------------------------------------- // Using autoAdvance=true cursor, add and read one-by-one. //-------------------------------------------------------------- TEST_F(ConveyorSimple, one_by_one) { int rv = 0; TestConveyorListener listener; auto settings = gSettings1; std::time_t ts = time(NULL); SPConveyor conveyor = ConveyorNew(settings); conveyor->deleteAndStartFresh(); auto cursor = conveyor->openCursor(true); int expBytes = 0; for (int i=0; i < settings.maxRecords * 2; i++) { rv = conveyor->addRecord(i % 2 == 0 ? rec2 : rec1, ts); ASSERT_EQ(0, rv); expBytes += (i % 2 == 0 ? rec2 : rec1).size(); EXPECT_EQ(1, conveyor->getNumRecords()); conveyor->enumerateRecords(listener, nullptr, cursor, ts); EXPECT_EQ(0, conveyor->getNumRecords()); } EXPECT_EQ(0, conveyor->getNumRecords()); EXPECT_EQ(settings.maxRecords*2, listener.numRecords); EXPECT_EQ(expBytes, listener.numBytes); } //-------------------------------------------------------------- // Tests the situation where the uint32 id rollsover back to 0. //-------------------------------------------------------------- TEST_F(ConveyorSimple, id_rollover) { int rv = 0; TestConveyorListener listener; auto settings = gSettings1; std::time_t ts = time(NULL); SPConveyor conveyor = ConveyorNew(settings); conveyor->testResetAtId((uint32_t)-6); auto cursor = conveyor->openCursor(/* autoAdvance= */true); int expBytes = 0; for (int i=0; i < settings.maxRecords; i++) { rv = conveyor->addRecord(i % 2 == 0 ? rec2 : rec1, ts); ASSERT_EQ(0, rv); expBytes += (i % 2 == 0 ? rec2 : rec1).size(); EXPECT_EQ(1, conveyor->getNumRecords()); conveyor->enumerateRecords(listener, nullptr, cursor, ts); EXPECT_EQ(0, conveyor->getNumRecords()); } EXPECT_EQ(0, conveyor->getNumRecords()); EXPECT_EQ(settings.maxRecords, listener.numRecords); EXPECT_EQ(expBytes, listener.numBytes); } //-------------------------------------------------------------- // Test filling with batch, then reading it back. //-------------------------------------------------------------- TEST_F(ConveyorSimple, batch_fill_and_read) { int rv = 0; auto settings = gSettings1; std::time_t ts = time(NULL); SPConveyor conveyor = ConveyorNew(settings); conveyor->deleteAndStartFresh(); int expBytes = 0; std::vector<std::string> batch; for (int i=0; i < settings.maxRecords; i++) { batch.push_back(i % 2 == 0 ? rec2 : rec1); expBytes += (i % 2 == 0 ? rec2 : rec1).size(); } rv = conveyor->addBatch(batch, ts); ASSERT_EQ(0,rv); TestConveyorListener listener; auto cursor = conveyor->openCursor(); conveyor->enumerateRecords(listener, nullptr, cursor, ts); EXPECT_EQ(settings.maxRecords, listener.numRecords); EXPECT_EQ(expBytes, listener.numBytes); } //-------------------------------------------------------------- // Multiple calls to addBatch(), testing the drop count. // batches can have partial success, partial drops //-------------------------------------------------------------- TEST_F(ConveyorSimple, batch_fill_drop_and_read) { int rv = 0; auto settings = gSettings1; std::time_t ts = time(NULL); SPConveyor conveyor = ConveyorNew(settings); conveyor->deleteAndStartFresh(); std::vector<std::string> batch = {"A","B","C","D","E"}; rv = conveyor->addBatch(batch, ts); ASSERT_EQ(0,rv); ASSERT_EQ(5,conveyor->getNumRecords()); rv = conveyor->addBatch(batch, ts); ASSERT_EQ(0,rv); ASSERT_EQ(10,conveyor->getNumRecords()); ASSERT_EQ(0,conveyor->getNumDrops()); // if rv > 0, it's the number of drops rv = conveyor->addBatch(batch, ts); int expectedDrops = 3; ASSERT_EQ(expectedDrops,rv); ASSERT_EQ(12,conveyor->getNumRecords()); ASSERT_EQ(expectedDrops,conveyor->getNumDrops()); rv = conveyor->addBatch(batch, ts); expectedDrops = 5; ASSERT_EQ(expectedDrops,rv); ASSERT_EQ(12,conveyor->getNumRecords()); ASSERT_EQ(3 + 5,conveyor->getNumDrops()); TestConveyorListener listener; auto cursor = conveyor->openCursor(); conveyor->enumerateRecords(listener, nullptr, cursor, ts); EXPECT_EQ(settings.maxRecords, listener.numRecords); EXPECT_EQ(12, listener.numBytes); } //-------------------------------------------------------------- // Test that expired records get discarded as they are read, // even if cursor is not autoAdvance. //-------------------------------------------------------------- TEST_F(ConveyorSimple, test_expiry) { int rv = 0; auto settings = gSettings1; settings.expirySeconds = 3; std::time_t ts = time(NULL); SPConveyor conveyor = ConveyorNew(settings); conveyor->deleteAndStartFresh(); rv = conveyor->addRecord(rec1, ts-3); rv = conveyor->addRecord(rec2, ts-3); rv = conveyor->addRecord(rec1, ts-2); rv = conveyor->addRecord(rec2, ts-2); rv = conveyor->addRecord(rec1, ts); rv = conveyor->addRecord(rec2, ts); TestConveyorListener listener; // this is not an autoAdvance cursor, but as records are expired, // the cursor will still be advanced and expired records discarded. auto cursor = conveyor->openCursor(); size_t numSkipped=0, numExpired=0, numNotified = 0; EXPECT_EQ(6, conveyor->getNumRecords()); conveyor->enumerateRecords(listener, nullptr, cursor, ts-3); EXPECT_EQ(6, listener.numRecords); EXPECT_EQ(6, conveyor->getNumRecords()); listener = TestConveyorListener(); conveyor->enumerateRecords(listener, nullptr, cursor, ts-2); EXPECT_EQ(6, listener.numRecords); EXPECT_EQ(6, conveyor->getNumRecords()); listener = TestConveyorListener(); conveyor->enumerateRecords(listener, nullptr, cursor, ts-1); EXPECT_EQ(6, listener.numRecords); EXPECT_EQ(6, conveyor->getNumRecords()); conveyor->testGetReadCounters(numSkipped, numExpired, numNotified); EXPECT_EQ(0,numExpired); // the next reads should start expiring records listener = TestConveyorListener(); conveyor->enumerateRecords(listener, nullptr, cursor, ts); EXPECT_EQ(4, listener.numRecords); EXPECT_EQ(4, conveyor->getNumRecords()); conveyor->testGetReadCounters(numSkipped, numExpired, numNotified); EXPECT_EQ(2,numExpired); listener = TestConveyorListener(); conveyor->enumerateRecords(listener, nullptr, cursor, ts+1); EXPECT_EQ(2, listener.numRecords); EXPECT_EQ(2, conveyor->getNumRecords()); conveyor->testGetReadCounters(numSkipped, numExpired, numNotified); EXPECT_EQ(2,numExpired); listener = TestConveyorListener(); conveyor->enumerateRecords(listener, nullptr, cursor, ts+2); EXPECT_EQ(2, listener.numRecords); EXPECT_EQ(2, conveyor->getNumRecords()); listener = TestConveyorListener(); conveyor->enumerateRecords(listener, nullptr, cursor, ts+3); EXPECT_EQ(0, listener.numRecords); EXPECT_EQ(0, conveyor->getNumRecords()); } //-------------------------------------------------------------- // Test loading of persisted state. //-------------------------------------------------------------- TEST_F(ConveyorSimple, fill_and_read_state) { int rv = 0; auto settings = gSettings1; std::time_t ts = time(NULL); SPConveyor conveyor = ConveyorNew(settings); conveyor->deleteAndStartFresh(); int expBytes = 0; for (int i=0; i < settings.maxRecords; i++) { rv = conveyor->addRecord(i % 2 == 0 ? rec2 : rec1, ts); expBytes += (i % 2 == 0 ? rec2 : rec1).size(); ASSERT_EQ(0, rv); } conveyor->persistState(); TestConveyorListener listener; conveyor = ConveyorNew(settings); // allocate new one, must read state from file auto cursor = conveyor->openCursor(); conveyor->loadPersistedState(); conveyor->enumerateRecords(listener, nullptr, cursor, ts); EXPECT_EQ(settings.maxRecords, listener.numRecords); EXPECT_EQ(expBytes, listener.numBytes); conveyor->enumerateRecords(listener, nullptr, cursor, ts); EXPECT_EQ(settings.maxRecords*2, listener.numRecords); EXPECT_EQ(expBytes*2, listener.numBytes); } //-------------------------------------------------------------- // Load persisted state, where the read cursor is not at the // start of a file. //-------------------------------------------------------------- TEST_F(ConveyorSimple, fill_and_read_state_offset) { int rv = 0; auto settings = gSettings1; std::time_t ts = time(NULL); SPConveyor conveyor = ConveyorNew(settings); conveyor->deleteAndStartFresh(); // first write 2 records and read them rv = conveyor->addRecord(rec1, ts); rv = conveyor->addRecord(rec2, ts); TestConveyorListener listener; auto cursor = conveyor->openCursor(); EXPECT_EQ(2,conveyor->getNumRecords()); conveyor->enumerateRecords(listener, nullptr, cursor, ts); // advance will clear the two records conveyor->advanceCursor(cursor); EXPECT_EQ(0,conveyor->getNumRecords()); EXPECT_EQ(2, listener.numRecords); // now write 10 records int expBytes = 0; for (int i=2; i < settings.maxRecords; i++) { rv = conveyor->addRecord(i % 2 == 0 ? rec2 : rec1, ts); expBytes += (i % 2 == 0 ? rec2 : rec1).size(); ASSERT_EQ(0, rv); } EXPECT_EQ(settings.maxRecords-2,conveyor->getNumRecords()); // save state conveyor->persistState(); // make new instance, load state conveyor = ConveyorNew(settings); // allocate new one, must read state from file conveyor->loadPersistedState(); EXPECT_EQ(settings.maxRecords-2,conveyor->getNumRecords()); cursor = conveyor->openCursor(); listener = TestConveyorListener(); conveyor->enumerateRecords(listener, nullptr, cursor, ts); EXPECT_EQ(settings.maxRecords - 2, listener.numRecords); EXPECT_EQ(expBytes, listener.numBytes); // At this point, all files are waiting to be read. // Even though 2 records from file 0 are 'discarded'. // so we will drop even though numRecords < maxRecords rv = conveyor->addRecord(rec1, ts); EXPECT_EQ(1,rv); // now read conveyor->enumerateRecords(listener, nullptr, cursor, ts); conveyor->advanceCursor(cursor); // can write again rv = conveyor->addRecord(rec2, ts); EXPECT_EQ(0,rv); rv = conveyor->addRecord(rec2, ts); EXPECT_EQ(0,rv); EXPECT_EQ(2,conveyor->getNumRecords()); } //-------------------------------------------------------------- // consecutive reads should seek to last cursor offset, // rather than reading entire file. //-------------------------------------------------------------- TEST_F(ConveyorSimple, ensure_read_seek) { int rv = 0; size_t numSkipped=0, numExpired=0, numNotified = 0; auto settings = gSettings1; settings.maxRecords = 100; settings.numChunks = 2; std::time_t ts = time(NULL); SPConveyor conveyor = ConveyorNew(settings); conveyor->deleteAndStartFresh(); for (int i=0; i < 75; i++) { rv = conveyor->addRecord(rec2, ts); } EXPECT_EQ(75,conveyor->getNumRecords()); TestConveyorListener listener; conveyor->testGetReadCounters(numSkipped, numExpired, numNotified); EXPECT_EQ(0,numSkipped); EXPECT_EQ(0,numExpired); EXPECT_EQ(0,numNotified); auto cursor = conveyor->openCursor(); conveyor->enumerateRecords(listener, nullptr, cursor, ts); conveyor->advanceCursor(cursor); conveyor->testGetReadCounters(numSkipped, numExpired, numNotified); EXPECT_EQ(0,conveyor->getNumRecords()); EXPECT_EQ(0,numSkipped); EXPECT_EQ(0,numExpired); EXPECT_EQ(75,numNotified); for (int i=0; i < 25; i++) { rv = conveyor->addRecord(rec2, ts); } EXPECT_EQ(25,conveyor->getNumRecords()); listener = TestConveyorListener(); conveyor->enumerateRecords(listener, nullptr, cursor, ts); EXPECT_EQ(25,conveyor->getNumRecords()); conveyor->testGetReadCounters(numSkipped, numExpired, numNotified); EXPECT_EQ(0,numSkipped); EXPECT_EQ(0,numExpired); EXPECT_EQ(25,numNotified); conveyor->enumerateRecords(listener, nullptr, cursor, ts); conveyor->advanceCursor(cursor); EXPECT_EQ(0,conveyor->getNumRecords()); conveyor->testGetReadCounters(numSkipped, numExpired, numNotified); EXPECT_EQ(0,numSkipped); EXPECT_EQ(0,numExpired); EXPECT_EQ(25,numNotified); } //-------------------------------------------------------------- // test 32KB record size //-------------------------------------------------------------- TEST_F(ConveyorSimple, fill_large) { int rv = 0; auto settings = gSettings1; settings.maxRecordSize = 32*1024; std::time_t ts = time(NULL); SPConveyor conveyor = ConveyorNew(settings); conveyor->deleteAndStartFresh(); std::string tmp; tmp.reserve(settings.maxRecordSize); tmp.resize(settings.maxRecordSize); // add 5 records rv = conveyor->addRecord(tmp, ts); ASSERT_EQ(0, rv); rv = conveyor->addRecord(tmp, ts); ASSERT_EQ(0, rv); rv = conveyor->addRecord(tmp, ts); ASSERT_EQ(0, rv); rv = conveyor->addRecord(tmp, ts); ASSERT_EQ(0, rv); rv = conveyor->addRecord(tmp, ts); ASSERT_EQ(0, rv); auto listener = TestConveyorListener(); auto cursor = conveyor->openCursor(); conveyor->enumerateRecords(listener, nullptr, cursor, ts); EXPECT_EQ(5, conveyor->getNumRecords()); EXPECT_EQ(5, listener.numRecords); EXPECT_EQ(settings.maxRecordSize * 5, listener.numBytes); conveyor->advanceCursor(cursor); EXPECT_EQ(0, conveyor->getNumRecords()); } //-------------------------------------------------------------- // Multiple cursors //-------------------------------------------------------------- TEST_F(ConveyorSimple, multiple_cursors) { int rv = 0; auto settings = gSettings1; std::time_t ts = time(NULL); SPConveyor conveyor = ConveyorNew(settings); conveyor->deleteAndStartFresh(); std::vector<std::string> batch = {"A","B","C"}; rv = conveyor->addBatch(batch, ts); ASSERT_EQ(0,rv); ASSERT_EQ(3,conveyor->getNumRecords()); auto cursor1 = conveyor->openCursor(); auto cursor2 = conveyor->openCursor(); TestConveyorListener listener1; TestConveyorListener listener2; conveyor->enumerateRecords(listener1, nullptr, cursor1, ts); conveyor->advanceCursor(cursor1); EXPECT_EQ(3, listener1.numRecords); rv = conveyor->addBatch(batch, ts); ASSERT_EQ(6,conveyor->getNumRecords()); conveyor->enumerateRecords(listener2, nullptr, cursor2, ts); conveyor->advanceCursor(cursor2); ASSERT_EQ(3,conveyor->getNumRecords()); EXPECT_EQ(3, listener1.numRecords); EXPECT_EQ(6, listener2.numRecords); } //-------------------------------------------------------------- // loop of partial-fill, read+advance //-------------------------------------------------------------- TEST_F(ConveyorSimple, many_loops_no_drops) { int rv = 0; int num_loops = 100; auto settings = gSettings1; std::time_t ts = time(NULL); SPConveyor conveyor = ConveyorNew(settings); conveyor->deleteAndStartFresh(); auto cursor = conveyor->openCursor(true); TestConveyorListener listener; auto num_records_per_file = (settings.maxRecords / settings.numChunks); auto num_records_n_minus_one_files = (settings.numChunks - 1) * num_records_per_file; for (int j=0; j < num_loops; j++) { // limit max fill to num_records_per_file, since it's possible to // have less than settings.maxRecords available int num_records_this_loop = j % (num_records_n_minus_one_files) + 1; for (int i=0; i < num_records_this_loop; i++) { rv = conveyor->addRecord(i % 2 == 0 ? rec2 : rec1, ts); ASSERT_EQ(0, rv); } EXPECT_EQ(num_records_this_loop, conveyor->getNumRecords()); // read, advancing cursor conveyor->enumerateRecords(listener, nullptr, cursor, ts); conveyor->advanceCursor(cursor); EXPECT_EQ(0, conveyor->getNumRecords()); } } //-------------------------------------------------------------- // loop of partial-fill, read+advance //-------------------------------------------------------------- TEST_F(ConveyorSimple, many_loops) { int rv = 0; int num_loops = 100; auto settings = gSettings1; std::time_t ts = time(NULL); SPConveyor conveyor = ConveyorNew(settings); conveyor->deleteAndStartFresh(); auto cursor = conveyor->openCursor(true); TestConveyorListener listener; for (int j=0; j < num_loops; j++) { int num_records_this_loop = j % settings.maxRecords + 1; auto prevDrops = conveyor->getNumDrops(); int num_drops = 0; for (int i=0; i < num_records_this_loop; i++) { rv = conveyor->addRecord(i % 2 == 0 ? rec2 : rec1, ts); ASSERT_TRUE(rv >= 0); if (rv > 0) num_drops += 1; } int num_records_written = num_records_this_loop - num_drops; EXPECT_EQ(prevDrops + num_drops, conveyor->getNumDrops()); EXPECT_EQ(num_records_written, conveyor->getNumRecords()); // read, advancing cursor conveyor->enumerateRecords(listener, nullptr, cursor, ts); conveyor->advanceCursor(cursor); EXPECT_EQ(0, conveyor->getNumRecords()); } }
#include <iostream> using namespace std; int a, b; int main() { cin >> a >> b; int relt = b - a; int total = 0; for (int i=1; i<relt; i++) { total += i; } cout << total - a; }
#include "MonitorarAPI.cpp" #include <vector> using namespace std; int main(int argc, char *argv[]){ /* aqui faz todas as configurações para os gio de entrada e saída */ long freeMem, maxMen; float percent; ifstream infoMem, infoPid; ifstream cpuLog; string aux; power light = off; int monitorarMemoria_ou_CPU; double totalCPU = 0; string percentCPU; vector<double> percentVectorCPU; while (true) { cout << endl << "Qual recurso voce deseja monitorar? memoria ou CPU? " << endl << "Digite 1 caso queira que seja a memoria. Se não, digite 2 para que a CPU seja monitorada... " << endl; cin >> monitorarMemoria_ou_CPU; if( monitorarMemoria_ou_CPU == 1){ /// MONITORANDO O USO DA MEMÓRIA system("cat /proc/meminfo | head -2 | awk '{print $2}' > mem.log"); infoMem.open("mem.log"); if (infoMem.is_open()) { getline(infoMem, aux); maxMen = stoi(aux); getline(infoMem, aux); freeMem = stoi(aux); infoMem.close(); system("rm mem.log"); } else { cerr << "Falha na leitura do arquivo que contem as infomacoes sobre a memoria!" << endl; system("rm mem.log"); exit(1); } } else{ /// MONITORANDO O USO DA CPU std::system("ps aux --sort=-%cpu | awk '{ print $3 }' > cpu.log" ); cpuLog.open("cpu.log"); if( cpuLog.is_open() ){ cpuLog >> percentCPU; while( cpuLog >> percentCPU ){ percentVectorCPU.push_back( std::stod(percentCPU) ); } for( auto& n: percentVectorCPU){ totalCPU += n; } } else { cerr << "Falha na leitura do arquivo que contem as infomacoes sobre a CPU!" << endl; system("rm cpu.log"); exit(1); } } if( monitorarMemoria_ou_CPU == 1) percent = (float)(maxMen - freeMem) *100 / maxMen; else percent = totalCPU; if(percent < 25.0f) { setVermelho(off); setAmarelo(off); setVerde(on); } else if (percent < 50.0f) { setVermelho(off); setAmarelo(on); setVerde(off); } else if (percent < 75.0f) { setVermelho(on); setAmarelo(off); setVerde(off); } else { if (buttonIsPressed()) { system("ps aux --sort=-%mem | head -2 | tail -1 | awk '{print $2}' > killAux.txt"); infoPid.open("killAux.txt"); if (infoPid.is_open()) { getline(infoPid, aux); infoPid.close(); system("rm killAux.txt"); string kill = "kill -9 "; kill += aux; system(kill.c_str()); // apaga todos setVermelho(off); setAmarelo(off); setVerde(off); // 3,5s + 0,5 padrão usleep(3500000); } else { cerr << "Falha na leitura do arquivo de info do PID!" << endl; system("rm killAux.txt"); exit(2); } } else { setAll(light); usleep(500000); if(light == off) light = on; else light = off; } } usleep(500000); } setAll(off); }
#pragma once #include "..\Common\Pch.h" class Direct3D { public: Direct3D(); ~Direct3D(); void Initialize(); void Clear(FLOAT r = 0.2F, FLOAT g = 0.2F, FLOAT b = 0.2F, FLOAT a = 1.0F); void Present(); // Get, Set ID3D11Device* GetDevice(); ID3D11DeviceContext* GetContext(); void SetDefaultRenderTarget(); void SetDefaultViewport(); Singleton_h(Direct3D) private: ID3D11Device* mDevice; ID3D11DeviceContext* mDeviceContext; UINT m4xMsaaQuality; IDXGISwapChain* mSwapChain; ID3D11RenderTargetView* mRenderTargetView; ID3D11Texture2D* mDepthStencilTexture; ID3D11DepthStencilView* mDepthStencilView; D3D11_VIEWPORT mViewport; void InitializeDeviceAndContext(); void InitializeMSAA(); void InitializeSwapChain(); void InitializeRenderTargetView(); void InitializeDepthStencilView(); void InitializeBindView(); void InitializeViewport(); };
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2008 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. * * @author Patricia Aas (psmaas) */ #ifndef UI_NODE_H #define UI_NODE_H #ifdef FEATURE_UI_TEST class OpAccessibilityExtension; class XMLFragment; #include "adjunct/ui_test_framework/OpExtensionContainer.h" /** * @brief A node representing a piece of the UI during testing * @author Patricia Aas */ class OpUiNode : public OpExtensionContainer::Listener { public: static OP_STATUS Create(OpExtensionContainer* element, OpUiNode*& node); virtual ~OpUiNode(); OP_STATUS Export(XMLFragment& fragment); OP_STATUS ClickAll(); OP_STATUS AddChild(OpUiNode* child); // Implementing the OpExtensionContainer::Listener interface virtual OP_STATUS OnChildAdded(OpExtensionContainer* child); virtual void OnExtensionContainerDeleted(); private: OpUiNode(); OP_STATUS SetExtensionContainer(OpExtensionContainer* container); OP_STATUS ExportNode(XMLFragment& fragment); OP_STATUS StoreAllData(); const uni_char* GetRoleAsString(); BOOL IsVisible(); BOOL IsEnabled(); BOOL IsFocused(); BOOL HasValue(); BOOL HasMinValue(); BOOL HasMaxValue(); OP_STATUS GetText(OpString& text); OP_STATUS GetDescription(OpString& description); OP_STATUS GetUrl(OpString& url); int GetValue(); int GetMinValue(); int GetMaxValue(); OpAccessibilityExtension::AccessibilityState GetState(); OpAccessibilityExtension::ElementKind GetRole(); OpAutoVector<OpUiNode> m_children; OpExtensionContainer* m_extension_container; OpAccessibilityExtensionListener* m_element; // Cached values for items that have been removed BOOL m_removed; BOOL m_visible; BOOL m_enabled; BOOL m_focused; BOOL m_has_value; BOOL m_has_min_value; BOOL m_has_max_value; int m_value; int m_min_value; int m_max_value; OpAccessibilityExtension::AccessibilityState m_state; OpAccessibilityExtension::ElementKind m_role; OpString m_text; OpString m_description; OpString m_url; }; #endif // FEATURE_UI_TEST #endif // UI_NODE_H
#ifdef DEBUG #define _GLIBCXX_DEBUG #endif #include <iostream> #include <algorithm> #include <cstdio> #include <cstdlib> #include <ctime> #include <memory.h> #include <cmath> #include <string> #include <cstring> #include <queue> #include <vector> #include <set> #include <deque> #include <map> #include <functional> #include <numeric> #include <sstream> #include <complex> typedef long double LD; typedef long long LL; typedef unsigned long long ULL; typedef unsigned int uint; #define PI 3.1415926535897932384626433832795 #define sqr(x) ((x)*(x)) using namespace std; int di[9], dj[9], dd[3][3], a[9][9], lg[1024]; bool solve(int st) { for (int i = 0; i < 81; ++i, ++st) { if (st >= 81) st = 0; int x = st / 9; int y = st % 9; int msk = di[x] & dj[y] & dd[x % 3][y % 3]; if ((msk & (msk - 1)) == 0) { a[x][y] = lg[msk]; if (solve(st)) } } for (int i = 0; i < 9; ++i) { for (int j = 0; j < 9; ++j) { if (msk & (msk - 1)) { } } } for (int i = 0; i < 9; ++i) if ((di[i] & (di[i] - 1)) == 0) { for (int j = 0; j < 9; ++j) if (a[i][j] == 0) { a[i][j] = lg[di[i]]; di[i] ^= (1 << a[i][j]); dj[j] ^= (1 << a[i][j]); dd[i % 3][j % 3] ^= (1 << a[i][j]); solve(); a[i][j] = 0; di[i] ^= (1 << a[i][j]); dj[j] ^= (1 << a[i][j]); dd[i % 3][j % 3] ^= (1 << a[i][j]); break; } } } int main() { freopen(".in", "r", stdin); freopen(".out", "w", stdout); for (int i = 0; i <= 9; ++i) lg[1 << i] = i; int T; scanf("%d", &T); while (T--) { for (int i = 0; i < 9; ++i) di[i] = dj[i] = dd[i % 3][i / 3] = (1 << 10) - 2; for (int i = 0; i < 9; ++i) { for (int j =0 ; j < 9; ++j) { scanf("%d", &a[i][j]); di[i] ^= (1 << a[i][j]); dj[j] ^= (1 << a[i][j]); dd[i % 3][j % 3] ^= (1 << a[i][j]); } } solve(); for (int i = 0; i < 9; ++i) { for (int j = 0; j < 9; ++j) printf("%d ", a[i][j]); puts(""); } } return 0; }
#include "utilityBase.h" utilityBase::utilityBase(const State& current, const StochProc& stoch, const EquilFns& fns) : curSt(&current), curStoch(stoch), curFns(fns) { } utilityBase::~utilityBase() { } double utilityBase::consUtil(double consumption){ return utilityFunctions::integer_power(consumption, 1 - RRA) / (1 - RRA); } double utilityBase::marginalConsUtil(double consumption){ return utilityFunctions::integer_power(consumption, -RRA); } void utilityBase::updateCurrent(const State& current){ curSt = &current; }
#include <iostream> #include <string> #include <boost/program_options.hpp> #include <boost/asio.hpp> #include "Server.hpp" #include "Database.hpp" #include "DatabaseServerApi.hpp" namespace po = boost::program_options; int main(int argc, char* argv[]) { po::variables_map vm; po::options_description desc{"simple database showcase"}; desc.add_options() ("help,h", "Help screen") ("port,p", po::value<short>()->default_value(20000), "port for client / server communication") ; try { po::store(parse_command_line(argc, argv, desc), vm); po::notify(vm); if (vm.count("help")) { std::cout << desc << std::endl; return 1; } } catch (const po::error& er) { std::cout << er.what() << std::endl; return -1; } catch (const std::exception& e) { std::cout << e.what() << std::endl; return -1; } boost::asio::io_context io_context; Server s(io_context, vm["port"].as<short>()); io_context.run(); return 0; }
#include "gromacsoptionfile.h" #include <QHBoxLayout> #include <QLineEdit> #include <QPushButton> #include <QFileDialog> #include <QFile> GromacsOptionFile::GromacsOptionFile(bool inputFile, QWidget *parent, QString value) : GromacsOptionEnter(parent, value), _gromacsToolsDefinition(GromacsToolsDefinition::GetInstance()), _error(false), _inputFile(inputFile) { if(_inputFile) { QPushButton *pushButton = new QPushButton("...", this); pushButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); _layout->addWidget(pushButton); connect(pushButton, SIGNAL(clicked()), this, SLOT(HandleSelectFileButton())); connect(_lineEdit, SIGNAL(textChanged(QString)), this, SLOT(HandleError())); HandleError(); } } bool GromacsOptionFile::CollectOption(QStringList &listOfOptions) { if(_error) { return false; } listOfOptions.push_back(_lineEdit->text()); return true; } void GromacsOptionFile::HandleSelectFileButton() { QString fileName = \ QFileDialog::getOpenFileName(this, tr("Select input file"), _gromacsToolsDefinition.ProjectsDefaultDirectory()); if("" != fileName) { _lineEdit->setText(fileName); } } void GromacsOptionFile::HandleError() { if(_inputFile && isEnabled() && (!QFile::exists(_lineEdit->text()))) { _lineEdit->setStyleSheet("background-color: red"); _error = true; } else { _lineEdit->setStyleSheet("background-color: white"); _error = false; } }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2012 Opera Software ASA. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #ifndef HISTORY_DELAYED_SAVE_H #define HISTORY_DELAYED_SAVE_H #if defined(DIRECT_HISTORY_SUPPORT) || defined(HISTORY_SUPPORT) #include "modules/prefs/prefsmanager/collections/pc_files.h" #include "modules/hardcore/timer/optimer.h" class DelayedSave : public OpTimerListener { public: DelayedSave() : m_is_dirty(FALSE), m_save_timer_enabled(TRUE), m_timeout_ms(HISTORY_WRITE_TIMEOUT_PERIOD) {} virtual ~DelayedSave() {} /** * * * @param force * @return OpStatus::OK or OpStatus::ERR_NO_MEMORY if out of memory */ OP_STATUS RequestSave(BOOL force = FALSE); /** * Enable the save timer (on by default) * @return OpStatus::OK or OpStatus::ERR_NO_MEMORY if out of memory */ OP_STATUS EnableTimer() {m_save_timer_enabled = TRUE; return OpStatus::OK;} /** * Disable the save timer (on by default) - no unforced saves will be performed * @return OpStatus::OK or OpStatus::ERR_NO_MEMORY if out of memory */ OP_STATUS DisableTimer() {m_save_timer_enabled = FALSE; return OpStatus::OK;} /** * This timeout function is activated when the data in the list * should be saved * * @param timer The timer that triggered the timeout */ virtual void OnTimeOut(OpTimer* timer); /** * Writes the items to file * * @param ofp - the file to write to * @return OpStatus::OK or OpStatus::ERR_NO_MEMORY if out of memory */ virtual OP_STATUS Write(OpFile *ofp) = 0; /** * @return the filepref of the file to save to */ virtual PrefsCollectionFiles::filepref GetFilePref() = 0; private: void SetDirty(); // Private fields OpTimer m_timer; BOOL m_is_dirty; BOOL m_save_timer_enabled; UINT32 m_timeout_ms; }; #endif // DIRECT_HISTORY_SUPPORT || HISTORY_SUPPORT #endif // HISTORY_DELAYED_SAVE_H
/* Name: Copyright: Author: Hill Bamboo Date: 2019/9/1 9:56:00 Description: --> input 5 1 3 1 1 2 --> expected 1 2 3 2 4 5 2 5 */ #include <bits/stdc++.h> using namespace std; const int maxm = 2000 + 10; const int maxn = 1000 + 10; int ans[maxm]; int tree[maxn]; int m, n; int main() { cin >> n; for (int i = 0; i < n; ++i) { scanf("%d", &tree[i]); m += tree[i]; } ans[0] = 1; --tree[0]; int cur = 0; bool no_ans = false; for (int i = 1; i < m; ++i) { int j = -1; if (cur == 0) { j = cur + 1; while (j < n && tree[j] <= 0) ++j; } else { j = cur - 1; while (j >= 0 && tree[j] <= 0) --j; } if (j < 0 || n <= j) { no_ans = true; break; } else { ans[i] = j + 1; --tree[j]; cur = j; } } // if (no_ans) { // cout << "-" << endl; // } else for (int i = 0; i < m; ++i) { printf("%d%c", ans[i], i == m - 1 ? '\n' : ' '); } return 0; }
#include "bilinear_form.hpp" #include <cmath> #include <map> #include <set> #include "datastructures/multi_tree_view.hpp" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "integration.hpp" #include "operators.hpp" #include "space/initial_triangulation.hpp" #include "space/triangulation.hpp" #include "space/triangulation_view.hpp" using namespace space; using namespace datastructures; using ::testing::ElementsAre; int bsd_rnd() { static unsigned int seed = 0; int a = 1103515245; int c = 12345; unsigned int m = 2147483648; return (seed = (a * seed + c) % m); } Eigen::VectorXd RandomVector(const TreeVector<HierarchicalBasisFn>& vec) { auto nodes = vec.Bfs(); Eigen::VectorXd result(nodes.size()); result.setRandom(); for (int v = 0; v < nodes.size(); v++) if (nodes[v]->node()->on_domain_boundary()) result[v] = 0; return result; } Eigen::MatrixXd MatrixQuad(const TreeVector<HierarchicalBasisFn>& tree_in, const TreeVector<HierarchicalBasisFn>& tree_out, bool deriv) { auto functions_in = tree_in.Bfs(); auto functions_out = tree_out.Bfs(); Eigen::MatrixXd mat(functions_out.size(), functions_in.size()); for (size_t i = 0; i < functions_out.size(); ++i) for (size_t j = 0; j < functions_in.size(); ++j) { double quad = 0; auto fn_out = functions_out[i]->node(); auto fn_in = functions_in[j]->node(); if (!fn_out->vertex()->on_domain_boundary && !fn_in->vertex()->on_domain_boundary) { auto elems_fine = fn_in->level() < fn_out->level() ? fn_out->support() : fn_in->support(); for (auto elem : elems_fine) { if (deriv) { quad += Integrate( [&](double x, double y) { return fn_out->EvalGrad(x, y).dot(fn_in->EvalGrad(x, y)); }, *elem, /*degree*/ 0); } else { quad += Integrate( [&](double x, double y) { return fn_out->Eval(x, y) * fn_in->Eval(x, y); }, *elem, /*degree*/ 2); } } } mat(i, j) = quad; } return mat; } constexpr int max_level = 5; TEST(BilinearForm, SymmetricQuadrature) { auto T = InitialTriangulation::UnitSquare(); T.hierarch_basis_tree.UniformRefine(max_level); auto vec_in = TreeVector<HierarchicalBasisFn>(T.hierarch_basis_meta_root); vec_in.DeepRefine(); auto vec_out = vec_in.DeepCopy(); auto mass_bil_form = CreateBilinearForm<MassOperator>(vec_in, vec_out); auto mass_mat = mass_bil_form.ToMatrix(); auto mass_quad = MatrixQuad(vec_in, vec_out, /*deriv*/ false); ASSERT_TRUE(mass_mat.isApprox(mass_quad)); // Check that the transpose is correct auto mass_tmat = mass_bil_form.Transpose().ToMatrix(); ASSERT_TRUE(mass_mat.transpose().isApprox(mass_tmat)); // Check also the apply of a random vector. Eigen::VectorXd v = RandomVector(vec_in); vec_in.FromVector(v); mass_bil_form.Apply(); ASSERT_TRUE(vec_out.ToVector().isApprox(mass_quad * v)); auto stiff_bil_form = CreateBilinearForm<StiffnessOperator>(vec_in, vec_out); auto stiff_mat = stiff_bil_form.ToMatrix(); auto stiff_quad = MatrixQuad(vec_in, vec_out, /*deriv*/ true); ASSERT_TRUE(stiff_mat.isApprox(stiff_quad)); // Check that the transpose is correct auto stiff_tmat = stiff_bil_form.Transpose().ToMatrix(); ASSERT_TRUE(stiff_mat.transpose().isApprox(stiff_tmat)); // Check also the apply of a random vector. v = RandomVector(vec_in); vec_in.FromVector(v); stiff_bil_form.Apply(); ASSERT_TRUE(vec_out.ToVector().isApprox(stiff_quad * v)); } TEST(BilinearForm, UnsymmetricQuadrature) { auto T = InitialTriangulation::UnitSquare(); T.hierarch_basis_tree.UniformRefine(max_level); for (bool subset : {true, false}) { for (size_t j = 0; j < 20; ++j) { auto vec_in = TreeVector<HierarchicalBasisFn>(T.hierarch_basis_meta_root); auto vec_out = TreeVector<HierarchicalBasisFn>(T.hierarch_basis_meta_root); vec_in.DeepRefine( /* call_filter */ [](auto&& nv) { return nv->level() <= 0 || bsd_rnd() % 3 != 0; }); vec_out.DeepRefine( /* call_filter */ [](auto&& nv) { return nv->level() <= 0 || bsd_rnd() % 3 != 0; }); if (subset) vec_out.Union(vec_in); else vec_in.Union(vec_out); auto mass_bil_form = CreateBilinearForm<MassOperator>(vec_in, vec_out); auto mass_mat = mass_bil_form.ToMatrix(); auto mass_quad = MatrixQuad(vec_in, vec_out, /*deriv*/ false); ASSERT_TRUE(mass_mat.isApprox(mass_quad)); // Check that the transpose is correct auto mass_tmat = mass_bil_form.Transpose().ToMatrix(); ASSERT_TRUE(mass_mat.transpose().isApprox(mass_tmat)); // Check also the apply of a random vector. Eigen::VectorXd v = RandomVector(vec_in); vec_in.FromVector(v); mass_bil_form.Apply(); ASSERT_TRUE(vec_out.ToVector().isApprox(mass_quad * v)); auto stiff_bil_form = CreateBilinearForm<StiffnessOperator>(vec_in, vec_out); auto stiff_mat = stiff_bil_form.ToMatrix(); auto stiff_quad = MatrixQuad(vec_in, vec_out, /*deriv*/ true); ASSERT_TRUE(stiff_mat.isApprox(stiff_quad)); // Check that the transpose is correct auto stiff_tmat = stiff_bil_form.Transpose().ToMatrix(); ASSERT_TRUE(stiff_mat.transpose().isApprox(stiff_tmat)); // Check also the apply of a random vector. v = RandomVector(vec_in); vec_in.FromVector(v); stiff_bil_form.Apply(); ASSERT_TRUE(vec_out.ToVector().isApprox(stiff_quad * v)); } } }
#include <bitset> #include <cassert> #include <iostream> #include <wiringPi.h> #include <wiringPiSPI.h> typedef unsigned char uchar; typedef unsigned int uint; typedef uint16_t u16; using namespace std; void method1(){ uchar data[2]; wiringPiSPIDataRW(0, data, 2); // discard auto ms = micros(); //u16 v; while(1) { //for(int i = 0; i<100; ++i) { wiringPiSPIDataRW(0, data, 2); u16 v = ((int) data[0] << 8) + (int) data[1] ; //cout << (int) data[0] << " " << (int) data[1] << " " << v << "\n"; //cout << std::bitset<16>(micros()) << std::bitset<16>(v); cout << (micros() -ms) << "\t" << v << "\n"; } ms = micros() - ms; //cout << "100 reads took " << ms << "us\n"; } void method2() { uchar data[200]; wiringPiSPIDataRW(0, data, sizeof(data)); int semi = sizeof(data)/2; for(int i=0; i<semi; ++i) { u16 val = ((int) data[i*2] << 8) + (int) data[i+2+1]; //val <<=8 + data[i*2]; cout << val << "\n"; } } int main() { int fd = wiringPiSPISetup(0, 1000000); assert(fd != -1); //cout << sizeof(uint) << "\n"; // s/b 4 bytes on 32-bit m/c method1(); }
#include "fetch.hh" #include "sql.h" #include "sqlext.h" #include "nctypes.hh" namespace NC { inline nc_variant_t get_value_at(nanodbc::result* result, int col_no) { if (result->is_null(col_no)) { return boost::blank(); } int datatype { result->column_datatype(col_no) }; switch (datatype) { case SQL_TINYINT: case SQL_SMALLINT: case SQL_BIT: case SQL_INTEGER: return result->get<nc_long_t>(col_no); case SQL_FLOAT: case SQL_REAL: case SQL_DOUBLE: return result->get<nc_number_t>(col_no); case SQL_CHAR: case SQL_NUMERIC: case SQL_DECIMAL: case SQL_BIGINT: return result->get<nc_string_t>(col_no); #ifdef NANODBC_ENABLE_UNICODE case SQL_WCHAR: case SQL_WVARCHAR: case SQL_WLONGVARCHAR: #endif case SQL_VARCHAR: case SQL_LONGVARCHAR: return result->get<nc_string_t>(col_no); case SQL_TYPE_DATE: return result->get<nc_date_t>(col_no); case SQL_TYPE_TIME: case SQL_TIME: return result->get<nc_time_t>(col_no); case SQL_TYPE_TIMESTAMP: case SQL_TIMESTAMP: return result->get<nc_timestamp_t>(col_no); case SQL_BINARY: case SQL_VARBINARY: case SQL_LONGVARBINARY: // fallthrough is intentional - try to handle // data as binary as last resort default: return result->get<nc_binary_t>(col_no); } } nc_result_t fetch_result_eagerly(nanodbc::result* result) { int columns = result->columns(); std::vector<nc_string_t> column_names {}; column_names.reserve(columns); for (nc_short_t i = 0; i < columns; ++i) { column_names.push_back(result->column_name(i)); } nc_result_t sql_result {}; sql_result.reserve(result->rowset_size()); while (result->next()) { nc_row_t row = nc_row_t {}; for (int i = 0; i < columns; ++i) { row.emplace_back(column_names[i], get_value_at(result, i)); } sql_result.push_back(std::move(row)); } return sql_result; } } // namespace NC
/**************************************************************************** * * * Author : lukasz.iwaszkiewicz@gmail.com * * ~~~~~~~~ * * License : see COPYING file for details. * * ~~~~~~~~~ * ****************************************************************************/ #ifndef BAJKA_MODEL_LAYOUT_H_ #define BAJKA_MODEL_LAYOUT_H_ #include "geometry/Point.h" #include "util/ReflectionMacros.h" #include "IGroupProperties.h" #include "Align.h" namespace Model { struct IModel; /** * Wałaściwości obiektu, który jest wewnątrz Model::RelativeGroup. Te właściwości definiują * rozmiary i położenie obiektu, który jest wewnątrz Model::RelativeGroup. Kiedy są ustawione, * to przesunięcie i rozmiary obiektu (Model::IModel::setTranslate etc) nie są brane pod * uwagę. */ struct RelativeGroupProperties : public IGroupProperties { C__ (void) RelativeGroupProperties () : hAlign (HA_CENTER), vAlign (VA_CENTER), width (-1), height (-1), translate (Geometry::makePoint (0, 0)) {} virtual ~RelativeGroupProperties () {} /** * Wyrównanie w poziomie. */ HAlign pe_ (hAlign); /** * Wyrównanie w pionie. */ VAlign pe_ (vAlign); /** * Szerokość w procentach. To pole jest brane pod uwagę tylko w przypadku, gdy model, któremu je usawimy * implementuje Model::IBox i nie są nałożone na niego trasformacje obrotu i skali. Czyli jednym słowem * pudełko równoległe do osi i bez skalowania. Wartość ujemna nie jest brana pod uwagę. */ float p_ (width); /** * Wysokość w procentach. To pole jest brane pod uwagę tylko w przypadku, gdy model, któremu je usawimy * implementuje Model::IBox i nie są nałożone na niego trasformacje obrotu i skali. Czyli jednym słowem * pudełko równoległe do osi i bez skalowania. Wartość ujemna nie jest brana pod uwagę. */ float p_ (height); /** * Przesunięcie względem rozmiarów rodzica. Działa tylko w gdy rodzic jest * typu RelativeGroup. Jednostką jest procent. <del>Wartość ujemna któregoś z koordynatów * oznacza wartość nieustaloną i nie brana pod uwagę.</del> */ Geometry::Point P_ (translate); E_ (RelativeGroupProperties) }; } /* namespace Model */ # endif /* LAYOUT_H_ */
#include <cppunit/extensions/HelperMacros.h> #include "cppunit/BetterAssert.h" #include "io/AutoClose.h" using namespace std; using namespace Poco; namespace BeeeOn { class AutoCloseTest : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(AutoCloseTest); CPPUNIT_TEST(testBlock); CPPUNIT_TEST(testTryCatch); CPPUNIT_TEST(testFailing); CPPUNIT_TEST_SUITE_END(); public: void testBlock(); void testTryCatch(); void testFailing(); }; CPPUNIT_TEST_SUITE_REGISTRATION(AutoCloseTest); class ToBeClosed { public: void close() { closed = true; } bool closed = false; }; class FailingOnClose { public: void close() { throw "terrible failure"; } }; void AutoCloseTest::testBlock() { ToBeClosed device; CPPUNIT_ASSERT(!device.closed); { AutoClose<ToBeClosed> wrapper(device); CPPUNIT_ASSERT(!device.closed); } CPPUNIT_ASSERT(device.closed); } void AutoCloseTest::testTryCatch() { ToBeClosed device; CPPUNIT_ASSERT(!device.closed); try { AutoClose<ToBeClosed> wrapper(device); CPPUNIT_ASSERT(!device.closed); throw "anything"; } catch (...) { CPPUNIT_ASSERT(device.closed); return; } CPPUNIT_FAIL("should never reach this point"); } static void failClose(FailingOnClose &device) { AutoClose<FailingOnClose> wrapper(device); } void AutoCloseTest::testFailing() { FailingOnClose device; CPPUNIT_ASSERT_NO_THROW(failClose(device)); } }
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ //bfs -written by myself class Codec { public: // Encodes a tree to a single string. string serialize(TreeNode* root) { string s = ""; queue<TreeNode*> tree; tree.push(root); while(!tree.empty()){ TreeNode* node = tree.front(); tree.pop(); if(node == NULL){ s += "n"; }else{ s += to_string(node->val); tree.push(node->left); tree.push(node->right); } s += '*'; } return s; } // Decodes your encoded data to tree. TreeNode* deserialize(string data) { size_t start = 0, mid, end = data.find("*"); string s = data.substr(start, end-start); if(s == "n") return NULL; TreeNode* root = new TreeNode(stoi(s)); queue<TreeNode*> tree; tree.push(root); while(!tree.empty()){ TreeNode* node = tree.front(); tree.pop(); start = end+1; mid = data.find("*", start); end = data.find("*", mid+1); string left = data.substr(start, mid-start); string right = data.substr(mid+1, end-mid-1); if(left != "n"){ TreeNode* leftChild = new TreeNode(stoi(left)); node->left = leftChild; tree.push(leftChild); } if(right != "n"){ TreeNode* rightChild = new TreeNode(stoi(right)); node->right = rightChild; tree.push(rightChild); } } return root; } }; // Your Codec object will be instantiated and called as such: // Codec codec; // codec.deserialize(codec.serialize(root));
#pragma once #include <vector> namespace hdd::gamma { class RawData { public: RawData(const std::string& filename); uint32_t Inputs() const; uint32_t Outputs() const; uint32_t Vectors() const; uint32_t Series() const; const std::vector<double>& operator[](uint32_t index) const; private: std::vector<std::vector<double>> data_; uint32_t inputs_; uint32_t outputs_; void ReadFirstLineAndDetectFileFormat(std::ifstream& inputStream); }; }
#ifndef OPTIONAL_H #define OPTIONAL_H template<typename T> class optional { public: optional(void) : _initialized(false) {} optional(const T& val) : _initialized(true) { ::new (_data.data()) T(val); } ~optional(void) { if (_initialized) data()->~T(); } T& operator*(void) { return *data(); } T* operator->(void) { return data(); } private: T* data(void) { return reinterpret_cast<T*>(_data.data()); } std::array<std::uint8_t, sizeof(T)> _data; bool _initialized; }; #endif // OPTIONAL_H
#include <iostream> #include <string> #include <fstream> #include <vector> #include <sstream> #include <Eigen/Core> #include <Eigen/Dense> #include <Eigen/Cholesky> #include <Eigen/SVD> #include <sophus/se3.hpp> void convertSE3ToTf(const Eigen::VectorXf &xi, Eigen::Matrix3f &rot, Eigen::Vector3f &t) { // rotation Sophus::SE3f se3 = Sophus::SE3f::exp(xi); Eigen::Matrix4f mat = se3.matrix(); rot = mat.topLeftCorner(3, 3); t = mat.topRightCorner(3, 1); } void convertTfToSE3(const Eigen::Matrix3f &rot, const Eigen::Vector3f &t, Eigen::VectorXf &xi) { Sophus::SE3f se3(rot, t); xi = Sophus::SE3f::log(se3); } cv::Mat loadIntensity(const std::string &filename) { cv::Mat imgGray = cv::imread(filename, CV_LOAD_IMAGE_GRAYSCALE); // convert gray to float cv::Mat gray; imgGray.convertTo(gray, CV_32FC1, 1.0f / 255.0f); return gray; } cv::Mat loadDepth(const std::string &filename) { //fill/read 16 bit depth image cv::Mat imgDepthIn = cv::imread(filename, CV_LOAD_IMAGE_ANYDEPTH | CV_LOAD_IMAGE_ANYCOLOR); cv::Mat imgDepth; imgDepthIn.convertTo(imgDepth, CV_32FC1, (1.0 / 5000.0)); return imgDepth; }
class Solution { public: vector<vector<int>> threeSum(vector<int>& nums) { sort(nums.begin(), nums.end()); vector< vector<int> > res; int N = nums.size(); for(int i=0;i<N;i++){ if(i > 0 && nums[i-1] == nums[i]) continue; int target = -nums[i]; int l = i+1, r = N-1; // two sum problem while(l < r){ int twoSum = nums[l] + nums[r]; if(twoSum < target) l++; else if(twoSum > target) r--; else{ // create solution tuple vector<int> subres; subres.push_back(nums[i]); subres.push_back(nums[l]); subres.push_back(nums[r]); res.push_back(subres); // increment l to prevent getting same solution while(subres[1] == nums[l]) l++; } } } return res; } };
// Created on: 1998-08-18 // Created by: Yves FRICAUD // Copyright (c) 1998-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _TopOpeBRepDS_Association_HeaderFile #define _TopOpeBRepDS_Association_HeaderFile #include <Standard.hxx> #include <TopOpeBRepDS_DataMapOfInterferenceListOfInterference.hxx> #include <Standard_Transient.hxx> #include <TopOpeBRepDS_ListOfInterference.hxx> #include <Standard_Boolean.hxx> class TopOpeBRepDS_Interference; class TopOpeBRepDS_Association; DEFINE_STANDARD_HANDLE(TopOpeBRepDS_Association, Standard_Transient) class TopOpeBRepDS_Association : public Standard_Transient { public: Standard_EXPORT TopOpeBRepDS_Association(); Standard_EXPORT void Associate (const Handle(TopOpeBRepDS_Interference)& I, const Handle(TopOpeBRepDS_Interference)& K); Standard_EXPORT void Associate (const Handle(TopOpeBRepDS_Interference)& I, const TopOpeBRepDS_ListOfInterference& LI); Standard_EXPORT Standard_Boolean HasAssociation (const Handle(TopOpeBRepDS_Interference)& I) const; Standard_EXPORT TopOpeBRepDS_ListOfInterference& Associated (const Handle(TopOpeBRepDS_Interference)& I); Standard_EXPORT Standard_Boolean AreAssociated (const Handle(TopOpeBRepDS_Interference)& I, const Handle(TopOpeBRepDS_Interference)& K) const; DEFINE_STANDARD_RTTIEXT(TopOpeBRepDS_Association,Standard_Transient) protected: private: TopOpeBRepDS_DataMapOfInterferenceListOfInterference myMap; }; #endif // _TopOpeBRepDS_Association_HeaderFile
#ifndef HW_264_ENCODER_H #define HW_264_ENCODER_H #include "MediaEncoder.h" #include "HwMediaEncoder.h" //from libhwcodec #include "SwsScale.h" //硬编码: YUV->h264 //////////////////////////////////////////////////////////////////////////////// class CHw264Encoder : public CMediaEncoder { public: CHw264Encoder(AVCodecContext *videoctx, int fmt, CHwMediaEncoder *pEncode); virtual ~CHw264Encoder(); public: virtual CBuffer *Encode(CBuffer *pRawdata/*YUV*/); virtual CBuffer *GetDelayedFrame(); private: CHwMediaEncoder *m_pEncode; CSwsScale *m_pScales; CLASS_LOG_DECLARE(CHw264Encoder); }; #endif
#include<MsTimer2.h> //左右电机码盘 #define ENCODER_R1 3 #define ENCODER_R2 4 #define ENCODER_L1 2 #define ENCODER_L2 5 //左右电机PWM波以及电机正负极接入 #define PWML_R 10 #define INL_R1 A2 #define INL_R2 A1 #define PWML_L 9 #define INL_L1 A4 #define INL_L2 A3 #define PERIOD 10 //从前进方向的最左边开始排序红外传感器引脚 #define trac1 A0 #define trac2 A5 #define trac3 6 #define trac4 7 #define trac5 8 #define trac6 11 #define trac7 13 #define tracL 12//车体左侧的 #define tracR 7 const float originTargetV = 60; float targetRv = originTargetV;//右轮目标速度 float targetLv = originTargetV;//左轮目标速度 volatile long encoderVal_R = 0; volatile long encoderVal_L = 0; volatile int encodertime_L = 0; volatile int encodertime_R = 0; #define MID 4 float error_midValLast2 = 0; float error_midValLast1 = 0; float dLast = 0; float midVal; int _redVal[7]; float midLast = 4; volatile float velocityR; volatile float velocityL; float ukR = 0; float ukL = 0; float ekR1 = 0;//last error float ekR2 = 0;//last last error float ekL1 = 0;//last error float ekL2 = 0;//last last error int data[7]; void getEncoderR(void) { //Serial.println("in func getEncoderR!"); encodertime_R++; if(digitalRead(ENCODER_R1) == LOW) { if(digitalRead(ENCODER_R2) == LOW) { encoderVal_R--; } else { encoderVal_R++; } } else { if(digitalRead(ENCODER_L2) == LOW) { encoderVal_R++; } else { encoderVal_R--; } } } void getEncoderL(void) { //Serial.println("L"); encodertime_L++; if(digitalRead(ENCODER_L1) == LOW) { if(digitalRead(ENCODER_L2) == LOW) { encoderVal_L--; } else { encoderVal_L++; } } else { if(digitalRead(ENCODER_L2) == LOW) { encoderVal_L++; } else { encoderVal_L--; } } } int pidControllerR(float lTargetRv,float currentRv) { float u; float output; float q0,q1,q2; float k = 25; float ti = 100;//积分时间 float td = 5;//微分事件 float ek = lTargetRv - currentRv; //Serial.println(ek); q0 = k*(1 + PERIOD/ti + td/PERIOD); q1 = -k*(1 + 2*td/PERIOD); q2 = k*td/PERIOD; u = q0*ek + q1*ekR1 + q2*ekR2; output = ukR+u; //Serial.println(output); if (output > 255) output = 255; if (output < -255) output = -255; ukR = output; ekR2 = ekR1; ekR1 = ek; return (int)output; } int pidControllerL(float lTargetLv,float currentLv) { float u; float output; float q0,q1,q2; float k = 14; float ti = 100;//积分时间 float td = 5;//微分事件 float ek = lTargetLv - currentLv; q0 = k*(1 + PERIOD/ti + td/PERIOD); q1 = -k*(1 + 2*td/PERIOD); q2 = k*td/PERIOD; u = q0*ek + q1*ekL1 + q2*ekL2; output = ukL+u; //Serial.println(output); if (output > 255) output = 255; if (output < -255) output = -255; ukL = output; ekL2 = ekL1; ekL1 = ek; return (int)output; } float pidRoute() { float Kp_Route = 17; float Ki_Route = 1; float Kd_Route = 0; float output; float u2= MID - midVal; float d = (u2 - error_midValLast1) * Kp_Route + (u2- 2*error_midValLast1 +error_midValLast2) * Kd_Route; //PD error_midValLast2 = error_midValLast1; error_midValLast1 = u2; output = d + dLast; dLast = output; return output; } void control(void) { velocityR = (encoderVal_R*2.0)*3.1415*2.0*(1000/PERIOD)/780; encoderVal_R = 0; velocityL = (encoderVal_L*2.0)*3.1415*2.0*(1000/PERIOD)/780; encoderVal_L = 0; float d = pidRoute(); // dVelocity = 10*data[0] +8*data[1] + 6*data[2] // - 6*data[4] - 8*data[5] - 10*data[6]; targetRv += d; targetLv -= d; int dutyCycleR2 = pidControllerR(targetRv,velocityR); int dutyCycleL2 = pidControllerL(targetLv,velocityL); targetRv = originTargetV; targetLv = originTargetV; //int dutyCycleL2 = dutyCycleL1 - D_value / 2; //int dutyCycleR2 = dutyCycleR1 + D_value / 2; if(dutyCycleR2 > 0) //control Right wheel { digitalWrite(INL_R1,LOW); digitalWrite(INL_R2,HIGH); analogWrite(PWML_R,dutyCycleR2); } else { digitalWrite(INL_R1,HIGH); digitalWrite(INL_R2,LOW); analogWrite(PWML_R,abs(dutyCycleR2)); } if(dutyCycleL2 > 0) //control Right wheel { digitalWrite(INL_L1,HIGH); digitalWrite(INL_L2,LOW); analogWrite(PWML_L,dutyCycleL2); } else { digitalWrite(INL_L1,LOW); digitalWrite(INL_L2,HIGH); analogWrite(PWML_L,abs(dutyCycleL2)); } } void setup() { TCCR1B = TCCR1B & B11111000 | B00000001; pinMode(INL_L1,OUTPUT); pinMode(INL_L2,OUTPUT); pinMode(PWML_L,OUTPUT); pinMode(INL_R1,OUTPUT); pinMode(INL_R2,OUTPUT); pinMode(PWML_R,OUTPUT); pinMode(ENCODER_R1,INPUT); pinMode(ENCODER_R2,INPUT); pinMode(ENCODER_L1,INPUT); pinMode(ENCODER_L2,INPUT); attachInterrupt(ENCODER_R1 - 2,getEncoderR,FALLING); attachInterrupt(ENCODER_L1 - 2,getEncoderL,FALLING); //寻迹模块D0引脚初始化 pinMode(trac1, INPUT); pinMode(trac2, INPUT); pinMode(trac3, INPUT); pinMode(trac4, INPUT); pinMode(trac5, INPUT); pinMode(trac6, INPUT); pinMode(trac7, INPUT); MsTimer2::set(PERIOD,control); MsTimer2::start(); Serial.begin(9600); } void readInfrared() { _redVal[0] = !digitalRead(trac1); _redVal[1] = digitalRead(trac2); _redVal[2] = digitalRead(trac3); _redVal[3] = digitalRead(trac4); _redVal[4] = digitalRead(trac5); _redVal[5] = digitalRead(trac6); _redVal[6] = !digitalRead(trac7); } float infraredFindMidVal() { float mid; int sum = 0; int n = 0; readInfrared(); for (int i = 0; i < 7; i++) { if (_redVal[i] == 0) { sum += (i + 1); n++; } } if (sum == 0) mid = midLast; else mid = (float)sum / n; midLast = mid; return mid; } void loop() { midVal = infraredFindMidVal(); //Serial.println(midVal); //readVault(); //delay(5); Serial.print(velocityL); Serial.print(","); Serial.println(velocityR); }
#include "Observer.h" #ifndef __Observer_H #error [E030] Не определен заголовочный файл Observer.h #endif /*int main() { Subject subj; DivObserver divObs1(&subj, 4); // 7. ?????? ??????????? ????? DivObserver divObs2(&subj, 3); // ? ???? ???????????? ModObserver modObs3(&subj, 3); subj.setVal(14); }*/
#include "nickmodel.h" NickModel::NickModel(): nick(""), pass(0), connected(false), connectionId(false) { } NickModel::NickModel(const QString& nick_p, quint64 pass_p): nick(nick_p), pass(pass_p), connected(false), connectionId(0) { } void NickModel::connect(quint64 id) { connected = true; connectionId = id; } void NickModel::disconnect() { connected = false; connectionId = 0; } bool NickModel::isConnected() const { return connected; } quint64 NickModel::getConnectionId() const { return connectionId; } bool NickModel::passwordMatch(quint64 pass_p) const { return pass == pass_p; } QString NickModel::getNick() const { return nick; }
/* * SvrConfig.h * * Created on: Jun 11, 2017 * Author: root */ #ifndef SVRCONFIG_H_ #define SVRCONFIG_H_ #include <string> using namespace std; typedef struct sLogConf { bool base; bool info; bool debug; bool warning; bool error; bool fatal; bool display; int fileLen; string filePath; string module; }LogConf; typedef struct sDBConf { string host; string db; string user; string passwd; int port; int size; int rate; }DBConf; enum EMapType { eOnlyMap=1,//唯一地图 eStaticMap,//静态地图,每个gateserver下面都可以管理多个相同的,开服时候创建 eCopyMap, //副本,可以创建多个,动态创建 eBeyondMap, //夸服副本 ePVEMap, //pve副本 eMapMax }; enum ECopyMapType { eCopyMax }; enum ServerMapType { eSceneType=0, //场景id eMapType, //地图id eStartPoint, //传送点 eBePointType, //带有传送点的类型(帮派战,在传送开始时就决定了到哪里) eChangeMapLine, //换线传送 }; //创建场景id(64位),t为地图的类型,a为gateserver的id(保持loginserver这里场景id的唯一性,夸服此字段为0,为了保持所有服组场景id的唯一) //g为gameserver的id,x为地图的id,i为编号(副本需要id标识,其他i为0) #define CREATE_MAP(t, a, g, x, i) (((CommBaseOut::int64)t << 40) | ((CommBaseOut::int64)a << 32) | ((CommBaseOut::int64)g << 24) | ((CommBaseOut::int64)x << 16) | i) //获取场景类型 #define GET_MAP_TYPE(m) ((m >> 40) & 0xff) //获取地图id #define GET_MAP_ID(m) ((m >> 16) & 0xff) //获取场景所在的gateserver #define GET_GATESVR_ID(m) ((m >> 32) & 0xff) //获取场景所在的gameserver #define GET_SERVER_ID(m) ((m >> 24) & 0xff) //客户端连接网关超时时间 #define CONN_GATESERVER_TIMEOUT 15 // gameserver的id的唯一id合成 t为gateserver的id,x为gs的id #define CREATE_GSID(t, x) ((t << 8) | x) #define CREATE_GATEID_GS(x, t) ((x << 16) | t) #define CREATE_DBID_GS(x, t) ((x << 16) | t) #define CREATE_CHARID_GS(x, t) (((int64)x << 48) | t) //根据CHARID获得服组ID #define GET_SERVER_CHARID(m) ((m >> 48) &0xffff) //根据数据查询ID获取服组ID #define GET_SERVER_DBID(m) ((m >> 32) &0xffff) //去除服组ID的CHARID #define GET_PLAYER_CHARID(m) ((m << 16 ) >> 16) #define SAVE_CHARCACHE_TODB 1*60*1000 #define DELETE_CHARCACHE_TIMEOUT 2*60*1000 #define CLIENT_HEART_BEAT 200*1000 #define CLIENT_SYNCH_POS 1 * 1000 #define CLIENT_POS_OFFSET 2 #define SECTOR_LENGTH 50 //距离传送点的最大距离 #define STARTPOINT_LENGTH 6 // 获取某类型size的二进制位数数量 #define GET_TYPE_BINARYDIGITS(T) (sizeof(T) * 8) #endif /* SVRCONFIG_H_ */
// // Created by dbond on 20.10.18. // #ifndef IPC_NDK_WORKERTHREAD_H #define IPC_NDK_WORKERTHREAD_H #include <atomic> #include <thread> #include <string> #include <queue> #include <android/looper.h> class WorkerThread { public: virtual ~WorkerThread(); void init(const char * c_appname, const char * c_shmname, const char * c_appname2, int strsize); int start(); void stop(); long long getLastActTime(); long long getCurJavaTime(); int getThreadState(); void sendShared(int8_t * array, int len); std::shared_ptr<std::vector<int8_t>> getShared(); std::string sendSock(const char * str); std::string getSock(); void sendALoop(const char * str); std::string getALoop(); private: std::mutex m_config; std::string _appname; std::string _appname2; std::string _shmname; int _strsize; ALooper* mainThreadLooper; int messagePipe[2]; std::atomic<bool> keepRun {false}; std::atomic<long long> lastAct {0}; std::atomic<int> sharedFd {-1}; std::atomic<int> alooperFd {-1}; //std::mutex m_queSendShared; std::queue<std::shared_ptr<std::vector<int8_t>>> queSendShared; std::mutex m_vecShared; std::shared_ptr<std::vector<int8_t>> vecShared; std::mutex m_strSock; std::string strSock; std::mutex m_strALooper; std::string strALooper; std::thread mainThread; std::thread sockThread; static void* mainThreadLoop(void* arg); void mainThreadRun(); static void* sockThreadLoop(void* arg); void sockThreadRun(); bool startShared(); void startSock(); bool startALoop(); void stopALoop(); void stopShared(); void stopSock(); void _sendShared(); void _getShared(); std::string sendCmdS(const char * serviceName, const char * cmd); bool file_exists(const char * path); std::string packFd(const char * prefix, int fd); int unPackFD(const char * first, int len); int getFD(const char * who); static int looperCallback(int fd, int events, void* data); /* mainThread thread stuff */ int l_strsize {0}; std::string l_appname; std::string l_shmname; }; #endif //IPC_NDK_WORKERTHREAD_H
#include<iostream> #include<cstdio> #include<map> #include<set> #include<vector> #include<stack> #include<queue> #include<string> #include<cstring> #include<sstream> #include<algorithm> #include<cmath> using namespace std; const int maxn = 1e5 + 10; int a[maxn],b[maxn]; int f[maxn],s[maxn]; int n,m,l; int lowbit(int k) { return k&(-k); } int queryf(int k) { int ans = 0; while (k > 0) { ans = max(f[k],ans); k -= lowbit(k); } return ans; } void updataf(int val,int k) { while (k <= m) { f[k] = max(f[k],val); k += lowbit(k); } } int querys(int k) { int ans = 0; while (k > 0) { ans = max(s[k],ans); k -= lowbit(k); } return ans; } void updatas(int val,int k) { while (k <= m) { s[k] = max(s[k],val); k += lowbit(k); } } int main() { int t; scanf("%d",&t); for (int ca = 1; ca <= t; ca++) { memset(f,0,sizeof(f)); memset(s,0,sizeof(s)); scanf("%d%d",&n,&l); int ans = 0; for (int i = 0; i < n; i++) { scanf("%d",&a[i]); b[i] = a[i]; } sort(b,b+n); m = unique(b,b+n) - b; for (int i = 0; i < n; i++) { int k1 = lower_bound(b,b+m,a[i]) - b + 1; int tmp1 = queryf(k1-1) + 1; if (i + l < n) { ans = max(ans,tmp1); int k2 = lower_bound(b,b+m,a[i+l]) - b + 1; int tmp2 = max(queryf(k2-1),querys(k2-1)) + 1; ans = max(ans,tmp2); updatas(tmp2,k2); } updataf(tmp1,k1); //cout << queryf(k1) << " " << querys(k1) << endl; } printf("Case #%d: %d\n",ca,ans); } return 0; }
#include <arpa/inet.h> #include <netinet/in.h> #include <Poco/Exception.h> #include <Poco/Net/IPAddress.h> #include "net/IPAddressRange.h" using namespace BeeeOn; using namespace Poco; using namespace Poco::Net; IPAddressRange::IPAddressRange(const IPAddress& address, const IPAddress& mask) { if (address.family() != IPAddress::Family::IPv4 || mask.family() != IPAddress::Family::IPv4) throw InvalidArgumentException("only IPv4 is supported"); if (!isValidMask(mask)) throw InvalidArgumentException("invalid net mask"); m_address = address; m_mask = mask; } IPAddressRange::~IPAddressRange() { } IPAddressRange::IPAddressIterator IPAddressRange::begin() const { return IPAddressRange::IPAddressIterator(m_address); } IPAddressRange::IPAddressIterator IPAddressRange::end() const { return IPAddressRange::IPAddressIterator(m_address | ~m_mask); } IPAddress IPAddressRange::broadcast() const { return (m_address | ~m_mask); } IPAddress IPAddressRange::network() const { return m_address & m_mask; } bool IPAddressRange::isValidMask(const IPAddress& mask) const { const uint32_t array[33] = {0x00000000, 0x80000000, 0xc0000000, 0xe0000000, 0xf0000000, 0xf8000000, 0xfc000000, 0xfe000000, 0xff000000, 0xff800000, 0xffc00000, 0xffe00000, 0xfff00000, 0xfff80000, 0xfffc0000, 0xfffe0000, 0xffff0000, 0xffff8000, 0xffffc000, 0xffffe000, 0xfffff000, 0xfffff800, 0xfffffc00, 0xfffffe00, 0xffffff00, 0xffffff80, 0xffffffc0, 0xffffffe0, 0xfffffff0, 0xfffffff8, 0xfffffffc, 0xfffffffe, 0xffffffff}; struct in_addr *addr = (struct in_addr *) mask.addr(); uint32_t addrRaw = ntohl(addr->s_addr); for (int i = 0; i < 33; i++) { if (addrRaw == array[i]) return true; } return false; } IPAddressRange::IPAddressIterator::IPAddressIterator(const IPAddress& address) { m_currentAddress = address; } IPAddressRange::IPAddressIterator::~IPAddressIterator() { } IPAddressRange::IPAddressIterator& IPAddressRange::IPAddressIterator::operator++() { struct in_addr *addr = (struct in_addr *) m_currentAddress.addr(); addr->s_addr = htonl(ntohl(addr->s_addr) + 1); m_currentAddress = IPAddress(addr, sizeof(*addr)); return *this; } IPAddressRange::IPAddressIterator& IPAddressRange::IPAddressIterator::operator++(int) { ++(*this); return *this; } bool IPAddressRange::IPAddressIterator::operator==(const IPAddressRange::IPAddressIterator& other) const { return m_currentAddress == other.m_currentAddress; } bool IPAddressRange::IPAddressIterator::operator!=(const IPAddressRange::IPAddressIterator& other) const { return m_currentAddress != other.m_currentAddress; } IPAddress& IPAddressRange::IPAddressIterator::operator*() { return m_currentAddress; }
#include "gtest/gtest.h" #include <sstream> #include <boost/scoped_ptr.hpp> #include "wali/domains/matrix/Matrix.hpp" #include "fixtures-boolmatrix.hpp" #include "matrix-equal.hpp" using namespace testing::boolmatrix; namespace wali { namespace domains { TEST(wali$domains$matrix$BoolMatrix$$constructorAndMatrix, basicTest3x3) { RandomMatrix1_3x3 f; BoolMatrix m(f.mat); EXPECT_EQ(m.matrix(), f.mat); } #define NUM_ELEMENTS(arr) ((sizeof arr)/(sizeof arr[0])) TEST(wali$domains$matrix$BoolMatrix$$equalAndIsZeroAndIsOne, battery) { MatrixFixtures_3x3 f; BoolMatrix mats[] = { BoolMatrix(f.zero.mat), BoolMatrix(f.id.mat), BoolMatrix(f.r1.mat), BoolMatrix(f.r2.mat), BoolMatrix(f.ext_r1_r2.mat), BoolMatrix(f.ext_r2_r1.mat), }; for (size_t left=0; left<NUM_ELEMENTS(mats); ++left) { for (size_t right=0; right<NUM_ELEMENTS(mats); ++right) { EXPECT_EQ(left == right, mats[left].equal(&mats[right])); } } } TEST(wali$domains$matrix$BoolMatrix$$zero_raw, basicTest3x3) { RandomMatrix1_3x3 f; ZeroBackingMatrix_3x3 z; BoolMatrix m(f.mat); BoolMatrix mz(z.mat); boost::scoped_ptr<BoolMatrix> result(m.zero_raw()); EXPECT_EQ(z.mat, result->matrix()); EXPECT_TRUE(mz.equal(result.get())); } TEST(wali$domains$matrix$BoolMatrix$$one_raw, basicTest3x3) { RandomMatrix1_3x3 f; IdBackingMatrix_3x3 z; BoolMatrix m(f.mat); BoolMatrix mid(z.mat); boost::scoped_ptr<BoolMatrix> result(m.one_raw()); EXPECT_EQ(z.mat, result->matrix()); EXPECT_TRUE(mid.equal(result.get())); } TEST(wali$domains$matrix$BoolMatrix$$extend_raw, twoRandomMatrices) { RandomMatrix1_3x3 f1; RandomMatrix2_3x3 f2; ExtendR1R2_3x3 fr12; ExtendR2R1_3x3 fr21; BoolMatrix m1(f1.mat); BoolMatrix m2(f2.mat); boost::scoped_ptr<BoolMatrix> result12(m1.extend_raw(&m2)); boost::scoped_ptr<BoolMatrix> result21(m2.extend_raw(&m1)); EXPECT_EQ(fr12.mat, result12->matrix()); EXPECT_EQ(fr21.mat, result21->matrix()); } TEST(wali$domains$matrix$BoolMatrix$$extend_raw, extendAgainstZero) { RandomMatrix1_3x3 f; ZeroBackingMatrix_3x3 z; BoolMatrix mf(f.mat); BoolMatrix mz(z.mat); boost::scoped_ptr<BoolMatrix> result1Z(mf.extend_raw(&mz)), resultZ1(mz.extend_raw(&mf)), resultZZ(mz.extend_raw(&mz)); EXPECT_EQ(z.mat, result1Z->matrix()); EXPECT_EQ(z.mat, resultZ1->matrix()); EXPECT_EQ(z.mat, resultZZ->matrix()); EXPECT_TRUE(mz.equal(result1Z.get())); EXPECT_TRUE(mz.equal(resultZ1.get())); EXPECT_TRUE(mz.equal(resultZZ.get())); } TEST(wali$domains$matrix$BoolMatrix$$extend_raw, extendAgainstOne) { RandomMatrix1_3x3 fr1; IdBackingMatrix_3x3 id; BoolMatrix mr1(fr1.mat); BoolMatrix mid(id.mat); boost::scoped_ptr<BoolMatrix> result_R1_Id(mr1.extend_raw(&mid)), result_Id_R1(mid.extend_raw(&mr1)), result_Id_Id(mid.extend_raw(&mid)); EXPECT_EQ(fr1.mat, result_R1_Id->matrix()); EXPECT_EQ(fr1.mat, result_Id_R1->matrix()); EXPECT_EQ(id.mat, result_Id_Id->matrix()); EXPECT_TRUE(mr1.equal(result_R1_Id.get())); EXPECT_TRUE(mr1.equal(result_Id_R1.get())); EXPECT_TRUE(mid.equal(result_Id_Id.get())); } TEST(wali$domains$matrix$BoolMatrix$$combine_raw, randomAndId) { RandomMatrix1_3x3 f1; IdBackingMatrix_3x3 f2; CombineR1Id_3x3 fr; BoolMatrix m1(f1.mat); BoolMatrix m2(f2.mat); BoolMatrix mr(fr.mat); boost::scoped_ptr<BoolMatrix> result12(m1.combine_raw(&m2)); boost::scoped_ptr<BoolMatrix> result21(m2.combine_raw(&m1)); EXPECT_EQ(fr.mat, result12->matrix()); EXPECT_EQ(fr.mat, result21->matrix()); EXPECT_TRUE(mr.equal(result12.get())); EXPECT_TRUE(mr.equal(result21.get())); } TEST(wali$domains$matrix$BoolMatrix$$print, random) { RandomMatrix1_3x3 f; BoolMatrix m(f.mat); std::stringstream ss; m.print(ss); EXPECT_EQ("Matrix: [3,3]((1,1,0),(1,0,1),(0,0,1))", ss.str()); } TEST(wali$domains$matrix$BoolMatrix, callWaliTestSemElemImpl) { RandomMatrix1_3x3 f; sem_elem_t m = new BoolMatrix(f.mat); test_semelem_impl(m); } } }
#ifndef GRAV_OBJ #define GRAV_OBJ #include <iostream> #include <string> #include <vector> #include "Vector.h" #include <SDL/SDL.h> #include <SDL/SDL_gfxPrimitives.h> #include "Parameters.h" #include <SDL/SDL.h> #include <SDL/SDL_image.h> #include <SDL/SDL_ttf.h> #include <iostream> #include <vector> #include "Vector.h" #include <SDL/SDL_gfxPrimitives.h> #include <cmath> #include <sstream> #include <SDL/SDL_rotozoom.h> #include "Parameters.h" class GravityObject { public: GravityObject(); GravityObject(int weight, Vector* position = new Vector(), Vector* speed = new Vector(), Vector* acceleration = new Vector()); GravityObject(const GravityObject &gravObj); ~GravityObject(); virtual int getWeight() const; virtual void setWeight(int weight); virtual Vector* getPosition() const; virtual Vector* getSpeed() const; virtual void addSpeed(Vector v); virtual void addAcceleration(Vector v); virtual Vector* getAcceleration() const; virtual void calculateGravityAcceleration(const std::vector<GravityObject*> &universe); virtual void calculateSpeed(); virtual void calculatePosition(); virtual Vector* getInfluenceFor(const GravityObject* gravObj); virtual void draw(SDL_Surface* screen, const Parameters* params) const; static const double G = 10e-5; protected: int _weight; Vector* _temporaryAcceleration; Vector* _position; Vector* _speed; Vector* _acceleration; }; #endif
// Copyright (c) 2019 The NavCoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "daoproposeanswer.h" DaoProposeAnswer::DaoProposeAnswer(QWidget *parent, CConsultation consultation, ValidatorFunc validator) : layout(new QVBoxLayout), consultation(consultation), answerInput(new QLineEdit), validatorFunc(validator) { this->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Expanding); this->setLayout(layout); CStateViewCache view(pcoinsTip); auto *bottomBox = new QFrame; auto *bottomBoxLayout = new QHBoxLayout; bottomBoxLayout->setContentsMargins(QMargins()); bottomBox->setLayout(bottomBoxLayout); QPushButton* proposeBtn = new QPushButton(tr("Submit")); connect(proposeBtn, SIGNAL(clicked()), this, SLOT(onPropose())); QPushButton* closeBtn = new QPushButton(tr("Close")); connect(closeBtn, SIGNAL(clicked()), this, SLOT(onClose())); bottomBoxLayout->addStretch(1); bottomBoxLayout->addWidget(proposeBtn); bottomBoxLayout->addWidget(closeBtn); warningLbl = new QLabel(""); warningLbl->setObjectName("warning"); warningLbl->setVisible(false); QString fee = QString::fromStdString(FormatMoney(GetConsensusParameter(Consensus::CONSENSUS_PARAM_CONSULTATION_ANSWER_MIN_FEE, view))); layout->addSpacing(15); layout->addWidget(new QLabel(tr("Submit an answer proposal for:<br>%1").arg(QString::fromStdString(consultation.strDZeel)))); layout->addSpacing(15); layout->addWidget(answerInput); layout->addWidget(warningLbl); layout->addSpacing(15); layout->addWidget(new QLabel(tr("By submitting the answer a contribution of %1 NAV to the Community Fund will occur from your wallet.").arg(fee))); layout->addWidget(bottomBox); layout->addSpacing(15); } void DaoProposeAnswer::setModel(WalletModel *model) { this->model = model; } void DaoProposeAnswer::showWarning(QString text) { warningLbl->setText(text); warningLbl->setVisible(text == "" ? false : true); adjustSize(); } void DaoProposeAnswer::onPropose() { if(!model) return; LOCK2(cs_main, pwalletMain->cs_wallet); CStateViewCache view(pcoinsTip); CNavCoinAddress address("NQFqqMUD55ZV3PJEJZtaKCsQmjLT6JkjvJ"); // Dummy address CWalletTx wtx; bool fSubtractFeeFromAmount = false; std::string sAnswer = answerInput->text().toStdString(); if (!(validatorFunc)(QString::fromStdString(sAnswer))) { showWarning(tr("Entry not valid")); return; } UniValue strDZeel(UniValue::VOBJ); uint64_t nVersion = CConsultationAnswer::BASE_VERSION; showWarning(""); sAnswer = consultation.IsAboutConsensusParameter() ? RemoveFormatConsensusParameter((Consensus::ConsensusParamsPos)consultation.nMin, sAnswer) : sAnswer; strDZeel.pushKV("h",consultation.hash.ToString()); strDZeel.pushKV("a",sAnswer); strDZeel.pushKV("v",(uint64_t)nVersion); wtx.strDZeel = strDZeel.write(); wtx.nCustomVersion = CTransaction::ANSWER_VERSION; // Ensure wallet is unlocked WalletModel::UnlockContext ctx(model->requestUnlock()); if(!ctx.isValid()) { // Unlock wallet was cancelled return; } // Check balance CAmount curBalance = pwalletMain->GetBalance(); string fee = FormatMoney(GetConsensusParameter(Consensus::CONSENSUS_PARAM_CONSULTATION_ANSWER_MIN_FEE, view)); if (curBalance <= GetConsensusParameter(Consensus::CONSENSUS_PARAM_CONSULTATION_ANSWER_MIN_FEE, view)) { QMessageBox msgBox(this); std::string str = tr("You require at least %1 NAV mature and available to propose an answer.\n").arg(QString::fromStdString(fee)).toStdString(); msgBox.setText(tr(str.c_str())); msgBox.addButton(tr("Ok"), QMessageBox::AcceptRole); msgBox.setIcon(QMessageBox::Warning); msgBox.setWindowTitle("Insufficient NAV"); msgBox.exec(); return; } QMessageBox::StandardButton btnRetVal = QMessageBox::question(this, tr("Fee"), tr("Proposing a new answer requires to pay a fee of %1 NAV.").arg(QString::fromStdString(fee)) + "<br><br>" + tr("Do you want to proceed?"), QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel); if(btnRetVal == QMessageBox::Cancel) return; CScript scriptPubKey; SetScriptForCommunityFundContribution(scriptPubKey); // Create and send the transaction CReserveKey reservekey(pwalletMain); CAmount nFeeRequired; std::string strError; vector<CRecipient> vecSend; int nChangePosRet = -1; CAmount nValue = GetConsensusParameter(Consensus::CONSENSUS_PARAM_CONSULTATION_ANSWER_MIN_FEE, view); CRecipient recipient = {scriptPubKey, nValue, fSubtractFeeFromAmount}; vecSend.push_back(recipient); bool created = true; if (!pwalletMain->CreateTransaction(vecSend, wtx, reservekey, nFeeRequired, nChangePosRet, strError, NULL, true)) { if (!fSubtractFeeFromAmount && nValue + nFeeRequired > pwalletMain->GetBalance()) { created = false; } } if (!pwalletMain->CommitTransaction(wtx, reservekey)) { created = false; } if (created) { // Display success UI and close current dialog if (QMessageBox::Yes == QMessageBox(QMessageBox::Information, tr("Success!"), tr("Your answer proposal has been correctly created.")+"<br><br>"+tr("Now you need to find support from stakers so it is included in the voting!")+"<br><br>"+tr("Do you want to support your own canswer?"), QMessageBox::Yes|QMessageBox::No).exec()) { bool duplicate; CConsultationAnswer answer; if (TxToConsultationAnswer(wtx.strDZeel, wtx.GetHash(), uint256(), answer)) { Support(answer.hash, duplicate); } } QDialog::accept(); return; } else { // Display something went wrong UI QMessageBox msgBox(this); msgBox.setText(tr("Answer proposal failed")); msgBox.addButton(tr("Ok"), QMessageBox::AcceptRole); msgBox.setIcon(QMessageBox::Warning); msgBox.setWindowTitle("Error"); msgBox.exec(); return; } } void DaoProposeAnswer::onClose() { close(); }
#ifndef FEATURE_H #define FEATURE_H #include "Common.h" #include "PascalImageDatabase.h" #include "ParametersMap.h" using namespace cv; typedef std::vector<float> Feature; typedef std::vector<Feature> FeatureCollection; //! Feature Extraction Class /*! This class implements an abstract feature extractor, it receives a database of images and return a vector of features obtained after the image processing. */ class FeatureExtractor { public: //! Constructor FeatureExtractor(const ParametersMap &params = ParametersMap()) {}; //! Destructor virtual ~FeatureExtractor() {}; virtual ParametersMap getParameters() const = 0; virtual std::string getFeatureType() const = 0; // Extract feature vector for image image. Decending classes must implement this method //void operator()(const Mat &image, Feature &feat) const; // Extract feature vector for image image. Decending classes must implement this method virtual void operator()(Mat &image, Feature &feat) const = 0; // Extracts descriptor for each image in the database, stores result in FeatureCollection, // this is used for training the support vector machine. void operator()(const PascalImageDatabase &db, FeatureCollection &featureCollection) const; void scale(FeatureCollection &featureCollection, FeatureCollection &scaledFeatureCollection); // Extracts descriptor for each level of imPyr and stores the results in featPyr void operator()(const std::vector<Mat> &imPyr, FeatureCollection &featPyr) const; // Ratio of input image size to output response size (necessary when computing location of detections) virtual double scaleFactor() const = 0; // Factory method that allocates the correct feature vector extractor given // the name of the extractor (caller is responsible for deallocating // extractor). To extend the code with other feature extractors or // other configurations for feature extractors add appropriate constructor // calls in implementation of this function. static FeatureExtractor *create(ParametersMap params = ParametersMap()); static FeatureExtractor *create(const std::string &featureType, const ParametersMap &params = ParametersMap()); static void save(FILE *f, const FeatureExtractor *feat); static FeatureExtractor *load(FILE *f); // TODO document this static ParametersMap getDefaultParameters(const std::string &featureType); }; //! HOG Feature Extraction Class /*! This class implements a HOG feature extractor, it receives a database of images and return a vector of HOG features obtained after the image processing. This is an inherited class from the FeatureExtractor class. */ class HOGFeatureExtractor : public FeatureExtractor { private: int _nAngularBins; // Number of angular bins bool _unsignedGradients; // If true then we only consider the orientation modulo 180 degrees (i.e., 190 // degrees is considered the same as 10 degrees) int _cellSize; // Support size of a cell, in pixels //HOGDescriptor _hog; public: std::string getFeatureType() const { return "hog"; }; static ParametersMap getDefaultParameters(); ParametersMap getParameters() const; //HOGFeatureExtractor(int nAngularBins = 18, bool unsignedGradients = true, int cellSize = 6); //! Constructor HOGFeatureExtractor(const ParametersMap &params = ParametersMap()); void operator()(Mat &image, Feature &feat) const; Mat renderHOG(Mat& img, Mat& out, vector<float>& descriptorValues, Size winSize, Size cellSize, int scaleFactor, double viz_factor) const; double scaleFactor() const { return 1.0 / double(_cellSize); } }; #endif // FEATURE_H
// // Created by 송지원 on 2020/06/29. // //바킹독 9강 BFS. boj2178 바킹독님 버젼 //여기서 굳이 vis 배열을 쓰지 않고 dist 배열을 -1로 초기화 해놓고 -1이면 방문하지 않았던 곳, -1이 아니면 방문한 곳 이렇게 구분! //그리고 board를 "string board[102];"로 정의하면 굳이 귀찮은 ㅇ일 안하고 이전코드처럼 쓸 수 있음! //-> 다만 값 비교할때 숫자가 아니라 문자임을 주의!! //fill 함수 사용법 : fill(dist[i], dist[i]+m, -1); #include <iostream> #include <queue> #include <utility> using namespace std; #define X first #define Y second string board[102]; int dist[102][102]; int n, m; int dx[4] = {1, 0, -1, 0}; int dy[4] = {0, 1, 0, -1}; int main() { ios::sync_with_stdio(0); cin.tie(0); cin >> n >> m; for (int i=0; i<n; i++) cin >> board[i]; for (int i=0; i<n; i++) fill(dist[i], dist[i]+m, -1); queue<pair<int, int>> Q; Q.push({0, 0}); dist[0][0] = 0; while (!Q.empty()) { auto cur = Q.front(); Q.pop(); for (int dir=0; dir<4; dir++) { int nx = cur.X + dx[dir]; int ny = cur.Y + dy[dir]; if (nx < 0 || nx >= n || ny < 0 || ny >= m) continue; if (board[nx][ny]=='0' || dist[nx][ny] != -1) continue; Q.push({nx, ny}); dist[nx][ny] = dist[cur.X][cur.Y] + 1; } } cout << dist[n-1][m-1] + 1; }
#include "_pch.h" #include "PathPatternEditor.h" #include "dlgselectcls_ctrlpnl.h" using namespace wh; //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // TmpStrPathItem //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- TmpStrPathItem::TmpStrPathItem(wxWindow *parent, wxWindowID id, const wxString& label, const wxPoint& pos, const wxSize& size, long style, const wxString& name) : wxStaticText(parent, id, label, pos, size, style, name) { Bind(wxEVT_ENTER_WINDOW, &TmpStrPathItem::OnEnter, this); Bind(wxEVT_LEAVE_WINDOW, &TmpStrPathItem::OnLeave, this); SetToolTip(wxT("Нажмите для редактирования")); } //--------------------------------------------------------------------------- void TmpStrPathItem::OnEnter(wxMouseEvent& event) { SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHT)); Refresh(); } //--------------------------------------------------------------------------- void TmpStrPathItem::OnLeave(wxMouseEvent& event) { SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW)); Refresh(); } //--------------------------------------------------------------------------- void TmpStrPathItem::SetModel(std::shared_ptr<temppath::model::Item>& newModel) { if (newModel == mModel) return; mModel = newModel; if (!mModel) return; namespace ph = std::placeholders; //namespace cat = wh::object_catalog; auto onChange = std::bind(&TmpStrPathItem::OnChange, this, ph::_1, ph::_2); connChange = mModel->DoConnect(moAfterUpdate, onChange); OnChange(mModel.get(), &mModel->GetData()); } //--------------------------------------------------------------------------- void TmpStrPathItem::OnChange(const IModel*, const temppath::model::Item::DataType* data) { if (!data) return; wxString chStr(" /* "); if (!data->mCls.mId.IsNull() || !data->mObj.mId.IsNull()) { const wxString clsStr = data->mCls.mId.IsNull() ? "*" : data->mCls.mLabel.toStr(); const wxString objStr = data->mObj.mId.IsNull() ? "*" : data->mObj.mLabel.toStr(); chStr = wxString::Format(L" /[%s]%s ", clsStr, objStr);//\u02C5 |v } SetLabel(chStr); // auto parent = GetParent(); while (parent) { parent->Layout(); parent = parent == GetParent() ? nullptr : GetParent(); } } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // PathPatternEditor //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- PathPatternEditor::PathPatternEditor(wxWindow *parent, wxWindowID winid, const wxPoint& pos, const wxSize& size, long style, const wxString& name) : wxScrolledWindow(parent, winid, pos, size, style, name) { SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW)); this->SetScrollRate(5, 5); wxBoxSizer* szrPath = new wxBoxSizer(wxHORIZONTAL); this->SetMinSize(wxSize(-1, 50)); this->SetSizer(szrPath); this->Layout(); szrPath->Fit(this); auto rc = ResMgr::GetInstance(); mMnuAddToLeft = AppendBitmapMenu(&mMenu, miAddToLeft, L"+ добавить слева", rc->m_ico_plus16); mMnuAddToRight = AppendBitmapMenu(&mMenu, miAddToRight, L"добавить справа +", rc->m_ico_plus16); mMnuRemove = AppendBitmapMenu(&mMenu, miRemove, L"удалить", rc->m_ico_delete16); mMenu.AppendSeparator(); mMnuSetAny = mMenu.Append(miSetAny, L"[*]* любой класс, любой объект"); mMnuSetCls = mMenu.Append(miSetCls, L"[?]* выбрать только класс,любой объект"); mMnuSetClsObj= mMenu.Append(miSetClsObj, L"[?]? выбрать объект и соответственно его класс"); mMnuSetFixObj = mMenu.Append(miSetFixObj, L"[X]? выбрать объект"); mMnuSetFixAny = mMenu.Append(miSetFixAny, L"[X]* любой объект"); //Bind(wxEVT_COMMAND_MENU_SELECTED, [](wxCommandEvent& evt){}, miAddToLeft); //Bind(wxEVT_COMMAND_MENU_SELECTED, &PathPatternEditor::PnlShowAct, this, miAddToLeft); Bind(wxEVT_MENU, &PathPatternEditor::OnCmdAddToLeft, this, miAddToLeft); Bind(wxEVT_MENU, &PathPatternEditor::OnCmdAddToRight, this, miAddToRight); Bind(wxEVT_MENU, &PathPatternEditor::OnCmdRemove, this, miRemove); Bind(wxEVT_MENU, &PathPatternEditor::OnCmdSetAny, this, miSetAny); Bind(wxEVT_MENU, &PathPatternEditor::OnCmdSetCls, this, miSetCls); Bind(wxEVT_MENU, &PathPatternEditor::OnCmdSetClsObj, this, miSetClsObj); Bind(wxEVT_MENU, &PathPatternEditor::OnCmdSetFixObj, this, miSetFixObj); Bind(wxEVT_MENU, &PathPatternEditor::OnCmdSetFixAny, this, miSetFixAny); } //--------------------------------------------------------------------------- bool PathPatternEditor::GetGiuItemIndex(TmpPathItem* ch, size_t& model_idx) { const PtrIdx& ptrIdx = mPathChoice.get<1>(); CPtrIterator ptrIt = ptrIdx.find(ch); if (ptrIdx.end() != ptrIt) { CRndIterator rndIt = mPathChoice.project<0>(ptrIt); CRndIterator rndBegin = mPathChoice.cbegin(); model_idx = std::distance(rndBegin, rndIt); return true; } return false; } //--------------------------------------------------------------------------- void PathPatternEditor::OnCmdAddToLeft(wxCommandEvent& evt) { size_t before_idx(0); if (!GetGiuItemIndex(mSelectedItem, before_idx)) return; const auto qty = mModel->GetChildQty(); auto new_item = mModel->CreateChild(); auto before_item = (qty > before_idx) ? mModel->GetChild(before_idx) : SptrIModel(nullptr); mModel->Insert(new_item, before_item); } //--------------------------------------------------------------------------- void PathPatternEditor::OnCmdAddToRight(wxCommandEvent& evt) { size_t before_idx(0); if (!GetGiuItemIndex(mSelectedItem, before_idx)) return; const auto qty = mModel->GetChildQty(); before_idx++; auto new_item = mModel->CreateChild(); auto before_item = (qty > before_idx) ? mModel->GetChild(before_idx) : SptrIModel(nullptr); mModel->Insert(new_item, before_item); } //--------------------------------------------------------------------------- void PathPatternEditor::OnCmdRemove(wxCommandEvent& evt) { size_t model_idx(0); if (GetGiuItemIndex(mSelectedItem, model_idx)) { if (mModel->GetChildQty() == 1 ) return; mModel->DelChild(model_idx); } } //--------------------------------------------------------------------------- void PathPatternEditor::OnCmdSetAny(wxCommandEvent& evt) { size_t model_idx(0); if (!GetGiuItemIndex(mSelectedItem, model_idx)) return; temppath::model::Item::DataType emptyData; mModel->at(model_idx)->SetData(emptyData); } //--------------------------------------------------------------------------- void PathPatternEditor::OnCmdSetCls(wxCommandEvent& evt) { size_t model_idx(0); if (!GetGiuItemIndex(mSelectedItem, model_idx)) return; auto tv = [this](const wh::rec::Cls* cls, const wh::rec::Obj* obj)->bool { if (ReqOne_ReqCls == mMode || ReqOne_FixCls == mMode) return cls && !obj && 1 == (long)cls->mType; return cls && !obj; }; CatDlg dlg(nullptr); dlg.SetTargetValidator(tv); auto catalog = std::make_shared<wh::object_catalog::MObjCatalog>(); catalog->SetCfg(rec::CatCfg(rec::catCls, false, false)); //if (FixOne_ReqCls != mMode) // catalog->SetFilterClsKind(ClsKind::QtyByOne, foLess, true); catalog->Load(); dlg.SetModel(catalog); if (wxID_OK == dlg.ShowModal()) { wh::rec::Cls cls; if (dlg.GetSelectedCls(cls)) { temppath::model::Item::DataType data; data.mCls = cls; mModel->at(model_idx)->SetData(data); } } }//--------------------------------------------------------------------------- void PathPatternEditor::OnCmdSetClsObj(wxCommandEvent& evt) { size_t model_idx(0); if (!GetGiuItemIndex(mSelectedItem, model_idx)) return; auto tv = [this](const wh::rec::Cls* cls, const wh::rec::Obj* obj)->bool { if (ReqOne_ReqCls == mMode || ReqOne_FixCls == mMode) return cls && obj && 1== (long)cls->mType; return cls && obj; }; CatDlg dlg(nullptr); dlg.SetTargetValidator(tv); auto catalog = std::make_shared<wh::object_catalog::MObjCatalog>(); catalog->SetCfg(rec::CatCfg(rec::catCls, false, true)); //catalog->SetCfg(rec::catObj, false, true); //if(FixOne_ReqCls!=mMode) // catalog->SetFilterClsKind(ClsKind::QtyByOne, foLess, true); catalog->Load(); dlg.SetModel(catalog); if (wxID_OK == dlg.ShowModal()) { wh::rec::ObjInfo obj; if (dlg.GetSelectedObj(obj)) { temppath::model::Item::DataType data; data.mCls = obj.mCls; data.mObj = obj.mObj; mModel->at(model_idx)->SetData(data); } } } //--------------------------------------------------------------------------- void PathPatternEditor::OnCmdSetFixObj(wxCommandEvent& evt) { size_t model_idx(0); if (!GetGiuItemIndex(mSelectedItem, model_idx)) return; auto m = mModel->at(model_idx); if (!m) return; const auto& cls_data = m->GetData(); long cls_id = cls_data.mCls.mId.IsNull() ? 0 : cls_id = cls_data.mCls.mId; if (!cls_id) return; auto catalog = std::make_shared<wh::object_catalog::MObjCatalog>(); catalog->SetCfg(rec::CatCfg(rec::catCustom, false, true)); catalog->SetFilterClsKind(ClsKind::QtyByOne, foLess, true); catalog->SetFilterClsId(cls_id, foEq, true); catalog->Load(); auto tv = [](const wh::rec::Cls* cls, const wh::rec::Obj* obj)->bool { return cls && obj; }; CatDlg dlg(nullptr); dlg.SetTargetValidator(tv); dlg.SetModel(catalog); if (wxID_OK == dlg.ShowModal()) { wh::rec::ObjInfo obj; if (dlg.GetSelectedObj(obj)) { temppath::model::Item::DataType data; data.mCls = obj.mCls; data.mObj = obj.mObj; mModel->at(model_idx)->SetData(data); } } } //--------------------------------------------------------------------------- void PathPatternEditor::OnCmdSetFixAny(wxCommandEvent& evt) { size_t model_idx(0); if (!GetGiuItemIndex(mSelectedItem, model_idx)) return; //if ((mModel->GetChildQty() - 1) == model_idx) { auto data = mModel->at(model_idx)->GetData(); data.mObj = rec::Base(); mModel->at(model_idx)->SetData(data); } } //--------------------------------------------------------------------------- void PathPatternEditor::SetModel(std::shared_ptr<temppath::model::Array>& newModel) { if (newModel == mModel) return; mModel = newModel; if (!mModel) return; namespace ph = std::placeholders; auto onBeforeRemove = std::bind(&PathPatternEditor::OnBeforeRemove, this, ph::_1, ph::_2); auto onAfterIns = std::bind(&PathPatternEditor::OnAfterInsert, this, ph::_1, ph::_2, ph::_3); connDel = mModel->ConnectBeforeRemove(onBeforeRemove); connAfterInsert = mModel->ConnAfterInsert(onAfterIns); ResetGui(); } //--------------------------------------------------------------------------- void PathPatternEditor::MakeGuiItem(unsigned int pos) { auto szrPath = this->GetSizer(); auto itPos = mPathChoice.begin() + pos; // получаем позицию GUI элемента auto ch = new TmpPathItem(this, wxID_ANY); // создаём новый GUI элемент ch->SetModel(mModel->at(pos)); // устанавливаем модель в GUI szrPath->Insert(pos, ch, 0, wxALL | wxALIGN_CENTER_VERTICAL, 1);//вставляем в GUI массив mPathChoice.insert(itPos, ch); // вставляем в перечень szrPath->Fit(this); this->GetParent()->Layout(); // меню элемента auto popupMenu = [this, ch](wxContextMenuEvent& evt) { //TmpPathItem* ch = mSelectedItem; TmpPathItem* ch = dynamic_cast<TmpPathItem*>(evt.GetEventObject()); size_t model_idx(0); if (GetGiuItemIndex(ch, model_idx)) { //bool isFirst = (0 == model_idx); bool isLast = (mModel->GetChildQty() - 1 == model_idx); //bool isOne = (mModel->GetChildQty() == 1); mMnuAddToLeft->Enable(false); mMnuAddToRight->Enable(false); mMnuRemove->Enable(false); mMnuSetAny->Enable(false); mMnuSetCls->Enable(false); mMnuSetClsObj->Enable(false); mMnuSetFixObj->Enable(false); mMnuSetFixAny->Enable(false); if (isLast && FixOne_ReqCls == mMode) { mMnuSetCls->Enable(true); mMnuSetClsObj->Enable(true); } else if (isLast && ReqOne_ReqCls == mMode) { mMnuAddToLeft->Enable(true); mMnuSetCls->Enable(true); mMnuSetClsObj->Enable(true); } else if (isLast && ReqOne_FixCls == mMode) { mMnuAddToLeft->Enable(true); mMnuSetFixObj->Enable(true); mMnuSetFixAny->Enable(true); } else { mMnuAddToLeft->Enable(true); mMnuAddToRight->Enable(true); mMnuRemove->Enable(true); mMnuSetAny->Enable(true); mMnuSetCls->Enable(true); mMnuSetClsObj->Enable(true); mMnuSetFixObj->Enable(true); mMnuSetFixAny->Enable(true); } } mSelectedItem = ch; wxRect rect = ch->GetRect(); wxPoint pt = this->ClientToScreen(rect.GetBottomLeft()); pt = ScreenToClient(pt); PopupMenu(&mMenu, pt); }; //ch->Bind(wxEVT_RIGHT_DOWN, popupMenu); //ch->Bind(wxEVT_LEFT_DOWN, popupMenu); ch->Bind(wxEVT_CONTEXT_MENU, popupMenu); // привязывем меню к элементу } //--------------------------------------------------------------------------- void PathPatternEditor::OnBeforeRemove(const IModel& vec, const std::vector<SptrIModel>& remVec) { std::vector<TmpPathItem*> to_del; for (const auto& remItem : remVec) { size_t idx = 0; if (vec.GetItemPosition(remItem, idx)) { auto it = mPathChoice.begin() + idx; to_del.emplace_back(*it); } } for (const auto ch : to_del) { delete ch; PtrIdx& ptrIdx = mPathChoice.get<1>(); PtrIterator ptrIt = ptrIdx.find(ch); if (ptrIdx.end() != ptrIt) ptrIdx.erase(ptrIt); } auto szrPath = this->GetSizer(); szrPath->Fit(this); this->GetParent()->Layout(); } //--------------------------------------------------------------------------- void PathPatternEditor::OnAfterInsert(const IModel& vec , const std::vector<SptrIModel>& newItems, const SptrIModel& itemBefore) { size_t pos; for (const auto& curr : newItems) { auto item = std::dynamic_pointer_cast<temppath::model::Item>(curr); if (!item || !vec.GetItemPosition(item, pos)) return; MakeGuiItem(pos); pos++; } } //--------------------------------------------------------------------------- void PathPatternEditor::ResetGui() { for (const auto ch : mPathChoice) delete ch; mPathChoice.clear(); auto qty = mModel->GetChildQty(); for (size_t i = 0; i < qty; i++) MakeGuiItem(i); auto szrPath = this->GetSizer(); szrPath->Fit(this); this->GetParent()->Layout(); } //-----------------------------------------------------------------------------
#include <iostream> #include <thread> #include <memory> #include <unistd.h> using namespace std; class Thread { public: Thread() :isClearThreadInUse(false) { thr.reset(new std::thread()); } ~Thread() { thr->join(); } void start() { std::unique_lock<std::mutex> lock(clearMutex); isClearThreadInUse = true; lock.unlock(); if (thr->joinable()) { thr->join(); } thr.reset(new std::thread(&Thread::Print, this)); } void Print() { std::cout << "Print." << std::endl; sleep(5); std::unique_lock<std::mutex> lock(clearMutex); isClearThreadInUse = false; } bool getSign() { std::unique_lock<std::mutex> lock(clearMutex); return isClearThreadInUse; } private: std::unique_ptr<std::thread> thr; std::mutex clearMutex; bool isClearThreadInUse; }; int main() { std::unique_ptr<Thread> th(new Thread()); int count = 0; while (count < 20) { if (!th->getSign()) { th->start(); } else { std::cout << "the last clear task hasn't over, please wait the next timer." << std::endl; } sleep(5); count++; } }
#pragma once #include <iostream> #include <string> #include <vector> using namespace std; enum ITEM { ITEM_EMPTY, ITEM_MONSTERBALL, ITEM_POTION, ITEM_ANTIDOTE, ITEM_PARLYZEHEAL, ITEM_BURNHEAL, ITEM_ICEHEAL, ITEM_AWAKENING, ITEM_FULLHEAL }; struct tagItemInfo { ITEM itemKind; string name; string description; int attribute; int price; int count; };
////////////////////////////////////////////////////////////////////////////// // // Copyright (c) Triad National Security, LLC. This file is part of the // Tusas code (LA-CC-17-001) and is subject to the revised BSD license terms // in the LICENSE file found in the top-level directory of this distribution. // ////////////////////////////////////////////////////////////////////////////// #include "elem_color.h" #include <Epetra_MapColoring.h> #include <Epetra_Util.h> #include <Tpetra_ComputeGatherMap.hpp> #include <Teuchos_DefaultComm.hpp> #include <Teuchos_ArrayRCPDecl.hpp> #include <Teuchos_VerboseObject.hpp> #include <Zoltan2_TpetraRowGraphAdapter.hpp> #include <Zoltan2_ColoringProblem.hpp> //#include <MatrixMarket_Tpetra.hpp> std::string getmypidstring(const int mypid, const int numproc); elem_color::elem_color(const Teuchos::RCP<const Epetra_Comm>& comm, Mesh *mesh, bool dorestart): comm_(comm), mesh_(mesh) { //ts_time_create= Teuchos::TimeMonitor::getNewTimer("Total Elem Create Color Time"); //ts_time_elemadj= Teuchos::TimeMonitor::getNewTimer("Total Elem Adj Fill Time"); ts_time_color= Teuchos::TimeMonitor::getNewTimer("Tusas: Total Elem Color Time"); Teuchos::TimeMonitor ElemcolTimer(*ts_time_color); //cn to revert to old functionality uncomment: dorestart = false; if(dorestart){ restart(); } else { //mesh_->compute_nodal_patch_overlap(); //compute_graph(); create_colorer(); init_mesh_data(); } } elem_color::~elem_color() { //delete mesh_; } void elem_color::compute_graph() { auto comm = Teuchos::DefaultComm<int>::getComm(); int mypid = comm_->MyPID(); if( 0 == mypid ) std::cout<<std::endl<<"elem_color::compute_graph() started."<<std::endl<<std::endl; //std::cout<<mypid<<" "<<mesh_->get_num_elem()<<" "<<mesh_->get_num_elem_in_blk(0)<<std::endl; using Teuchos::rcp; std::vector<Mesh::mesh_lint_t> elem_num_map(*(mesh_->get_elem_num_map())); //map_->Print(std::cout); const global_size_t numGlobalEntries = Teuchos::OrdinalTraits<Tpetra::global_size_t>::invalid(); const global_ordinal_type indexBase = 0; std::vector<global_ordinal_type> elem_num_map1(elem_num_map.begin(),elem_num_map.end()); Teuchos::ArrayView<global_ordinal_type> AV(elem_num_map1); elem_map_ = rcp(new map_type(numGlobalEntries, AV, indexBase, comm)); map_ = rcp(new Epetra_Map(-1, elem_num_map.size(), &elem_num_map[0], 0, *comm_)); //elem_map_ ->describe(*(Teuchos::VerboseObjectBase::getDefaultOStream()),Teuchos::EVerbosityLevel::VERB_EXTREME ); #ifdef ELEM_COLOR_USE_ZOLTAN //size_t ni = 27;//hex now; dont know what this would be for tri/tet size_t ni = 81;//hex now; dont know what this would be for tri/tet elem_graph_ = Teuchos::rcp(new crs_graph_type(elem_map_, ni)); #else graph_ = rcp(new Epetra_CrsGraph(Copy, *map_, 0)); #endif if( 0 == mypid ) std::cout<<std::endl<<"Mesh::compute_elem_adj() started."<<std::endl<<std::endl; mesh_->compute_elem_adj(); if( 0 == mypid ) std::cout<<std::endl<<"Mesh::compute_elem_adj() ended."<<std::endl<<std::endl; for(int blk = 0; blk < mesh_->get_num_elem_blks(); blk++){ for (int ne=0; ne < mesh_->get_num_elem_in_blk(blk); ne++) { Mesh::mesh_lint_t row = mesh_->get_global_elem_id(ne); std::vector<Mesh::mesh_lint_t> col = mesh_->get_elem_connect(ne);//this is appearently global id, not local #ifdef ELEM_COLOR_USE_ZOLTAN std::vector<global_ordinal_type> col1(col.begin(),col.end()); const Teuchos::ArrayView<global_ordinal_type> CV(col1); //for(int k =0;k<col1.size(); k++)std::cout<<ne<<" "<<CV[k]<<std::endl; const global_ordinal_type row1 = row; elem_graph_->insertGlobalIndices(row1, CV); #else graph_->InsertGlobalIndices(row, (int)(col.size()), &col[0]); #endif }//ne }//blk //graph_->Print(std::cout); //elem_graph_->describe(*(Teuchos::VerboseObjectBase::getDefaultOStream()),Teuchos::EVerbosityLevel::VERB_EXTREME ); //#define COLOR_USE_OFFPROC #ifdef ELEM_COLOR_USE_OFFPROC insert_off_proc_elems(); #endif #ifdef ELEM_COLOR_USE_ZOLTAN elem_graph_->fillComplete(); //describe outputs -1 for most column locations; even though insertion appears correct and the coloring //is ultimately correct. Similar output for W_graph in the preconditioner. //dumping via matrix market produces the right data. //elem_graph_->describe(*(Teuchos::VerboseObjectBase::getDefaultOStream()),Teuchos::EVerbosityLevel::VERB_EXTREME ); // const std::string graphName=""; // const std::string graphDescription=""; // const std::string fname="g.dat"; // Tpetra::MatrixMarket::Writer<Tpetra::CrsMatrix<> >::writeSparseGraphFile(fname, *elem_graph_, graphName, graphDescription, false); // exit(0); #else //if (graph_->GlobalAssemble() != 0){ if (graph_->FillComplete() != 0){ std::cout<<"error graph_->GlobalAssemble()"<<std::endl; exit(0); } //graph_->Print(std::cout); #endif //exit(0); if( 0 == mypid ) std::cout<<std::endl<<"elem_color::compute_graph() ended."<<std::endl<<std::endl; } void elem_color::create_colorer() { using Teuchos::rcp; compute_graph(); #ifdef ELEM_COLOR_USE_ZOLTAN auto comm = Teuchos::DefaultComm<int>::getComm(); int mypid = comm->getRank(); #else int mypid = comm_->MyPID(); #endif std::cout<<std::endl<<"elem_color::create_colorer() started on proc "<<mypid<<std::endl<<std::endl; #ifdef ELEM_COLOR_USE_ZOLTAN typedef Tpetra::RowGraph<local_ordinal_type, global_ordinal_type, node_type> row_graph_type; typedef Zoltan2::TpetraRowGraphAdapter<row_graph_type> graphAdapter_type; Teuchos::RCP<row_graph_type> RowGraph = Teuchos::rcp_dynamic_cast<row_graph_type>(elem_graph_); // Teuchos::RCP<const row_graph_type> constRowGraph = // Teuchos::rcp_const_cast<const row_graph_type>(RowGraph); graphAdapter_type adapter(RowGraph); Teuchos::ParameterList params; std::string colorMethod("FirstFit"); params.set("color_choice", colorMethod); Zoltan2::ColoringProblem<graphAdapter_type> problem(&adapter, &params, comm); problem.solve(); size_t checkLength; int *checkColoring; Zoltan2::ColoringSolution<graphAdapter_type> *soln = problem.getSolution(); checkLength = soln->getColorsSize(); checkColoring = soln->getColors(); num_color_ = soln->getNumColors (); //std::cout<<"checkLength = "<<checkLength<<" znumcolor = "<<num_color_<<std::endl<<std::endl; elem_LIDS_.resize(num_color_); for ( int i = 0; i < (int)checkLength; i++ ){ const int color = checkColoring[i]-1; if ( color < 0 ){ if( 0 == mypid ){ std::cout<<std::endl<<"elem_color::create_colorer() error. color < 0."<<std::endl<<std::endl; exit(0); } } const int lid = i; //std::cout<<comm->getRank()<<" "<<lid<<" "<<color<<std::endl; elem_LIDS_[color].push_back(lid); } //RowGraph->describe(*(Teuchos::VerboseObjectBase::getDefaultOStream()),Teuchos::EVerbosityLevel::VERB_EXTREME ); elem_graph_ = Teuchos::null; elem_map_ = Teuchos::null; //exit(0); #else //cn looks like the default is a distance-2 coloring, // we need a distance-1 coloring Teuchos::ParameterList paramList; paramList.set("DISTANCE","1",""); //cn this call is very expensive......it seems that it might be mpi-only and not threaded in any way Teuchos::RCP<Isorropia::Epetra::Colorer> elem_colorer_; { //Teuchos::TimeMonitor ElemcreTimer(*ts_time_create); elem_colorer_ = rcp(new Isorropia::Epetra::Colorer( graph_.getConst(), paramList, true)); } Teuchos::RCP< Epetra_MapColoring > map_coloring_ = rcp( new Epetra_MapColoring( *(elem_colorer_->Isorropia::Epetra::Colorer::generateRowMapColoring()) ) ); //map_coloring_->Print(std::cout); num_color_ = elem_colorer_->numColors(); color_list_.assign(map_coloring_->ListOfColors(),map_coloring_->ListOfColors()+num_color_); elem_LIDS_.resize(num_color_); //colors seem to begin with 1, which is the defaultcolor? //int default_color_=map_coloring_->DefaultColor(); for(int i = 1; i < num_color_+1; i++){ //int num_elem = map_coloring_->NumElementsWithColor(color_list_[i]); int num_elem = elem_colorer_->numElemsWithColor(i); elem_LIDS_[i-1].resize(num_elem); elem_colorer_->elemsWithColor(i, &elem_LIDS_[i-1][0], num_elem ) ; //elem_LIDS_[i].assign(map_coloring_->ColorLIDList(color_list_[i]),map_coloring_->ColorLIDList(color_list_[i])+num_elem); //elem_LIDS_[i].assign(map_coloring_->ColorLIDList(i),map_coloring_->ColorLIDList(i)+num_elem); //std::cout<<color_list_[i]<<" ("<<map_coloring_->NumElementsWithColor(color_list_[i])<<") "; } graph_ = Teuchos::null; map_ = Teuchos::null; #endif // int sum = 0; // for ( int i = 0; i < num_color_; i++){ // std::cout<<mypid<<" "<<i<<" "<<elem_LIDS_[i].size()<<std::endl; // sum = sum + elem_LIDS_[i].size(); // } // std::cout<<mypid<<" sum = "<<sum<<std::endl; std::cout<<std::endl<<"elem_color::create_colorer() ended on proc "<<mypid<<". With num_color_ = "<<num_color_<<std::endl<<std::endl; //exit(0); } void elem_color::init_mesh_data() { std::string cstring="color"; mesh_->add_elem_field(cstring); return; } void elem_color::update_mesh_data() { int num_elem = mesh_->get_elem_num_map()->size(); std::vector<double> color(num_elem,0.); for(int c = 0; c < num_color_; c++){ std::vector<int> elem_map = get_color(c); int num_elem = elem_map.size(); for (int ne=0; ne < num_elem; ne++) {// Loop Over # of Finite Elements on Processor const int lid = elem_LIDS_[c][ne]; color[lid] = c; } } std::string cstring="color"; mesh_->update_elem_data(cstring, &color[0]); return; } void elem_color::insert_off_proc_elems(){ //see comments below about create_root_map... //right now we need an epetra map in order to facilitate this. //we probably need to fix this by implementing our own create_root_map //for tpetra::map //note this is very similar to how we can create the patch for error estimator... //although we would need to communicate the nodes also... auto comm = Teuchos::DefaultComm<int>::getComm(); const int mypid = comm_->MyPID(); if( 0 == mypid ) std::cout<<std::endl<<"elem_color::insert_off_proc_elems() started."<<std::endl<<std::endl; std::vector<Mesh::mesh_lint_t> node_num_map(mesh_->get_node_num_map()); // Teuchos::RCP<const Epetra_Map> o_map_= Teuchos::rcp(new Epetra_Map(-1, // node_num_map.size(), // &node_num_map[0], // 0, // *comm_)); //map_->Print(std::cout); //o_map_->Print(std::cout); const global_size_t numGlobalEntries = Teuchos::OrdinalTraits<Tpetra::global_size_t>::invalid(); const global_ordinal_type indexBase = 0; std::vector<global_ordinal_type> node_num_map1(node_num_map.begin(),node_num_map.end()); Teuchos::ArrayView<global_ordinal_type> AV(node_num_map1); Teuchos::RCP<const map_type> overlap_map_ = rcp(new map_type(numGlobalEntries, AV, indexBase, comm)); //overlap_map_ ->describe(*(Teuchos::VerboseObjectBase::getDefaultOStream()),Teuchos::EVerbosityLevel::VERB_EXTREME ); //exit(0); const int blk = 0; const int n_nodes_per_elem = mesh_->get_num_nodes_per_elem_in_blk(blk); const int num_elem = mesh_->get_num_elem(); //Teuchos::RCP<const Epetra_Map> n_map_; Teuchos::RCP<const map_type> node_map_; if( 1 == comm_->NumProc() ){ //n_map_ = o_map_; node_map_ = overlap_map_; }else{ // #ifdef MESH_64 // n_map_ = Teuchos::rcp(new Epetra_Map(Create_OneToOne_Map64(*o_map_))); // #else // n_map_ = Teuchos::rcp(new Epetra_Map(Epetra_Util::Create_OneToOne_Map(*o_map_))); // #endif GreedyTieBreak<local_ordinal_type,global_ordinal_type> greedy_tie_break; node_map_ = Teuchos::rcp(new map_type(*(Tpetra::createOneToOne(overlap_map_,greedy_tie_break)))); } //n_map_->Print(std::cout); std::vector<Mesh::mesh_lint_t> shared_nodes; //for(int i = 0; i < o_map_->NumMyElements (); i++){ for(int i = 0; i < overlap_map_->getNodeNumElements(); i++){ // #ifdef MESH_64 // Mesh::mesh_lint_t ogid = o_map_->GID64(i); // #else // Mesh::mesh_lint_t ogid = o_map_->GID(i); // #endif const Mesh::mesh_lint_t ogid = overlap_map_->getGlobalElement ((local_ordinal_type) i); //global_ordinal_type //std::cout<<comm_->MyPID()<<" "<<ogid<<" "<<n_map_->LID(ogid)<<std::endl; //if(n_map_->LID(ogid) < 0 ) shared_nodes.push_back(ogid); if((local_ordinal_type)(node_map_->getLocalElement(ogid)) == Teuchos::OrdinalTraits<Tpetra::Details::DefaultTypes::local_ordinal_type>::invalid() ) shared_nodes.push_back(ogid); } Teuchos::RCP<const Epetra_Map> s_map_= Teuchos::rcp(new Epetra_Map(-1, shared_nodes.size(), &shared_nodes[0], 0, *comm_)); //s_map_->Print(std::cout); std::vector<global_ordinal_type> shared_nodes1(shared_nodes.begin(),shared_nodes.end()); Teuchos::ArrayView<global_ordinal_type> AV1(shared_nodes1); Teuchos::RCP<const map_type> shared_node_map_ = rcp(new map_type(numGlobalEntries, AV1, indexBase, comm)); //shared_node_map_->describe(*(Teuchos::VerboseObjectBase::getDefaultOStream()),Teuchos::EVerbosityLevel::VERB_EXTREME ); //exit(0); #ifdef MESH_64 Teuchos::RCP<const Epetra_Map> o_shared_node_map_ = Teuchos::rcp(new Epetra_Map(Create_OneToOne_Map64(*s_map_))); #else Teuchos::RCP<const Epetra_Map> o_shared_node_map_ = Teuchos::rcp(new Epetra_Map(Epetra_Util::Create_OneToOne_Map(*s_map_))); #endif //o_shared_node_map_->Print(std::cout); #ifdef MESH_64 Teuchos::RCP<const Epetra_Map> r_shared_node_map_ = Teuchos::rcp(new Epetra_Map(Create_Root_Map64( *o_shared_node_map_, -1))); #else Teuchos::RCP<const Epetra_Map> r_shared_node_map_ = Teuchos::rcp(new Epetra_Map(Epetra_Util::Create_Root_Map( *o_shared_node_map_, -1))); #endif // GreedyTieBreak<local_ordinal_type,global_ordinal_type> greedy_tie_break; // Teuchos::RCP<const map_type> onetoone_shared_node_map_ = Teuchos::rcp(new map_type(*(Tpetra::createOneToOne(shared_node_map_,greedy_tie_break)))); //would like to create a replicated tpetra::map, not clear how to easily do this.... Teuchos::RCP<Teuchos::FancyOStream> out = Teuchos::VerboseObjectBase::getDefaultOStream(); Teuchos::RCP<const map_type> rep_shared_node_map_ = Tpetra::Details::computeGatherMap (shared_node_map_, out); //Teuchos::rcp(new map_type(*(Tpetra::createLocalMapWithNode<local_ordinal_type, global_ordinal_type, node_type>((size_t)(onetoone_shared_node_map_->getGlobalNumElements()), comm)))); const global_ordinal_type ng = rep_shared_node_map_->getGlobalNumElements(); Teuchos::RCP<const map_type> rep_map_ = rcp(new map_type(ng, indexBase, comm, Tpetra::LocallyReplicated)); Tpetra::Import<local_ordinal_type, global_ordinal_type, node_type> rep_importer_(rep_map_, rep_shared_node_map_); Tpetra::Vector<global_ordinal_type, local_ordinal_type, global_ordinal_type, node_type> rep_shared_vec_(rep_shared_node_map_); for (int i=0; i<rep_shared_node_map_->getNodeNumElements(); i++) { rep_shared_vec_.replaceLocalValue(i, (long long) rep_shared_node_map_->getGlobalElement(i)); } Tpetra::Vector<global_ordinal_type, local_ordinal_type, global_ordinal_type, node_type> rep_vec_(rep_map_); rep_vec_.doImport(rep_shared_vec_,rep_importer_,Tpetra::INSERT); rep_vec_.describe(*(Teuchos::VerboseObjectBase::getDefaultOStream()),Teuchos::EVerbosityLevel::VERB_EXTREME ); Teuchos::ArrayRCP<global_ordinal_type> rv = rep_vec_.get1dViewNonConst(); std::vector<global_ordinal_type> vals(rep_vec_.getLocalLength()); for(int i = 0; i < rep_vec_.getLocalLength(); i++){ vals[i] = (global_ordinal_type)rv[i]; } const Teuchos::ArrayView<global_ordinal_type> AV2(vals); Teuchos::RCP<const map_type> replicated_map_ = rcp(new map_type( rep_vec_.getLocalLength(), AV2, indexBase, comm)); r_shared_node_map_->Print(std::cout); replicated_map_->describe(*(Teuchos::VerboseObjectBase::getDefaultOStream()),Teuchos::EVerbosityLevel::VERB_EXTREME ); //exit(0); std::cout<<r_shared_node_map_->NumMyElements ()<<" "<<rep_shared_node_map_->getNodeNumElements ()<<std::endl; for(int i = 0; i < r_shared_node_map_->NumMyElements (); i++){ //for(int i = 0; i < rep_shared_node_map_->getNodeNumElements (); i++){ #ifdef MESH_64 const Mesh::mesh_lint_t rsgid = r_shared_node_map_->GID64(i); #else const Mesh::mesh_lint_t rsgid = r_shared_node_map_->GID(i); #endif //const int rsgid = r_shared_node_map_->GID(i); //const int ogid = o_map_->LID(rsgid);//local const int ogid = overlap_map_->getLocalElement(rsgid);//local std::vector<int> mypatch;//local if(ogid != -1){ mypatch = mesh_->get_nodal_patch_overlap(ogid);//get local elem_id } int p_size = mypatch.size(); int max_size = 0; comm_->MaxAll(&p_size, &max_size, (int)1 ); std::vector<Mesh::mesh_lint_t> gidmypatch(max_size,(Mesh::mesh_lint_t)(-99)); for(int j = 0; j < p_size; j++){ #ifdef ELEM_COLOR_USE_ZOLTAN gidmypatch[j] = elem_map_->getGlobalElement(mypatch[j]); #else gidmypatch[j] = map_->GID(mypatch[j]); #endif //std::cout<<" "<<rsgid<<" "<<gidmypatch[j]<<" "<<mypatch[j]<<std::endl; }//j int count = comm_->NumProc()*max_size; std::vector<Mesh::mesh_lint_t> AllVals(count,-99); comm_->GatherAll(&gidmypatch[0], &AllVals[0], max_size ); //cn need to fix Allvals here std::vector<Mesh::mesh_lint_t> g_gids; for(int j = 0; j< count ;j++){ if(-99 < AllVals[j]) { //std::cout<<" "<<comm_->MyPID()<<" "<<i<<" "<<AllVals[j]<<" "<<rsgid<<std::endl; g_gids.push_back(AllVals[j]); } }//j for(int j = 0; j < g_gids.size(); j++){ int elid = map_->LID(g_gids[j]); if(elid > -1){ for(int k = 0;k< g_gids.size(); k++){ #ifdef ELEM_COLOR_USE_ZOLTAN local_ordinal_type eelid = elem_map_->getLocalElement (g_gids[k]);//local_ordinal_type #else int eelid = map_->LID(g_gids[k]); #endif //if(eelid > -1){ //std::cout<<" "<<comm_->MyPID()<<" "<<g_gids[j]<<" "<<g_gids[k]<<std::endl;//" "<<rsgid<<" "<<elid<<std::endl; #ifdef ELEM_COLOR_USE_ZOLTAN global_ordinal_type gk = (global_ordinal_type)g_gids[k]; elem_graph_->insertGlobalIndices(g_gids[j], (local_ordinal_type)1, &gk); #else graph_->InsertGlobalIndices(g_gids[j], (int)1, &g_gids[k]); #endif //} }//k }//elid }//j }//i //exit(0); //graph_->Print(std::cout); //exit(0); if( 0 == mypid ) std::cout<<std::endl<<"elem_color::insert_off_proc_elems() ended."<<std::endl<<std::endl; return; } void elem_color::restart(){ //we will first read in a vector of size num elem on this proc // fill it with color //find the min and max values to determine the number of colors //allocate first dimension of elem_LIDS_ to num colors //fill each color with elem ids via push back //verify that this is by LID int mypid = comm_->MyPID(); int numproc = comm_->NumProc(); std::cout<<std::endl<<"elem_color::restart() started on proc "<<mypid<<std::endl<<std::endl; const int num_elem = mesh_->get_num_elem(); int ex_id_; //this code is replicated in a number of places. Need to have a function for this somewhere if( 1 == numproc ){//cn for now //if( 0 == mypid ){ const char *outfilename = "results.e"; ex_id_ = mesh_->open_exodus(outfilename,Mesh::READ); std::cout<<" Opening file for restart; ex_id_ = "<<ex_id_<<" filename = "<<outfilename<<std::endl; } else{ std::string decompPath="decomp/"; //std::string pfile = decompPath+std::to_string(mypid+1)+"/results.e."+std::to_string(numproc)+"."+std::to_string(mypid); std::string mypidstring(getmypidstring(mypid,numproc)); std::string pfile = decompPath+"results.e."+std::to_string(numproc)+"."+mypidstring; ex_id_ = mesh_->open_exodus(pfile.c_str(),Mesh::READ); std::cout<<" Opening file for restart; ex_id_ = "<<ex_id_<<" filename = "<<pfile<<std::endl; //cn we want to check the number of procs listed in the nem file as well int nem_proc = -99; int error = mesh_->read_num_proc_nemesis(ex_id_, &nem_proc); if( 0 > error ) { std::cout<<"Error obtaining restart num procs in file"<<std::endl; exit(0); } if( nem_proc != numproc ){ std::cout<<"Error restart nem_proc = "<<nem_proc<<" does not equal numproc = "<<numproc<<std::endl; exit(0); } } int step = -99; int error = mesh_->read_last_step_exodus(ex_id_,step); if( 0 == mypid ) std::cout<<" Reading restart last step = "<<step<<std::endl; if( 0 > error ) { std::cout<<"Error obtaining restart last step"<<std::endl; exit(0); } //we read a double from exodus; convert to int below std::vector<double> colors(num_elem); //note that in the future (and in case of nemesis) there may be other elem data in the file, ie error_est or procid //we will need to sort through this init_mesh_data(); std::string cstring="color"; error = mesh_->read_elem_data_exodus(ex_id_,step,cstring,&colors[0]); if( 0 > error ) { std::cout<<"Error reading color at step "<<step<<std::endl; exit(0); } mesh_->close_exodus(ex_id_); int max_color = (int)(*max_element(colors.begin(), colors.end())); int min_color = (int)(*min_element(colors.begin(), colors.end())); num_color_ = max_color - min_color+1; elem_LIDS_.resize(num_color_); for(int i = 0; i < num_elem; i++){ const int c = (int)colors[i]; const int lid = i; //std::cout<<mypid<<" : "<<c<<" "<<lid<<std::endl; elem_LIDS_[c].push_back(lid); } //std::cout<<mypid<<" : "<<*max_element(colors.begin(), colors.end())<<" "<<num_color_<<std::endl; std::cout<<std::endl<<"elem_color::restart() ended on proc "<<mypid<<std::endl<<std::endl; //exit(0); }
#include <iostream> inline double square(double x) { return x * x; } int main() { using namespace std; double a, b; double c = 13.0; a = square(5.0); b = square(4.5 + 7.5); cout << "a = " << a << ", b = " << b << "\n"; cout << "c = " << c; cout << ", c squared = " << square(c++) << "\n"; cout << "Now c = " << c << "\n"; while (cin.get() != 'q') ; return 0; } #define SQUARE(X) X*X a = SQUARE(5.0); ~ a = 5.0*5.0; a = SQUARE(4.5 + 7.5); ~ a = 4.5 + 7.5 * 4.5 * 7.5; a = SQUARE(c++); ~ a = c++*c++; 而从上面函数运行结果来看,内联函数的参数为表达式的时候,内联函数传递的是表达式的值,这使得内联函数的功能比宏定义要强得多。
#include<iostream> #include<vector> #include<algorithm> using namespace std; struct ListNode { int val; ListNode* next; ListNode(int x) : val(x), next(NULL) {} }; void Init_ListNode(ListNode* head, vector<int> vec) { if (vec.size() == 0) { head = NULL; return; } ListNode* p; p = head; p->val = vec[0]; for (int i = 1; i < vec.size(); i++) { ListNode* q = new ListNode(vec[i]); p->next = q; p = p->next; } } class Solution { public: void deleteNode(ListNode* node) { //基本思想:单链表基本操作 ListNode* post = node->next; node->val = post->val; node->next = post->next; delete(post); //如果是new出来的需要delete,而题目的节点不知道是栈空间还是堆空间 return; } }; int main() { Solution solute; ListNode* head = new ListNode(0); vector<int> vec = { 1,2,3,4,5 }; Init_ListNode(head, vec); solute.deleteNode(head->next->next); while (head) { cout << head->val << endl; head = head->next; } return 0; }
#include <iostream> #include <cmath> #include "Double.h" /** * Evaluate a function u given as linear combination of shape function * values in a single quadrature point * * \param[in] u \fk^3$ values, coefficients for the linear combination * \param[in] phi \f$k$ values of shape functions in a single * quadrature point. */ template<int k> Double __attribute__ ((noinline)) point(Double u[k][k][k], Double phi[k]) { Double f; for (int i3 = 0; i3<k; ++i3) for (int i2 = 0; i2<k; ++i2) for (int i1 = 0; i1<k; ++i1) { f.operator+=(((u[i1][i2][i3].operator*(phi[i1])).operator*(phi[i2])).operator*(phi[i3])); } return f; } template<int k> Double __attribute__ ((noinline)) point_fact(Double u[k][k][k], Double phi[k]) { Double f3; for (int i3 = 0; i3<k; ++i3) { Double f2; for (int i2 = 0; i2<k; ++i2) { do { Double f1; for (int i1 = 0; i1<k; ++i1) { f1.operator+=(u[i1][i2][i3].operator*(phi[i1])); } f2.operator+=(f1.operator*(phi[i2])); } while(NULL); } f3.operator+=(f2.operator*(phi[i3])); } return f3; }
#include "SimG4Core/DD4hepGeometry/interface/DD4hep_DDDWorld.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" #include "DetectorDescription/DDCMS/interface/DDDetector.h" #include "DDG4/Geant4Converter.h" #include "DDG4/Geant4GeometryInfo.h" #include "DD4hep/Detector.h" #include "G4RunManagerKernel.hh" #include "G4PVPlacement.hh" #include "G4TransportationManager.hh" using namespace edm; using namespace cms; DDDWorld::DDDWorld(const DDDetector* ddd) { dd4hep::DetElement world = ddd->description()->world(); const dd4hep::Detector& detector = *ddd->description(); dd4hep::sim::Geant4Converter g4Geo(detector); dd4hep::sim::Geant4GeometryInfo* geometry = g4Geo.create(world).detach(); m_world = geometry->world(); SetAsWorld(m_world); } DDDWorld::~DDDWorld() {} void DDDWorld::SetAsWorld(G4VPhysicalVolume * pv) { G4RunManagerKernel* kernel = G4RunManagerKernel::GetRunManagerKernel(); if(kernel) kernel->DefineWorldVolume(pv); else edm::LogError("SimG4CoreGeometry") << "No G4RunManagerKernel?"; edm::LogInfo("SimG4CoreGeometry") << " World volume defined "; } void DDDWorld::WorkerSetAsWorld(G4VPhysicalVolume * pv) { G4RunManagerKernel* kernel = G4RunManagerKernel::GetRunManagerKernel(); if(kernel) { kernel->WorkerDefineWorldVolume(pv); // The following does not get done in WorkerDefineWorldVolume() // because we don't use G4MTRunManager G4TransportationManager* transM = G4TransportationManager::GetTransportationManager(); transM->SetWorldForTracking(pv); } else edm::LogError("SimG4CoreGeometry") << "No G4RunManagerKernel?"; edm::LogInfo("SimG4CoreGeometry") << " World volume defined (for worker) "; }
#ifndef DEVICESETTINGS_H #define DEVICESETTINGS_H #include <QObject> #include <QQmlEngine> class DeviceSettings { Q_GADGET Q_PROPERTY(QString apName READ apName WRITE setApName) Q_PROPERTY(QString apPass READ apPass WRITE setApPass) Q_PROPERTY(quint8 devId READ devId WRITE setDevId) Q_PROPERTY(QString devName READ devName WRITE setDevName) Q_PROPERTY(ApType apType READ apType WRITE setApType) Q_PROPERTY(bool isValid READ isValid) QString m_apName; QString m_apPass; quint8 m_devId; QString m_devName; public: enum ApType { STATION = 1, SOFTAP }; Q_ENUM(ApType) DeviceSettings(bool valid = false); QString apName() const; QString apPass() const; quint8 devId() const; QString devName() const; ApType apType() const; bool isValid() const; public slots: void setApName(QString apName); void setApPass(QString apPass); void setDevId(quint8 devId); void setDevName(QString devName); void setApType(ApType apType); private: ApType m_apType; bool m_isValid; }; Q_DECLARE_METATYPE(DeviceSettings) #endif // DEVICESETTINGS_H
#include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup(){ player.load("dog.mp4"); player.play(); for (int i = 0; i < 16; i++) { table[i] = ofRandom(0, 255); } } //-------------------------------------------------------------- void ofApp::update(){ player.update(); if (functionTwo == true) { if (player.isFrameNew()) { //getting pixels ofPixels pixels = player.getPixels(); //scan all the pixels for (int y = 0; y < pixels.getHeight(); y++){ for (int x = 0; x < pixels.getWidth(); x++){ //getting pixel colot ofColor col = pixels.getColor(x, y); //calculate the distance between each poxel and //the mouse's position //change pixels' color float d = ofDist(x, y, ofGetMouseX(), ofGetMouseY()); float adjustbrightness = ofMap(d, 0, 100, 8, 0); col.r *= adjustbrightness; col.g *= adjustbrightness; col.b *= adjustbrightness; //set color back to pixel pixels.setColor(x, y, col); } } //set pixel array to the image image.setFromPixels(pixels); } } } //-------------------------------------------------------------- void ofApp::draw(){ //scale video //ofScale(zoomFactor, zoomFactor); player.draw(0,0); if (functionOne == true) { //getting the video's pixels ofPixels &pixels = player.getPixels(); //define variables w,h equal to frame width and height int w = pixels.getWidth(); int h = pixels.getHeight(); //define circle variables int step = 20; int r = ofMap(ofGetMouseX(), 0, ofGetWidth(), 5, 10); int locx = 0; int locy = 0; //draw circle for (int x = 0; x < w; x = x + step) { ofColor color = pixels.getColor(x , h/2); ofSetColor(color); for (int i = 0; i < w; i = i + step) ofDrawCircle(locx, locy, r); for (int j = 0; j < h; j = j + step) { ofDrawCircle(locx, locy, r); locy = locy + step; } locx = locx + step; locy = 0; } } //draw the image ofSetColor(255, 255, 255); image.draw(0,0); } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ switch(key){ case 'z': functionOne = !functionOne; functionTwo = false; break; case 'x': functionTwo = !functionTwo; functionOne = false; break; } } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y ){ if (functionOne == true) { //connect the speed variable with mouse X float mappedSpeed = ofMap(float(x), 0.0f, ofGetWidth(), 0, 2.0f); player.setSpeed(mappedSpeed); //connect the zoom factor with mouse Y zoomFactor = ofMap(float(y), 0.0f, ofGetHeight(), 0, 2.0f); } } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseEntered(int x, int y){ } //-------------------------------------------------------------- void ofApp::mouseExited(int x, int y){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2011 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. */ #include "core/pch.h" #if defined DRAG_SUPPORT || defined USE_OP_CLIPBOARD #include "modules/dom/src/domdatatransfer/domdatatransfer.h" #ifdef DRAG_SUPPORT #include "modules/dragdrop/dragdrop_manager.h" #endif // DRAG_SUPPORT #ifdef USE_OP_CLIPBOARD #include "modules/dragdrop/clipboard_manager.h" #endif // USE_OP_CLIPBOARD #include "modules/dragdrop/dragdrop_data_utils.h" #include "modules/pi/OpDragObject.h" #include "modules/dom/src/domfile/domfile.h" #include "modules/layout/box/box.h" #include "modules/doc/html_doc.h" #include "modules/dom/src/domenvironmentimpl.h" #include "modules/ecmascript_utils/esasyncif.h" #include "modules/dom/src/domcore/element.h" #include "modules/dom/src/domcore/domdoc.h" #define IS_READ_WRITE(data_store_elm, runtime) \ (data_store_elm->HasProtectionModeOverridden() ? \ (data_store_elm->GetOverriddenProtectionMode() == DATA_STORE_MODE_READ_WRITE) : \ (DOM_DataTransfer::GetDataStoreMode(runtime) == DATA_STORE_MODE_READ_WRITE)) #define IS_PROTECTED(data_store_elm, runtime) \ (data_store_elm->HasProtectionModeOverridden() ? \ (data_store_elm->GetOverriddenProtectionMode() == DATA_STORE_MODE_PROTECTED) : \ (DOM_DataTransfer::GetDataStoreMode(runtime) == DATA_STORE_MODE_PROTECTED)) #define IS_FILE(item) (item->GetKind() == DOM_DataTransferItem::DATA_TRANSFER_ITEM_KIND_FILE) #define IS_STRING(item) (item->GetKind() == DOM_DataTransferItem::DATA_TRANSFER_ITEM_KIND_TEXT) #define IS_VALID(runtime) (DOM_DataTransfer::IsDataStoreValid(runtime)) /* static */ OP_STATUS DOM_DataTransferItem::Make(DOM_DataTransferItem*& data_transfer_item, DOM_DataTransferItems* parent, DOM_File* file, DOM_Runtime* runtime, BOOL set_underying_data /* = TRUE */) { RETURN_IF_ERROR(DOMSetObjectRuntime(data_transfer_item = OP_NEW(DOM_DataTransferItem, ()), runtime, runtime->GetPrototype(DOM_Runtime::DATATRANSFERITEM_PROTOTYPE), "DataTransferItem")); data_transfer_item->m_store.m_kind = DATA_TRANSFER_ITEM_KIND_FILE; OP_ASSERT(parent); data_transfer_item->m_parent = parent; OP_ASSERT(data_transfer_item->GetDataStore()); RETURN_IF_ERROR(data_transfer_item->m_type.Set(file->GetContentType() ? file->GetContentType() : UNI_L("application/octet-stream"))); data_transfer_item->m_type.MakeLower(); if (set_underying_data) RETURN_IF_ERROR(data_transfer_item->GetDataStore()->SetData(file->GetPath(), data_transfer_item->m_type.CStr(), TRUE, FALSE)); RETURN_IF_ERROR(DOM_File::Make(data_transfer_item->m_store.m_data.file, file->GetPath(), FALSE, FALSE, runtime)); return OpStatus::OK; } /* static */ OP_STATUS DOM_DataTransferItem::Make(DOM_DataTransferItem*& data_transfer_item, DOM_DataTransferItems* parent, const uni_char* format, const uni_char* data, DOM_Runtime* runtime, BOOL set_underying_data /* = TRUE */) { RETURN_IF_ERROR(DOMSetObjectRuntime(data_transfer_item = OP_NEW(DOM_DataTransferItem, ()), runtime, runtime->GetPrototype(DOM_Runtime::DATATRANSFERITEM_PROTOTYPE), "DataTransferItem")); data_transfer_item->m_store.m_kind = DATA_TRANSFER_ITEM_KIND_TEXT; OP_ASSERT(parent); data_transfer_item->m_parent = parent; OP_ASSERT(data_transfer_item->GetDataStore()); RETURN_IF_ERROR(data_transfer_item->m_type.Set(format)); data_transfer_item->m_type.MakeLower(); data_transfer_item->m_store.m_data.data = NULL; if (data) if (!(data_transfer_item->m_store.m_data.data = UniSetNewStr(data))) return OpStatus::ERR_NO_MEMORY; if (set_underying_data) RETURN_IF_ERROR(data_transfer_item->GetDataStore()->SetData(data_transfer_item->m_store.m_data.data, data_transfer_item->m_type.CStr(), FALSE, TRUE)); return OpStatus::OK; } /* virtual */ ES_GetState DOM_DataTransferItem::GetName(OpAtom property_name, ES_Value* value, ES_Runtime* origining_runtime) { switch (property_name) { case OP_ATOM_kind: if (value) { if (IS_VALID(origining_runtime) && m_parent->Contains(this)) DOMSetString(value, IS_STRING(this) ? UNI_L("string") : UNI_L("file")); else DOMSetString(value); } return GET_SUCCESS; case OP_ATOM_type: if (value) { if (IS_VALID(origining_runtime) && m_parent->Contains(this)) DOMSetString(value, m_type.CStr()); else DOMSetString(value); } return GET_SUCCESS; default: return DOM_Object::GetName(property_name, value, origining_runtime); } } /* virtual */ ES_PutState DOM_DataTransferItem::PutName(OpAtom property_name, ES_Value* value, ES_Runtime* origining_runtime) { switch (property_name) { case OP_ATOM_kind: case OP_ATOM_type: return PUT_READ_ONLY; default: return DOM_Object::PutName(property_name, value, origining_runtime); } } /* static */ int DOM_DataTransferItem::get(DOM_Object* this_object, ES_Value* argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime, int data) { DOM_THIS_OBJECT(data_transfer_item, DOM_TYPE_DATA_TRANSFER_ITEM, DOM_DataTransferItem); DataStoreMode dsmode = data_transfer_item->HasProtectionModeOverridden() ? data_transfer_item->GetOverriddenProtectionMode() : DOM_DataTransfer::GetDataStoreMode(origining_runtime); if (data == 1) { DOM_CHECK_ARGUMENTS("O"); if (argv[0].type == VALUE_UNDEFINED || argv[0].type == VALUE_NULL || (dsmode != DATA_STORE_MODE_READ_WRITE && dsmode != DATA_STORE_MODE_READ_ONLY) || !IS_STRING(data_transfer_item)) return ES_FAILED; ES_AsyncInterface* asyncif = origining_runtime->GetEnvironment()->GetAsyncInterface(); ES_Value argument; DOMSetString(&argument, data_transfer_item->m_store.m_data.data); asyncif->CallFunction(argv[0].value.object, NULL, 1, &argument, NULL, NULL); } else { if ((dsmode == DATA_STORE_MODE_READ_WRITE || dsmode == DATA_STORE_MODE_READ_ONLY) && IS_FILE(data_transfer_item)) DOMSetObject(return_value, data_transfer_item->m_store.m_data.file); else DOMSetNull(return_value); return ES_VALUE; } return ES_FAILED; } DOM_DataTransferItem::~DOM_DataTransferItem() { if (IS_STRING(this)) OP_DELETEA(m_store.m_data.data); } void DOM_DataTransferItem::GCTrace() { if (IS_FILE(this)) GCMark(m_store.m_data.file); GCMark(m_parent); } OpDragObject* DOM_DataTransferItem::GetDataStore() { return m_parent->GetDataStore(); } BOOL DOM_DataTransferItem::HasProtectionModeOverridden() { return m_parent->HasProtectionModeOverridden(); } DataStoreMode DOM_DataTransferItem::GetOverriddenProtectionMode() { return m_parent->GetOverriddenProtectionMode(); } /* static */ OP_STATUS DOM_DataTransferItems::Make(DOM_DataTransferItems*& data_transfer_items, DOM_DataTransfer* parent, DOM_Runtime* runtime) { RETURN_IF_ERROR(DOMSetObjectRuntime(data_transfer_items = OP_NEW(DOM_DataTransferItems, ()), runtime, runtime->GetPrototype(DOM_Runtime::DATATRANSFERITEMS_PROTOTYPE), "DataTransferItemList")); RETURN_IF_ERROR(data_transfer_items->Initialize(parent, runtime)); return OpStatus::OK; } OP_STATUS DOM_DataTransferItems::Initialize(DOM_DataTransfer* parent, DOM_Runtime* runtime) { OP_ASSERT(parent); m_parent = parent; OpDragObject* drag_object = GetDataStore(); OP_ASSERT(drag_object); OpDragDataIterator& iter = drag_object->GetDataIterator(); if (!iter.First()) return OpStatus::OK; do { DOM_DataTransferItem* item; if (iter.IsFileData()) { DOM_File* dom_file; RETURN_IF_ERROR(DOM_File::Make(dom_file, iter.GetFileData()->GetFullPath(), FALSE, FALSE, runtime)); RETURN_IF_ERROR(DOM_DataTransferItem::Make(item, this, dom_file, runtime, FALSE)); } else RETURN_IF_ERROR(DOM_DataTransferItem::Make(item, this, iter.GetMimeType(), iter.GetStringData(), runtime, FALSE)); RETURN_IF_ERROR(m_items.Add(item)); } while (iter.Next()); return OpStatus::OK; } OP_STATUS DOM_DataTransferItems::GetTypes(DOM_DOMStringList *&types, DOM_Runtime *runtime) { if (!IS_VALID(runtime)) { /* Have to return the same DOMStringList */ if (!m_types_empty) RETURN_IF_ERROR(DOM_DOMStringList::Make(m_types_empty, NULL, NULL, runtime)); types = m_types_empty; } else { if (!m_types) { if (OpDragObject* data_store = GetDataStore()) RETURN_IF_ERROR(DragDrop_Data_Utils::DOMGetFormats(data_store, m_generator.GetFormats())); RETURN_IF_ERROR(DOM_DOMStringList::Make(m_types, m_parent, &m_generator, runtime)); m_generator.SetClient(m_types); } types = m_types; } return OpStatus::OK; } OP_STATUS DOM_DataTransferItems::GetFiles(DOM_FileList*& files, DOM_Runtime *runtime) { if (!IS_VALID(runtime) || IS_PROTECTED(this, runtime)) { /* Have to return the same FileList */ if (!m_files_empty) RETURN_IF_ERROR(DOM_FileList::Make(m_files_empty, runtime)); files = m_files_empty; } else { if (!m_files) { RETURN_IF_ERROR(DOM_FileList::Make(m_files, runtime)); for (unsigned i = 0; i < m_items.GetCount(); ++i) { DOM_DataTransferItem *it = m_items.Get(i); if (IS_FILE(it)) RETURN_IF_ERROR(m_files->Add(it->GetFileData())); } } files = m_files; } return OpStatus::OK; } void DOM_DataTransferItems::GCTrace() { for (unsigned index = 0; index < m_items.GetCount(); ++index) GCMark(m_items.Get(index)); GCMark(m_types); GCMark(m_types_empty); GCMark(m_files); GCMark(m_files_empty); GCMark(m_parent); } BOOL DOM_DataTransferItems::Contains(DOM_DataTransferItem* item) { return m_items.Find(item) != -1; } OP_STATUS DOM_DataTransferItems::Add(DOM_DataTransferItem* item) { RETURN_IF_ERROR(m_items.Add(item)); if (m_files && IS_FILE(item)) RETURN_IF_ERROR(m_files->Add(item->GetFileData())); return OpStatus::OK; } void DOM_DataTransferItems::ClearData(const uni_char* format) { OP_ASSERT(GetDataStore()); #ifdef USE_OP_CLIPBOARD g_clipboard_manager->OnDataObjectClear(GetDataStore()); #endif // USE_OP_CLIPBOARD if (!format) { m_items.DeleteAll(); GetDataStore()->ClearData(); if (m_files) m_files->Clear(); } else { UINT32 count = m_items.GetCount(); for (UINT32 iter = 0; iter < count;) { if (IS_STRING(m_items.Get(iter)) && uni_str_eq(m_items.Get(iter)->GetType().CStr(), format)) { DragDrop_Data_Utils::ClearStringData(GetDataStore(), m_items.Get(iter)->GetType().CStr()); --count; m_items.Delete(iter); } else ++iter; } } } OP_STATUS DOM_DataTransferItems::SetData(const uni_char* format, const uni_char* data, DOM_Runtime* runtime) { DOM_DataTransferItem* item; for (UINT32 index = 0; index < m_items.GetCount(); ++index) { item = m_items.Get(index); if (IS_STRING(item) && uni_str_eq(item->GetType().CStr(), format)) m_items.RemoveByItem(item); } RETURN_IF_ERROR(DOM_DataTransferItem::Make(item, this, format, data, runtime, TRUE)); RETURN_IF_ERROR(m_items.Add(item)); return OpStatus::OK; } const uni_char* DOM_DataTransferItems::GetData(const uni_char* format) { for (UINT32 index = 0; index < m_items.GetCount(); ++index) { DOM_DataTransferItem* item = m_items.Get(index); if (IS_STRING(item) && uni_str_eq(item->GetType().CStr(), format)) return item->GetStringData(); } return NULL; } /* virtual */ ES_GetState DOM_DataTransferItems::GetName(OpAtom property_name, ES_Value* value, ES_Runtime* origining_runtime) { if (property_name == OP_ATOM_length) { DOMSetNumber(value, !IS_VALID(origining_runtime) ? 0 : static_cast<double>(m_items.GetCount())); return GET_SUCCESS; } return DOM_Object::GetName(property_name, value, origining_runtime); } /* virtual */ ES_PutState DOM_DataTransferItems::PutName(OpAtom property_name, ES_Value* value, ES_Runtime* origining_runtime) { if (property_name == OP_ATOM_length) return PUT_READ_ONLY; return DOM_Object::PutName(property_name, value, origining_runtime); } /* virtual */ ES_DeleteStatus DOM_DataTransferItems::DeleteIndex(int property_index, ES_Runtime* origining_runtime) { if (!IS_READ_WRITE(this, origining_runtime)) return DELETE_REJECT; property_index = static_cast<unsigned>(property_index); if (static_cast<unsigned>(property_index) < m_items.GetCount()) { ClearData(m_items.Get(property_index)->GetType().CStr()); return DELETE_OK; } return DELETE_REJECT; } /* virtual */ ES_GetState DOM_DataTransferItems::GetIndex(int property_index, ES_Value* value, ES_Runtime* origining_runtime) { if (!IS_VALID(origining_runtime)) return GET_FAILED; property_index = static_cast<UINT32>(property_index); if (static_cast<UINT32>(property_index) < m_items.GetCount()) { DOMSetObject(value, m_items.Get(property_index)); return GET_SUCCESS; } return GET_FAILED; } /* static */ int DOM_DataTransferItems::add(DOM_Object* this_object, ES_Value* argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime) { DOM_THIS_OBJECT(data_transfer_items, DOM_TYPE_DATA_TRANSFER_ITEMS, DOM_DataTransferItems); if (!IS_READ_WRITE(data_transfer_items, origining_runtime)) { DOMSetNull(return_value); return ES_VALUE; } if (argc > 0) { DOM_DataTransferItem* item = NULL; if (argc > 1) { if (argv[0].type != VALUE_STRING) { DOMSetNumber(return_value, ES_CONVERT_ARGUMENT(ES_CALL_NEEDS_STRING, 0)); return ES_NEEDS_CONVERSION; } else if (argv[1].type != VALUE_STRING) { DOMSetNumber(return_value, ES_CONVERT_ARGUMENT(ES_CALL_NEEDS_STRING, 1)); return ES_NEEDS_CONVERSION; } DOM_CHECK_ARGUMENTS("ss"); for (UINT32 iter = 0; iter < data_transfer_items->m_items.GetCount(); ++iter) { if (IS_STRING(data_transfer_items->m_items.Get(iter)) && data_transfer_items->m_items.Get(iter)->GetType().CompareI(argv[1].value.string) == 0) return DOM_CALL_DOMEXCEPTION(NOT_SUPPORTED_ERR); } OpString type; CALL_FAILED_IF_ERROR(type.Set(argv[1].value.string)); type.MakeLower(); #ifdef DRAG_SUPPORT if (!DragDropManager::IsOperaSpecialMimeType(type.CStr()) || !data_transfer_items->m_parent->IsDragAndDrops() ) CALL_FAILED_IF_ERROR(DOM_DataTransferItem::Make(item, data_transfer_items, type.CStr(), argv[0].value.string, origining_runtime)); #endif // DRAG_SUPPORT } else { DOM_CHECK_ARGUMENTS("o"); DOM_HOSTOBJECT_SAFE(file, argv[0].value.object, DOM_TYPE_FILE, DOM_File); if (!file) return ES_FAILED; CALL_FAILED_IF_ERROR(DOM_DataTransferItem::Make(item, data_transfer_items, file, origining_runtime)); } if (item) { CALL_FAILED_IF_ERROR(data_transfer_items->Add(item)); DOMSetObject(return_value, item); } else DOMSetNull(return_value); return ES_VALUE; } return ES_FAILED; } /* static */ int DOM_DataTransferItems::clear(DOM_Object* this_object, ES_Value* argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime) { DOM_THIS_OBJECT(data_transfer_items, DOM_TYPE_DATA_TRANSFER_ITEMS, DOM_DataTransferItems); if (!IS_READ_WRITE(data_transfer_items, origining_runtime)) return GET_FAILED; data_transfer_items->ClearData(NULL); return ES_FAILED; } /* virtual */ unsigned DOM_DataTransferItems::FormatsGenerator::StringList_length() { return m_formats.GetCount(); } /* virtual */ OP_STATUS DOM_DataTransferItems::FormatsGenerator::StringList_item(int index, const uni_char *&name) { OpString *s = m_formats.Get(index); name = s->CStr(); return OpStatus::OK; } BOOL DOM_DataTransferItems::FormatsGenerator::StringList_contains(const uni_char *string) { for (unsigned i = 0, n = m_formats.GetCount(); i < n; i++) if (m_formats.Get(i)->CompareI(string) == 0) return TRUE; return FALSE; } OpDragObject* DOM_DataTransferItems::GetDataStore() { return m_parent->GetDataStore(); } BOOL DOM_DataTransferItems::HasProtectionModeOverridden() { return m_parent->HasProtectionModeOverridden(); } DataStoreMode DOM_DataTransferItems::GetOverriddenProtectionMode() { return m_parent->GetOverriddenProtectionMode(); } #ifdef DRAG_SUPPORT static const uni_char* GetDropTypeString(unsigned drop_type) { if (drop_type == DROP_NONE) return UNI_L("none"); else if (drop_type == (DROP_COPY | DROP_MOVE | DROP_LINK)) return UNI_L("all"); else if (drop_type == DROP_UNINITIALIZED) return UNI_L("uninitialized"); if (drop_type & DROP_COPY) return (drop_type & DROP_LINK) ? UNI_L("copyLink") : (drop_type & DROP_MOVE) ? UNI_L("copyMove") : UNI_L("copy"); else if (drop_type & DROP_LINK) return (drop_type & DROP_MOVE) ? UNI_L("linkMove") : UNI_L("link"); else if (drop_type & DROP_MOVE) return UNI_L("move"); OP_ASSERT(!"Bad drop_type value"); return UNI_L("none"); } static int GetDropType(OpAtom property_name, const uni_char* s) { int len = uni_strlen(s); if (len != 4 && property_name == OP_ATOM_dropEffect) return -1; if (uni_str_eq(s, UNI_L("none"))) return DROP_NONE; else if (uni_strncmp(s, UNI_L("copy"), 4) == 0) { if (len == 4) return DROP_COPY; else if (property_name == OP_ATOM_effectAllowed) { if (uni_str_eq(s + 4, "Link")) return DROP_COPY | DROP_LINK; else if (uni_str_eq(s + 4, "Move")) return DROP_COPY | DROP_MOVE; } } else if (uni_strncmp(s, UNI_L("link"), 4) == 0) { if (len == 4) return DROP_LINK; else if (property_name == OP_ATOM_effectAllowed) if (uni_str_eq(s + 4, "Move")) return DROP_LINK | DROP_MOVE; } else if (uni_str_eq(s, UNI_L("move"))) return DROP_MOVE; else if (uni_str_eq(s, UNI_L("all"))) return (DROP_COPY | DROP_MOVE | DROP_LINK); else if (uni_str_eq(s, UNI_L("uninitialized"))) return DROP_UNINITIALIZED; return -1; } #endif // DRAG_SUPPORT DOM_DataTransfer::DOM_DataTransfer() : m_items(NULL) , m_overridden_data_store_mode(DATA_STORE_MODE_PROTECTED) , m_has_overridden_data_store_mode(FALSE) { } DOM_DataTransfer::~DOM_DataTransfer() { OP_ASSERT(m_data_store_info.type > DataStoreType_Unknown); if (m_data_store_info.type == DataStoreType_Local) OP_DELETE(m_data_store_info.info.object); } /* static */ BOOL DOM_DataTransfer::IsDataStoreValid(ES_Runtime* origining_runtime) { ES_Thread* thread = GetCurrentThread(origining_runtime); return IsDataStoreValid(thread); } /* static */ BOOL DOM_DataTransfer::IsDataStoreValid(ES_Thread* thread) { while (thread) { ES_ThreadInfo info = thread->GetInfo(); if (info.type == ES_THREAD_EVENT) { #ifdef DRAG_SUPPORT if (info.data.event.type == ONDRAG || info.data.event.type == ONDRAGEND || info.data.event.type == ONDRAGENTER || info.data.event.type == ONDRAGLEAVE || info.data.event.type == ONDRAGOVER || info.data.event.type == ONDRAGSTART || info.data.event.type == ONDROP) return TRUE; #endif // DRAG_SUPPORT #ifdef USE_OP_CLIPBOARD if (info.data.event.type == ONCOPY || info.data.event.type == ONCUT || info.data.event.type == ONPASTE) return TRUE; #endif // USE_OP_CLIPBOARD } thread = thread->GetInterruptedThread(); } return FALSE; } /* static */ DataStoreMode DOM_DataTransfer::GetDataStoreMode(ES_Runtime* origining_runtime, BOOL search_start_drop_up /* = FALSE */) { ES_Thread* thread = GetCurrentThread(origining_runtime); while (thread) { ES_ThreadInfo info = thread->GetInfo(); if (info.type == ES_THREAD_EVENT) { #ifdef DRAG_SUPPORT if(info.data.event.type == ONDRAGSTART) return DATA_STORE_MODE_READ_WRITE; else if (info.data.event.type == ONDROP) return DATA_STORE_MODE_READ_ONLY; else if (!search_start_drop_up && (info.data.event.type == ONDRAGENTER || info.data.event.type == ONDRAG || info.data.event.type == ONDRAGOVER || info.data.event.type == ONDRAGLEAVE || info.data.event.type == ONDRAGEND)) return DATA_STORE_MODE_PROTECTED; else #endif // DRAG_SUPPORT { #ifdef USE_OP_CLIPBOARD if (info.data.event.type == ONPASTE) return DATA_STORE_MODE_READ_ONLY; else if (info.data.event.type == ONCUT || info.data.event.type == ONCOPY) return DATA_STORE_MODE_READ_WRITE; #endif // USE_OP_CLIPBOARD } } thread = thread->GetInterruptedThread(); } return DATA_STORE_MODE_PROTECTED; } OpDragObject* DOM_DataTransfer::GetDataStore() { OP_ASSERT(m_data_store_info.type > DataStoreType_Unknown); if (m_data_store_info.type == DataStoreType_Global) { #ifdef DRAG_SUPPORT if (m_data_store_info.drag_and_drops) return g_drag_manager->GetDragObject(); else #endif // DRAG_SUPPORT #ifdef USE_OP_CLIPBOARD return g_clipboard_manager->GetEventObject(m_data_store_info.info.id); #else return NULL; #endif // USE_OP_CLIPBOARD } else return m_data_store_info.info.object; } /* static */ OP_STATUS DOM_DataTransfer::Make(DOM_DataTransfer*& data_transfer, DOM_Runtime* runtime, BOOL set_origin, DataStoreInfo &data_store_info, ES_Object* inherit_properties /* = NULL */) { RETURN_IF_ERROR(DOMSetObjectRuntime(data_transfer = OP_NEW(DOM_DataTransfer, ()), runtime, runtime->GetPrototype(DOM_Runtime::DATATRANSFER_PROTOTYPE), "DataTransfer")); OP_ASSERT(data_store_info.type > DOM_DataTransfer::DataStoreType_Unknown); data_transfer->m_data_store_info = data_store_info; #ifdef DRAG_SUPPORT OpDragObject* data_store = data_transfer->GetDataStore(); if (set_origin) { URL origin_url = runtime->GetOriginURL(); DragDropManager::SetOriginURL(data_store, origin_url); } if (inherit_properties) { const uni_char* property_value = data_transfer->DOMGetDictionaryString(inherit_properties, UNI_L("dropEffect"), NULL); if (property_value) { int drop_type = GetDropType(OP_ATOM_dropEffect, property_value); if (drop_type >= 0) data_store->SetDropType(static_cast<DropType>(drop_type)); } property_value = data_transfer->DOMGetDictionaryString(inherit_properties, UNI_L("effectAllowed"), NULL); if (property_value) { int effects = GetDropType(OP_ATOM_effectAllowed, property_value); if (effects >= 0) data_store->SetEffectsAllowed(static_cast<unsigned int>(effects)); } } #endif // DRAG_SUPPORT RETURN_IF_ERROR(DOM_DataTransferItems::Make(data_transfer->m_items, data_transfer, runtime)); return OpStatus::OK; } /* virtual */ ES_GetState DOM_DataTransfer::GetName(OpAtom property_name, ES_Value* value, ES_Runtime* origining_runtime) { switch (property_name) { case OP_ATOM_types: if (value) { DOM_DOMStringList* types; GET_FAILED_IF_ERROR(m_items->GetTypes(types, static_cast<DOM_Runtime *>(origining_runtime))); DOMSetObject(value, types); } break; case OP_ATOM_items: DOMSetObject(value, m_items); break; case OP_ATOM_files: if (value) { DOM_FileList* files; GET_FAILED_IF_ERROR(m_items->GetFiles(files, static_cast<DOM_Runtime *>(origining_runtime))); DOMSetObject(value, files); } break; #ifdef DRAG_SUPPORT case OP_ATOM_dropEffect: DOMSetString(value, GetDropTypeString(static_cast<unsigned>(GetDataStore() ? GetDataStore()->GetDropType() : DROP_NONE))); break; case OP_ATOM_effectAllowed: DOMSetString(value, GetDropTypeString(static_cast<unsigned>(GetDataStore() ? GetDataStore()->GetEffectsAllowed() : static_cast<unsigned>(DROP_UNINITIALIZED)))); break; case OP_ATOM_origin: DOMSetString(value, GetDataStore() && DragDropManager::GetOriginURL(GetDataStore()) ? DragDropManager::GetOriginURL(GetDataStore()): UNI_L("null")); break; #endif // DRAG_SUPPORT default: return DOM_Object::GetName(property_name, value, origining_runtime); } return GET_SUCCESS; } /* virtual */ ES_PutState DOM_DataTransfer::PutName(OpAtom property_name, ES_Value* value, ES_Runtime* origining_runtime) { switch (property_name) { #ifdef DRAG_SUPPORT case OP_ATOM_effectAllowed: if (!IS_READ_WRITE(this, origining_runtime)) return PUT_READ_ONLY; // Fall through. case OP_ATOM_dropEffect: { if (OpDragObject* data_store = GetDataStore()) { if (value->type != VALUE_STRING) return PUT_NEEDS_STRING; int d = GetDropType(property_name, value->value.string); if (d >= 0) { if (property_name == OP_ATOM_dropEffect) data_store->SetDropType(static_cast<DropType>(d)); else data_store->SetEffectsAllowed(static_cast<unsigned int>(d)); } } return PUT_SUCCESS; } case OP_ATOM_origin: #endif // DRAG_SUPPORT case OP_ATOM_items: case OP_ATOM_files: case OP_ATOM_types: return PUT_READ_ONLY; default: return DOM_Object::PutName(property_name, value, origining_runtime); } } /* virtual */ void DOM_DataTransfer::GCTrace() { GCMark(m_items); } /* static */ int DOM_DataTransfer::handleData(DOM_Object* this_object, ES_Value* argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime, int data) { DOM_THIS_OBJECT(data_transfer, DOM_TYPE_DATA_TRANSFER, DOM_DataTransfer); if (data < 2 && (!IS_VALID(origining_runtime) || !IS_READ_WRITE(data_transfer, origining_runtime))) return ES_FAILED; OpString format; BOOL convert_to_url = FALSE; if (argc > 0 && argv[0].type == VALUE_STRING) { CALL_FAILED_IF_ERROR(format.Set(argv[0].value.string)); format.MakeLower(); if (uni_str_eq(format.CStr(), "url")) { CALL_FAILED_IF_ERROR(format.Set(UNI_L("text/uri-list"))); convert_to_url = TRUE; } else if (uni_str_eq(format.CStr(), "text")) CALL_FAILED_IF_ERROR(format.Set(UNI_L("text/plain"))); } BOOL forbidden = FALSE; #ifdef DRAG_SUPPORT if (format.CStr() && data_transfer->IsDragAndDrops() ) forbidden = DragDropManager::IsOperaSpecialMimeType(format.CStr()); #endif // DRAG_SUPPORT if (data == 0) { DOM_CHECK_ARGUMENTS("|s"); if (argc == 0) data_transfer->m_items->ClearData(NULL); else data_transfer->m_items->ClearData(format); } else if (data == 1) { DOM_CHECK_ARGUMENTS("ss"); if (forbidden) return ES_FAILED; CALL_FAILED_IF_ERROR(data_transfer->m_items->SetData(format, argv[1].value.string, origining_runtime)); #ifdef USE_OP_CLIPBOARD if (!data_transfer->IsDragAndDrops()) g_clipboard_manager->OnDataObjectSet(data_transfer->GetDataStore()); #endif // USE_OP_CLIPBOARD } else { DOM_CHECK_ARGUMENTS("s"); TempBuffer* data = GetEmptyTempBuf(); if (IS_VALID(origining_runtime) && !IS_PROTECTED(data_transfer, origining_runtime)) { CALL_FAILED_IF_ERROR(data->Append(data_transfer->m_items->GetData(format))); if (convert_to_url) CALL_FAILED_IF_ERROR(DragDrop_Data_Utils::GetURL(data_transfer->GetDataStore(), data)); } DOMSetString(return_value, data->GetStorage()); return ES_VALUE; } return ES_FAILED; } #ifdef DRAG_SUPPORT /* static */ int DOM_DataTransfer::setFeedbackElement(DOM_Object* this_object, ES_Value* argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime, int data) { DOM_THIS_OBJECT(data_transfer, DOM_TYPE_DATA_TRANSFER, DOM_DataTransfer); if (!IS_VALID(origining_runtime) || !IS_READ_WRITE(data_transfer, origining_runtime)) return ES_FAILED; if (data == 0) { DOM_CHECK_ARGUMENTS("onn"); DOM_HOSTOBJECT_SAFE(element, argv[0].value.object, DOM_TYPE_ELEMENT, DOM_Element); if (element && element->GetThisElement() && element->GetOwnerDocument() && data_transfer->GetFramesDocument()) { DOM_Document* owner_doc = element->GetOwnerDocument(); HTML_Document* data_transfer_doc = data_transfer->GetFramesDocument()->GetHtmlDocument(); if (owner_doc && owner_doc->GetFramesDocument() && owner_doc->GetFramesDocument()->GetHtmlDocument() && data_transfer_doc) { OpPoint point(TruncateDoubleToInt(argv[1].value.number), TruncateDoubleToInt(argv[2].value.number)); g_drag_manager->SetFeedbackElement(data_transfer_doc, element->GetThisElement(), owner_doc->GetFramesDocument()->GetHtmlDocument(), point); } } } else { DOM_CHECK_ARGUMENTS("o"); DOM_HOSTOBJECT_SAFE(element, argv[0].value.object, DOM_TYPE_ELEMENT, DOM_Element); if (element && element->GetThisElement() && element->GetOwnerDocument() && data_transfer->GetFramesDocument()) { DOM_Document* owner_doc = element->GetOwnerDocument(); HTML_Document* data_transfer_doc = data_transfer->GetFramesDocument()->GetHtmlDocument(); if (owner_doc && owner_doc->GetFramesDocument() && owner_doc->GetFramesDocument()->GetHtmlDocument() && data_transfer_doc) CALL_FAILED_IF_ERROR(g_drag_manager->AddElement(data_transfer_doc, element->GetThisElement(), owner_doc->GetFramesDocument()->GetHtmlDocument())); } } return ES_FAILED; } /* static */ int DOM_DataTransfer::allowTargetOrigin(DOM_Object* this_object, ES_Value* argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime) { DOM_THIS_OBJECT(data_transfer, DOM_TYPE_DATA_TRANSFER, DOM_DataTransfer); if (argc < 1 || argv[0].type != VALUE_STRING) return DOM_CALL_DOMEXCEPTION(SYNTAX_ERR); if (!IS_VALID(origining_runtime) || !IS_READ_WRITE(data_transfer, origining_runtime)) return DOM_CALL_DOMEXCEPTION(SECURITY_ERR); const uni_char* url = argv[0].value.string; unsigned int url_len = argv[0].string_length; if (url_len < 1) return DOM_CALL_DOMEXCEPTION(SYNTAX_ERR); URL resolved_url; if (url_len == 1 && *url == '/') resolved_url = origining_runtime->GetOriginURL(); else { resolved_url = g_url_api->GetURL(url, origining_runtime->GetOriginURL().GetContextId()); if (url_len > 1 || *url != '*') { if (!resolved_url.IsValid() || resolved_url.Type() == URL_NULL_TYPE || resolved_url.Type() == URL_UNKNOWN || DOM_Utils::IsOperaIllegalURL(resolved_url)) return DOM_CALL_DOMEXCEPTION(SYNTAX_ERR); if (resolved_url.Type() != URL_DATA) { if (resolved_url.Type() != URL_JAVASCRIPT && (!resolved_url.GetServerName() || !resolved_url.GetServerName()->UniName())) return DOM_CALL_DOMEXCEPTION(SYNTAX_ERR); } else { const uni_char* scheme_end = uni_strstr(url, ":"); if (!scheme_end || !(scheme_end + 1) || !(*(scheme_end + 1))) return DOM_CALL_DOMEXCEPTION(SYNTAX_ERR); // To check if it has e.g. data:text/plain, form (the comma after a mime type and before data). const uni_char* comma = uni_strstr(url, ","); if (!comma) return DOM_CALL_DOMEXCEPTION(SYNTAX_ERR); } } } if (url_len == 1 && *url == '*') CALL_FAILED_IF_ERROR(DragDropManager::AllowAllURLs(data_transfer->GetDataStore())); else CALL_FAILED_IF_ERROR(DragDropManager::AddAllowedTargetURL(data_transfer->GetDataStore(), resolved_url)); return ES_FAILED; } #endif // DRAG_SUPPORT #include "modules/dom/src/domglobaldata.h" DOM_FUNCTIONS_WITH_DATA_START(DOM_DataTransfer) DOM_FUNCTIONS_WITH_DATA_FUNCTION(DOM_DataTransfer, DOM_DataTransfer::handleData, 0, "clearData", "s-") DOM_FUNCTIONS_WITH_DATA_FUNCTION(DOM_DataTransfer, DOM_DataTransfer::handleData, 1, "setData", "ss-") DOM_FUNCTIONS_WITH_DATA_FUNCTION(DOM_DataTransfer, DOM_DataTransfer::handleData, 2, "getData", "s-") #ifdef DRAG_SUPPORT DOM_FUNCTIONS_WITH_DATA_FUNCTION(DOM_DataTransfer, DOM_DataTransfer::setFeedbackElement, 0, "setDragImage", "-nn-") DOM_FUNCTIONS_WITH_DATA_FUNCTION(DOM_DataTransfer, DOM_DataTransfer::setFeedbackElement, 1, "addElement", "-") #endif // DRAG_SUPPORT DOM_FUNCTIONS_WITH_DATA_END(DOM_DataTransfer) DOM_FUNCTIONS_START(DOM_DataTransfer) #ifdef DRAG_SUPPORT DOM_FUNCTIONS_FUNCTION(DOM_DataTransfer, DOM_DataTransfer::allowTargetOrigin, "allowTargetOrigin", "s-") #endif // DRAG_SUPPORT DOM_FUNCTIONS_END(DOM_DataTransfer) DOM_FUNCTIONS_START(DOM_DataTransferItems) DOM_FUNCTIONS_FUNCTION(DOM_DataTransferItems, DOM_DataTransferItems::clear, "clear", "-") DOM_FUNCTIONS_FUNCTION(DOM_DataTransferItems, DOM_DataTransferItems::add, "add", "-") DOM_FUNCTIONS_END(DOM_DataTransferItems) DOM_FUNCTIONS_WITH_DATA_START(DOM_DataTransferItem) DOM_FUNCTIONS_WITH_DATA_FUNCTION(DOM_DataTransferItem, DOM_DataTransferItem::get, 1, "getAsString", "-") DOM_FUNCTIONS_WITH_DATA_FUNCTION(DOM_DataTransferItem, DOM_DataTransferItem::get, 0, "getAsFile", "-") DOM_FUNCTIONS_WITH_DATA_END(DOM_DataTransferItem) #endif // DRAG_SUPPORT || USE_OP_CLIPBOARD
// Created on: 1993-08-25 // Created by: Bruno DUMORTIER // Copyright (c) 1993-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _GeomProjLib_HeaderFile #define _GeomProjLib_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <Standard_Real.hxx> #include <Standard_Boolean.hxx> class Geom2d_Curve; class Geom_Curve; class Geom_Surface; class Geom_Plane; class gp_Dir; //! Projection of a curve on a surface. class GeomProjLib { public: DEFINE_STANDARD_ALLOC //! gives the 2d-curve of a 3d-curve lying on a //! surface ( uses GeomProjLib_ProjectedCurve ) //! The 3dCurve is taken between the parametrization //! range [First, Last] //! <Tolerance> is used as input if the projection needs //! an approximation. In this case, the reached //! tolerance is set in <Tolerance> as output. //! WARNING : if the projection has failed, this //! method returns a null Handle. Standard_EXPORT static Handle(Geom2d_Curve) Curve2d (const Handle(Geom_Curve)& C, const Standard_Real First, const Standard_Real Last, const Handle(Geom_Surface)& S, const Standard_Real UFirst, const Standard_Real ULast, const Standard_Real VFirst, const Standard_Real VLast, Standard_Real& Tolerance); //! gives the 2d-curve of a 3d-curve lying on a //! surface ( uses GeomProjLib_ProjectedCurve ) //! The 3dCurve is taken between the parametrization //! range [First, Last] //! <Tolerance> is used as input if the projection needs //! an approximation. In this case, the reached //! tolerance is set in <Tolerance> as output. //! WARNING : if the projection has failed, this //! method returns a null Handle. Standard_EXPORT static Handle(Geom2d_Curve) Curve2d (const Handle(Geom_Curve)& C, const Standard_Real First, const Standard_Real Last, const Handle(Geom_Surface)& S, Standard_Real& Tolerance); //! gives the 2d-curve of a 3d-curve lying on a //! surface ( uses GeomProjLib_ProjectedCurve ) //! The 3dCurve is taken between the parametrization //! range [First, Last] //! If the projection needs an approximation, //! Precision::PApproximation() is used. //! WARNING : if the projection has failed, this //! method returns a null Handle. Standard_EXPORT static Handle(Geom2d_Curve) Curve2d (const Handle(Geom_Curve)& C, const Standard_Real First, const Standard_Real Last, const Handle(Geom_Surface)& S); //! gives the 2d-curve of a 3d-curve lying on a //! surface ( uses GeomProjLib_ProjectedCurve ). //! If the projection needs an approximation, //! Precision::PApproximation() is used. //! WARNING : if the projection has failed, this //! method returns a null Handle. Standard_EXPORT static Handle(Geom2d_Curve) Curve2d (const Handle(Geom_Curve)& C, const Handle(Geom_Surface)& S); //! gives the 2d-curve of a 3d-curve lying on a //! surface ( uses GeomProjLib_ProjectedCurve ). //! If the projection needs an approximation, //! Precision::PApproximation() is used. //! WARNING : if the projection has failed, this //! method returns a null Handle. //! can expand a little the bounds of surface Standard_EXPORT static Handle(Geom2d_Curve) Curve2d (const Handle(Geom_Curve)& C, const Handle(Geom_Surface)& S, const Standard_Real UDeb, const Standard_Real UFin, const Standard_Real VDeb, const Standard_Real VFin); //! gives the 2d-curve of a 3d-curve lying on a //! surface ( uses GeomProjLib_ProjectedCurve ). //! If the projection needs an approximation, //! Precision::PApproximation() is used. //! WARNING : if the projection has failed, this //! method returns a null Handle. //! can expand a little the bounds of surface Standard_EXPORT static Handle(Geom2d_Curve) Curve2d (const Handle(Geom_Curve)& C, const Handle(Geom_Surface)& S, const Standard_Real UDeb, const Standard_Real UFin, const Standard_Real VDeb, const Standard_Real VFin, Standard_Real& Tolerance); //! Constructs the 3d-curve from the normal //! projection of the Curve <C> on the surface <S>. //! WARNING : if the projection has failed, returns a //! null Handle. Standard_EXPORT static Handle(Geom_Curve) Project (const Handle(Geom_Curve)& C, const Handle(Geom_Surface)& S); //! Constructs the 3d-curves from the projection //! of the curve <Curve> on the plane <Plane> along //! the direction <Dir>. //! If <KeepParametrization> is true, the parametrization //! of the Projected Curve <PC> will be the same as the //! parametrization of the initial curve <C>. //! It means: proj(C(u)) = PC(u) for each u. //! Otherwise, the parametrization may change. Standard_EXPORT static Handle(Geom_Curve) ProjectOnPlane (const Handle(Geom_Curve)& Curve, const Handle(Geom_Plane)& Plane, const gp_Dir& Dir, const Standard_Boolean KeepParametrization); protected: private: }; #endif // _GeomProjLib_HeaderFile
#ifndef _MODEL_WF_H_ #define _MODEL_WF_H_ #include "Model.h" using namespace std; class ModelWF : public Model{ private: vector<Individual> dst; unsigned int processDNAGenes(unsigned int marker_pos, ProfileMarker &marker, Pool *pool, mt19937 &generator); unsigned int processMSGenes(unsigned int marker_pos, ProfileMarker &marker, unsigned int ploidy, Pool *pool, mt19937 &generator); public: ModelWF(); ModelWF(const ModelWF &original); ModelWF& operator=(const ModelWF& original); virtual Model *clone(); virtual ~ModelWF(); virtual void run(Population *population, Profile *profile, mt19937 &generator); // Metodo de debug virtual void print(){ cout << "ModelWF::print - type: " << type << "\n"; } }; #endif
#pragma once #include "Point.hpp" #include <vector> #include <glm/glm.hpp> #include "Volume.hpp" #include "AABB.hpp" using namespace std; using namespace glm; /* * CLASS PointCloud */ template <class PointT> class PointCloud { public: // List of point cloud points vector<Point<PointT>> points; // Bounding box AABB<PointT> aabb; public: PointCloud() {}; ~PointCloud() {}; /* * Converts volumetric data to point cloud representation */ template <typename T> void setFromVolume(Volume<T> &volume, T isovalue, bool normalize = true); /* * Functions required by KD-Tree */ inline size_t kdtree_get_point_count() const { return points.size(); } inline PointT kdtree_distance(const PointT *p1, const size_t idx_p2, size_t /*size*/) const { const PointT d0 = p1[0] - points[idx_p2].position.x; const PointT d1 = p1[1] - points[idx_p2].position.y; const PointT d2 = p1[2] - points[idx_p2].position.z; return sqrt(d0*d0 + d1*d1 + d2*d2); } inline PointT kdtree_get_pt(const size_t idx, int dim) const { if (dim == 0) { return points[idx].position.x; } else if (dim == 1) { return points[idx].position.y; } else { return points[idx].position.z; } } template <class BBOX> bool kdtree_get_bbox(BBOX&) const { return false; } private: /* * Masks unwanted volume artifacts */ template <typename T> vector<bool> &generateMask(Volume<T> &volume, T isovalue); /* * Generates points based on the input parameters and returns the number of newly added points */ int generateAndAddPoints(vector<bool> &neighbourStates, int nActive, tvec3<PointT> volPos, tvec3<PointT> gradient, vector<Point<PointT>> *points); }; /* //////////////////////////////////////////// * ////////////// DEFINITIONS ///////////// */ //////////////////////////////////////////// template <class PointT> template <typename T> void PointCloud<PointT>::setFromVolume(Volume<T> &volume, T isovalue, bool normalize) { vector<int> dim = volume.dimensions(); // Used to mask insignificant voxels //vector<bool> mask = this->generateMask(volume, isovalue); // Index converter auto at = [dim](int x, int y, int z) { return x + dim[1] * (y + dim[2] * z); }; // Generate point cloud tvec3<PointT> gradient; int nActive = 0; vector<bool> neighbourStates(6, false); vector<Point<PointT>> points; for (int i = 1; i < dim[0] - 1; i++) { for (int j = 1; j < dim[1] - 1; j++) { for (int k = 1; k < dim[2] - 1; k++) { gradient = tvec3<PointT>(0.0f, 0.0f, 0.0f); // Check if the voxel is turned off and is not masked if (volume[i][j][k] < isovalue /*&& !mask[at(i, j, k]*/) { // Check which neighbours are activated if (volume[i][j][k - 1] > isovalue) { neighbourStates[0] = true; gradient[2]++; nActive++; } if (volume[i][j][k + 1] > isovalue) { neighbourStates[1] = true; gradient[2]--; nActive++; } if (volume[i][j - 1][k] > isovalue) { neighbourStates[2] = true; gradient[1]++; nActive++; } if (volume[i][j + 1][k] > isovalue) { neighbourStates[3] = true; gradient[1]--; nActive++; } if (volume[i - 1][j][k] > isovalue) { neighbourStates[4] = true; gradient[0]++; nActive++; } if (volume[i + 1][j][k] > isovalue) { neighbourStates[5] = true; gradient[0]--; nActive++; } gradient = glm::normalize(gradient); // Adds new points based on the neighbour states (modifies points vector) generateAndAddPoints(neighbourStates, nActive, tvec3<PointT>(i, j, k), gradient, &points); // Reset neighbour vector neighbourStates = { false, false, false, false, false, false }; nActive = 0; } } } } // Normalize the points to a cube with unit-length diagonal if (normalize) { AABB<PointT> aabb(points); tvec3<PointT> center = aabb.getCenter(); PointT maxEdgeAABB = aabb.getLongestEdge(); for (size_t i = 0; i < points.size(); i++) { points[i].position -= center; points[i].position.x /= maxEdgeAABB; points[i].position.y /= maxEdgeAABB; points[i].position.z /= maxEdgeAABB; } // Fix the aabb (actually create AAAA) aabb.setAABB(tvec3<PointT>(-0.5, -0.5, -0.5), tvec3<PointT>(0.5, 0.5, 0.5)); this->aabb = aabb; } else { this->aabb = AABB<PointT>(points); } this->points = points; } template <class PointT> int PointCloud<PointT>::generateAndAddPoints(vector<bool> &neighbourStates, int nActive, tvec3<PointT> volPos, tvec3<PointT> gradient, vector<Point<PointT>> *points) { int count = 0; switch (nActive) { // One neighbour is active case 1: if (neighbourStates[0]) { (*points).push_back(Point<PointT>(tvec3<PointT>(volPos.x + 0.5f, volPos.y + 0.5f, volPos.z), gradient)); } else if (neighbourStates[1]) { (*points).push_back(Point<PointT>(tvec3<PointT>(volPos.x + 0.5f, volPos.y + 0.5f, volPos.z + 1.0f), gradient)); } else if (neighbourStates[2]) { (*points).push_back(Point<PointT>(tvec3<PointT>(volPos.x + 0.5f, volPos.y, volPos.z + 0.5f), gradient)); } else if (neighbourStates[3]) { (*points).push_back(Point<PointT>(tvec3<PointT>(volPos.x + 0.5f, volPos.y + 1.0f, volPos.z + 0.5f), gradient)); } else if (neighbourStates[4]) { (*points).push_back(Point<PointT>(tvec3<PointT>(volPos.x, volPos.y + 0.5, volPos.z + 0.5f), gradient)); } else { (*points).push_back(Point<PointT>(tvec3<PointT>(volPos.x + 1.0f, volPos.y + 0.5, volPos.z + 0.5f), gradient)); } count++; break; // Two neighbours are active case 2: if (neighbourStates[0] && neighbourStates[1]) { (*points).push_back(Point<PointT>(tvec3<PointT>(volPos.x + 0.5f, volPos.y + 0.5f, volPos.z), tvec3<PointT>(0.0f, 0.0f, 1.0f))); (*points).push_back(Point<PointT>(tvec3<PointT>(volPos.x + 0.5f, volPos.y + 0.5f, volPos.z + 1.0f), tvec3<PointT>(0.0f, 0.0f, -1.0f))); count += 2; } else if (neighbourStates[2] && neighbourStates[3]) { (*points).push_back(Point<PointT>(tvec3<PointT>(volPos.x + 0.5f, volPos.y, volPos.z + 0.5f), tvec3<PointT>(0.0f, 1.0f, 0.0f))); (*points).push_back(Point<PointT>(tvec3<PointT>(volPos.x + 0.5f, volPos.y + 1.0f, volPos.z + 0.5f), tvec3<PointT>(0.0f, -1.0f, 0.0f))); count += 2; } else if (neighbourStates[4] && neighbourStates[5]) { (*points).push_back(Point<PointT>(tvec3<PointT>(volPos.x, volPos.y + 0.5f, volPos.z + 0.5f), tvec3<PointT>(1.0f, 0.0f, 0.0f))); (*points).push_back(Point<PointT>(tvec3<PointT>(volPos.x + 1.0f, volPos.y + 0.5f, volPos.z + 0.5f), tvec3<PointT>(-1.0f, 0.0f, 0.0f))); count += 2; } else { (*points).push_back(Point<PointT>(tvec3<PointT>(volPos.x + 0.5f, volPos.y + 0.5f, volPos.z + 0.5f), gradient)); count++; } break; // Three neighbours are active case 3: (*points).push_back(Point<PointT>(tvec3<PointT>(volPos.x + 0.5f, volPos.y + 0.5f, volPos.z + 0.5f), gradient)); count++; break; // Four neighbours are active case 4: if (!neighbourStates[0] && !neighbourStates[1]) { (*points).push_back(Point<PointT>(tvec3<PointT>(volPos.x + 0.5f, volPos.y, volPos.z + 0.5f), tvec3<PointT>(0.0f, 1.0f, 0.0f))); (*points).push_back(Point<PointT>(tvec3<PointT>(volPos.x + 0.5f, volPos.y + 1.0f, volPos.z + 0.5f), tvec3<PointT>(0.0f, -1.0f, 0.0f))); (*points).push_back(Point<PointT>(tvec3<PointT>(volPos.x, volPos.y + 0.5f, volPos.z + 0.5f), tvec3<PointT>(1.0f, 0.0f, 0.0f))); (*points).push_back(Point<PointT>(tvec3<PointT>(volPos.x + 1.0f, volPos.y + 0.5f, volPos.z + 0.5f), tvec3<PointT>(-1.0f, 0.0f, 0.0f))); } else if (!neighbourStates[2] && !neighbourStates[3]) { (*points).push_back(Point<PointT>(tvec3<PointT>(volPos.x + 0.5f, volPos.y + 0.5f, volPos.z), tvec3<PointT>(0.0f, 0.0f, 1.0f))); (*points).push_back(Point<PointT>(tvec3<PointT>(volPos.x + 0.5f, volPos.y + 0.5f, volPos.z + 1.0f), tvec3<PointT>(0.0f, 0.0f, -1.0f))); (*points).push_back(Point<PointT>(tvec3<PointT>(volPos.x, volPos.y + 0.5f, volPos.z + 0.5f), tvec3<PointT>(1.0f, 0.0f, 0.0f))); (*points).push_back(Point<PointT>(tvec3<PointT>(volPos.x + 1.0f, volPos.y + 0.5f, volPos.z + 0.5f), tvec3<PointT>(-1.0f, 0.0f, 0.0f))); } else if (!neighbourStates[4] && !neighbourStates[5]) { (*points).push_back(Point<PointT>(tvec3<PointT>(volPos.x + 0.5f, volPos.y, volPos.z + 0.5f), tvec3<PointT>(0.0f, 1.0f, 0.0f))); (*points).push_back(Point<PointT>(tvec3<PointT>(volPos.x + 0.5f, volPos.y + 1.0f, volPos.z + 0.5f), tvec3<PointT>(0.0f, -1.0f, 0.0f))); (*points).push_back(Point<PointT>(tvec3<PointT>(volPos.x + 0.5f, volPos.y + 0.5f, volPos.z), tvec3<PointT>(0.0f, 0.0f, 1.0f))); (*points).push_back(Point<PointT>(tvec3<PointT>(volPos.x + 0.5f, volPos.y + 0.5f, volPos.z + 1.0f), tvec3<PointT>(0.0f, 0.0f, -1.0f))); } count += 2; break; // Five neighbours are active case 5: if (!neighbourStates[0]) { (*points).push_back(Point<PointT>(tvec3<PointT>(volPos.x + 0.5f, volPos.y + 0.5f, volPos.z + 1.0f), gradient)); } else if (!neighbourStates[1]) { (*points).push_back(Point<PointT>(tvec3<PointT>(volPos.x + 0.5f, volPos.y + 0.5f, volPos.z), gradient)); } else if (!neighbourStates[2]) { (*points).push_back(Point<PointT>(tvec3<PointT>(volPos.x + 0.5f, volPos.y + 1.0f, volPos.z + 0.5f), gradient)); } else if (!neighbourStates[3]) { (*points).push_back(Point<PointT>(tvec3<PointT>(volPos.x + 0.5f, volPos.y, volPos.z + 0.5f), gradient)); } else if (!neighbourStates[4]) { (*points).push_back(Point<PointT>(tvec3<PointT>(volPos.x + 1.0f, volPos.y + 0.5, volPos.z + 0.5f), gradient)); } else { (*points).push_back(Point<PointT>(tvec3<PointT>(volPos.x, volPos.y + 0.5, volPos.z + 0.5f), gradient)); } count++; break; } return count; } template <class PointT> template <typename T> vector<bool> &PointCloud<PointT>::generateMask(Volume<T> &volume, T isovalue) { vector<int> dim = volume.dimensions(); // Used to mask insignificant voxels vector<bool> mask(dim[0] * dim[1] * dim[2], false); // Index converter auto at = [](int x, int y, int z) { return x + dim[1] * (y + dim[2] * z); }; // Remove 1 voxel holes in the model for (int i = 1; i< dim[0] - 1; i++) { for (int j = 1; j < dim[1] - 1; j++) { for (int k = 1; k < dim[2] - 1; k++) { if (volume[i][j][k] > isovalue && volume[i][j][k - 1] < isovalue && volume[i][j][k + 1] < isovalue && volume[i][j - 1][k] < isovalue && volume[i][j + 1][k] < isovalue && volume[i - 1][j][k] < isovalue && volume[i + 1][j][k] < isovalue && volume[i][j + 1][k - 1] < isovalue && volume[i][j - 1][k - 1] < isovalue && volume[i + 1][j][k - 1] < isovalue && volume[i - 1][j][k - 1] < isovalue && volume[i][j + 1][k + 1] < isovalue && volume[i][j - 1][k + 1] < isovalue && volume[i + 1][j][k + 1] < isovalue && volume[i - 1][j][k + 1] < isovalue && volume[i + 1][j - 1][k] < isovalue && volume[i + 1][j + 1][k] < isovalue && volume[i - 1][j - 1][k] < isovalue && volume[i - 1][j + 1][k] < isovalue) { mask[at(i, j, k)] = true; } } } } return mask; } /* //////////////////////////////////////////// * //////////// KD-TREE Adaptor /////////// */ //////////////////////////////////////////// template <typename Derived> struct PointCloudAdaptor { const Derived &obj; //!< A const ref to the data set origin // The constructor that sets the data set source PointCloudAdaptor(const Derived &obj_) : obj(obj_) { } // CRTP helper method inline const Derived& derived() const { return obj; } // Must return the number of data points inline size_t kdtree_get_point_count() const { return derived().points.size(); } // Returns the distance between the vector "p1[0:size-1]" and the data point with index "idx_p2" stored in the class: inline float kdtree_distance(const float *p1, const size_t idx_p2, size_t /*size*/) const { const float d0 = p1[0] - derived().points[idx_p2].position.x; const float d1 = p1[1] - derived().points[idx_p2].position.y; const float d2 = p1[2] - derived().points[idx_p2].position.z; return d0*d0 + d1*d1 + d2*d2; } // Returns the dim'th component of the idx'th point in the class: // Since this is inlined and the "dim" argument is typically an immediate value, the // "if/else's" are actually solved at compile time. inline float kdtree_get_pt(const size_t idx, int dim) const { if (dim == 0) { return derived().points[idx].position.x; } else if (dim == 1) { return derived().points[idx].position.y; } else { return derived().points[idx].position.z; } } // Optional bounding-box computation: return false to default to a standard bbox computation loop. // Return true if the BBOX was already computed by the class and returned in "bb" so it can be avoided to redo it again. // Look at bb.size() to find out the expected dimensionality (e.g. 2 or 3 for point clouds) template <class BBOX> bool kdtree_get_bbox(BBOX& /*bb*/) const { return false; } };
#pragma once #include"ybBasicMacro.h" NS_YB_BEGIN template<class T> class Buffer2D { public: typedef T ElementType; Buffer2D(int width, int height,bool init=0) :_width(width), _height(height) { _buffer = new T[_width*_height]; if (init) { memset(_buffer, 0, sizeof(T)*_width*_height); } } T* Element(int x, int y) { return &_buffer[y*_width + x]; } ~Buffer2D() { delete[] _buffer; } private: int _width; int _height; T* _buffer; }; NS_YB_END
#include <conio.h> #include <stdio.h> void main () { clrscr(); int A[5][5], a=0, r, c; gotoxy(25,8); printf("SYMMETRIC MATRIX\n\n"); printf("\n\n\tMatrix A"); printf("\n\nEnter No. of Rows: "); scanf("%d",&r); printf("\n\nEnter No. of Columns: "); scanf("%d",&c); if (r==c) { printf("\n\n\tEnter values for Matrix A in matrix order\n\n"); printf("\tA = "); for(int i=0; i<r; i++) { for(int j=0; j<c; j++) scanf("%d",&A[i][j]); printf("\n\t "); } // End of for for(i=0; i<r; i++) { for(int j=0; j<c; j++) if (A[i][j]==A[j][i]) a+=1; } // End of for if (a==r*c) printf("\n\n\tSymmetric Matrix"); } else printf("\n\n\tNon-Square Matrix"); getche(); }
#ifndef _PLATE_1D_ORTHOBUILDER_ #define _PLATE_1D_ORTHOBUILDER_ 1 #include "plate_var_types.h" #include "VarVect.h" #include <iostream> #include <vector> #include <Eigen/Eigen> #include <complex> using std::cout; using std::endl; using std::vector; using std::complex; using namespace Eigen; class SolInfo { public: SolInfo(); ~SolInfo(); vector<PL_NUM> o; //omega matrix to restore the solution vector<PL_NUM> z1; //basis vectors of the solution, orthonormalized vector<PL_NUM> z2; vector<PL_NUM> z3; vector<PL_NUM> z4; vector<PL_NUM> z5; vector<PL_NUM> C; void flushO(); }; class OrthoBuilder { public: OrthoBuilder(); virtual ~OrthoBuilder(); virtual void setParams( int _Km ); //virtual void orthonorm( int baseV, int n, vector<PL_NUM>* NtoOrt ) {}; virtual void orthonorm( int baseV, int n, Matrix<PL_NUM, EQ_NUM, 1>* NtoOrt ) {}; virtual void buildSolution( vector<VarVect>* _mesh ) {}; virtual void flushO( int x ); virtual void setInitVects( const Matrix<PL_NUM, EQ_NUM, 1> &N1, const Matrix<PL_NUM, EQ_NUM, 1> &N2, const Matrix<PL_NUM, EQ_NUM, 1> &N3, const Matrix<PL_NUM, EQ_NUM, 1> &N4, const Matrix<PL_NUM, EQ_NUM, 1> &N5 ); virtual void orthogTest( int x ); protected: int eq_num; int Km; vector<SolInfo> solInfoMap; }; class OrthoBuilderGodunov : public OrthoBuilder { public: OrthoBuilderGodunov() {}; ~OrthoBuilderGodunov() {}; //void orthonorm( int baseV, int n, vector<PL_NUM>* NtoOrt ); //void orthonorm( int baseV, int n, PL_NUM* NtoOrt ); void buildSolution( vector<VarVect>* _mesh ); }; class OrthoBuilderGSh : public OrthoBuilder { public: OrthoBuilderGSh() {}; ~OrthoBuilderGSh() {}; //void orthonorm( int baseV, int n, vector<PL_NUM>* NtoOrt ); void orthonorm( int baseV, int n, Matrix<PL_NUM, EQ_NUM, 1>* NtoOrt ); void buildSolution( vector<VarVect>* _mesh ); }; #endif
#ifndef UTIL_HPP #define UTIL_HPP #include <iostream> #include <fstream> #include <unistd.h> #include <limits.h> #define PI 3.14159 #define DEGREES_TO_RADIANS(d) ((d) * PI/180.f) #define RADIANS_TO_DEGRESS(r) ((d) * 180.f/PI) #define ARRAY_SIZE(ar) (sizeof((ar))/sizeof((ar)[0])) #define RANDOM(min, max) ((min) + (rand() % (max - min + 1))) // typedef unsigned int ld38_uint; // typedef unsigned long ld38_ulong; std::string read_file(char const * file_name); #endif
#include "AvatarView.h" #include <iostream> #include "MyGL.h" #include <sstream> AvatarView::AvatarView() : m_curAnim(NULL), m_flip(false) { } AvatarView::~AvatarView() { //clean anims? } void AvatarView::addAnim(const std::string& name, RectangleMesh *mesh) { m_anim.insert(std::pair<std::string, RectangleMesh*>(name, mesh)); if (m_curAnim == NULL) { m_curAnimName = name; m_curAnim = mesh; } } void AvatarView::setAnim(const std::string& name) { std::map<std::string, RectangleMesh*>::const_iterator found = m_anim.find(name); if (found == m_anim.end()) { std::cerr << "E: anim not found " << name << std::endl; return; } //Si la hemos encontrado la marcamos como activa m_curAnimName = found->first; m_curAnim = found->second; } void AvatarView::prepareNewAnim() { if(m_avatarModel->getState() == AvatarModel::AvatarState::AVATAR_STATE_IDLE) { //we keep displaying the previous animation } else { //resetCounters m_animCounter = 0; m_animDisplayTime = 0; m_animReferenceTime = getAnimTimeout(); //set flipping on/off if(m_animFlipped[m_avatarModel->getState()]) { m_flip = true; } else { m_flip = false; } setNextAnim(); } } void AvatarView::setNextAnim() { float timeout = m_avatarModel->getTimeout(); //in case the maximum of animations has been reached we start a new round /*if(m_animCounter == getNumAnims()) { m_animCounter = 0; m_animDisplayTime = 0; m_animReferenceTime = getAnimTimeout(); }*/ //set the animation std::stringstream ss; ss<<m_animCounter; setAnim(getAnimString() + ss.str()); //if enough time has elapsed we prepare to draw the next animation if((m_animDisplayTime) > getAnimTimeout()/getNumAnims()) { m_animCounter++; m_animDisplayTime = 0; m_animReferenceTime = timeout; } //compute how long the current anim has been displayed m_animDisplayTime = m_animReferenceTime - timeout; } void AvatarView::draw() { if (m_curAnim == NULL) { std::cerr << "W: anim not set" << std::endl; return; } //Primero de todo tenemos que posicionar el avatar dentro de la pantalla glPushMatrix(); //actualizar lo siguiente glTranslatef(m_avatarModel->getScreenPosition()[0], m_avatarModel->getScreenPosition()[1], 0); if(m_flip)glScalef(-1.0f,1.0f,1.0); m_curAnim->draw(); glPopMatrix(); } void AvatarView::setAnimString(AvatarModel::AvatarState state, std::string str) { m_animStrings.insert(std::make_pair(state, str)); } void AvatarView::setNumAnim(AvatarModel::AvatarState state, int numAnim) { m_numAnims.insert(std::make_pair(state, numAnim)); } void AvatarView::setAnimTimeout(AvatarModel::AvatarState state, float timeout) { m_animTimeouts.insert(std::make_pair(state, timeout )); } const std::string AvatarView::getAnimString() { return m_animStrings[m_avatarModel->getState()]; } const float AvatarView::getNumAnims() { return m_numAnims[m_avatarModel->getState()]; } const float AvatarView::getAnimTimeout() { return m_animTimeouts[m_avatarModel->getState()]; } const bool AvatarView::isAnimFlipped() { return m_animFlipped[m_avatarModel->getState()]; } void AvatarView::setAnimFlipped(AvatarModel::AvatarState state, bool flipped) { m_animFlipped.insert(std::make_pair(state, flipped )); }
#ifndef JSON_HH #define JSON_HH #include "jansson/jansson.h" #include <memory> namespace ten { typedef std::shared_ptr<json_t> json_ptr; } // end namespace ten #endif // JSON_HH
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2005 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** */ #ifndef DOM_SVGOBJECT_H #define DOM_SVGOBJECT_H #ifdef SVG_DOM #include "modules/dom/src/domsvg/domsvglocation.h" #include "modules/svg/svg_dominterfaces.h" #include "modules/dom/src/domcore/element.h" class SVGDOMItem; class SVGDOMPoint; class SVGDOMRect; class SVGDOMMatrix; #ifdef SVG_FULL_11 class SVGDOMNumber; class SVGDOMLength; class SVGDOMAngle; class SVGDOMTransform; class SVGDOMAnimatedValue; class SVGDOMList; class DOM_SVGList; #endif // SVG_FULL_11 class DOM_SVGObjectStore; /** Retrieves the DOM part of the this obejct and checks that it is the right type of DOM object. If it isn't, or if the object is a native object, it returns ES_FAILED. It also checks the sync between the dom object and svg item. It is missing the type check of this_object to DOM_SVGObject, so make sure the macro is used on DOM_SVGObjects. */ #define DOM_SVG_THIS_ITEM(VARIABLE, TYPE, CLASS) \ int svg_this_object_result = DOM_CheckType((DOM_Runtime *) origining_runtime, this_object, DOM_TYPE_SVG_OBJECT, return_value, DOM_Object::WRONG_THIS_ERR); \ if (svg_this_object_result != ES_VALUE) \ return svg_this_object_result; \ CLASS *VARIABLE; \ SVGDOMItem* VARIABLE ## _tmp_ = ((DOM_SVGObject*)this_object)->GetSVGDOMItem(); \ if (VARIABLE ## _tmp_->IsA(TYPE)) \ { \ VARIABLE = (CLASS *)VARIABLE ## _tmp_; \ } \ else \ return ES_FAILED; \ /** Retrieves the DOM part of the this obejct and checks that it is the right type of DOM object. If it isn't, or if the object is a native object, it returns ES_FAILED. It also checks the sync between the dom object and svg item. It is missing the type check of this_object to DOM_SVGObject, so make sure the macro is used on DOM_SVGObjects. */ #define DOM_SVG_THIS_OBJECT_ITEM(VAR1, VAR2, TYPE, CLASS) \ int svg_this_object_result = DOM_CheckType((DOM_Runtime *) origining_runtime, this_object, DOM_TYPE_SVG_OBJECT, return_value, DOM_Object::WRONG_THIS_ERR); \ if (svg_this_object_result != ES_VALUE) \ return svg_this_object_result; \ DOM_SVGObject *VAR1 = static_cast<DOM_SVGObject*>(this_object); \ CLASS *VAR2; \ SVGDOMItem* VAR2 ## _tmp_ = static_cast<DOM_SVGObject*>(this_object)->GetSVGDOMItem(); \ if (VAR2 ## _tmp_->IsA(TYPE)) \ { \ VAR2 = static_cast<CLASS *>(VAR2 ## _tmp_); \ } \ else \ return ES_FAILED; \ /** Retrieves the SVG Item from a DOM_SVGObject from an argument and checks that it is the right type of SVG Item. If it isn't, or if the object is a native object, it returns ES_FAILED. */ #define DOM_SVG_ARGUMENT_OBJECT(VARIABLE, INDEX, TYPE, CLASS) \ CLASS *VARIABLE = NULL; \ DOM_ARGUMENT_OBJECT(VARIABLE ## _tmp__1, INDEX, DOM_TYPE_SVG_OBJECT, DOM_SVGObject); \ if (VARIABLE ## _tmp__1 != NULL) \ { \ SVGDOMItem* VARIABLE ## _tmp_ = VARIABLE ## _tmp__1->GetSVGDOMItem(); \ if (VARIABLE ## _tmp_->IsA(TYPE)) \ { \ VARIABLE = (CLASS *)VARIABLE ## _tmp_; \ } \ else \ { \ return ES_FAILED; \ } \ } \ else \ { \ return ES_FAILED; \ } \ struct DOM_SVGObjectStatic { SVGDOMItemType iface; double number; char* name; }; class DOM_SVGObject : public DOM_Object { public: virtual ~DOM_SVGObject(); static OP_STATUS Make(DOM_SVGObject *&obj, SVGDOMItem* svg_item, const DOM_SVGLocation& location, DOM_EnvironmentImpl *environment); virtual BOOL IsA(int type) { return type == DOM_TYPE_SVG_OBJECT || DOM_Object::IsA(type); } SVGDOMItem* GetSVGDOMItem() { return svg_item; } void Release(); #ifdef SVG_FULL_11 DOM_SVGList* InList() { return in_list; } void SetInList(DOM_SVGList* list); #endif // SVG_FULL_11 HTML_Element* GetThisElement() { return location.GetThisElement(); } void Invalidate(BOOL was_removed = FALSE) { location.Invalidate(was_removed); } void SetLocation(const DOM_SVGLocation& l) { location = l; } BOOL IsValid() { return location.IsValid(); } BOOL GetIsSignificant() { return (is_significant == 1); } void SetIsSignificant() { is_significant = 1; } BOOL HaveNativeProperty() { return (have_native_property == 1); } void SetHaveNativeProperty() { have_native_property = 1; } virtual void GCTrace(); virtual ES_GetState GetName(OpAtom property_name, ES_Value* value, ES_Runtime* origining_runtime); virtual ES_PutState PutName(OpAtom property_name, ES_Value* value, ES_Runtime* origining_runtime); static void PutConstructorsL(DOM_Object* target); static void InitializeConstructorsTableL(OpString8HashTable<DOM_ConstructorInformation> *table); static ES_Object *CreateConstructorL(DOM_Runtime *runtime, DOM_Object *target, const char *name, unsigned id); static void ConstructDOMImplementationSVGObjectL(ES_Object *element, SVGDOMItemType type, DOM_Runtime *runtime); #ifdef SVG_FULL_11 DOM_DECLARE_FUNCTION_WITH_DATA(newValueSpecifiedUnits); DOM_DECLARE_FUNCTION_WITH_DATA(convertToSpecifiedUnits); DOM_DECLARE_FUNCTION(matrixTransform); DOM_DECLARE_FUNCTION_WITH_DATA(transformMethods); #endif // SVG_FULL_11 DOM_DECLARE_FUNCTION_WITH_DATA(matrixMethods); #ifdef SVG_FULL_11 DOM_DECLARE_FUNCTION(setUri); DOM_DECLARE_FUNCTION(setPaint); DOM_DECLARE_FUNCTION(setRGBColor); DOM_DECLARE_FUNCTION(getFloatValue); #endif // SVG_FULL_11 #ifdef SVG_TINY_12 // begin uDOM methods DOM_DECLARE_FUNCTION(getComponent); DOM_DECLARE_FUNCTION_WITH_DATA(mutableMatrixMethods); DOM_DECLARE_FUNCTION_WITH_DATA(svgPathBuilder); // end uDOM methods #endif // SVG_TINY_12 protected: DOM_SVGObject() : is_significant(0), have_native_property(0) {} #ifdef SVG_FULL_11 ES_GetState GetLengthValue(OpAtom property_name, ES_Value* value, SVGDOMLength* svg_length, ES_Runtime* origining_runtime); #endif // SVG_FULL_11 DOM_SVGObjectStore* object_store; #ifdef SVG_FULL_11 DOM_SVGList* in_list; ///< List that contains this object, if any #endif // SVG_FULL_11 SVGDOMItem* svg_item; DOM_SVGLocation location; unsigned is_significant:1; unsigned have_native_property:1; private: DOM_SVGObject(const DOM_SVGObject&); // Don't implememnt to avoid accidental clones }; class DOM_SVGObject_Prototype { private: static void ConstructL(ES_Object *prototype, DOM_Runtime::SVGObjectPrototype type, DOM_Runtime *runtime); public: static OP_STATUS Construct(ES_Object *prototype, DOM_Runtime::SVGObjectPrototype type, DOM_Runtime *runtime); }; #endif // SVG_DOM #endif // DOM_SVGOBJECT_H
#ifndef LOOKAHEAD_THINKER_H_INCLUDED #define LOOKAHEAD_THINKER_H_INCLUDED #include "tracker_thinker.h" struct LookaheadThinker final : TrackerThinker { protected: Response decideResponse(int guess) const override; }; #endif // LOOKAHEAD_THINKER_H_INCLUDED
// // Ordenamiento.cpp // Ordenamiento // // Created by Daniel on 01/09/14. // Copyright (c) 2014 Gotomo. All rights reserved. // #include "Ordenamiento.h"
/* * tinyweb.cc * * Created on: Dec 11, 2012 * Author: suntus * 主程序流程 * 1.打开系统日志,设置成静态 * 2.初始化记时器,记录系统运行时间 * 3.初始化服务器:建立套接字,设置监听... * 4.主循环 * { * fork()... * } * 5.关闭http server对象 * 6.关闭系统日志 * 7.退出 *包括在这里定义初始化函数Init() */ #include "tinyweb.h" int Init(int& port, BL*); int OpenListen(int& listenfd, int port); int Accept(int, SAL&, BL*); int Dd2hex(char*); int visitedlog(FILE*, const SAL &); int main(int argc, char **argv) { int port; SAL clientaddr; int listenfd, connfd; pid_t pid; BL Block; //打开系统日志 openlog(argv[0], LOG_PID | LOG_CONS, LOG_USER); FILE* bp = fopen("VisitLog", "a"); Init(port, &Block); listenfd = OpenListen(listenfd, port); while ((connfd = Accept(listenfd, clientaddr, &Block)) != -1) { pid = fork(); if (pid < 0) Syslog("accept failed."); else if (pid == 0) { pid = fork(); if (pid == 0) break; else exit(0); //连续两次fork() 避免僵死进程 } else continue; } if (pid == 0) { visitedlog(bp, clientaddr); HttpSession session(connfd); session.Handler(Block.flag); } return 0; } int Dd2hex(char* buf) { struct in_addr add; inet_aton(buf, &add); return htonl(add.s_addr); } int Init(int& port, BL* Block) { FILE* fp; char buf[16]; if ((fp = fopen("./config/tiny.config", "r")) == NULL) { Syslog("set port failed."); } fgets(buf, 6, fp); if (strcmp(buf, "port:") == 0) fscanf(fp, "%d", &port); else Syslog("set port failed."); FILE* bp; int c, count = 0; if ((bp = freopen("./config/BLIST", "r", stdin)) == NULL) fprintf(stderr, "DB open error"); else { while (fgets(buf, 16, bp) != NULL && count != MAXLIST) { c = Dd2hex(buf); (Block->list)[count++] = htonl(c); } Block->length = count; } return 0; } int OpenListen(int &listenfd, int port) { SAL serveraddr; //端口号复用 if ((listenfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) Syslog("set socket failed."); int opt = SO_REUSEADDR; if (setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) == -1) { Syslog("set socketopt failed."); } memset((char*) &serveraddr, 0, sizeof(serveraddr)); serveraddr.sin_family = AF_INET; serveraddr.sin_addr.s_addr = htonl(INADDR_ANY ); serveraddr.sin_port = htons((unsigned short) port); if (bind(listenfd, (SA*) &serveraddr, sizeof(serveraddr)) != 0) Syslog("bind failed."); if (listen(listenfd, BACKLOG) != 0) Syslog("listen failed."); return listenfd; } int Accept(int listenfd, SAL& clientaddr, BL* Block) { unsigned clientlen = sizeof(clientaddr); int connfd; if ((connfd = accept(listenfd, (SA*) &clientaddr, &clientlen)) == -1) Syslog("accept failed."); int address = clientaddr.sin_addr.s_addr; unsigned* listend = Block->list + Block->length; if (std::find(Block->list, listend, address) == listend) Block->flag = true; else Block->flag = false; return connfd; } int visitedlog(FILE* bp, const SAL &clientaddr) { time_t st; struct tm *t; st = time(NULL); t = localtime(&st); fprintf(bp, "%s ", inet_ntoa(clientaddr.sin_addr)); fprintf(bp, " %d/%d %d/%d/%d \n", t->tm_mon, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec); }
#pragma once #ifndef GAME_OVER_SCREEN_H #define GAME_OVER_SCREEN_H #include "Screen.h" #include "Texture.h" #include "GamePlayScreen.h" class GameOverScreen:public Screen { private: Texture* title; int time; TTF_Font *font; public: void start(SDL_Renderer*) override; void handleEvents(float&) override; void update(float&) override; void render(SDL_Renderer*) override; void close() override; }; #endif
#include "generalwindow.h" #include "ui_generalwindow.h" GeneralWindow::GeneralWindow(QDialog *parent) : QDialog(parent), ui(new Ui::GeneralWindow) { ui->setupUi(this); //Тінь фрейму QGraphicsDropShadowEffect *shadow_effect1 = new QGraphicsDropShadowEffect(this); shadow_effect1->setOffset(0, 0); shadow_effect1->setColor(QColor(38, 78, 119, 127)); shadow_effect1->setBlurRadius(22); ui->frame1->setGraphicsEffect(shadow_effect1); //Підключаємо базу даних для таблиці Виготовлена продукція Login conn; conn.connectToDB(); QSqlQueryModel * modal1=new QSqlQueryModel(); QSqlQuery* qry1 = new QSqlQuery(conn.db); qry1->prepare("SELECT Продукція,Кількість,Дата,Зміна FROM made_production"); qry1->exec(); modal1->setQuery(*qry1); ui->tableViewCakes->setModel(modal1); ui->tableViewCakes->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch); ui->tableViewCakes->horizontalHeader()->setSectionResizeMode(2, QHeaderView::Stretch); ui->tableViewCakes->horizontalHeader()->setSectionResizeMode(3, QHeaderView::Stretch); conn.closeDB(); //Підключаємо базу даних для таблиці Використана сировина conn.connectToDB(); QSqlQueryModel * modal2=new QSqlQueryModel(); QSqlQuery* qry2 = new QSqlQuery(conn.db); qry2->prepare("SELECT Сировина,Кількість,Дата,Зміна FROM used_raw"); qry2->exec(); modal2->setQuery(*qry2); ui->tableViewRaw->setModel(modal2); ui->tableViewRaw->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch); ui->tableViewRaw->horizontalHeader()->setSectionResizeMode(2, QHeaderView::Stretch); ui->tableViewRaw->horizontalHeader()->setSectionResizeMode(3, QHeaderView::Stretch); conn.closeDB(); //Підключаємо базу даних для таблиці Відправлення на магазини conn.connectToDB(); QSqlQueryModel * modal3=new QSqlQueryModel(); QSqlQuery* qry3 = new QSqlQuery(conn.db); qry3->prepare("SELECT Магазин,Продукція,Кількість,Дата,Зміна FROM send_to_shops"); qry3->exec(); modal3->setQuery(*qry3); ui->tableView->setModel(modal3); ui->tableView->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Stretch); ui->tableView->horizontalHeader()->setSectionResizeMode(3, QHeaderView::Stretch); ui->tableView->horizontalHeader()->setSectionResizeMode(4, QHeaderView::Stretch); conn.closeDB(); conn.connectToDB(); QSqlQueryModel * modal5 = new QSqlQueryModel(); QSqlQuery* query5 = new QSqlQuery(conn.db); query5->prepare("SELECT FullName FROM employees_info"); query5->exec(); modal5->setQuery(*query5); ui->comboBoxEmp1->setModel(modal5); ui->comboBoxEmp2->setModel(modal5); ui->comboBoxEmp3->setModel(modal5); conn.closeDB(); } GeneralWindow::~GeneralWindow() { delete ui; } void GeneralWindow::on_EditData_clicked() { EditData ed; this->close(); ed.setModal(true); ed.exec(); } void GeneralWindow::on_LogOut_clicked() { Login l; this->close(); } void GeneralWindow::on_AddDailyWork_clicked() { DailyReport r; this->close(); r.setModal(true); r.exec(); } void GeneralWindow::on_pushButtonFindEmp1_clicked() { const QString employee = ui->comboBoxEmp1->currentText(); Login conn; conn.connectToDB(); QSqlQueryModel * modal5 = new QSqlQueryModel(); QSqlQuery* query5 = new QSqlQuery(conn.db); query5->prepare("SELECT Продукція,Кількість,Дата,Зміна from made_production where Зміна='"+employee+"'"); query5->exec(); modal5->setQuery(*query5); ui->tableViewCakes->setModel(modal5); ui->tableViewCakes->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch); ui->tableViewCakes->horizontalHeader()->setSectionResizeMode(2, QHeaderView::Stretch); conn.closeDB(); } void GeneralWindow::on_pushButtonFindDate1_clicked() { const QString date = ui->dateEdit1->text(); Login conn; conn.connectToDB(); QSqlQueryModel * modal1=new QSqlQueryModel(); QSqlQuery* qry1 = new QSqlQuery(conn.db); qry1->prepare("SELECT Продукція,Кількість,Дата,Зміна from made_production where Дата='"+date+"'"); qry1->exec(); modal1->setQuery(*qry1); ui->tableViewCakes->setModel(modal1); ui->tableViewCakes->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch); ui->tableViewCakes->horizontalHeader()->setSectionResizeMode(2, QHeaderView::Stretch); ui->tableViewCakes->horizontalHeader()->setSectionResizeMode(3, QHeaderView::Stretch); conn.closeDB(); } void GeneralWindow::on_pushButtonFindEmp2_clicked() { const QString employee = ui->comboBoxEmp2->currentText(); Login conn; conn.connectToDB(); QSqlQueryModel * modal5 = new QSqlQueryModel(); QSqlQuery* query5 = new QSqlQuery(conn.db); query5->prepare("SELECT Сировина,Кількість,Дата,Зміна from used_raw where Зміна='"+employee+"'"); query5->exec(); modal5->setQuery(*query5); ui->tableViewRaw->setModel(modal5); ui->tableViewRaw->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch); ui->tableViewRaw->horizontalHeader()->setSectionResizeMode(2, QHeaderView::Stretch); conn.closeDB(); } void GeneralWindow::on_pushButtonFindDate2_clicked() { const QString date = ui->dateEdit2->text(); Login conn; conn.connectToDB(); QSqlQueryModel * modal1=new QSqlQueryModel(); QSqlQuery* qry1 = new QSqlQuery(conn.db); qry1->prepare("SELECT Сировина,Кількість,Дата,Зміна from used_raw where Дата='"+date+"'"); qry1->exec(); modal1->setQuery(*qry1); ui->tableViewRaw->setModel(modal1); ui->tableViewRaw->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch); ui->tableViewRaw->horizontalHeader()->setSectionResizeMode(2, QHeaderView::Stretch); ui->tableViewRaw->horizontalHeader()->setSectionResizeMode(3, QHeaderView::Stretch); conn.closeDB(); } void GeneralWindow::on_pushButtonFindEmp3_clicked() { const QString employee = ui->comboBoxEmp3->currentText(); Login conn; conn.connectToDB(); QSqlQueryModel * modal5 = new QSqlQueryModel(); QSqlQuery* query5 = new QSqlQuery(conn.db); query5->prepare("SELECT Магазин,Продукція,Кількість,Дата,Зміна FROM send_to_shops where Зміна='"+employee+"'"); query5->exec(); modal5->setQuery(*query5); ui->tableView->setModel(modal5); ui->tableView->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch); ui->tableView->horizontalHeader()->setSectionResizeMode(2, QHeaderView::Stretch); conn.closeDB(); } void GeneralWindow::on_pushButtonFindDate3_clicked() { const QString date = ui->dateEdit3->text(); Login conn; conn.connectToDB(); QSqlQueryModel * modal1=new QSqlQueryModel(); QSqlQuery* qry1 = new QSqlQuery(conn.db); qry1->prepare("SELECT Магазин,Продукція,Кількість,Дата,Зміна FROM send_to_shops where Дата='"+date+"'"); qry1->exec(); modal1->setQuery(*qry1); ui->tableView->setModel(modal1); ui->tableView->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch); ui->tableView->horizontalHeader()->setSectionResizeMode(2, QHeaderView::Stretch); ui->tableView->horizontalHeader()->setSectionResizeMode(3, QHeaderView::Stretch); conn.closeDB(); }
#ifndef _GetTableDetailProc_H_ #define _GetTableDetailProc_H_ #include "BaseProcess.h" class GetTableDetailProc :public BaseProcess { public: GetTableDetailProc(); virtual ~GetTableDetailProc(); virtual int doRequest(CDLSocketHandler* clientHandler, InputPacket* inputPacket, Context* pt); virtual int doResponse(CDLSocketHandler* clientHandler, InputPacket* inputPacket, Context* pt); }; #endif
/* author chonepieceyb, operatiing-system lab2 2020年 03月 31日 星期二 21:24:51 CST */ #include<iostream> #include <sys/types.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include<string> #include <sys/ipc.h> #include <sys/shm.h> #define MAX_SEQUENCE 50 // fbi 最大的个数 using namespace std; struct shared_data{ long fib_sequence[MAX_SEQUENCE]; //数组 int sequence_size; }; int main( int argc, char** argv){ if(argc!=2){ cout<<"请输入一个参数\n"; exit(-1); } int parm = std::stoi(string(argv[1])); // 将字符串转化为 整形 if(!(parm>=0&& parm <MAX_SEQUENCE) ){ cout<<"参数不能小于0!或者大于等于50"<<endl; exit(-1); } // 创建共享内存 int shm_id = shmget((int)getpid(),sizeof(shared_data),IPC_CREAT); if(shm_id ==-1){ //如果没有成功开辟共享内容 cout<<"child p fail to get a shared memory !"<<endl; exit(-1); } // 开辟子进程 int pid = fork(); if(pid<0){ cout<<"child p fail to fork child process!\n"; exit(-1); }else if(pid ==0){ //如果是子进程的话 // attach到共享进程 void* shm = shmat(shm_id,NULL,0); // 由操作系统自动分配,有读写权限 if(shm == (void*)-1){ cout<<"child p fail to attach to shared memory!\n"; exit(-1); } shared_data * share = (shared_data*)shm; //强转 if(parm ==0){ share->fib_sequence[0] = 0; share->sequence_size = 1; }else if(parm == 1){ share->fib_sequence[1] = 1; share->sequence_size =2; }else{ share->fib_sequence[0] = 0; share->fib_sequence[1] = 1; share->sequence_size =2; long fb1 = 0 , fb2 = 1; for(int i =2 ; i<=parm;i++){ long v = fb1 + fb2; share->fib_sequence[i] = v; share->sequence_size ++ ; fb1 = fb2; fb2 = v ; } } // detach if(shmdt(shm)==-1){ cout<<"child p fail to detach shared memory!\n"; exit(-1); }else{ exit(0); } }else{ int status; waitpid(pid,&status,WUNTRACED); // waitpid的作用和wait 类似等待 pid = pid的子进程结束; // attach to shared memory void* shm = shmat(shm_id,NULL, SHM_RDONLY); // 由操作系统自动分配,只有读权限 if(shm == (void*)-1){ cout<<"main process fail to attach to shared memory!\n"; exit(-1); } shared_data* share = (shared_data*)shm; //强转 for(int i=0;i<share->sequence_size;i++){ printf("fib%d=%ld\n",i,share->fib_sequence[i]); } // detach if(shmdt(shm)==-1){ cout<<"main p fail to detach shared memory!\n"; exit(-1); }else{ exit(0); } // delete shared memory shmctl(shm_id, IPC_RMID ,NULL); exit(0); } }
#pragma once namespace BroodWar { namespace Api { namespace Enum { //direct mapping public enum class Latency { SinglePlayer = 2, LanLow = 5, LanMedium = 7, LanHigh = 9, BattlenetLow = 14, BattlenetMedium = 19, BattlenetHigh = 24 }; } } }
#include <iostream> #include <fstream> #include <cmath> #include <vector> #include <cstdio> #include <ctime> #include <cstring> #ifdef _WIN32 #include <SDL.h> #include <SDL_image.h> #include <SDL_ttf.h> #include <SDL_mixer.h> #elif defined __unix__ #include <SDL2/SDL.h> #include <SDL2/SDL_image.h> #include <SDL2/SDL_ttf.h> #include <SDL2/SDL_mixer.h> #elif defined __APPLE__ #include <SDL2/SDL.h> #include <SDL2_image/SDL_image.h> #include <SDL2_ttf/SDL_ttf.h> #include <SDL2_mixer/SDL_mixer.h> #endif #include "zombies_vs_soldier.hpp" #include "SDL_Class.hpp" #include "bullet.hpp" #include "zombie.hpp" #include "soldier.hpp" #include "scores.hpp" #include "menu.hpp" #include "game.hpp" Zombie::Zombie() { type=rand()%2; Pos.w=gZombie.getWidth()/9; Pos.h=gZombie.getHeight()/2; Vel.x=0; Vel.y=0; for(int i=0; i<9; i++) { Clip[i].y=type*Pos.h; Clip[i].x=i*Pos.w; Clip[i].w=Pos.w; Clip[i].h=Pos.h; } rad=(rand()%360)*(PI/180); Pos.x=(rand()%2)?(-rand()%100):(SCREEN_WIDTH+rand()%100); Pos.y=(rand()%2)?(-rand()%100):(SCREEN_HEIGHT+rand()%100); anim=0; frame=0; health=100; state=Alive; center={Pos.w/2, Pos.h/2}; } void Zombie::Update(std::vector<Bullet>* bullets, SDL_Rect* SolPos, std::vector<Zombie>* zombies) { Vector2Df v2={0, 0}, v4={0, 0}; std::vector<Zombie>::iterator t; int x=SolPos->x; int y=SolPos->y; SDL_Point a, b; rad=atan2(y-Pos.y-(Pos.h/2), Pos.x+(Pos.w/2)-x)+PI; if(state==Alive) { if(frame%((rand())%600+180)==0) { Mix_PlayChannel(-1, gGrunt, 0); } if(!zombies->empty()) { for(std::vector<Zombie>::iterator it=zombies->begin(); it!=zombies->end(); it++) { if(&(*it)!=this && it->getZomState()==Alive) { if(distance({Pos.x, Pos.y}, {it->getPos().x, it->getPos().y})<64) { v2.x-=5*(it->getPos().x-Pos.x); v2.y-=5*(it->getPos().y-Pos.y); } } else { t=it; } } } v4.x=(SolPos->x-Pos.x)/100; v4.y=(SolPos->y-Pos.y)/100; Vel.x=Vel.x+v2.x+v4.x; Vel.y=Vel.y+v2.y+v4.y; if(sqrt(pow(Vel.x, 2)+pow(Vel.y, 2))>2) { Vel.x=(2*(Vel.x))/sqrt(pow(Vel.x, 2)+pow(Vel.y, 2)); Vel.y=(2*(Vel.y))/sqrt(pow(Vel.x, 2)+pow(Vel.y, 2)); } if(!Collide(SolPos, &Pos)) { Pos.x+=ceil(Vel.x); Pos.y+=ceil(Vel.y); } else { if(frame%(rand()%360+180)) { Mix_PlayChannel(-1, gEat, 0); } } for(Uint8 i=0; i<bullets->size();) { a=bullets->operator[](i).getPos(); a.x+=5; a.y+=5; b.x=Pos.x+Pos.w/2; b.y=Pos.y+Pos.h/2; if(distance(a, b)<40) { health-=15+2*(!type); if(health<=0) { state=ZomDead; deadangle=rand()%135; frame=0; } bullets->erase(bullets->begin()+i); } else { i++; } } } } void Zombie::Render() { if(state==Alive) { frame++; if(frame%4==0) { anim=(anim+1)%8; } SDL_Rect fillRect={Pos.x, Pos.y-15, (int)(health*0.25*(!(type)+2)), 5}; SDL_SetRenderDrawColor(gRenderer, 0xFF, 0x00, 0x00, 0xFF); SDL_RenderFillRect(gRenderer, &fillRect); gZombie.render(Pos.x, Pos.y, 1, &Clip[anim], 90-rad*(180/PI), &center, SDL_FLIP_NONE); } else if(frame<240) { gZombie.render(Pos.x, Pos.y, 1, &Clip[8], deadangle, &center, SDL_FLIP_NONE); frame++; } else { state=Disapp; } } SDL_Rect* Zombie::getRect() { return &Pos; } SDL_Point Zombie::getPos() { return {Pos.x, Pos.y}; } Vector2Df Zombie::getVel() { return Vel; } ZombieState Zombie::getZomState() { return state; } int Zombie::getType() { return type; } int Zombie::getHealth() { return health; }
#include<iostream> #include<string.h> using namespace std; char stack[100]; int top=-1 , size=100; int push(int data) { if(top==size-1) { cout<<"Overflow! "; } else { top++; stack[top]=data; } } char pop() { if(top==-1) { cout<<"Underflow"; } else { int data=stack[top]; top--; return data; } } int balance_parentheses() { char s[10],t; cout <<"\nEnter string : "; cin >>s; int valid=0; for (int i=0;i<strlen(s);i++) { if(s[i]=='{' || s[i]=='[' || s[i]=='(') { push(s[i]); } else if(s[i]==')'|| s[i]=='}'|| s[i]==']') { if(top==-1) { cout<<"Invalid string "; } else { t=pop(); if(t=='(' && (s[i]==']' || s[i]=='}')) { valid=0; } else if(t=='[' && (s[i]==')' || s[i]=='}')) { valid=0; } if(t=='{' && (s[i]==']' || s[i]==')')) { valid=0; } else { valid++; } } } } if(top>=0) { valid=0; } if(valid>=1) { cout<<"\nValid expression "; } else { cout<<"\nInvalid expression"; } return 0; } int main() { int n; cout<<"Enter number of test cases : "; cin>>n; for(int i=0;i<n;i++) { balance_parentheses(); } return 0; }
// // main.cpp // baekjoon // // Created by Honggu Kang on 2020/06/20. // Copyright © 2020 Honggu Kang. All rights reserved. // //#include <iostream> #include <stdio.h> //#include "DrawStar.h" #include "womenPres.h" int main(int argc, const char * argv[]) { // std::cout << "Hello, World!\n"; /* Drawing stars int N; scanf("%d",&N); DrawStar(N); */ int T; scanf("%d",&T); int arr[T][2]; //arr[floor #][room #] for(int i=0;i<T;i++){ scanf("%d",&arr[i][0]); scanf("%d",&arr[i][1]); } int Ans[T]; for(int i=0; i<T; i++){ Ans[i]=peopleNumber(arr[i][0],arr[i][1]); printf("%d\n",Ans[i]); } return 0; }
//知识点:树上差分, 树链剖分,lca /* By:Luckyblock 首先,这是个不可做的神仙题 考虑部分分: si=ti 10分: 每个人的起点和终点相同,第0秒时即到达终点 由于一个人到达终点后 ,就不可被观察到 所以 可以观察到人的观察员, 只有wj=0的观察员. 则需要找到所有 起点与 wj=0的观察员相同的人. wj=0 10分: 观察员只会在第0秒观察. 也就是说, 只有 起点 与 观察员所在点 相同的人 , 才会被观察到. */ #include<cstdio> #include<ctype.h> #include<vector> const int MARX = 1010; //============================================================= struct edge { int u,v,ne; }e[MARX<<1]; int n,m,num , head[MARX],w[MARX],ans[MARX]; bool zero[MARX]; //============================================================= inline int read() { int s=1, w=0; char ch=getchar(); for(; !isdigit(ch);ch=getchar()) if(ch=='-') s =-1; for(; isdigit(ch);ch=getchar()) w = w*10+ch-'0'; return s*w; } inline void add(int u,int v) { e[++num].u=u,e[num].v=v; e[num].ne=head[u],head[u]=num; } //============================================================= signed main() { n=read(),m=read(); for(int i=1; i<n; i++) { int u=read(),v=read(); add(u,v),add(v,u); } for(int i=1; i<=n; i++) { w[i]=read(); if(!w[i]) zero[i]=1; } for(int i=1; i<=m; i++) { int s=read(),t=read(); if(zero[s]) ans[s]++; } for(int i=1; i<=n; i++) printf("%d ",ans[i]); }
#include <iostream> #include <vector> using namespace std; void test(int x) { } int a; int b; int main() { int x = 10; int y = 20; int z; cout << "x: " << x << endl; cout << "&x: " << &x << endl; cout << "&y: " << &y << endl; cout << "&z: " << &z << endl; cout << "&a: " << &a << endl; cout << "&b: " << &b << endl; cout << "&test() " << (long)&test << endl; }
// // devicesettingsuit.hpp // AutoCaller // // Created by Micheal Chen on 2017/7/17. // // #ifndef devicesettingsuit_hpp #define devicesettingsuit_hpp //设备状态管理相关的用例 #include "testbase/BaseTest.h" #include "cocos2d.h" DEFINE_TEST_SUITE(DeviceManageerTests); static const char *users[] = {"XXX1000", "xxx1001", "xxx1002"}; static const char *rooms[] = {"1111234", "1111235", "1111236"}; class IYouMeVoiceEngine; class DeviceBase : public TestCase { public: virtual std::string title() const override { return "Device setting test"; } virtual void onEnter() override; protected: IYouMeVoiceEngine* _engine; }; //设置 获取扬声器状态 //包含接口 : SetSpeakerMute & GetSpeakerMute class SpeakerMuteTest : public DeviceBase { public: CREATE_FUNC(SpeakerMuteTest); virtual std::string subtitle() const override { return "Speak mute test"; } virtual void onEnter() override; }; //设置、获取麦克风状态 class MicroPhoneMuteTest : public DeviceBase { public: CREATE_FUNC(MicroPhoneMuteTest); virtual std::string subtitle() const override { return "Micro Phone Mute Test"; } virtual void onEnter() override; }; //音量设置 class VolumeTest : public DeviceBase { public: CREATE_FUNC(VolumeTest); virtual std::string subtitle() const override { return "Volume Test"; } virtual void onEnter() override; }; //设置是否通知他人 扬声器和麦克风的开关 //接口: SetAutoSendStatus class AutoSendStatusTest : public DeviceBase { public: CREATE_FUNC(AutoSendStatusTest); virtual std::string subtitle() const override { return "Auto Send Status Test"; } virtual void onEnter() override; }; //控制别人的麦克风 class CtrlWhosMicroPhoneTest : public DeviceBase { public: CREATE_FUNC(CtrlWhosMicroPhoneTest); virtual std::string subtitle() const override { return "Ctrl Who‘s MicroPhone Test"; } virtual void onEnter() override; }; //控制别人的扬声器 class CtrlWhosSpeakerMuteTest : public DeviceBase { public: CREATE_FUNC(CtrlWhosSpeakerMuteTest); virtual std::string subtitle() const override { return "Ctrl Who’s Speaker Mute Test"; } virtual void onEnter() override; }; //设置是否听某个人的语音 //SetListenOtherVoice class SetListeneWhosVoiceTest : public DeviceBase { public: CREATE_FUNC(SetListeneWhosVoiceTest); virtual std::string subtitle() const override { return "Set Listen Who‘s Voice Test"; } virtual void onEnter() override; }; //设置语音检测回调 //SetVadCallbackEnabled class SetVadCallbackEnabledTest : public DeviceBase { public: CREATE_FUNC(SetVadCallbackEnabledTest); virtual std::string subtitle() const override { return "Set Vad Callback Enabled Test"; } virtual void onEnter() override; }; //设置语音监听 :插耳机的情况下的开启或关闭语音监听 //SetHeadsetMonitorOn(bool b) class SetHeadsetMonitorOnTest : public DeviceBase { public: CREATE_FUNC(SetHeadsetMonitorOnTest); virtual std::string subtitle() const override { return "Set Headset Monitor On Test"; } virtual void onEnter() override; }; //混响音效设置 //SetReverbEnabled class SetReverbEnabledTest : public DeviceBase { public: CREATE_FUNC(SetReverbEnabledTest); virtual std::string subtitle() const override { return "Set Reverb Enabled Test"; } virtual void onEnter() override; }; #endif /* devicesettingsuit_hpp */
#pragma once #include "bricks/imaging/image.h" #include "bricks/imaging/bitmap.h" namespace Bricks { namespace Imaging { class Subimage : public BitmapImage { protected: AutoPointer<Image> image; BitmapImage* bitmap; u32 offsetX; u32 offsetY; u32 width; u32 height; public: Subimage(BitmapImage* image, u32 offsetX = 0, u32 offsetY = 0, u32 width = 0, u32 height = 0) : image(image), bitmap(image), offsetX(offsetX), offsetY(offsetY), width(width), height(height) { if (bitmap && bitmap->GetInterlaceType() != InterlaceType::None) BRICKS_FEATURE_THROW(NotSupportedException()); } Subimage(Image* image, u32 offsetX = 0, u32 offsetY = 0, u32 width = 0, u32 height = 0) : image(image), bitmap(CastToDynamic<BitmapImage>(image)), offsetX(offsetX), offsetY(offsetY), width(width), height(height) { if (bitmap && bitmap->GetInterlaceType() != InterlaceType::None) BRICKS_FEATURE_THROW(NotSupportedException()); } void* GetImageData() const { if (!bitmap) BRICKS_FEATURE_THROW(NotSupportedException()); return bitmap->GetImageData(); } u32 GetImageDataSize() const { if (!bitmap) BRICKS_FEATURE_THROW(NotSupportedException()); return Bitmap::CalculateImageDataSize(image->GetWidth(), height, bitmap->GetPixelDescription()); } u32 GetImageDataStride() const { if (!bitmap) BRICKS_FEATURE_THROW(NotSupportedException()); return bitmap->GetImageDataStride(); } const PixelDescription& GetPixelDescription() const { if (!bitmap) BRICKS_FEATURE_THROW(NotSupportedException()); return bitmap->GetPixelDescription(); } InterlaceType::Enum GetInterlaceType() const { return InterlaceType::None; } u32 GetOffsetX() const { return offsetX; } u32 GetOffsetY() const { return offsetY; } u32 GetWidth() const { return width; } u32 GetHeight() const { return height; } void SetOffset(u32 offsetX, u32 offsetY) { this->offsetX = offsetX; this->offsetY = offsetY; } void SetSize(u32 width, u32 height) { this->width = width; this->height = height; } Colour GetPixel(u32 x, u32 y) const { if (x >= width || y >= height) BRICKS_FEATURE_RELEASE_THROW_FATAL(InvalidArgumentException()); return image->GetPixel(offsetX + x, offsetY + y); } void SetPixel(u32 x, u32 y, const Colour& colour) { if (x >= width || y >= height) BRICKS_FEATURE_RELEASE_THROW_FATAL(InvalidArgumentException()); image->SetPixel(offsetX + x, offsetY + y, colour); } }; } }
#ifndef BASE_H #define BASE_H #include <QDebug> #include <QSqlQuery> #include <QSqlError> #include <QObject> #include <QDateTime> class Base : public QObject { Q_OBJECT Q_PROPERTY(QDateTime createdAt READ getCreatedAt NOTIFY propChanged) Q_PROPERTY(QDateTime updatedAt READ getUpdatedAt NOTIFY propChanged) protected: QDateTime _createdAt; QDateTime _updatedAt; public: Base(QObject *parent = 0); QDateTime getCreatedAt(); QDateTime getUpdatedAt(); void setCreatedAt(QDateTime createdAt); void setUpdatedAt(QDateTime updatedAt); signals: void propChanged(); }; #endif // BASE_H
#include<iostream> #include<cstdio> #include<map> #include<set> #include<vector> #include<stack> #include<queue> #include<string> #include<cstring> #include<sstream> #include<algorithm> #include<cmath> #define INF 0x3f3f3f3f #define eps 1e-8 #define pi acos(-1.0) using namespace std; typedef long long LL; const int maxn = 4e5 + 100; struct point{ int op,x,y; }; point rec[maxn]; int lazy[400100],t[400100],V[400100]; void down(int l,int mid,int r,int k) { if (lazy[k]) { t[k<<1] = lazy[k<<1] = V[mid+1]-V[l]; t[k<<1|1] = lazy[k<<1|1] = V[r+1]-V[mid+1]; lazy[k] = 0; } } void updata(int l,int r,int k,int x,int y) { if (x <= l && r <= y) { t[k] = lazy[k] = V[r+1]-V[l]; return; } int mid = (l + r) >> 1; down(l,mid,r,k); if (x <= mid) updata(l,mid,k<<1,x,y); if (y > mid) updata(mid+1,r,k<<1|1,x,y); t[k] = t[k<<1] + t[k<<1|1]; } int query(int l,int r,int k,int x,int y) { if (x <= l && r <= y) return t[k]; int mid = (l + r) >> 1,ans = 0; down(l,mid,r,k); if (x <= mid) ans += query(l,mid,k<<1,x,y); if (y > mid) ans += query(mid+1,r,k<<1|1,x,y); return ans; } int main() { int n,q,cnt = 0; scanf("%d%d",&n,&q); for (int i = 0;i < q; i++) { scanf("%d%d%d",&rec[i].op,&rec[i].x,&rec[i].y); V[++cnt] = rec[i].x;V[++cnt] = rec[i].y;V[++cnt] = rec[i].y+1; } sort(V+1,V+cnt+1); int m = unique(V+1,V+cnt+1) - V; for (int i = 0;i < q; i++) { int x = lower_bound(V+1,V+m,rec[i].x) - V, y = lower_bound(V+1,V+m,rec[i].y) - V, num = rec[i].y-rec[i].x+1; if (rec[i].op == 1) updata(1,m-2,1,x,y); else printf("%d\n",num - query(1,m-2,1,x,y)); } return 0; }
// Copyright Lionel Miele-Herndon 2020 #pragma once #include "CoreMinimal.h" #include "ShooterStarterGameModeBase.h" #include "KillEmAllGameMode.generated.h" /** * */ UCLASS() class SHOOTERSTARTER_API AKillEmAllGameMode : public AShooterStarterGameModeBase { GENERATED_BODY() public: void PawnKilled(APawn* PawnKilled) override; private: void EndGame() };
#pragma once #include "gameNode.h" #define PI 3.141592 #define DEGREE(p) (PI/180*(p)) struct tagBoss { image* _img; image* _explosion; RECT _rc; float width; float height; bool isActive; bool isDie; float speed; int e_count; int e_index; bool e_move; float x; float y; float angle; float angle2; int hp; int _count; int _index; int time; //float b_speed; bool b_dir; }; class boss : public gameNode { private: tagBoss _boss; bool respone; int selectPattern; public: HRESULT init(); void release(); void update(); void render(); void animation(); void create(); void bossMove(); void bossFire(); bool bossColl(RECT rc , int _damage); void anim(); RECT getbossRC() { return _boss._rc; } boss() {} ~boss() {} };
#include "Scene.h" #include <fstream> #include <string> #include <iostream> using namespace std; void Scene::addLight(PointLight light) { lightList.push_back(light); } void Scene::getpoint(string a, int(&b)[3]) { //cout << a << endl; int temp = 0; int num = 0; int p = 0; while (num < a.length()) { if (a[num] == '/') { b[p] = temp; //cout << b[p] << endl; temp = 0; p++; } else { temp = temp * 10; temp += (int)(a[num] - '0'); } num++; } b[p] = temp; } int Scene::getBlend(string name) { for (int i = 0;i < blendColor.size();i++) { if (blendColor[i].name == name) return i; } } void Scene::loadBlend(const char* file) { ifstream texture; texture.open(file); string a; while (!texture.eof()) { texture >> a; if (a == "newmtl") { Blend bcolor; texture >> a; bcolor.name = a; bcolor.refl = DEFAULTR; bcolor.spec = DEFAULTS; while (1) { texture >> a; if (a == "Kd") { float x, y, z; texture >> x >> y >> z; bcolor.Color.x = x; bcolor.Color.y = y; bcolor.Color.z = z; } if (a == "#refl") { float refl; texture >> refl; bcolor.refl = refl; } if (a == "Ks") { float r; texture >> r; bcolor.spec = r; break; } } blendColor.push_back(bcolor); } } } void Scene::loadScene(char* file) { sphere = Sphere(); ifstream Model; Model.open(file); cout << "打开文件" << file << "成功\n"; string a; int colorCode=0; while (!Model.eof()) { Model >> a; if (a == "mtllib") { string fname; Model >> fname; const char* name = fname.data(); loadBlend(name); cout << "Load texture complete\n"; } if (a == "usemtl") { Model >> a; colorCode = getBlend(a); } if (a == "v") { float x, y, z; Model >> x >> y >> z; Vector pot = Vector(x, y, z); pointList.push_back(pot); } if (a == "vn") { float x, y, z; Model >> x >> y >> z; Vector norm = Vector(x, y, z); normalList.push_back(norm); } if (a == "f") { //cout << "face " << triangleList.size() + 1 << endl; //cout << pointList.size() << " " << normalList.size() << " " << blendColor[colorCode].Color.x << endl; int b[3]; Model >> a; getpoint(a, b); Vector t0 = pointList.at(b[0]-1); Vector norm = normalList.at(b[2]-1); Model >> a; getpoint(a, b); Vector t1 = pointList.at(b[0]-1); Model >> a; getpoint(a, b); Vector t2 = pointList.at(b[0]-1); Triangle tri = Triangle(t0, t1, t2, norm, blendColor[colorCode].Color); tri.setSpec(blendColor[colorCode].spec); tri.setRefl(blendColor[colorCode].refl); triangleList.push_back(tri); } } /*cout << "场景输入完成\n"; for (int i = 0;i < triangleList.size();i++) { cout << "face " << i << endl; cout << triangleList[i].t0.x << " " << triangleList[i].t0.y << " " << triangleList[i].t0.z << endl; cout << triangleList[i].t1.x << " " << triangleList[i].t1.y << " " << triangleList[i].t1.z << endl; cout << triangleList[i].t2.x << " " << triangleList[i].t2.y << " " << triangleList[i].t2.z << endl; cout << triangleList[i].tnormal.x << " " << triangleList[i].tnormal.y << " " << triangleList[i].tnormal.z << endl; cout << triangleList[i].col.x << " " << triangleList[i].col.y << " " << triangleList[i].col.z << endl; cout << triangleList[i].refl << " " << triangleList[i].spec << endl; } system("pause");*/ }
#include <iostream> #include <cmath> #include <iomanip> using namespace std; /* Problema 1.1 Complejidad de tiempo: O(1) */ int main() { int casos; cin >> casos; for (int i = 0; i < casos; i++) { int lado; cin >> lado; float altura = lado * sqrt(3) / 2; cout << fixed << setprecision(2); cout << altura << endl; } }
#include <iostream> #include <climits> using namespace std; void floyd(int D[100][100], int n) { for (int k = 0; k < n; k++) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (D[i][k] != INT_MAX && D[k][j] != INT_MAX) D[i][j] = D[i][j] < (D[i][k] > D[k][j] ? D[i][k] :D[k][j]) ? D[i][j] : (D[i][k] > D[k][j] ? D[i][k] :D[k][j]); //D[i][j] = min(D[i][j],max(D[k][j],D[k][j])); } } } } int main() { int cant, n, m, q, a, b, c, D[100][100]; cin>>cant; for(int k = 1; k <= cant;k++) { cin >> n >> m >> q; for (int i = 0; i < n; i++) { D[i][i] = 0; for (int j = i + 1; j < n; j++) { D[i][j] = D[j][i] = INT_MAX; } } for (int i = 0; i < m; i++) { cin >> a >> b >> c; D[a - 1][b - 1] = D[b - 1][a - 1] = c; } floyd(D, n); for (int i = 0; i < q; i++) { cin>>a>>b; if(!i) cout<< "Case " << k << ":"<<endl; D[a-1][b-1] == INT_MAX ? cout<< "no path" <<endl : cout <<D[a-1][b-1] <<endl; } } return 0; }
#ifndef LAB2_MAIN_H_H #define LAB2_MAIN_H_H #include <c++/array> #include <c++/iostream> #include "matrix.h" using namespace std; using matrix::Matrix; using T = double; const int N = 8; const int M = 8; int main(); void doTask(); void doResearch(int pRange); Matrix<T, N, M> findMatrixR(Matrix<T, N, M> matrix); #endif
//: C12:AutomaticOperatorEquals.cpp // Kod zrodlowy pochodzacy z ksiazki // "Thinking in C++. Edycja polska" // (c) Bruce Eckel 2000 // Informacje o prawie autorskim znajduja sie w pliku Copyright.txt #include <iostream> using namespace std; class Cargo { public: Cargo& operator=(const Cargo&) { cout << "wewnatrz Cargo::operator=()" << endl; return *this; } }; class Truck { Cargo b; }; int main() { Truck a, b; a = b; // Drukuje: "wewnatrz Cargo::operator=()" } ///:~
#include<iostream> using namespace std; //find out all the inversions in an array void MERGE(int* a, int* sorted, int start, int mid, int end,int& count) { //we divide the array into two parts,the letf array and the right array //the index of the left array int startL = start; int endL = mid; //the index of the right array int startR = mid + 1; int endR = end; //the index of the sorted array int index = start; while (startL <= endL&&startR <= endR) { if (a[startL] <= a[startR]) { sorted[index++] = a[startL++]; } else { //element indexed from startL to endL is greater than element indexed startR for (int i = startL; i <= endL; i++) { //print the inversion item count++; cout << "{" << a[i] << "," << a[startR] <<"}"<< endl; } sorted[index++] = a[startR++]; } } while (startL <= endL) { sorted[index++] = a[startL++]; } while (startR <= endR) { sorted[index++] = a[startR++]; } for (int i = start; i <= end; i++) { *(a + i) = *(sorted + i); } } //recusively call the merge_sort void merge_sort(int*a, int* sorted, int start, int end,int& count) { if (start < end) { int mid = (end + start) / 2; merge_sort(a, sorted, start, mid,count); merge_sort(a, sorted, mid + 1, end,count); MERGE(a, sorted, start, mid, end,count); } } void invertions_demo() { int a[10] = {2,3,1,5,4,6,8,7,10,6}; int count = 0; int* sorted = new int[10]; cout << "the inversions are :" << endl; clock_t start = clock(); merge_sort(a, sorted, 0,9,count); clock_t end = clock(); delete[] sorted; cout << " the total inversion amount is " << count << endl; }
#include"conio.h" #include"stdio.h" void main(void) { clrscr(); getch(); }
#include <iostream> using namespace std; #include "game.h" main() { cout<<" ~AKINATOR THE GENIE~ "<<endl; cout<<"THINK ABOUT ANY TEACHER AND I WILL TRY TO GUESS IT"<<endl; string start="yes"; system("pause"); while(start=="yes"||start=="YES"||start=="Yes") { game a; a.start(); cout<<endl<<"do you want to play again"<<endl; cin>>start; } system("pasue"); }
#include<iostream> #include<cstdio> #include<vector> #include<map> #include<string> #include<cstring> #include<algorithm> using namespace std; const int pri[] = {3,5,7,11,13,17,19,23,29,31,37}; int use[30],num[30],n,ans = 0; void print() { for (int i = 1;i < n; i++) printf("%d ",num[i]); printf("%d\n",num[n]); } bool prime(int k) { for (int i = 0;i <= 10; i++) if (k == pri[i]) return true; return false; } void dfs(int k) { if (k == n) {if ( prime(num[n]+1) ) print(); return; } for (int i = 2;i <= n; i++) if (!use[i] && prime( i+num[k] ) ) {use[i] = 1; num[k+1] = i; dfs(k+1); use[i] = 0; } } int main() {int t = 0; while (cin >> n) {printf("Case %d:\n",++t); memset(use,0,sizeof(use)); num[1] = 1; dfs(1); printf("\n"); } return 0; }
#include "RTClib.h" #include <zeroseg.h> // one of my fantabulous libraries #include <Timezone.h> // https://github.com/JChristensen/Timezone #include <debounce.h> // a project here that does falling buttons typedef unsigned long ulong; //typedef unsigned long micros_t; typedef ulong ms_t; typedef uint32_t u32; /////////////////////////////////////////////////////////// // DS3231 TimeChangeRule myBST = {"BST", Last, Sun, Mar, 1, 60}; TimeChangeRule mySTD = {"GMT", Last, Sun, Oct, 2, 0}; Timezone myTZ(myBST, mySTD); TimeChangeRule *tcr; //pointer to the time change rule, use to get TZ abbrev RTC_DS3231 rtc; DateTime get_time() { DateTime dt = rtc.now(); auto tim = dt.unixtime(); tim = myTZ.toLocal(tim, &tcr); DateTime dt_local{tim}; return dt_local; } // DS3231 end /////////////////////////////////////////////////////////// // COMMON COMPONENTS typedef void (*sm_func_t)(int); // state machine pointer void sm_default(int ev); sm_func_t sm_func = &sm_default; // COMMON COMPONENTS end /////////////////////////////////////////////////////////// // BUZZER #define BZR 8 u32 buzzer_started = 0; bool buzzer_enabled = false; void buzzer_poll() { if (!buzzer_enabled) return; u32 elapsed = millis() - buzzer_started; ulong segment = elapsed % 5000; bool on = segment < 250 || ( 500 < segment && segment < 750); //Serial.print("sound "); if (on) { tone(BZR, 2525);// quindar //Serial.println("on"); } else { noTone(BZR); digitalWrite(BZR, LOW); //Serial.println("off"); } } void buzzer_start() { if (buzzer_enabled) return; // don't restart an already-running buzzer pinMode(BZR, OUTPUT); buzzer_started = millis(); buzzer_enabled = true; buzzer_poll(); } void buzzer_stop() { buzzer_enabled = false; noTone(BZR); } /////////////////////////////////////////////////////////// enum {ev_poll, ev_blue_falling, ev_white_falling, ev_white_rising, ev_sw_left_falling, ev_sw_right_falling }; Debounce blue(3); // 0seg left button is A0, right button is A2 Debounce white(2); // adjust time up or down Debounce sw_left(A0); Debounce sw_right(A2); //ezButton sw0(3); //#define SW_ADJ 2 void setup() { init_7219(); rtc.begin(); Serial.begin(115200); //update_regular_display(); //sm_func(666); // test out the function // see if I can get rid of the buzzing sound // doesn't seem to help though rtc.disable32K(); rtc.disableAlarm(0); rtc.disableAlarm(1); rtc.disableAlarm(2); //pinMode(2, INPUT_PULLUP); } void show_dec(int pos, int val, bool dp = false) { int v = val % 10; if (dp) v |= 1 << 7; // add in the decimal point transfer_7219(pos, v); transfer_7219(pos + 1, val / 10); } bool show_clock = true; void update_regular_display() { DateTime dt = get_time(); show_dec(5, dt.minute()); show_dec(7, dt.hour(), true); transfer_7219(3, 0b1111); // blank transfer_7219(4, 0b1111); // blank show_dec(1, dt.day()); } void update_counter_display(ulong elapsed) { show_dec(1, elapsed % 60); show_dec(3, elapsed / 60, true); for (int i = 5; i < 9; i++) { transfer_7219(i, 0b1111); // blank } } ulong om_start_time; void sm_om_timing(int ev) { ulong elapsed_secs = (millis() - om_start_time) / 1000; switch (ev) { case ev_blue_falling: buzzer_stop(); sm_func = sm_default; break; case ev_poll: update_counter_display(elapsed_secs); if (elapsed_secs >= 60UL * 30UL) { buzzer_start(); } } } void sm_om_starting(int ev) { if (ev != ev_poll) return; om_start_time = millis(); sm_func = sm_om_timing; } void sm_adjusting(int ev) { //Serial.println("sm_adjusting() called"); int delta = 0; switch (ev) { case ev_white_rising: sm_func = sm_default; break; case ev_sw_left_falling: Serial.println("sm_adjusting found ev_sw_left_falling"); delta = -1; break; case ev_sw_right_falling: delta = 1; break; } if (delta != 0) { DateTime dt = rtc.now(); // NB this is in UTC, not local time dt = dt + TimeSpan(delta); rtc.adjust(dt); } // adjusting display DateTime dt = get_time(); show_dec(3, dt.second()); show_dec(5, dt.minute(), true); show_dec(7, dt.hour(), true); transfer_7219(1, 0b1111); // blank transfer_7219(2, 0b1111); // blank } void sm_default(int ev) { switch (ev) { case ev_blue_falling: sm_func = sm_om_starting; break; case ev_white_falling: sm_func = sm_adjusting; break; case ev_poll: default: update_regular_display(); } } void loop() { buzzer_poll(); //if(sw_left.falling()) Serial.println("1"); if (blue.falling()) { Serial.println("loop: blue falling"); sm_func(ev_blue_falling); } else if (white.falling()) { Serial.println("loop: white falling"); sm_func(ev_white_falling); } else if (white.rising()) { Serial.println("loop: white rising"); sm_func(ev_white_rising); } else if (sw_left.falling()) { Serial.println("loop: sw_left falling"); sm_func(ev_sw_left_falling); } else if (sw_right.falling()) { Serial.println("loop: sw_right falling"); sm_func(ev_sw_right_falling); } else { sm_func(ev_poll); } delay(1); }
#include <iostream> using std::cout; using std::endl; #include <vector> using std::vector; #include <string> using std::string; #include <sstream> using std::istringstream; #include <fstream> using std::ifstream; struct PersonInfo { string name; vector<string> phones; }; int main(int argc, char** argv) { string line, word; vector<PersonInfo> people; ifstream ifs(argv[1]); while(getline(ifs, line)) { PersonInfo info; istringstream iss(line); iss >> info.name; while(iss >> word) { info.phones.push_back(word); } people.push_back(info); } for(auto p : people) { cout << "name: " << p.name << endl; for(auto w : p.phones) { cout << "phone: " << w << endl; } } return 0; }