blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
listlengths
1
1
author
stringlengths
0
119
f3d92e390ec0a7d49e9cd426f4537442409e2fa0
6efcf227f1263d49db0bc51148a4fbdf73cf5842
/Dengs FOC V2.0/Dengs FOC V2.0 测试例程(支持库SimpleFOC 2.1.1)/1 双电机开环速度控制/1_open_loop_velocity/1_open_loop_velocity_example.ino
51cc3da9c5d86de0abc312674445336407c86e2c
[ "Apache-2.0" ]
permissive
power-u/Deng-s-foc-controller
25e92778391087f2b608f2c501ffa6a80096ecd3
b8cdf899f2f1616e7baa4b17d2c4cb0ee231e6c6
refs/heads/main
2023-06-21T10:04:03.008769
2021-07-16T01:40:20
2021-07-16T01:40:20
386,682,002
0
1
Apache-2.0
2021-07-16T15:24:51
2021-07-16T15:24:50
null
UTF-8
C++
false
false
1,773
ino
// Deng's FOC 开环速度控制例程 测试库:SimpleFOC 2.1.1 测试硬件:灯哥开源FOC V2.0 // 串口中输入"T+数字"设定两个电机的转速,如设置电机以 10rad/s 转动,输入 "T10",电机上电时默认会以 5rad/s 转动 // 在使用自己的电机时,请一定记得修改默认极对数,即 BLDCMotor(14) 中的值,设置为自己的极对数数字 // 程序默认设置的供电电压为 16.8V,用其他电压供电请记得修改 voltage_power_supply , voltage_limit 变量中的值 #include <SimpleFOC.h> BLDCMotor motor = BLDCMotor(14); BLDCDriver3PWM driver = BLDCDriver3PWM(32, 33, 25, 22); BLDCMotor motor1 = BLDCMotor(14); BLDCDriver3PWM driver1 = BLDCDriver3PWM(26, 27, 14, 12); //目标变量 float target_velocity = 5; //串口指令设置 Commander command = Commander(Serial); void doTarget(char* cmd) { command.scalar(&target_velocity, cmd); } void setup() { driver.voltage_power_supply = 16.8; driver.init(); motor.linkDriver(&driver); motor.voltage_limit = 16.8; // [V] motor.velocity_limit = 15; // [rad/s] driver1.voltage_power_supply = 16.8; driver1.init(); motor1.linkDriver(&driver1); motor1.voltage_limit = 16.8; // [V] motor1.velocity_limit = 15; // [rad/s] //开环控制模式设置 motor.controller = MotionControlType::velocity_openloop; motor1.controller = MotionControlType::velocity_openloop; //初始化硬件 motor.init(); motor1.init(); //增加 T 指令 command.add('T', doTarget, "target velocity"); Serial.begin(115200); Serial.println("Motor ready!"); Serial.println("Set target velocity [rad/s]"); _delay(1000); } void loop() { motor.move(target_velocity); motor1.move(target_velocity); //用户通讯 command.run(); }
[ "30995326+Glocklein@users.noreply.github.com" ]
30995326+Glocklein@users.noreply.github.com
a560667a8075238087f9b1b740d3b0b5f1ff0ed0
2699a4a53437c4b5d9559245a7101cbe8f14d102
/maze/maze.cpp
960186dadc89f9df1c6eacc1cf72cf97e8b33c55
[]
no_license
theoport/Cpp_revision
f4aed05a8e87f633e595a2e54b7375a7cab59825
48d852cfacc3fcfc1e1275aa0654357893892c46
refs/heads/master
2021-01-13T15:28:10.561979
2017-09-12T17:47:36
2017-09-12T17:47:36
80,144,702
0
0
null
null
null
null
UTF-8
C++
false
false
5,294
cpp
#include <iostream> #include <iomanip> #include <fstream> #include <cassert> #include <cstring> #include <string> #include "maze.h" using namespace std; /* You are pre-supplied with the functions below. Add your own function definitions to the end of this file. */ /* helper function which allocates a dynamic 2D array */ char **allocate_2D_array(int rows, int columns) { char **m = new char *[rows]; assert(m); for (int r=0; r<rows; r++) { m[r] = new char[columns]; assert(m[r]); } return m; } /* helper function which deallocates a dynamic 2D array */ void deallocate_2D_array(char **m, int rows) { for (int r=0; r<rows; r++) delete [] m[r]; delete [] m; } /* helper function for internal use only which gets the dimensions of a maze */ bool get_maze_dimensions(const char *filename, int &height, int &width) { char line[512]; ifstream input(filename); height = width = 0; input.getline(line,512); while (input) { if ( (int) strlen(line) > width) width = strlen(line); height++; input.getline(line,512); } if (height > 0) return true; return false; } /* pre-supplied function to load a maze from a file*/ char **load_maze(const char *filename, int &height, int &width) { bool success = get_maze_dimensions(filename, height, width); if (!success) return NULL; char **m = allocate_2D_array(height, width); ifstream input(filename); char line[512]; for (int r = 0; r<height; r++) { input.getline(line, 512); strcpy(m[r], line); } return m; } /* pre-supplied function to print a maze */ void print_maze(char **m, int height, int width) { cout << setw(4) << " " << " "; for (int c=0; c<width; c++) if (c && (c % 10) == 0) cout << c/10; else cout << " "; cout << endl; cout << setw(4) << " " << " "; for (int c=0; c<width; c++) cout << (c % 10); cout << endl; for (int r=0; r<height; r++) { cout << setw(4) << r << " "; for (int c=0; c<width; c++) cout << m[r][c]; cout << endl; } } bool find_marker(char ch, char** maze, int height, int width, int& row, int& column){ for (size_t i=0;i<height;i++){ for (size_t m=0;m<width;m++){ if (maze[i][m]==ch){ row=i; column=m; return true; } } } row=-1; column=-1; return false; } bool valid_solution(const char* path, char** maze, int height, int width){ int row, column; assert(find_marker('>',maze,height,width,row,column)); for (size_t i=0;i<strlen(path);i++){ switch (path[i]){ case 'E': if (iswall(maze[row][column+1])) return false; else if((column+1)>(width-1)) return false; else{ column++; } break; case 'W': if (iswall(maze[row][column-1])) return false; else if((column-1)<0) return false; else{ column--; } break; case 'S': if (iswall(maze[row+1][column])) return false; else if((row+1)>(height-1)) return false; else{ row++; } break; case 'N': if (iswall(maze[row-1][column])) return false; else if((row-1)<0) return false; else{ row--; } break; } } return true; } bool iswall(char a){ switch (a){ case '-': case '|': case '+': case '#': return true; default: return false; } } const char* find_path(char** maze, int height, int width, char start, char end){ int row_e,column_e,row_s,column_s; assert (find_marker(start,maze,height,width,row_s,column_s)); assert (find_marker(end,maze,height,width,row_e,column_e)); char path[512]; int count(0); if (make_path(maze,height,width,row_s,column_s,row_s,column_s,row_e,column_e,path,count)) return reverse(path,count); else return "no solution"; } bool make_path(char** maze, int height, int width, int current_row, int current_column, int row_s, int column_s, int row_e, int column_e, char* path, int& count){ if (current_row==row_e&&current_column==column_e) return true; else if(iswall(maze[current_row][current_column])) return false; else if(out_of_scope(current_row,current_column,height,width)) return false; else if ((isalpha(maze[current_row][current_column])||(maze[current_row][current_column]=='>')) &&!(current_row==row_s&&current_column==column_s)) return false; maze[current_row][current_column]='#'; if (make_path(maze,height,width,current_row+1,current_column,row_s,column_s,row_e,column_e, path,count)){ strcat(path,"S"); count++; return true; } else if (make_path(maze,height,width,current_row-1,current_column,row_s,column_s,row_e,column_e, path,count)){ strcat(path,"N"); count++; return true; } else if (make_path(maze,height,width,current_row,current_column+1,row_s,column_s,row_e,column_e, path,count)){ strcat(path,"E"); count++; return true; } else if (make_path(maze,height,width,current_row,current_column-1,row_s,column_s,row_e,column_e, path,count)){ strcat(path,"W"); count++; return true; } else{ maze[current_row][current_column]=' '; return false; } } bool out_of_scope(int a, int b, int x, int y){ return (a<0||a>x||b<0||b>y); } char* reverse(char *p,int count){ char temp[512]; for (size_t i=0;i<count;i++) temp[i]=p[count-(i+1)]; strcpy(p,temp); p[count]='\0'; return p; }
[ "theodor.port16@imperial.ac.uk" ]
theodor.port16@imperial.ac.uk
23df7916eb89d2fcb5b955295d349b112acdfa60
15736c955a83aff301bf9d3ef049767918d8c998
/llvm/.svn/pristine/23/23df7916eb89d2fcb5b955295d349b112acdfa60.svn-base
afded91598245f053696e42781a8b34ec7b38a25
[ "NCSA" ]
permissive
sangeeta0201/fpsanitizer
02f2aa40cb9341b625893840d8f81cf2fc8d368a
402467edf31f3f70b4cb3f52ec27cbdc50cebf9f
refs/heads/master
2020-03-19T02:22:02.058623
2019-09-30T18:41:59
2019-09-30T18:41:59
135,622,400
1
0
null
null
null
null
UTF-8
C++
false
false
13,858
//===-- R600MachineScheduler.cpp - R600 Scheduler Interface -*- C++ -*-----===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // /// \file /// R600 Machine Scheduler interface // //===----------------------------------------------------------------------===// #include "R600MachineScheduler.h" #include "AMDGPUSubtarget.h" #include "R600InstrInfo.h" #include "MCTargetDesc/AMDGPUMCTargetDesc.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/IR/LegacyPassManager.h" #include "llvm/Pass.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; #define DEBUG_TYPE "machine-scheduler" void R600SchedStrategy::initialize(ScheduleDAGMI *dag) { assert(dag->hasVRegLiveness() && "R600SchedStrategy needs vreg liveness"); DAG = static_cast<ScheduleDAGMILive*>(dag); const R600Subtarget &ST = DAG->MF.getSubtarget<R600Subtarget>(); TII = static_cast<const R600InstrInfo*>(DAG->TII); TRI = static_cast<const R600RegisterInfo*>(DAG->TRI); VLIW5 = !ST.hasCaymanISA(); MRI = &DAG->MRI; CurInstKind = IDOther; CurEmitted = 0; OccupedSlotsMask = 31; InstKindLimit[IDAlu] = TII->getMaxAlusPerClause(); InstKindLimit[IDOther] = 32; InstKindLimit[IDFetch] = ST.getTexVTXClauseSize(); AluInstCount = 0; FetchInstCount = 0; } void R600SchedStrategy::MoveUnits(std::vector<SUnit *> &QSrc, std::vector<SUnit *> &QDst) { QDst.insert(QDst.end(), QSrc.begin(), QSrc.end()); QSrc.clear(); } static unsigned getWFCountLimitedByGPR(unsigned GPRCount) { assert (GPRCount && "GPRCount cannot be 0"); return 248 / GPRCount; } SUnit* R600SchedStrategy::pickNode(bool &IsTopNode) { SUnit *SU = nullptr; NextInstKind = IDOther; IsTopNode = false; // check if we might want to switch current clause type bool AllowSwitchToAlu = (CurEmitted >= InstKindLimit[CurInstKind]) || (Available[CurInstKind].empty()); bool AllowSwitchFromAlu = (CurEmitted >= InstKindLimit[CurInstKind]) && (!Available[IDFetch].empty() || !Available[IDOther].empty()); if (CurInstKind == IDAlu && !Available[IDFetch].empty()) { // We use the heuristic provided by AMD Accelerated Parallel Processing // OpenCL Programming Guide : // The approx. number of WF that allows TEX inst to hide ALU inst is : // 500 (cycles for TEX) / (AluFetchRatio * 8 (cycles for ALU)) float ALUFetchRationEstimate = (AluInstCount + AvailablesAluCount() + Pending[IDAlu].size()) / (FetchInstCount + Available[IDFetch].size()); if (ALUFetchRationEstimate == 0) { AllowSwitchFromAlu = true; } else { unsigned NeededWF = 62.5f / ALUFetchRationEstimate; LLVM_DEBUG(dbgs() << NeededWF << " approx. Wavefronts Required\n"); // We assume the local GPR requirements to be "dominated" by the requirement // of the TEX clause (which consumes 128 bits regs) ; ALU inst before and // after TEX are indeed likely to consume or generate values from/for the // TEX clause. // Available[IDFetch].size() * 2 : GPRs required in the Fetch clause // We assume that fetch instructions are either TnXYZW = TEX TnXYZW (need // one GPR) or TmXYZW = TnXYZW (need 2 GPR). // (TODO : use RegisterPressure) // If we are going too use too many GPR, we flush Fetch instruction to lower // register pressure on 128 bits regs. unsigned NearRegisterRequirement = 2 * Available[IDFetch].size(); if (NeededWF > getWFCountLimitedByGPR(NearRegisterRequirement)) AllowSwitchFromAlu = true; } } if (!SU && ((AllowSwitchToAlu && CurInstKind != IDAlu) || (!AllowSwitchFromAlu && CurInstKind == IDAlu))) { // try to pick ALU SU = pickAlu(); if (!SU && !PhysicalRegCopy.empty()) { SU = PhysicalRegCopy.front(); PhysicalRegCopy.erase(PhysicalRegCopy.begin()); } if (SU) { if (CurEmitted >= InstKindLimit[IDAlu]) CurEmitted = 0; NextInstKind = IDAlu; } } if (!SU) { // try to pick FETCH SU = pickOther(IDFetch); if (SU) NextInstKind = IDFetch; } // try to pick other if (!SU) { SU = pickOther(IDOther); if (SU) NextInstKind = IDOther; } LLVM_DEBUG(if (SU) { dbgs() << " ** Pick node **\n"; SU->dump(DAG); } else { dbgs() << "NO NODE \n"; for (unsigned i = 0; i < DAG->SUnits.size(); i++) { const SUnit &S = DAG->SUnits[i]; if (!S.isScheduled) S.dump(DAG); } }); return SU; } void R600SchedStrategy::schedNode(SUnit *SU, bool IsTopNode) { if (NextInstKind != CurInstKind) { LLVM_DEBUG(dbgs() << "Instruction Type Switch\n"); if (NextInstKind != IDAlu) OccupedSlotsMask |= 31; CurEmitted = 0; CurInstKind = NextInstKind; } if (CurInstKind == IDAlu) { AluInstCount ++; switch (getAluKind(SU)) { case AluT_XYZW: CurEmitted += 4; break; case AluDiscarded: break; default: { ++CurEmitted; for (MachineInstr::mop_iterator It = SU->getInstr()->operands_begin(), E = SU->getInstr()->operands_end(); It != E; ++It) { MachineOperand &MO = *It; if (MO.isReg() && MO.getReg() == R600::ALU_LITERAL_X) ++CurEmitted; } } } } else { ++CurEmitted; } LLVM_DEBUG(dbgs() << CurEmitted << " Instructions Emitted in this clause\n"); if (CurInstKind != IDFetch) { MoveUnits(Pending[IDFetch], Available[IDFetch]); } else FetchInstCount++; } static bool isPhysicalRegCopy(MachineInstr *MI) { if (MI->getOpcode() != R600::COPY) return false; return !TargetRegisterInfo::isVirtualRegister(MI->getOperand(1).getReg()); } void R600SchedStrategy::releaseTopNode(SUnit *SU) { LLVM_DEBUG(dbgs() << "Top Releasing "; SU->dump(DAG);); } void R600SchedStrategy::releaseBottomNode(SUnit *SU) { LLVM_DEBUG(dbgs() << "Bottom Releasing "; SU->dump(DAG);); if (isPhysicalRegCopy(SU->getInstr())) { PhysicalRegCopy.push_back(SU); return; } int IK = getInstKind(SU); // There is no export clause, we can schedule one as soon as its ready if (IK == IDOther) Available[IDOther].push_back(SU); else Pending[IK].push_back(SU); } bool R600SchedStrategy::regBelongsToClass(unsigned Reg, const TargetRegisterClass *RC) const { if (!TargetRegisterInfo::isVirtualRegister(Reg)) { return RC->contains(Reg); } else { return MRI->getRegClass(Reg) == RC; } } R600SchedStrategy::AluKind R600SchedStrategy::getAluKind(SUnit *SU) const { MachineInstr *MI = SU->getInstr(); if (TII->isTransOnly(*MI)) return AluTrans; switch (MI->getOpcode()) { case R600::PRED_X: return AluPredX; case R600::INTERP_PAIR_XY: case R600::INTERP_PAIR_ZW: case R600::INTERP_VEC_LOAD: case R600::DOT_4: return AluT_XYZW; case R600::COPY: if (MI->getOperand(1).isUndef()) { // MI will become a KILL, don't considers it in scheduling return AluDiscarded; } default: break; } // Does the instruction take a whole IG ? // XXX: Is it possible to add a helper function in R600InstrInfo that can // be used here and in R600PacketizerList::isSoloInstruction() ? if(TII->isVector(*MI) || TII->isCubeOp(MI->getOpcode()) || TII->isReductionOp(MI->getOpcode()) || MI->getOpcode() == R600::GROUP_BARRIER) { return AluT_XYZW; } if (TII->isLDSInstr(MI->getOpcode())) { return AluT_X; } // Is the result already assigned to a channel ? unsigned DestSubReg = MI->getOperand(0).getSubReg(); switch (DestSubReg) { case R600::sub0: return AluT_X; case R600::sub1: return AluT_Y; case R600::sub2: return AluT_Z; case R600::sub3: return AluT_W; default: break; } // Is the result already member of a X/Y/Z/W class ? unsigned DestReg = MI->getOperand(0).getReg(); if (regBelongsToClass(DestReg, &R600::R600_TReg32_XRegClass) || regBelongsToClass(DestReg, &R600::R600_AddrRegClass)) return AluT_X; if (regBelongsToClass(DestReg, &R600::R600_TReg32_YRegClass)) return AluT_Y; if (regBelongsToClass(DestReg, &R600::R600_TReg32_ZRegClass)) return AluT_Z; if (regBelongsToClass(DestReg, &R600::R600_TReg32_WRegClass)) return AluT_W; if (regBelongsToClass(DestReg, &R600::R600_Reg128RegClass)) return AluT_XYZW; // LDS src registers cannot be used in the Trans slot. if (TII->readsLDSSrcReg(*MI)) return AluT_XYZW; return AluAny; } int R600SchedStrategy::getInstKind(SUnit* SU) { int Opcode = SU->getInstr()->getOpcode(); if (TII->usesTextureCache(Opcode) || TII->usesVertexCache(Opcode)) return IDFetch; if (TII->isALUInstr(Opcode)) { return IDAlu; } switch (Opcode) { case R600::PRED_X: case R600::COPY: case R600::CONST_COPY: case R600::INTERP_PAIR_XY: case R600::INTERP_PAIR_ZW: case R600::INTERP_VEC_LOAD: case R600::DOT_4: return IDAlu; default: return IDOther; } } SUnit *R600SchedStrategy::PopInst(std::vector<SUnit *> &Q, bool AnyALU) { if (Q.empty()) return nullptr; for (std::vector<SUnit *>::reverse_iterator It = Q.rbegin(), E = Q.rend(); It != E; ++It) { SUnit *SU = *It; InstructionsGroupCandidate.push_back(SU->getInstr()); if (TII->fitsConstReadLimitations(InstructionsGroupCandidate) && (!AnyALU || !TII->isVectorOnly(*SU->getInstr()))) { InstructionsGroupCandidate.pop_back(); Q.erase((It + 1).base()); return SU; } else { InstructionsGroupCandidate.pop_back(); } } return nullptr; } void R600SchedStrategy::LoadAlu() { std::vector<SUnit *> &QSrc = Pending[IDAlu]; for (unsigned i = 0, e = QSrc.size(); i < e; ++i) { AluKind AK = getAluKind(QSrc[i]); AvailableAlus[AK].push_back(QSrc[i]); } QSrc.clear(); } void R600SchedStrategy::PrepareNextSlot() { LLVM_DEBUG(dbgs() << "New Slot\n"); assert (OccupedSlotsMask && "Slot wasn't filled"); OccupedSlotsMask = 0; // if (HwGen == R600Subtarget::NORTHERN_ISLANDS) // OccupedSlotsMask |= 16; InstructionsGroupCandidate.clear(); LoadAlu(); } void R600SchedStrategy::AssignSlot(MachineInstr* MI, unsigned Slot) { int DstIndex = TII->getOperandIdx(MI->getOpcode(), R600::OpName::dst); if (DstIndex == -1) { return; } unsigned DestReg = MI->getOperand(DstIndex).getReg(); // PressureRegister crashes if an operand is def and used in the same inst // and we try to constraint its regclass for (MachineInstr::mop_iterator It = MI->operands_begin(), E = MI->operands_end(); It != E; ++It) { MachineOperand &MO = *It; if (MO.isReg() && !MO.isDef() && MO.getReg() == DestReg) return; } // Constrains the regclass of DestReg to assign it to Slot switch (Slot) { case 0: MRI->constrainRegClass(DestReg, &R600::R600_TReg32_XRegClass); break; case 1: MRI->constrainRegClass(DestReg, &R600::R600_TReg32_YRegClass); break; case 2: MRI->constrainRegClass(DestReg, &R600::R600_TReg32_ZRegClass); break; case 3: MRI->constrainRegClass(DestReg, &R600::R600_TReg32_WRegClass); break; } } SUnit *R600SchedStrategy::AttemptFillSlot(unsigned Slot, bool AnyAlu) { static const AluKind IndexToID[] = {AluT_X, AluT_Y, AluT_Z, AluT_W}; SUnit *SlotedSU = PopInst(AvailableAlus[IndexToID[Slot]], AnyAlu); if (SlotedSU) return SlotedSU; SUnit *UnslotedSU = PopInst(AvailableAlus[AluAny], AnyAlu); if (UnslotedSU) AssignSlot(UnslotedSU->getInstr(), Slot); return UnslotedSU; } unsigned R600SchedStrategy::AvailablesAluCount() const { return AvailableAlus[AluAny].size() + AvailableAlus[AluT_XYZW].size() + AvailableAlus[AluT_X].size() + AvailableAlus[AluT_Y].size() + AvailableAlus[AluT_Z].size() + AvailableAlus[AluT_W].size() + AvailableAlus[AluTrans].size() + AvailableAlus[AluDiscarded].size() + AvailableAlus[AluPredX].size(); } SUnit* R600SchedStrategy::pickAlu() { while (AvailablesAluCount() || !Pending[IDAlu].empty()) { if (!OccupedSlotsMask) { // Bottom up scheduling : predX must comes first if (!AvailableAlus[AluPredX].empty()) { OccupedSlotsMask |= 31; return PopInst(AvailableAlus[AluPredX], false); } // Flush physical reg copies (RA will discard them) if (!AvailableAlus[AluDiscarded].empty()) { OccupedSlotsMask |= 31; return PopInst(AvailableAlus[AluDiscarded], false); } // If there is a T_XYZW alu available, use it if (!AvailableAlus[AluT_XYZW].empty()) { OccupedSlotsMask |= 15; return PopInst(AvailableAlus[AluT_XYZW], false); } } bool TransSlotOccuped = OccupedSlotsMask & 16; if (!TransSlotOccuped && VLIW5) { if (!AvailableAlus[AluTrans].empty()) { OccupedSlotsMask |= 16; return PopInst(AvailableAlus[AluTrans], false); } SUnit *SU = AttemptFillSlot(3, true); if (SU) { OccupedSlotsMask |= 16; return SU; } } for (int Chan = 3; Chan > -1; --Chan) { bool isOccupied = OccupedSlotsMask & (1 << Chan); if (!isOccupied) { SUnit *SU = AttemptFillSlot(Chan, false); if (SU) { OccupedSlotsMask |= (1 << Chan); InstructionsGroupCandidate.push_back(SU->getInstr()); return SU; } } } PrepareNextSlot(); } return nullptr; } SUnit* R600SchedStrategy::pickOther(int QID) { SUnit *SU = nullptr; std::vector<SUnit *> &AQ = Available[QID]; if (AQ.empty()) { MoveUnits(Pending[QID], AQ); } if (!AQ.empty()) { SU = AQ.back(); AQ.pop_back(); } return SU; }
[ "sc1696@scarletmail.rutgers.edu" ]
sc1696@scarletmail.rutgers.edu
e61152ef145307fdd6edb7be3e924d55f5864e97
a2111a80faf35749d74a533e123d9da9da108214
/raw/pmsb13/pmsb13-data-20130530/sources/427smdvbnknp0jra/2013-05-17T23-23-11.575+0200/sandbox/gruppe1/apps/PEMer_Lite/PEMer_Lite.h
a35286e54df5a03a56d3a745ca4ff4f473b97c6d
[ "MIT" ]
permissive
bkahlert/seqan-research
f2c550d539f511825842a60f6b994c1f0a3934c2
21945be863855077eec7cbdb51c3450afcf560a3
refs/heads/master
2022-12-24T13:05:48.828734
2015-07-01T01:56:22
2015-07-01T01:56:22
21,610,669
1
0
null
null
null
null
ISO-8859-1
C++
false
false
3,669
h
/* Name: saminput Author: Lars Zerbe <larszerbe@live.de> Author: Stephan Peter <s.peter@fu-berlin.de> Maintainer: Lars Zerbe <larszerbe@live.de> License: GPL v3 Copyright: 2008-2012, FU Berlin Status: under development */ #ifndef PEMER_LITE_H_ #define PEMER_LITE_H_ #include <seqan/basic.h> #include <seqan/sequence.h> #include <algorithm> #include <iterator> #include <iostream> #include <seqan/bam_io.h> #include <seqan/file.h> #include <seqan/arg_parse.h> #include <math.h> #include <vector> #include <fstream> #include <string> struct medianTree // struktur welche den Median Speichert, abhängig von allen in eingegebenen Werten mit konstantem Speicher. { private: int leftSize, rightSize, wert; //Initialisierung: wert speichert den aktuellen Median, leftSize und rightSize die größe der elemente die kleiner oder gößer des Medians sind. public: medianTree() : //konstruktor der beim erzeugen 'leftSize, rightSize, wert' mit Anfangswerten definiert. leftSize(0), rightSize(0),wert(NULL) {} void add(int x) // add fügt eine neues Element x ein und überprüft ob es ein Median ist. { if(x<=wert){leftSize+=1;} //ist x kleiner/gleich als der aktuelle Median wird leftSize erhöht. else{rightSize+=1;} //ist x größer als der aktuelle Median wird rightSize erhöht. // Jetzt wir dgeprüft ob der aktuelle wert immer noch der Median ist oder ob x an seine Stelle kommt. // Dazu wird geprüft ob die differenz der Anzahl der Elemente die größer oder kleiner sind größer als 1 ist. if((leftSize-rightSize)>1){wert=x;leftSize-=1;rightSize+=1;} // x ist neuer Median, da die kleineren Elemente in der Anzahl größer sind als die großen Elemente. Es findet eine Verschiebung statt und der alte Median wird ersetzt, sowie die größen von kleiner und größeren Elementen angepasst if((leftSize-rightSize)<0){wert=x;rightSize-=1;leftSize+=1;} // x ist neuer Median, da die größeren Elemente in der Anzahl größer sind als die kleinen Elemente. Es findet eine Verschiebung statt und der alte Median wird ersetzt, sowie die größen von kleiner und größeren Elementen angepasst } int getMedian(){return wert;} // gibt den Median aus. }; struct candidate { enum form{undefine,deletion,insertion}; // form definiert den Type der Kandidaten ob u:undefiniert(0); d:deletion(1); i:insertion(2) unsigned pos; // speichert die Positon unsigned ref; // speichert die Referenz unsigned len; // speichert die Laenge form type; // speichert den Type void addvalues(unsigned r,unsigned p,unsigned l,form t) { ref=r; pos=p; len=l; type=t; } }; struct modifier { unsigned x,y,sd,e; bool p; seqan::CharString inputFile; modifier() : x(1), y(1),e(0),sd(0),p(false) {} }; struct statisticals { unsigned e_value; unsigned standardDegression; statisticals() : standardDegression(0) {} }; typedef std::vector<candidate> candidates; seqan::ArgumentParser::ParseResult commands(modifier &options, int argc, char const ** argv); unsigned generateStandardDegression(candidates &input,int e_value); int saminput(candidates &save, modifier &options, statisticals &stats, std::vector<std::string> &header); int devide(candidates &input,candidates &result,modifier &options,statisticals &stats); int output(std::vector<std::vector<unsigned>> &input,candidates &ref, char *out, std::vector<std::string> &header); int findCluster(candidates &input, std::vector<std::vector<unsigned> > &dest, candidate::form indel); #endif // PEMER_LITE_HEADER_H_
[ "mail@bkahlert.com" ]
mail@bkahlert.com
e5e8bf97b25e9aa1969c16b57a6fadfc97b40037
84cd56effcc82a925af8e8e6ec528be806e45b7d
/src/qt/test/rpcnestedtests.h
1f4ee8a0f4da2bb9a5ab123ef06c6b6680bd5e2d
[ "MIT" ]
permissive
Deimoscoin/deimos
85c2258fe51135e33e272a9c86736a1487871e16
c03a65c72ffe6fadb840bc87e6fd6b4e012def08
refs/heads/master
2021-06-08T02:39:47.495894
2021-05-29T07:22:38
2021-05-29T07:22:38
135,105,359
0
1
null
null
null
null
UTF-8
C++
false
false
557
h
// Copyright (c) 2009-2019 The Bitcoin Core developers // Copyright (c) 2014-2019 The DeimOS Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef DEIMOS_QT_TEST_RPCNESTEDTESTS_H #define DEIMOS_QT_TEST_RPCNESTEDTESTS_H #include <QObject> #include <QTest> #include <txdb.h> #include <txmempool.h> class RPCNestedTests : public QObject { Q_OBJECT private Q_SLOTS: void rpcNestedTests(); }; #endif // DEIMOS_QT_TEST_RPCNESTEDTESTS_H
[ "admin@deimoscoin.org" ]
admin@deimoscoin.org
6e98356665a06ee3be7b8719c115be16c98fc45e
87fe556ebdd1823922372905fd2319c5391f1a0f
/Source/CSUE/CSUEBomb.h
bab45b806b6a4ab83dbdd36f1e222a71489c57cf
[]
no_license
narmour/CSUE
2805a212a65b3d6addcb945d5abc84b3cde91061
bbb0374d5d575bc00c634a8e75c4377c5b4e515d
refs/heads/master
2016-09-14T08:30:17.453002
2016-05-16T07:29:03
2016-05-16T07:29:03
56,551,813
0
0
null
2016-05-16T18:43:25
2016-04-19T00:28:08
C++
UTF-8
C++
false
false
996
h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "GameFramework/Actor.h" #include "CSUEBomb.generated.h" UCLASS() class CSUE_API ACSUEBomb : public AActor { GENERATED_BODY() public: // Sets default values for this actor's properties ACSUEBomb(); // Called when the game starts or when spawned virtual void BeginPlay() override; // Called every frame virtual void Tick( float DeltaSeconds ) override; void checkOverlap(); void bombDefused(); void bombExplode(); UFUNCTION(BlueprintCallable, Category = "bomb") bool isPlanted() { return planted; }; private: UPROPERTY(EditAnywhere, Category = "Mesh") UStaticMeshComponent *bombMesh; UPROPERTY(EditDefaultsOnly, Category = "Effects") UParticleSystem *explosionFX; //function to play explosion effect UParticleSystemComponent *startExplosion(UParticleSystem *particle); FTimerHandle defuseTimer; FTimerHandle bombTimer; bool planted = false; };
[ "n.armour0@gmail.com" ]
n.armour0@gmail.com
854720aa9e431eab1890db973e5400a1b32e3445
ff86d9235f9662a43b3ec7002529e9ea2f1f51b1
/Practice/spoj/coins.cpp
5043df314f460b16e44442e8b46b40d29fa10d17
[]
no_license
virresh/CompetitiveProgrammingCodes
f50cf70bd04dfbadd94a0b67bb97a34c8ada8e68
112c7e9ef6ee60a64a38b7bab46faff097b9b5f2
refs/heads/master
2020-03-13T15:26:25.014234
2018-04-26T16:52:37
2018-04-26T16:52:37
131,176,770
1
0
null
null
null
null
UTF-8
C++
false
false
533
cpp
#include <bits/stdc++.h> using namespace std; #define ll long long #define sz 100000 ll mem[sz]; ll f(ll n) { if(n==1){return 1;} else if(n==0){return 0;} else if(n<sz && mem[n]!=-1) { return mem[n]; } else { ll ans; ans= max(n, (f(n/2) + f(n/3) + f(n/4))); if(n<sz){mem[n]=ans;} return ans; } } int main() { ll n; mem[1]=1; mem[0]=0; memset(mem,-1,sizeof(mem)); while(cin>>n) { cout<<f(n)<<"\n"; } return 0; }
[ "viresh16118@iiitd.ac.in" ]
viresh16118@iiitd.ac.in
3f0203839d1b67aa21e8cce08bcde03dc3f3bde6
a3d6556180e74af7b555f8d47d3fea55b94bcbda
/chrome/browser/ui/webui/side_panel/customize_chrome/customize_chrome_page_handler.cc
1382c0d72d33a5d1dff1babc2fe8b3dcd6747aab
[ "BSD-3-Clause" ]
permissive
chromium/chromium
aaa9eda10115b50b0616d2f1aed5ef35d1d779d6
a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c
refs/heads/main
2023-08-24T00:35:12.585945
2023-08-23T22:01:11
2023-08-23T22:01:11
120,360,765
17,408
7,102
BSD-3-Clause
2023-09-10T23:44:27
2018-02-05T20:55:32
null
UTF-8
C++
false
false
20,317
cc
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/webui/side_panel/customize_chrome/customize_chrome_page_handler.h" #include "base/containers/contains.h" #include "base/metrics/histogram_functions.h" #include "base/metrics/histogram_macros.h" #include "chrome/browser/new_tab_page/modules/new_tab_page_modules.h" #include "chrome/browser/new_tab_page/new_tab_page_util.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/search/background/ntp_background_service_factory.h" #include "chrome/browser/themes/theme_service.h" #include "chrome/browser/themes/theme_service_factory.h" #include "chrome/browser/ui/browser_navigator.h" #include "chrome/browser/ui/browser_navigator_params.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/chrome_select_file_policy.h" #include "chrome/browser/ui/color/chrome_color_id.h" #include "chrome/browser/ui/search/ntp_user_data_types.h" #include "chrome/browser/ui/webui/new_tab_page/ntp_pref_names.h" #include "chrome/browser/ui/webui/side_panel/customize_chrome/customize_chrome_section.h" #include "chrome/common/pref_names.h" #include "chrome/grit/generated_resources.h" #include "components/prefs/pref_service.h" #include "components/prefs/scoped_user_pref_update.h" #include "content/public/browser/web_contents.h" #include "extensions/browser/extension_registry.h" #include "extensions/common/extension.h" #include "mojo/public/cpp/bindings/pending_remote.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/ui_base_features.h" #include "ui/color/color_provider.h" #include "ui/native_theme/native_theme.h" CustomizeChromePageHandler::CustomizeChromePageHandler( mojo::PendingReceiver<side_panel::mojom::CustomizeChromePageHandler> pending_page_handler, mojo::PendingRemote<side_panel::mojom::CustomizeChromePage> pending_page, NtpCustomBackgroundService* ntp_custom_background_service, content::WebContents* web_contents, const std::vector<std::pair<const std::string, int>> module_id_names) : ntp_custom_background_service_(ntp_custom_background_service), profile_(Profile::FromBrowserContext(web_contents->GetBrowserContext())), web_contents_(web_contents), ntp_background_service_( NtpBackgroundServiceFactory::GetForProfile(profile_)), theme_service_(ThemeServiceFactory::GetForProfile(profile_)), module_id_names_(module_id_names), page_(std::move(pending_page)), receiver_(this, std::move(pending_page_handler)) { CHECK(ntp_custom_background_service_); CHECK(theme_service_); CHECK(ntp_background_service_); ntp_background_service_->AddObserver(this); native_theme_observation_.Observe(ui::NativeTheme::GetInstanceForNativeUi()); theme_service_observation_.Observe(theme_service_); pref_change_registrar_.Init(profile_->GetPrefs()); pref_change_registrar_.Add( prefs::kNtpModulesVisible, base::BindRepeating(&CustomizeChromePageHandler::UpdateModulesSettings, base::Unretained(this))); pref_change_registrar_.Add( prefs::kNtpDisabledModules, base::BindRepeating(&CustomizeChromePageHandler::UpdateModulesSettings, base::Unretained(this))); if (IsCartModuleEnabled()) { pref_change_registrar_.Add( prefs::kCartDiscountEnabled, base::BindRepeating(&CustomizeChromePageHandler::UpdateModulesSettings, base::Unretained(this))); } pref_change_registrar_.Add( ntp_prefs::kNtpUseMostVisitedTiles, base::BindRepeating( &CustomizeChromePageHandler::UpdateMostVisitedSettings, base::Unretained(this))); pref_change_registrar_.Add( ntp_prefs::kNtpShortcutsVisible, base::BindRepeating( &CustomizeChromePageHandler::UpdateMostVisitedSettings, base::Unretained(this))); ntp_custom_background_service_observation_.Observe( ntp_custom_background_service_.get()); } CustomizeChromePageHandler::~CustomizeChromePageHandler() { ntp_background_service_->RemoveObserver(this); if (select_file_dialog_) { select_file_dialog_->ListenerDestroyed(); } } void CustomizeChromePageHandler::ScrollToSection( CustomizeChromeSection section) { last_requested_section_ = section; side_panel::mojom::CustomizeChromeSection mojo_section; switch (section) { case CustomizeChromeSection::kUnspecified: // Cannot scroll to unspecified section. return; case CustomizeChromeSection::kAppearance: mojo_section = side_panel::mojom::CustomizeChromeSection::kAppearance; break; case CustomizeChromeSection::kShortcuts: mojo_section = side_panel::mojom::CustomizeChromeSection::kShortcuts; break; case CustomizeChromeSection::kModules: mojo_section = side_panel::mojom::CustomizeChromeSection::kModules; break; } page_->ScrollToSection(mojo_section); } void CustomizeChromePageHandler::SetDefaultColor() { theme_service_->UseDeviceTheme(false); theme_service_->UseDefaultTheme(); } void CustomizeChromePageHandler::SetFollowDeviceTheme(bool follow) { theme_service_->UseDeviceTheme(follow); } void CustomizeChromePageHandler::SetBackgroundImage( const std::string& attribution_1, const std::string& attribution_2, const GURL& attribution_url, const GURL& image_url, const GURL& thumbnail_url, const std::string& collection_id) { ntp_custom_background_service_->SetCustomBackgroundInfo( image_url, thumbnail_url, attribution_1, attribution_2, attribution_url, collection_id); } void CustomizeChromePageHandler::SetDailyRefreshCollectionId( const std::string& collection_id) { // Only populating the |collection_id| turns on refresh daily which overrides // the the selected image. ntp_custom_background_service_->SetCustomBackgroundInfo( /* image_url */ GURL(), /* thumbnail_url */ GURL(), /* attribution_line_1= */ "", /* attribution_line_2= */ "", /* action_url= */ GURL(), collection_id); } void CustomizeChromePageHandler::GetBackgroundCollections( GetBackgroundCollectionsCallback callback) { if (!ntp_background_service_ || background_collections_callback_) { std::move(callback).Run( std::vector<side_panel::mojom::BackgroundCollectionPtr>()); return; } background_collections_request_start_time_ = base::TimeTicks::Now(); background_collections_callback_ = std::move(callback); ntp_background_service_->FetchCollectionInfo(); } void CustomizeChromePageHandler::GetBackgroundImages( const std::string& collection_id, GetBackgroundImagesCallback callback) { if (background_images_callback_) { std::move(background_images_callback_) .Run(std::vector<side_panel::mojom::CollectionImagePtr>()); } if (!ntp_background_service_) { std::move(callback).Run( std::vector<side_panel::mojom::CollectionImagePtr>()); return; } images_request_collection_id_ = collection_id; background_images_request_start_time_ = base::TimeTicks::Now(); background_images_callback_ = std::move(callback); ntp_background_service_->FetchCollectionImageInfo(collection_id); } void CustomizeChromePageHandler::ChooseLocalCustomBackground( ChooseLocalCustomBackgroundCallback callback) { // Early return if the select file dialog is already active. if (select_file_dialog_) { std::move(callback).Run(false); return; } select_file_dialog_ = ui::SelectFileDialog::Create( this, std::make_unique<ChromeSelectFilePolicy>(web_contents_)); ui::SelectFileDialog::FileTypeInfo file_types; file_types.allowed_paths = ui::SelectFileDialog::FileTypeInfo::NATIVE_PATH; file_types.extensions.resize(1); file_types.extensions[0].push_back(FILE_PATH_LITERAL("jpg")); file_types.extensions[0].push_back(FILE_PATH_LITERAL("jpeg")); file_types.extensions[0].push_back(FILE_PATH_LITERAL("png")); file_types.extensions[0].push_back(FILE_PATH_LITERAL("gif")); file_types.extension_description_overrides.push_back( l10n_util::GetStringUTF16(IDS_UPLOAD_IMAGE_FORMAT)); DCHECK(!choose_local_custom_background_callback_); choose_local_custom_background_callback_ = std::move(callback); select_file_dialog_->SelectFile( ui::SelectFileDialog::SELECT_OPEN_FILE, std::u16string(), profile_->last_selected_directory(), &file_types, 0, base::FilePath::StringType(), web_contents_->GetTopLevelNativeWindow(), nullptr); } void CustomizeChromePageHandler::RemoveBackgroundImage() { if (ntp_custom_background_service_) { ntp_custom_background_service_->ResetCustomBackgroundInfo(); } } void CustomizeChromePageHandler::UpdateTheme() { if (ntp_custom_background_service_) { ntp_custom_background_service_->RefreshBackgroundIfNeeded(); } auto theme = side_panel::mojom::Theme::New(); auto custom_background = ntp_custom_background_service_ ? ntp_custom_background_service_->GetCustomBackground() : absl::nullopt; auto background_image = side_panel::mojom::BackgroundImage::New(); if (custom_background.has_value()) { background_image->url = custom_background->custom_background_url; background_image->snapshot_url = custom_background->custom_background_snapshot_url; background_image->is_uploaded_image = custom_background->is_uploaded_image; background_image->title = custom_background->custom_background_attribution_line_1; background_image->collection_id = custom_background->collection_id; background_image->daily_refresh_enabled = custom_background->daily_refresh_enabled; } else { background_image = nullptr; } theme->background_image = std::move(background_image); theme->follow_device_theme = theme_service_->UsingDeviceTheme(); auto user_color = theme_service_->GetUserColor(); // If a user has the GM3 flag enabled but a GM2 theme set they are in a limbo // state between the 2 theme types. We need to get the color of their theme // with GetAutogeneratedThemeColor still until they set a GM3 theme, use the // old way of detecting default, and use the old color tokens to keep an // accurate representation of what the user is seeing. if (features::IsChromeWebuiRefresh2023() && user_color.has_value()) { theme->background_color = web_contents_->GetColorProvider().GetColor(ui::kColorSysInversePrimary); if (user_color.value() != SK_ColorTRANSPARENT) { theme->foreground_color = theme->background_color; } } else { theme->background_color = web_contents_->GetColorProvider().GetColor(kColorNewTabPageBackground); if (!theme_service_->UsingDefaultTheme() && !theme_service_->UsingSystemTheme()) { theme->foreground_color = web_contents_->GetColorProvider().GetColor(ui::kColorFrameActive); } } theme->background_managed_by_policy = ntp_custom_background_service_->IsCustomBackgroundDisabledByPolicy(); if (theme_service_->UsingExtensionTheme()) { const extensions::Extension* theme_extension = extensions::ExtensionRegistry::Get(profile_) ->enabled_extensions() .GetByID(theme_service_->GetThemeID()); if (theme_extension) { auto third_party_theme_info = side_panel::mojom::ThirdPartyThemeInfo::New(); third_party_theme_info->id = theme_extension->id(); third_party_theme_info->name = theme_extension->name(); theme->third_party_theme_info = std::move(third_party_theme_info); } } page_->SetTheme(std::move(theme)); } void CustomizeChromePageHandler::OpenChromeWebStore() { NavigateParams navigate_params( profile_, GURL("https://chrome.google.com/webstore?category=theme"), ui::PAGE_TRANSITION_LINK); navigate_params.window_action = NavigateParams::WindowAction::SHOW_WINDOW; navigate_params.disposition = WindowOpenDisposition::NEW_FOREGROUND_TAB; Navigate(&navigate_params); UMA_HISTOGRAM_ENUMERATION("NewTabPage.ChromeWebStoreOpen", NtpChromeWebStoreOpen::kAppearance); } void CustomizeChromePageHandler::OpenThirdPartyThemePage( const std::string& theme_id) { NavigateParams navigate_params( profile_, GURL("https://chrome.google.com/webstore/detail/" + theme_id), ui::PAGE_TRANSITION_LINK); navigate_params.window_action = NavigateParams::WindowAction::SHOW_WINDOW; navigate_params.disposition = WindowOpenDisposition::NEW_FOREGROUND_TAB; Navigate(&navigate_params); UMA_HISTOGRAM_ENUMERATION("NewTabPage.ChromeWebStoreOpen", NtpChromeWebStoreOpen::kCollections); } void CustomizeChromePageHandler::SetMostVisitedSettings( bool custom_links_enabled, bool visible) { if (IsCustomLinksEnabled() != custom_links_enabled) { profile_->GetPrefs()->SetBoolean(ntp_prefs::kNtpUseMostVisitedTiles, !custom_links_enabled); LogEvent(NTP_CUSTOMIZE_SHORTCUT_TOGGLE_TYPE); } if (IsShortcutsVisible() != visible) { profile_->GetPrefs()->SetBoolean(ntp_prefs::kNtpShortcutsVisible, visible); LogEvent(NTP_CUSTOMIZE_SHORTCUT_TOGGLE_VISIBILITY); } } void CustomizeChromePageHandler::UpdateMostVisitedSettings() { page_->SetMostVisitedSettings(IsCustomLinksEnabled(), IsShortcutsVisible()); } void CustomizeChromePageHandler::SetModulesVisible(bool visible) { profile_->GetPrefs()->SetBoolean(prefs::kNtpModulesVisible, visible); } void CustomizeChromePageHandler::SetModuleDisabled(const std::string& module_id, bool disabled) { ScopedListPrefUpdate update(profile_->GetPrefs(), prefs::kNtpDisabledModules); base::Value::List& list = update.Get(); base::Value module_id_value(module_id); if (disabled) { if (!base::Contains(list, module_id_value)) { list.Append(std::move(module_id_value)); } } else { list.EraseValue(module_id_value); } } void CustomizeChromePageHandler::UpdateModulesSettings() { std::vector<std::string> disabled_module_ids; for (const auto& id : profile_->GetPrefs()->GetList(prefs::kNtpDisabledModules)) { disabled_module_ids.push_back(id.GetString()); } std::vector<side_panel::mojom::ModuleSettingsPtr> modules_settings; for (const auto& id_name_pair : module_id_names_) { auto module_settings = side_panel::mojom::ModuleSettings::New(); module_settings->id = id_name_pair.first; module_settings->name = l10n_util::GetStringUTF8(id_name_pair.second); module_settings->enabled = !base::Contains(disabled_module_ids, module_settings->id); modules_settings.push_back(std::move(module_settings)); } page_->SetModulesSettings( std::move(modules_settings), profile_->GetPrefs()->IsManagedPreference(prefs::kNtpModulesVisible), profile_->GetPrefs()->GetBoolean(prefs::kNtpModulesVisible)); } void CustomizeChromePageHandler::UpdateScrollToSection() { ScrollToSection(last_requested_section_); } void CustomizeChromePageHandler::LogEvent(NTPLoggingEventType event) { switch (event) { case NTP_CUSTOMIZE_SHORTCUT_TOGGLE_TYPE: UMA_HISTOGRAM_ENUMERATION( "NewTabPage.CustomizeShortcutAction", CustomizeShortcutAction::CUSTOMIZE_SHORTCUT_ACTION_TOGGLE_TYPE); break; case NTP_CUSTOMIZE_SHORTCUT_TOGGLE_VISIBILITY: UMA_HISTOGRAM_ENUMERATION( "NewTabPage.CustomizeShortcutAction", CustomizeShortcutAction::CUSTOMIZE_SHORTCUT_ACTION_TOGGLE_VISIBILITY); break; default: break; } } bool CustomizeChromePageHandler::IsCustomLinksEnabled() const { return !profile_->GetPrefs()->GetBoolean(ntp_prefs::kNtpUseMostVisitedTiles); } bool CustomizeChromePageHandler::IsShortcutsVisible() const { return profile_->GetPrefs()->GetBoolean(ntp_prefs::kNtpShortcutsVisible); } void CustomizeChromePageHandler::OnNativeThemeUpdated( ui::NativeTheme* observed_theme) { UpdateTheme(); } void CustomizeChromePageHandler::OnThemeChanged() { UpdateTheme(); } void CustomizeChromePageHandler::OnCustomBackgroundImageUpdated() { OnThemeChanged(); } void CustomizeChromePageHandler::OnNtpCustomBackgroundServiceShuttingDown() { ntp_custom_background_service_observation_.Reset(); ntp_custom_background_service_ = nullptr; } void CustomizeChromePageHandler::OnCollectionInfoAvailable() { if (!background_collections_callback_) { return; } base::TimeDelta duration = base::TimeTicks::Now() - background_collections_request_start_time_; UMA_HISTOGRAM_MEDIUM_TIMES( "NewTabPage.BackgroundService.Collections.RequestLatency", duration); // Any response where no collections are returned is considered a failure. if (ntp_background_service_->collection_info().empty()) { UMA_HISTOGRAM_MEDIUM_TIMES( "NewTabPage.BackgroundService.Collections.RequestLatency.Failure", duration); } else { UMA_HISTOGRAM_MEDIUM_TIMES( "NewTabPage.BackgroundService.Collections.RequestLatency.Success", duration); } std::vector<side_panel::mojom::BackgroundCollectionPtr> collections; for (const auto& info : ntp_background_service_->collection_info()) { auto collection = side_panel::mojom::BackgroundCollection::New(); collection->id = info.collection_id; collection->label = info.collection_name; collection->preview_image_url = GURL(info.preview_image_url); collections.push_back(std::move(collection)); } std::move(background_collections_callback_).Run(std::move(collections)); } void CustomizeChromePageHandler::OnCollectionImagesAvailable() { if (!background_images_callback_) { return; } base::TimeDelta duration = base::TimeTicks::Now() - background_images_request_start_time_; UMA_HISTOGRAM_MEDIUM_TIMES( "NewTabPage.BackgroundService.Images.RequestLatency", duration); // Any response where no images are returned is considered a failure. if (ntp_background_service_->collection_images().empty()) { UMA_HISTOGRAM_MEDIUM_TIMES( "NewTabPage.BackgroundService.Images.RequestLatency.Failure", duration); } else { UMA_HISTOGRAM_MEDIUM_TIMES( "NewTabPage.BackgroundService.Images.RequestLatency.Success", duration); } std::vector<side_panel::mojom::CollectionImagePtr> images; if (ntp_background_service_->collection_images().empty()) { std::move(background_images_callback_).Run(std::move(images)); return; } auto collection_id = ntp_background_service_->collection_images()[0].collection_id; for (const auto& info : ntp_background_service_->collection_images()) { DCHECK(info.collection_id == collection_id); auto image = side_panel::mojom::CollectionImage::New(); image->attribution_1 = !info.attribution.empty() ? info.attribution[0] : ""; image->attribution_2 = info.attribution.size() > 1 ? info.attribution[1] : ""; image->attribution_url = info.attribution_action_url; image->image_url = info.image_url; image->preview_image_url = info.thumbnail_image_url; image->collection_id = collection_id; images.push_back(std::move(image)); } std::move(background_images_callback_).Run(std::move(images)); } void CustomizeChromePageHandler::OnNextCollectionImageAvailable() {} void CustomizeChromePageHandler::OnNtpBackgroundServiceShuttingDown() { ntp_background_service_->RemoveObserver(this); ntp_background_service_ = nullptr; } void CustomizeChromePageHandler::FileSelected(const base::FilePath& path, int index, void* params) { DCHECK(choose_local_custom_background_callback_); if (ntp_custom_background_service_) { theme_service_->UseDefaultTheme(); profile_->set_last_selected_directory(path.DirName()); ntp_custom_background_service_->SelectLocalBackgroundImage(path); } select_file_dialog_ = nullptr; std::move(choose_local_custom_background_callback_).Run(true); } void CustomizeChromePageHandler::FileSelectionCanceled(void* params) { DCHECK(choose_local_custom_background_callback_); select_file_dialog_ = nullptr; std::move(choose_local_custom_background_callback_).Run(false); }
[ "chromium-scoped@luci-project-accounts.iam.gserviceaccount.com" ]
chromium-scoped@luci-project-accounts.iam.gserviceaccount.com
737c854008a89282a31627f025af12457fd80a2b
13c9b902cb7f03034ae89f0bcca8d9e852964793
/picturepublisher.cpp
4bff971b97c4e5aa514ad52bd9b298fcd29e6c7d
[]
no_license
xunshuidezhu/lidar
1110e9d456d5d5b36e9184513d62861cdd86ab1f
cfb8367029cc23528cd51cd301c6ec649fafc5cb
refs/heads/master
2020-05-30T11:13:53.970736
2019-06-01T05:44:13
2019-06-01T05:44:13
189,695,109
0
0
null
null
null
null
UTF-8
C++
false
false
799
cpp
#include <ros/ros.h> #include <image_transport/image_transport.h> #include <opencv2/highgui/highgui.hpp> #include <cv_bridge/cv_bridge.h> #include <assert.h> int main(int argc, char** argv) { ros::init(argc, argv, "image_publisher"); ros::NodeHandle image_pub_n; image_transport::ImageTransport it(image_pub_n); image_transport::Publisher pub = it.advertise("camera/image", 1); cv::Mat image = cv::imread(argv[1], CV_LOAD_IMAGE_COLOR); sensor_msgs::ImagePtr msg = cv_bridge::CvImage(std_msgs::Header(), "bgr8", image).toImageMsg(); ros::Rate loop_rate(5); while (1) { if (!image_pub_n.ok()) { perror("image_pub_n pub error"); break; } pub.publish(msg); ros::spinOnce(); loop_rate.sleep(); } }
[ "1816703663@qq.com" ]
1816703663@qq.com
6c5b60fdfedf31606a0732364dc6e2077c98daa3
b7e793cd4f981bdea10cae69fd423bae291d7e0d
/storage.h
921558bd3ac629c454cdbd4cfaefb39ce71e45df
[]
no_license
aifei7320/boardServer
9ee8fcd959acbfa6f1ecda9b91c21a6bda911b7f
e55785d3e625997de92bd7b35a6d674395a425b1
refs/heads/master
2021-01-20T14:59:11.401582
2017-04-08T10:15:00
2017-04-08T10:15:00
82,788,627
0
0
null
null
null
null
UTF-8
C++
false
false
1,273
h
/************************************************************************* > File Name: storage.h > Author: zxf > Mail: zhengxiaofeng333@163.com > Created Time: 2017年02月25日 星期六 11时53分05秒 ************************************************************************/ #ifndef _STORAGE_H_ #define _STORAGE_H_ #include <QThread> #include <QString> #include <QByteArray> #include <QSemaphore> #include <QVector> #include <QSqlQuery> #include <QDebug> #include <QMutex> #include <QWaitCondition> #include <QSqlError> #include <iostream> #include <unistd.h> struct boardInfo{ qint32 magicNum = -1; QString serialNum; qreal length = -1; qreal width = -1; qreal realWidth = 0.0; qreal realLength = 0.0; qint32 total = -1; qint32 ngcount = -1; qint32 okcount = -1; qint8 lengthMatch = -1; qint8 widthMatch = -1; qint8 boardPerfect = -1; qint16 devNum = -1; }; Q_DECLARE_METATYPE(boardInfo) typedef struct boardInfo page; using namespace std; class Storage : public QThread { Q_OBJECT public: Storage(QObject *parent=0); void stop(){stopRunning = false;} protected: void run()Q_DECL_OVERRIDE; private: bool stopRunning; private Q_SLOTS: void deletethis(); }; #endif
[ "zhengxiaofeng333@163.com" ]
zhengxiaofeng333@163.com
d182d40af8861aacf550d51e88f36fe3467ac460
aee8f8efc9e0653eeb2f5bb084bbe0b55607b7df
/ready/III/Sorter.h
e748ba80bab66971510b13879e95df0d10922ec0
[]
no_license
iamclock/C-algorithms
2bcd76186fad1da0b1e9197105dda7fb933362dc
79dda3c5b93584f26c5247b9beab1b66adf80ee3
refs/heads/master
2021-04-06T19:58:58.477389
2018-03-15T03:39:00
2018-03-15T03:39:00
125,250,874
0
0
null
null
null
null
UTF-8
C++
false
false
847
h
#ifndef SORTER_H #define SORTER_H #include "Array.h" #include <cstdio> #include <assert.h> template <class ArrayType> void swap(ArrayType *a, ArrayType *b); template <class ArrayType> class Sorter{ public: enum SortType{ shell=0, quick=1, bubble=2, selection=3, insertion=4, heap=5 }; Sorter(SortType enum_sort=shell); void sort(Array<ArrayType> &a); //sort с копированием массива void change_type(SortType enum_temp); private: SortType Sort; void Shell(Array<ArrayType> &a); void Quick(Array<ArrayType> &a, int l, int r); void Bubble(Array<ArrayType> &a); void Selection(Array<ArrayType> &a); void Insertion(Array<ArrayType> &a); void Piramid(Array<ArrayType> &a); void HeapSort(Array<ArrayType> &a); void shiftDown(Array<ArrayType> &a, int i, int j); }; #endif
[ "double7@mail.ru" ]
double7@mail.ru
851886de7967003d147475db61e11fb43d6bc68a
b7893fb307f6aef65b0ae69ffdc3d6d8aa75907d
/cocos/editor-support/cocosbuilder/CCParticleSystemQuadLoader.cpp
3251c58c1d3ed894d410c0d3c2faabcd637f376a
[ "MIT" ]
permissive
fusijie/cocos2d-x-lite
794314a4f4005c8fc083ca212389b78929895bc0
bcb288c02205a0c70d3e05febffe095eb7cf4a82
refs/heads/master
2021-01-19T07:54:31.768900
2016-05-04T07:44:30
2016-05-04T07:44:30
58,064,994
1
0
null
2016-05-04T15:56:12
2016-05-04T15:56:12
null
UTF-8
C++
false
false
7,128
cpp
#include "CCParticleSystemQuadLoader.h" using namespace cocos2d; #define PROPERTY_EMITERMODE "emitterMode" #define PROPERTY_POSVAR "posVar" #define PROPERTY_EMISSIONRATE "emissionRate" #define PROPERTY_DURATION "duration" #define PROPERTY_TOTALPARTICLES "totalParticles" #define PROPERTY_LIFE "life" #define PROPERTY_STARTSIZE "startSize" #define PROPERTY_ENDSIZE "endSize" #define PROPERTY_STARTSPIN "startSpin" #define PROPERTY_ENDSPIN "endSpin" #define PROPERTY_ANGLE "angle" #define PROPERTY_STARTCOLOR "startColor" #define PROPERTY_ENDCOLOR "endColor" #define PROPERTY_BLENDFUNC "blendFunc" #define PROPERTY_GRAVITY "gravity" #define PROPERTY_SPEED "speed" #define PROPERTY_TANGENTIALACCEL "tangentialAccel" #define PROPERTY_RADIALACCEL "radialAccel" #define PROPERTY_TEXTURE "texture" #define PROPERTY_STARTRADIUS "startRadius" #define PROPERTY_ENDRADIUS "endRadius" #define PROPERTY_ROTATEPERSECOND "rotatePerSecond" namespace cocosbuilder { void ParticleSystemQuadLoader::onHandlePropTypeIntegerLabeled(Node * pNode, Node * pParent, const char * pPropertyName, int pIntegerLabeled, CCBReader * ccbReader) { if(strcmp(pPropertyName, PROPERTY_EMITERMODE) == 0) { ((ParticleSystemQuad *)pNode)->setEmitterMode((ParticleSystem::Mode)pIntegerLabeled); } else { NodeLoader::onHandlePropTypeIntegerLabeled(pNode, pParent, pPropertyName, pIntegerLabeled, ccbReader); } } void ParticleSystemQuadLoader::onHandlePropTypePoint(Node * pNode, Node * pParent, const char * pPropertyName, Vec2 pPoint, CCBReader * ccbReader) { if(strcmp(pPropertyName, PROPERTY_POSVAR) == 0) { ((ParticleSystemQuad *)pNode)->setPosVar(pPoint); } else if(strcmp(pPropertyName, PROPERTY_GRAVITY) == 0) { ((ParticleSystemQuad *)pNode)->setGravity(pPoint); } else { NodeLoader::onHandlePropTypePoint(pNode, pParent, pPropertyName, pPoint, ccbReader); } } void ParticleSystemQuadLoader::onHandlePropTypeFloat(Node * pNode, Node * pParent, const char * pPropertyName, float pFloat, CCBReader * ccbReader) { if(strcmp(pPropertyName, PROPERTY_EMISSIONRATE) == 0) { ((ParticleSystemQuad *)pNode)->setEmissionRate(pFloat); } else if(strcmp(pPropertyName, PROPERTY_DURATION) == 0) { ((ParticleSystemQuad *)pNode)->setDuration(pFloat); } else { NodeLoader::onHandlePropTypeFloat(pNode, pParent, pPropertyName, pFloat, ccbReader); } } void ParticleSystemQuadLoader::onHandlePropTypeInteger(Node * pNode, Node * pParent, const char * pPropertyName, int pInteger, CCBReader * ccbReader) { if(strcmp(pPropertyName, PROPERTY_TOTALPARTICLES) == 0) { ((ParticleSystemQuad *)pNode)->setTotalParticles(pInteger); } else { NodeLoader::onHandlePropTypeInteger(pNode, pParent, pPropertyName, pInteger, ccbReader); } } void ParticleSystemQuadLoader::onHandlePropTypeFloatVar(Node * pNode, Node * pParent, const char * pPropertyName, float * pFloatVar, CCBReader * ccbReader) { if(strcmp(pPropertyName, PROPERTY_LIFE) == 0) { ((ParticleSystemQuad *)pNode)->setLife(pFloatVar[0]); ((ParticleSystemQuad *)pNode)->setLifeVar(pFloatVar[1]); } else if(strcmp(pPropertyName, PROPERTY_STARTSIZE) == 0) { ((ParticleSystemQuad *)pNode)->setStartSize(pFloatVar[0]); ((ParticleSystemQuad *)pNode)->setStartSizeVar(pFloatVar[1]); } else if(strcmp(pPropertyName, PROPERTY_ENDSIZE) == 0) { ((ParticleSystemQuad *)pNode)->setEndSize(pFloatVar[0]); ((ParticleSystemQuad *)pNode)->setEndSizeVar(pFloatVar[1]); } else if(strcmp(pPropertyName, PROPERTY_STARTSPIN) == 0) { ((ParticleSystemQuad *)pNode)->setStartSpin(pFloatVar[0]); ((ParticleSystemQuad *)pNode)->setStartSpinVar(pFloatVar[1]); } else if(strcmp(pPropertyName, PROPERTY_ENDSPIN) == 0) { ((ParticleSystemQuad *)pNode)->setEndSpin(pFloatVar[0]); ((ParticleSystemQuad *)pNode)->setEndSpinVar(pFloatVar[1]); } else if(strcmp(pPropertyName, PROPERTY_ANGLE) == 0) { ((ParticleSystemQuad *)pNode)->setAngle(pFloatVar[0]); ((ParticleSystemQuad *)pNode)->setAngleVar(pFloatVar[1]); } else if(strcmp(pPropertyName, PROPERTY_SPEED) == 0) { ((ParticleSystemQuad *)pNode)->setSpeed(pFloatVar[0]); ((ParticleSystemQuad *)pNode)->setSpeedVar(pFloatVar[1]); } else if(strcmp(pPropertyName, PROPERTY_TANGENTIALACCEL) == 0) { ((ParticleSystemQuad *)pNode)->setTangentialAccel(pFloatVar[0]); ((ParticleSystemQuad *)pNode)->setTangentialAccelVar(pFloatVar[1]); } else if(strcmp(pPropertyName, PROPERTY_RADIALACCEL) == 0) { ((ParticleSystemQuad *)pNode)->setRadialAccel(pFloatVar[0]); ((ParticleSystemQuad *)pNode)->setRadialAccelVar(pFloatVar[1]); } else if(strcmp(pPropertyName, PROPERTY_STARTRADIUS) == 0) { ((ParticleSystemQuad *)pNode)->setStartRadius(pFloatVar[0]); ((ParticleSystemQuad *)pNode)->setStartRadiusVar(pFloatVar[1]); } else if(strcmp(pPropertyName, PROPERTY_ENDRADIUS) == 0) { ((ParticleSystemQuad *)pNode)->setEndRadius(pFloatVar[0]); ((ParticleSystemQuad *)pNode)->setEndRadiusVar(pFloatVar[1]); } else if(strcmp(pPropertyName, PROPERTY_ROTATEPERSECOND) == 0) { ((ParticleSystemQuad *)pNode)->setRotatePerSecond(pFloatVar[0]); ((ParticleSystemQuad *)pNode)->setRotatePerSecondVar(pFloatVar[1]); } else { NodeLoader::onHandlePropTypeFloatVar(pNode, pParent, pPropertyName, pFloatVar, ccbReader); } } void ParticleSystemQuadLoader::onHandlePropTypeColor4FVar(Node * pNode, Node * pParent, const char * pPropertyName, Color4F * pColor4FVar, CCBReader * ccbReader) { if(strcmp(pPropertyName, PROPERTY_STARTCOLOR) == 0) { ((ParticleSystemQuad *)pNode)->setStartColor(pColor4FVar[0]); ((ParticleSystemQuad *)pNode)->setStartColorVar(pColor4FVar[1]); } else if(strcmp(pPropertyName, PROPERTY_ENDCOLOR) == 0) { ((ParticleSystemQuad *)pNode)->setEndColor(pColor4FVar[0]); ((ParticleSystemQuad *)pNode)->setEndColorVar(pColor4FVar[1]); } else { NodeLoader::onHandlePropTypeColor4FVar(pNode, pParent, pPropertyName, pColor4FVar, ccbReader); } } void ParticleSystemQuadLoader::onHandlePropTypeBlendFunc(Node * pNode, Node * pParent, const char * pPropertyName, BlendFunc pBlendFunc, CCBReader * ccbReader) { if(strcmp(pPropertyName, PROPERTY_BLENDFUNC) == 0) { ((ParticleSystemQuad *)pNode)->setBlendFunc(pBlendFunc); } else { NodeLoader::onHandlePropTypeBlendFunc(pNode, pParent, pPropertyName, pBlendFunc, ccbReader); } } void ParticleSystemQuadLoader::onHandlePropTypeTexture(Node * pNode, Node * pParent, const char * pPropertyName, Texture2D * pTexture2D, CCBReader * ccbReader) { if(strcmp(pPropertyName, PROPERTY_TEXTURE) == 0) { static_cast<ParticleSystemQuad*>(pNode)->setTexture(pTexture2D); if(pTexture2D) { static_cast<ParticleSystemQuad*>(pNode)->setBlendAdditive(true); } } else { NodeLoader::onHandlePropTypeTexture(pNode, pParent, pPropertyName, pTexture2D, ccbReader); } } }
[ "wenhai.lin@chukong-inc.com" ]
wenhai.lin@chukong-inc.com
fea668bf848c4a4d73ed0ba5812a597b5e3e5783
8bff2eb3b352c0286bced00af7eabbfe6216689d
/serwer/repozytorium.cpp
10a607d3eece73d0a244f36ad020981f772d5412
[]
no_license
hania1441/Projekt-SK
f094f07de13f0ec80883037c1266b0efed6386e1
7f3a158a1ecb69be2d0242061e94ce89432fc8dc
refs/heads/master
2020-04-09T08:25:01.777430
2015-04-14T21:46:01
2015-04-14T21:46:01
33,951,730
0
0
null
null
null
null
UTF-8
C++
false
false
5,741
cpp
/* * File: repozytorium.cpp * Author: mariuszl * */ #include "repozytorium.h" repozytorium::repozytorium() { uzytkownicy = new vector<User*>; document.push_back(77); document.push_back(65); document.push_back(77); document.push_back(65); } repozytorium::~repozytorium() { } void repozytorium::addUser(User* newUser) { string nazwa = inet_ntoa(newUser->userAdress.sin_addr); newUser->cursorPosition = getDocumentSize(); for(int i = 0; i < getUzytkownicyCount(); i++) { if(inet_ntoa(uzytkownicy->at(i)->userAdress.sin_addr) == nazwa) { uzytkownicy->at(i) = newUser; return; } } uzytkownicy->push_back(newUser); } int* repozytorium::getDocument() { int* doc = new int[getDocumentSize()]; for(int i = 0; i < getDocumentSize(); ++i) { if(document.at(i) == 10) doc[i] = 32; else doc[i] = document.at(i); } return doc; } int repozytorium::getDocumentSize() { return document.size(); } int repozytorium::getUzytkownicyCount() { return uzytkownicy->size(); } void repozytorium::addLetter(int letter, int tryb, string user, int xMax) { int position = getPosition(user); lastChange.pozycja = position; lastChange.tryb = tryb; lastChange.znak = letter; if(lastChange.znak == 127) { int i = 1; vector<int>::iterator it = document.begin(); while( i < position) { it++; i++; } document.erase(it); changePosition(position, -1); lastChange.rozmiar = getDocumentSize(); sendChangeToAll(user); } else if(lastChange.znak == 10) { int i = 0; vector<int>::iterator it = document.begin(); cout<<position<<endl; while( i < position) { it++; i++; } int ile = i = (position % xMax); for(; i < xMax; i++) { cout<<i<<endl; if(position < getDocumentSize()) { it = document.insert(it, 10); } else document.push_back(10); changePosition(position, 1); position ++; } cout<<position<<endl; dopelnijEnter(position, xMax, ile); lastChange.rozmiar = getDocumentSize(); cout<<"wyslany rozmiar "<< lastChange.rozmiar<<endl; sendChangeToAll(user); } else if(tryb == CHANGE) { if(position < getDocumentSize()) { document.at(position) = letter; changeCursorPosition(user, 1); } else { document.push_back(letter); changePosition(position, 1); } lastChange.rozmiar = getDocumentSize(); sendChangeToAll(user); } else if(tryb == INSERT) { int i = 0; vector<int>::iterator it = document.begin(); while( i < position) { it++; i++; } if(position < getDocumentSize()) { document.insert(it, letter); changePosition(position, 1); } else { document.push_back(letter); changePosition(position, 1); } lastChange.rozmiar = getDocumentSize(); sendChangeToAll(user); } } void repozytorium::sendChangeToAll(string wlasciciel) { for(int i = 0; i < getUzytkownicyCount(); ++i) { cout<<inet_ntoa(uzytkownicy->at(i)->userAdress.sin_addr)<<endl; if(inet_ntoa(uzytkownicy->at(i)->userAdress.sin_addr) == wlasciciel) { lastChange.wlasciciel = true; } else { lastChange.wlasciciel = false; } write(uzytkownicy->at(i)->userSocket, &lastChange, sizeof(Change)); } } int repozytorium::getPosition(string user) { for(int i = 0; i < getUzytkownicyCount(); ++i) { if(inet_ntoa(uzytkownicy->at(i)->userAdress.sin_addr ) == user) { return uzytkownicy->at(i)->cursorPosition; } } return 0; } void repozytorium::changePosition(int za, int o_ile) { for(int i = 0; i < getUzytkownicyCount(); ++i) { if(uzytkownicy->at(i)->cursorPosition >= za) { uzytkownicy->at(i)->cursorPosition += o_ile; } } } void repozytorium::changeCursorPosition(string user, int offset) { cout<<user<<endl; for(int i = 0; i < getUzytkownicyCount(); ++i) { if(inet_ntoa(uzytkownicy->at(i)->userAdress.sin_addr ) == user) { uzytkownicy->at(i)->cursorPosition += offset; break; } } for(int i = 0; i < getUzytkownicyCount(); ++i) { cout<<inet_ntoa(uzytkownicy->at(i)->userAdress.sin_addr)<<endl; cout<< uzytkownicy->at(i)->cursorPosition <<endl; } } void repozytorium::dopelnijEnter(int position, int xMax, int ile) { int pom = 1; position++; int odniesienie = position + xMax - ile; while((pom <= xMax) && (position < getDocumentSize()) && (position < odniesienie)) { position++; pom++; } if(position >= getDocumentSize()) return; int i = 0; vector<int>::iterator it = document.begin(); cout<<position<<endl; while( i < position) { it++; i++; } it--; cout<<"zaczynam wstawianie na pozycji "<< position<<endl; while (pom <= xMax) { it = document.insert(it, 10); changePosition(position, 1); position ++; pom++; } cout<<"koncze wstawianie na pozycji "<< position<<endl; }
[ "hania1441@gmail.com" ]
hania1441@gmail.com
2aaff38c5bb04c7f74703a6391dd288849c4e20e
4d623ea7a585e58e4094c41dc212f60ba0aec5ea
/C_Three_Parts_of_the_Array.cpp
54ab0a74f417a1a5d12a41d65567252c26cfd3cd
[]
no_license
akshit-04/CPP-Codes
624aadeeec35bf608ef4e83f1020b7b54d992203
ede0766d65df0328f7544cadb3f8ff0431147386
refs/heads/main
2023-08-30T13:28:14.748412
2021-11-19T12:04:43
2021-11-19T12:04:43
429,779,083
0
0
null
null
null
null
UTF-8
C++
false
false
449
cpp
#include<bits/stdc++.h> #define ll long long using namespace std; int main() { int n; cin>>n; ll a[n],left=0,right=0,ans=0; for(int i=0;i<n;i++) cin>>a[i]; //psum[0]=a[0]; int i=0,k=n-1; bool flag=false; while(i<=k) { if(left>right) right+=a[k--]; else { left+=a[i++]; } if(left==right) ans=left; } cout<<ans; }
[ "ishu.akshitgarg@gmail.com" ]
ishu.akshitgarg@gmail.com
8155a917a09f8f18f93630923e21ab53ab3e77ab
19eb97436a3be9642517ea9c4095fe337fd58a00
/private/shell/browseui/autocomp.cpp
e84046abf1e6e94cddc331aa1457b1b3b005254c
[]
no_license
oturan-boga/Windows2000
7d258fd0f42a225c2be72f2b762d799bd488de58
8b449d6659840b6ba19465100d21ca07a0e07236
refs/heads/main
2023-04-09T23:13:21.992398
2021-04-22T11:46:21
2021-04-22T11:46:21
360,495,781
2
0
null
null
null
null
UTF-8
C++
false
false
135,631
cpp
// Copyright 1996-98 Microsoft #include "priv.h" #include "sccls.h" #include "autocomp.h" #include "dbgmem.h" #include "itbar.h" #include "address.h" #include "addrlist.h" #include "resource.h" #include "mluisupp.h" #ifdef UNIX #include "unixstuff.h" #endif #include "apithk.h" extern HRESULT CACLMRU_CreateInstance(IUnknown *punkOuter, IUnknown **ppunk, LPCOBJECTINFO poi, LPCTSTR pszMRU); #define WZ_REGKEY_QUICKCOMPLETE L"Software\\Microsoft\\Internet Explorer\\Toolbar\\QuickComplete" #define WZ_DEFAULTQUICKCOMPLETE L"http://www.%s.com" // Statics const static TCHAR c_szAutoDefQuickComp[] = TEXT("%s"); const static TCHAR c_szAutoCompleteProp[] = TEXT("CAutoComplete_This"); const static TCHAR c_szParentWindowProp[] = TEXT("CParentWindow_This"); const static TCHAR c_szAutoSuggest[] = TEXT("AutoSuggest Drop-Down"); const static TCHAR c_szAutoSuggestTitle[] = TEXT("Internet Explorer"); BOOL CAutoComplete::s_fNoActivate = FALSE; HWND CAutoComplete::s_hwndDropDown = NULL; HHOOK CAutoComplete::s_hhookMouse = NULL; #define MAX_QUICK_COMPLETE_STRING 64 #define LISTVIEW_COLUMN_WIDTH 30000 // // FLAGS for dwFlags // #define ACF_RESET 0x00000000 #define ACF_IGNOREUPDOWN 0x00000004 #define URL_SEPARATOR_CHAR TEXT('/') #ifdef UNIX #define DIR_SEPARATOR_CHAR TEXT('/') #define DIR_SEPARATOR_STRING TEXT("/") #else #define DIR_SEPARATOR_CHAR TEXT('\\') #define DIR_SEPARATOR_STRING TEXT("\\") #endif ///////////////////////////////////////////////////////////////////////////// // Line Break Character Table // // This was swipped from mlang. Special break characters added for URLs // have an "IE:" in the comment. Note that this table must be sorted! const WCHAR g_szBreakChars[] = { 0x0009, // TAB 0x0020, // SPACE 0x0021, // IE: ! 0x0022, // IE: " 0x0023, // IE: # 0x0024, // IE: $ 0x0025, // IE: % 0x0026, // IE: & 0x0027, // IE: ' 0x0028, // LEFT PARENTHESIS 0x0029, // RIGHT PARENTHESIS 0x002A, // IE: * 0x002B, // IE: + 0x002C, // IE: , 0x002D, // HYPHEN 0x002E, // IE: . 0x002F, // IE: / 0x003A, // IE: : 0x003B, // IE: ; 0x003C, // IE: < 0x003D, // IE: = 0x003E, // IE: > 0x003F, // IE: ? 0x0040, // IE: @ 0x005B, // LEFT SQUARE BRACKET 0x005C, // IE: '\' 0x005D, // RIGHT SQUARE BRACKET 0x005E, // IE: ^ 0x005F, // IE: _ 0x0060, // IE:` 0x007B, // LEFT CURLY BRACKET 0x007C, // IE: | 0x007D, // RIGHT CURLY BRACKET 0x007E, // IE: ~ 0x00AB, // LEFT-POINTING DOUBLE ANGLE QUOTATION MARK 0x00AD, // OPTIONAL HYPHEN 0x00BB, // RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK 0x02C7, // CARON 0x02C9, // MODIFIER LETTER MACRON 0x055D, // ARMENIAN COMMA 0x060C, // ARABIC COMMA 0x2002, // EN SPACE 0x2003, // EM SPACE 0x2004, // THREE-PER-EM SPACE 0x2005, // FOUR-PER-EM SPACE 0x2006, // SIX-PER-EM SPACE 0x2007, // FIGURE SPACE 0x2008, // PUNCTUATION SPACE 0x2009, // THIN SPACE 0x200A, // HAIR SPACE 0x200B, // ZERO WIDTH SPACE 0x2013, // EN DASH 0x2014, // EM DASH 0x2016, // DOUBLE VERTICAL LINE 0x2018, // LEFT SINGLE QUOTATION MARK 0x201C, // LEFT DOUBLE QUOTATION MARK 0x201D, // RIGHT DOUBLE QUOTATION MARK 0x2022, // BULLET 0x2025, // TWO DOT LEADER 0x2026, // HORIZONTAL ELLIPSIS 0x2027, // HYPHENATION POINT 0x2039, // SINGLE LEFT-POINTING ANGLE QUOTATION MARK 0x203A, // SINGLE RIGHT-POINTING ANGLE QUOTATION MARK 0x2045, // LEFT SQUARE BRACKET WITH QUILL 0x2046, // RIGHT SQUARE BRACKET WITH QUILL 0x207D, // SUPERSCRIPT LEFT PARENTHESIS 0x207E, // SUPERSCRIPT RIGHT PARENTHESIS 0x208D, // SUBSCRIPT LEFT PARENTHESIS 0x208E, // SUBSCRIPT RIGHT PARENTHESIS 0x226A, // MUCH LESS THAN 0x226B, // MUCH GREATER THAN 0x2574, // BOX DRAWINGS LIGHT LEFT 0x3001, // IDEOGRAPHIC COMMA 0x3002, // IDEOGRAPHIC FULL STOP 0x3003, // DITTO MARK 0x3005, // IDEOGRAPHIC ITERATION MARK 0x3008, // LEFT ANGLE BRACKET 0x3009, // RIGHT ANGLE BRACKET 0x300A, // LEFT DOUBLE ANGLE BRACKET 0x300B, // RIGHT DOUBLE ANGLE BRACKET 0x300C, // LEFT CORNER BRACKET 0x300D, // RIGHT CORNER BRACKET 0x300E, // LEFT WHITE CORNER BRACKET 0x300F, // RIGHT WHITE CORNER BRACKET 0x3010, // LEFT BLACK LENTICULAR BRACKET 0x3011, // RIGHT BLACK LENTICULAR BRACKET 0x3014, // LEFT TORTOISE SHELL BRACKET 0x3015, // RIGHT TORTOISE SHELL BRACKET 0x3016, // LEFT WHITE LENTICULAR BRACKET 0x3017, // RIGHT WHITE LENTICULAR BRACKET 0x3018, // LEFT WHITE TORTOISE SHELL BRACKET 0x3019, // RIGHT WHITE TORTOISE SHELL BRACKET 0x301A, // LEFT WHITE SQUARE BRACKET 0x301B, // RIGHT WHITE SQUARE BRACKET 0x301D, // REVERSED DOUBLE PRIME QUOTATION MARK 0x301E, // DOUBLE PRIME QUOTATION MARK 0x3041, // HIRAGANA LETTER SMALL A 0x3043, // HIRAGANA LETTER SMALL I 0x3045, // HIRAGANA LETTER SMALL U 0x3047, // HIRAGANA LETTER SMALL E 0x3049, // HIRAGANA LETTER SMALL O 0x3063, // HIRAGANA LETTER SMALL TU 0x3083, // HIRAGANA LETTER SMALL YA 0x3085, // HIRAGANA LETTER SMALL YU 0x3087, // HIRAGANA LETTER SMALL YO 0x308E, // HIRAGANA LETTER SMALL WA 0x309B, // KATAKANA-HIRAGANA VOICED SOUND MARK 0x309C, // KATAKANA-HIRAGANA SEMI-VOICED SOUND MARK 0x309D, // HIRAGANA ITERATION MARK 0x309E, // HIRAGANA VOICED ITERATION MARK 0x30A1, // KATAKANA LETTER SMALL A 0x30A3, // KATAKANA LETTER SMALL I 0x30A5, // KATAKANA LETTER SMALL U 0x30A7, // KATAKANA LETTER SMALL E 0x30A9, // KATAKANA LETTER SMALL O 0x30C3, // KATAKANA LETTER SMALL TU 0x30E3, // KATAKANA LETTER SMALL YA 0x30E5, // KATAKANA LETTER SMALL YU 0x30E7, // KATAKANA LETTER SMALL YO 0x30EE, // KATAKANA LETTER SMALL WA 0x30F5, // KATAKANA LETTER SMALL KA 0x30F6, // KATAKANA LETTER SMALL KE 0x30FC, // KATAKANA-HIRAGANA PROLONGED SOUND MARK 0x30FD, // KATAKANA ITERATION MARK 0x30FE, // KATAKANA VOICED ITERATION MARK 0xFD3E, // ORNATE LEFT PARENTHESIS 0xFD3F, // ORNATE RIGHT PARENTHESIS 0xFE30, // VERTICAL TWO DOT LEADER 0xFE31, // VERTICAL EM DASH 0xFE33, // VERTICAL LOW LINE 0xFE34, // VERTICAL WAVY LOW LINE 0xFE35, // PRESENTATION FORM FOR VERTICAL LEFT PARENTHESIS 0xFE36, // PRESENTATION FORM FOR VERTICAL RIGHT PARENTHESIS 0xFE37, // PRESENTATION FORM FOR VERTICAL LEFT CURLY BRACKET 0xFE38, // PRESENTATION FORM FOR VERTICAL RIGHT CURLY BRACKET 0xFE39, // PRESENTATION FORM FOR VERTICAL LEFT TORTOISE SHELL BRACKET 0xFE3A, // PRESENTATION FORM FOR VERTICAL RIGHT TORTOISE SHELL BRACKET 0xFE3B, // PRESENTATION FORM FOR VERTICAL LEFT BLACK LENTICULAR BRACKET 0xFE3C, // PRESENTATION FORM FOR VERTICAL RIGHT BLACK LENTICULAR BRACKET 0xFE3D, // PRESENTATION FORM FOR VERTICAL LEFT DOUBLE ANGLE BRACKET 0xFE3E, // PRESENTATION FORM FOR VERTICAL RIGHT DOUBLE ANGLE BRACKET 0xFE3F, // PRESENTATION FORM FOR VERTICAL LEFT ANGLE BRACKET 0xFE40, // PRESENTATION FORM FOR VERTICAL RIGHT ANGLE BRACKET 0xFE41, // PRESENTATION FORM FOR VERTICAL LEFT CORNER BRACKET 0xFE42, // PRESENTATION FORM FOR VERTICAL RIGHT CORNER BRACKET 0xFE43, // PRESENTATION FORM FOR VERTICAL LEFT WHITE CORNER BRACKET 0xFE44, // PRESENTATION FORM FOR VERTICAL RIGHT WHITE CORNER BRACKET 0xFE4F, // WAVY LOW LINE 0xFE50, // SMALL COMMA 0xFE51, // SMALL IDEOGRAPHIC COMMA 0xFE59, // SMALL LEFT PARENTHESIS 0xFE5A, // SMALL RIGHT PARENTHESIS 0xFE5B, // SMALL LEFT CURLY BRACKET 0xFE5C, // SMALL RIGHT CURLY BRACKET 0xFE5D, // SMALL LEFT TORTOISE SHELL BRACKET 0xFE5E, // SMALL RIGHT TORTOISE SHELL BRACKET 0xFF08, // FULLWIDTH LEFT PARENTHESIS 0xFF09, // FULLWIDTH RIGHT PARENTHESIS 0xFF0C, // FULLWIDTH COMMA 0xFF0E, // FULLWIDTH FULL STOP 0xFF1C, // FULLWIDTH LESS-THAN SIGN 0xFF1E, // FULLWIDTH GREATER-THAN SIGN 0xFF3B, // FULLWIDTH LEFT SQUARE BRACKET 0xFF3D, // FULLWIDTH RIGHT SQUARE BRACKET 0xFF40, // FULLWIDTH GRAVE ACCENT 0xFF5B, // FULLWIDTH LEFT CURLY BRACKET 0xFF5C, // FULLWIDTH VERTICAL LINE 0xFF5D, // FULLWIDTH RIGHT CURLY BRACKET 0xFF5E, // FULLWIDTH TILDE 0xFF61, // HALFWIDTH IDEOGRAPHIC FULL STOP 0xFF62, // HALFWIDTH LEFT CORNER BRACKET 0xFF63, // HALFWIDTH RIGHT CORNER BRACKET 0xFF64, // HALFWIDTH IDEOGRAPHIC COMMA 0xFF67, // HALFWIDTH KATAKANA LETTER SMALL A 0xFF68, // HALFWIDTH KATAKANA LETTER SMALL I 0xFF69, // HALFWIDTH KATAKANA LETTER SMALL U 0xFF6A, // HALFWIDTH KATAKANA LETTER SMALL E 0xFF6B, // HALFWIDTH KATAKANA LETTER SMALL O 0xFF6C, // HALFWIDTH KATAKANA LETTER SMALL YA 0xFF6D, // HALFWIDTH KATAKANA LETTER SMALL YU 0xFF6E, // HALFWIDTH KATAKANA LETTER SMALL YO 0xFF6F, // HALFWIDTH KATAKANA LETTER SMALL TU 0xFF70, // HALFWIDTH KATAKANA-HIRAGANA PROLONGED SOUND MARK 0xFF9E, // HALFWIDTH KATAKANA VOICED SOUND MARK 0xFF9F, // HALFWIDTH KATAKANA SEMI-VOICED SOUND MARK 0xFFE9, // HALFWIDTH LEFTWARDS ARROW 0xFFEB, // HALFWIDTH RIGHTWARDS ARROW }; /* // // AutoComplete Common Functions / Structures // const struct { UINT idMenu; UINT idCmd; } MenuToMessageId[] = { { IDM_AC_UNDO, WM_UNDO }, { IDM_AC_CUT, WM_CUT }, { IDM_AC_COPY, WM_COPY }, { IDM_AC_PASTE, WM_PASTE } }; */ //+------------------------------------------------------------------------- // IUnknown methods //-------------------------------------------------------------------------- HRESULT CAutoComplete::QueryInterface(REFIID riid, void **ppvObj) { if (IsEqualIID(riid, IID_IUnknown) || IsEqualIID(riid, IID_IAutoComplete) || IsEqualIID(riid, IID_IAutoComplete2)) { *ppvObj = SAFECAST(this, IAutoComplete2*); } else if (IsEqualIID(riid, IID_IAutoCompleteDropDown)) { *ppvObj = SAFECAST(this, IAutoCompleteDropDown*); } else if (IsEqualIID(riid, IID_IEnumString)) { *ppvObj = SAFECAST(this, IEnumString*); } else { return _DefQueryInterface(riid, ppvObj); } AddRef(); return S_OK; } ULONG CAutoComplete::AddRef(void) { InterlockedIncrement((LPLONG)&m_dwRefCount); TraceMsg(AC_GENERAL, "CAutoComplete::AddRef() --- m_dwRefCount = %i ", m_dwRefCount); return m_dwRefCount; } ULONG CAutoComplete::Release(void) { ASSERT(m_dwRefCount > 0); if (InterlockedDecrement((LPLONG)&m_dwRefCount)) { TraceMsg(AC_GENERAL, "CAutoComplete::Release() --- m_dwRefCount = %i", m_dwRefCount); return m_dwRefCount; } TraceMsg(AC_GENERAL, "CAutoComplete::Release() --- m_dwRefCount = %i", m_dwRefCount); delete this; return 0; } /* IAutoComplete methods */ //+------------------------------------------------------------------------- // This object can be Inited in two ways. This function will init it in // the first way, which works as follows: // // 1. The caller called CoInitialize or OleInitialize() and the corresponding // uninit will not be called until the control we are subclassing and // our selfs are long gone. // 2. The caller calls us on their main thread and we create and destroy // the background thread as needed. //-------------------------------------------------------------------------- HRESULT CAutoComplete::Init ( HWND hwndEdit, // control to be subclassed IUnknown *punkACL, // autocomplete list LPCOLESTR pwszRegKeyPath, // reg location where ctrl-enter completion is stored stored LPCOLESTR pwszQuickComplete // default format string for ctrl-enter completion ) { HRESULT hr = S_OK; TraceMsg(AC_GENERAL, "CAutoComplete::Init(hwndEdit=0x%x, punkACL = 0x%x, pwszRegKeyPath = 0x%x, pwszQuickComplete = 0x%x)", hwndEdit, punkACL, pwszRegKeyPath, pwszQuickComplete); #ifdef DEBUG // Ensure that the Line Break Character Table is ordered WCHAR c = g_szBreakChars[0]; for (int i = 1; i < ARRAYSIZE(g_szBreakChars); ++i) { ASSERT(c < g_szBreakChars[i]); c = g_szBreakChars[i]; } #endif if (m_hwndEdit != NULL) { // Can currently only be initialized once ASSERT(FALSE); return E_FAIL; } m_hwndEdit = hwndEdit; #ifndef UNIX // Add our custom word-break callback so that we recognize URL delimitors when // ctrl-arrowing around. // // There is a bug with how USER handles WH_CALLWNDPROC global hooks in Win95 that // causes us to blow up if one is installed and a wordbreakproc is set. Thus, // if an app is running that has one of these hooks installed (intellipoint 1.1 etc.) then // if we install our wordbreakproc the app will fault when the proc is called. There // does not appear to be any way for us to work around it since USER's thunking code // trashes the stack so this API is disabled for Win95. // m_oldEditWordBreakProc = (EDITWORDBREAKPROC)SendMessage(m_hwndEdit, EM_GETWORDBREAKPROC, 0, 0); if (g_fRunningOnNT && IsWindowUnicode(m_hwndEdit)) { SendMessage(m_hwndEdit, EM_SETWORDBREAKPROC, 0, (DWORD_PTR)EditWordBreakProcW); } #endif // // bug 81414 : To avoid clashing with app messages used by the edit window, we // use registered messages. // m_uMsgSearchComplete = RegisterWindowMessageA("AC_SearchComplete"); m_uMsgItemActivate = RegisterWindowMessageA("AC_ItemActivate"); if (m_uMsgSearchComplete == 0) { m_uMsgSearchComplete = WM_APP + 300; } if (m_uMsgItemActivate == 0) { m_uMsgItemActivate = WM_APP + 301; } _SetQuickCompleteStrings(pwszRegKeyPath, pwszQuickComplete); // IEnumString required ASSERT(m_pes == NULL); EVAL(SUCCEEDED(punkACL->QueryInterface(IID_IEnumString, (void **)&m_pes))); // IACList optional ASSERT(m_pacl == NULL); punkACL->QueryInterface(IID_IACList, (void **)&m_pacl); AddRef(); // Hold on to a ref for our Subclass. // Initial creation should have failed if the thread object was not allocated! ASSERT(m_pThread); m_pThread->Init(m_pes, m_pacl); // subclass the edit window SetWindowSubclass(m_hwndEdit, &s_EditWndProc, 0, (DWORD_PTR)this); // See what autocomplete features are enabled _SeeWhatsEnabled(); // See if hwndEdit is part of a combobox HWND hwndParent = GetParent(m_hwndEdit); WCHAR szClass[30]; int nLen = GetClassName(hwndParent, szClass, ARRAYSIZE(szClass)); if (nLen != 0 && (StrCmpI(szClass, L"combobox") == 0 || StrCmpI(szClass, L"comboboxex") == 0)) { m_hwndCombo = hwndParent; } // If we've already got focus, then we need to call GotFocus... if (GetFocus() == hwndEdit) { m_pThread->GotFocus(); } return hr; } //+------------------------------------------------------------------------- // Checks to see if autoappend or autosuggest freatures are enabled //-------------------------------------------------------------------------- void CAutoComplete::_SeeWhatsEnabled() { #ifdef ALLOW_ALWAYS_DROP_UP m_fAlwaysDropUp = SHRegGetBoolUSValue(REGSTR_PATH_AUTOCOMPLETE, TEXT("AlwaysDropUp"), FALSE, /*default:*/FALSE); #endif // If autosuggest was just enabled, create the dropdown window if (_IsAutoSuggestEnabled() && NULL == m_hwndDropDown) { // Create the dropdown Window WNDCLASS wc = {0}; wc.lpfnWndProc = s_DropDownWndProc; wc.cbWndExtra = SIZEOF(CAutoComplete*); wc.hInstance = HINST_THISDLL; wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wc.lpszClassName = c_szAutoSuggestClass; SHRegisterClass(&wc); DWORD dwExStyle = WS_EX_TOPMOST | WS_EX_TOOLWINDOW | WS_EX_NOPARENTNOTIFY; if(_IsRTLReadingEnabled()) { dwExStyle |= WS_EX_RIGHT | WS_EX_RTLREADING | WS_EX_LEFTSCROLLBAR; } #ifdef UNIX // BUGBUG // IEUNIX : Working around window activation problems in mainwin // Autocomplete is completely hosed without this flag on UNIX. dwExStyle |= WS_EX_MW_UNMANAGED_WINDOW; #endif m_hwndDropDown = CreateWindowEx(dwExStyle, c_szAutoSuggestClass, c_szAutoSuggestTitle, // GPF dialog is picking up this name! WS_POPUP | WS_BORDER | WS_CLIPCHILDREN, 0, 0, 100, 100, NULL, NULL, HINST_THISDLL, this); if (m_hwndDropDown) { m_fDropDownResized = FALSE; } } else if (!_IsAutoSuggestEnabled() && NULL != m_hwndDropDown) { // We don't need the dropdown Window. if (m_hwndList) { DestroyWindow(m_hwndList); } DestroyWindow(m_hwndDropDown); m_hwndDropDown = NULL; m_hwndList = NULL; m_hwndScroll = NULL; m_hwndGrip = NULL; } } //+------------------------------------------------------------------------- // Returns TRUE if autocomplete is currently enabled //-------------------------------------------------------------------------- BOOL CAutoComplete::IsEnabled() { BOOL fRet; // // If we have not used the new IAutoComplete2 interface, we revert // to the old IE4 global registry setting // if (m_dwOptions & ACO_UNINITIALIZED) { fRet = SHRegGetBoolUSValue(REGSTR_PATH_AUTOCOMPLETE, REGSTR_VAL_USEAUTOCOMPLETE, FALSE, TRUE); } else { fRet = (m_dwOptions & (ACO_AUTOAPPEND | ACO_AUTOSUGGEST)); } return fRet; } //+------------------------------------------------------------------------- // Enables/disables the up down arrow for autocomplete. Used by comboboxes // to disable arrow keys when the combo box is dropped. (This function is // now redundent because we check to see of the combo is dropped.) //-------------------------------------------------------------------------- HRESULT CAutoComplete::Enable(BOOL fEnable) { TraceMsg(AC_GENERAL, "CAutoComplete::Enable(0x%x)", fEnable); HRESULT hr = (m_dwFlags & ACF_IGNOREUPDOWN) ? S_FALSE : S_OK; if (fEnable) m_dwFlags &= ~ACF_IGNOREUPDOWN; else m_dwFlags |= ACF_IGNOREUPDOWN; return hr; } /* IAutocomplete2 methods */ //+------------------------------------------------------------------------- // Enables/disables various autocomplete features (see ACO_* flags) //-------------------------------------------------------------------------- HRESULT CAutoComplete::SetOptions(DWORD dwOptions) { m_dwOptions = dwOptions; _SeeWhatsEnabled(); return S_OK; } //+------------------------------------------------------------------------- // Returns the current option settings //-------------------------------------------------------------------------- HRESULT CAutoComplete::GetOptions(DWORD* pdwOptions) { HRESULT hr = E_INVALIDARG; if (pdwOptions) { *pdwOptions = m_dwOptions; hr = S_OK; } return hr; } /* IAutocompleteDropDown methods */ //+------------------------------------------------------------------------- // Returns the current dropdown status //-------------------------------------------------------------------------- HRESULT CAutoComplete::GetDropDownStatus(DWORD *pdwFlags, LPWSTR *ppwszString) { if (m_hwndDropDown && IsWindowVisible(m_hwndDropDown)) { if (pdwFlags) { *pdwFlags = ACDD_VISIBLE; } if (ppwszString) { *ppwszString=NULL; if (m_hwndList) { int iCurSel = ListView_GetNextItem(m_hwndList, -1, LVNI_SELECTED); if (iCurSel != -1) { WCHAR szBuf[MAX_URL_STRING]; _GetItem(iCurSel, szBuf, ARRAYSIZE(szBuf), FALSE); *ppwszString = (LPWSTR) CoTaskMemAlloc((lstrlenW(szBuf)+1)*sizeof(WCHAR)); if (*ppwszString) { StrCpyW(*ppwszString, szBuf); } } } } } else { if (pdwFlags) { *pdwFlags = 0; } if (ppwszString) { *ppwszString = NULL; } } return S_OK; } HRESULT CAutoComplete::ResetEnumerator() { _StopSearch(); _ResetSearch(); _FreeDPAPtrs(m_hdpa); m_hdpa = NULL; // If the dropdown is currently visible, re-search the IEnumString // and show the dropdown. Otherwise wait for user input. if (m_hwndDropDown && IsWindowVisible(m_hwndDropDown)) { _StartCompletion(FALSE, TRUE); } return S_OK; } /* IEnumString methods */ //+------------------------------------------------------------------------- // Resets the IEnumString functionality exposed for external users. //-------------------------------------------------------------------------- HRESULT CAutoComplete::Reset() { HRESULT hr = E_FAIL; if (!m_szEnumString) // If we needed it once, we will most likely continue to need it. m_szEnumString = (LPTSTR) TrcLocalAlloc(LPTR, MAX_URL_STRING * SIZEOF(TCHAR)); if (!m_szEnumString) return E_OUTOFMEMORY; GetWindowText(m_hwndEdit, m_szEnumString, MAX_URL_STRING); if (m_pesExtern) hr = m_pesExtern->Reset(); else { hr = m_pes->Clone(&m_pesExtern); if (SUCCEEDED(hr)) hr = m_pesExtern->Reset(); } return hr; } //+------------------------------------------------------------------------- // Returns the next BSTR from the autocomplete enumeration. // // For consistant results, the caller should not allow the AutoComplete text // to change between one call to Next() and another call to Next(). // AutoComplete text should change only before Reset() is called. //-------------------------------------------------------------------------- HRESULT CAutoComplete::Next ( ULONG celt, // number items to fetch, needs to be 1 LPOLESTR *rgelt, // returned BSTR, caller must free ULONG *pceltFetched // number of items returned ) { HRESULT hr = S_FALSE; LPOLESTR pwszUrl; ULONG cFetched; // Pre-init in case of error if (rgelt) *rgelt = NULL; if (pceltFetched) *pceltFetched = 0; if (!EVAL(rgelt) || (!EVAL(pceltFetched)) || (!EVAL(1 == celt)) || !EVAL(m_pesExtern)) return E_INVALIDARG; while (S_OK == (hr = m_pesExtern->Next(1, &pwszUrl, &cFetched))) { if (!StrCmpNI(m_szEnumString, pwszUrl, lstrlen(m_szEnumString))) { TraceMsg(TF_BAND|TF_GENERAL, "CAutoComplete: Next(). AutoSearch Failed URL=%s.", pwszUrl); break; } else { // If the string can't be added to our list, we will free it. TraceMsg(TF_BAND|TF_GENERAL, "CAutoComplete: Next(). AutoSearch Match URL=%s.", pwszUrl); CoTaskMemFree(pwszUrl); } } if (S_OK == hr) { *rgelt = (LPOLESTR)pwszUrl; *pceltFetched = 1; // We will always only fetch one. } return hr; } #pragma warning(disable:4355) // using 'this' in constructor /* Constructor / Destructor / CreateInstance */ //+------------------------------------------------------------------------- // Constructor //-------------------------------------------------------------------------- CAutoComplete::CAutoComplete() { DllAddRef(); TraceMsg(AC_GENERAL, "CAutoComplete::CAutoComplete()"); // This class requires that this COM object be allocated in Zero INITed // memory. If the asserts below go off, then this was violated. ASSERT(!m_dwFlags); ASSERT(!m_hwndEdit); ASSERT(!m_pszCurrent); ASSERT(!m_iCurrent); ASSERT(!m_dwLastSearchFlags); ASSERT(!m_pes); ASSERT(!m_pacl); ASSERT(!m_pesExtern); ASSERT(!m_szEnumString); ASSERT(!m_pThread); m_dwOptions = ACO_UNINITIALIZED; m_dwRefCount = 1; } //+------------------------------------------------------------------------- // Destructor //-------------------------------------------------------------------------- CAutoComplete::~CAutoComplete() { TraceMsg(AC_GENERAL, "CAutoComplete::~CAutoComplete()"); if (m_hwndDropDown) { DestroyWindow(m_hwndDropDown); m_hwndDropDown = NULL; } SAFERELEASE(m_pes); SAFERELEASE(m_pacl); SAFERELEASE(m_pesExtern); SetStr(&m_pszCurrent, NULL); if (m_szEnumString) TrcLocalFree(m_szEnumString); _FreeDPAPtrs(m_hdpa); if (m_pThread) { m_pThread->SyncShutDownBGThread(); SAFERELEASE(m_pThread); } DllRelease(); } STDMETHODIMP CAutoComplete::get_accName(VARIANT varChild, BSTR *pszName) { HRESULT hr; if (varChild.vt == VT_I4) { if (varChild.lVal > 0) { WCHAR szBuf[MAX_URL_STRING]; _GetItem(varChild.lVal - 1, szBuf, ARRAYSIZE(szBuf), TRUE); *pszName = SysAllocString(szBuf); } else { *pszName = NULL; } hr = S_OK; } else { hr = E_UNEXPECTED; } return hr; } //+------------------------------------------------------------------------- // Private initialization //-------------------------------------------------------------------------- BOOL CAutoComplete::_Init() { m_pThread = new CACThread(*this); #ifdef DEBUG // May get freed from background tread so disable leak checking if (m_pThread) { DbgRemoveFromMemList(m_pThread); } #endif return (NULL != m_pThread); } //+------------------------------------------------------------------------- // Creates and instance of CAutoComplete //-------------------------------------------------------------------------- HRESULT CAutoComplete_CreateInstance(IUnknown* pUnkOuter, IUnknown** ppunk, LPCOBJECTINFO poi) { // Note - Aggregation checking is handled in class factory *ppunk = NULL; CAutoComplete* p = new CAutoComplete(); if (p) { if (p->_Init()) { *ppunk = SAFECAST(p, IAutoComplete *); return S_OK; } delete p; } return E_OUTOFMEMORY; } //+------------------------------------------------------------------------- // Helper function to add default autocomplete functionality to and edit // window. //-------------------------------------------------------------------------- HRESULT SHUseDefaultAutoComplete ( HWND hwndEdit, IBrowserService * pbs, IN OPTIONAL IAutoComplete2 ** ppac, OUT OPTIONAL IShellService ** ppssACLISF, OUT OPTIONAL BOOL fUseCMDMRU ) { HRESULT hr; IUnknown * punkACLMulti; if (ppac) *ppac = NULL; if (ppssACLISF) *ppssACLISF = NULL; hr = CoCreateInstance(CLSID_ACLMulti, NULL, CLSCTX_INPROC_SERVER, IID_IUnknown, (void **)&punkACLMulti); if (SUCCEEDED(hr)) { DbgRemoveFromMemList(punkACLMulti); IObjMgr * pomMulti; hr = punkACLMulti->QueryInterface(IID_IObjMgr, (LPVOID *)&pomMulti); if (SUCCEEDED(hr)) { BOOL fReady = FALSE; // Fail only if all we are not able to create at least one list. // ADD The MRU List IUnknown * punkACLMRU; hr = CACLMRU_CreateInstance(NULL, &punkACLMRU, NULL, fUseCMDMRU ? SZ_REGKEY_TYPEDURLMRU : SZ_REGKEY_TYPEDCMDMRU); if (SUCCEEDED(hr)) { DbgRemoveFromMemList(punkACLMRU); pomMulti->Append(punkACLMRU); punkACLMRU->Release(); fReady = TRUE; } // ADD The History List IUnknown * punkACLHist; hr = CoCreateInstance(CLSID_ACLHistory, NULL, CLSCTX_INPROC_SERVER, IID_IUnknown, (void **)&punkACLHist); if (SUCCEEDED(hr)) { DbgRemoveFromMemList(punkACLHist); pomMulti->Append(punkACLHist); punkACLHist->Release(); fReady = TRUE; } // ADD The ISF List IUnknown * punkACLISF; hr = CoCreateInstance(CLSID_ACListISF, NULL, CLSCTX_INPROC_SERVER, IID_IUnknown, (void **)&punkACLISF); if (SUCCEEDED(hr)) { DbgRemoveFromMemList(punkACLISF); // We need to give the ISF AutoComplete List a pointer to the IBrowserService // so it can retrieve the current browser location to AutoComplete correctly. IShellService * pss; hr = punkACLISF->QueryInterface(IID_IShellService, (LPVOID *)&pss); if (SUCCEEDED(hr)) { if (pbs) pss->SetOwner(pbs); if (ppssACLISF) *ppssACLISF = pss; else pss->Release(); } // // Set options // IACList2* pacl; if (SUCCEEDED(punkACLISF->QueryInterface(IID_IACList2, (LPVOID *)&pacl))) { // Specify directories to search pacl->SetOptions(ACLO_CURRENTDIR | ACLO_FAVORITES | ACLO_MYCOMPUTER | ACLO_DESKTOP); pacl->Release(); } pomMulti->Append(punkACLISF); punkACLISF->Release(); fReady = TRUE; } if (fReady) { IAutoComplete2 * pac; // Create the AutoComplete Object hr = CoCreateInstance(CLSID_AutoComplete, NULL, CLSCTX_INPROC_SERVER, IID_IAutoComplete2, (void **)&pac); if (SUCCEEDED(hr)) { hr = pac->Init(hwndEdit, punkACLMulti, WZ_REGKEY_QUICKCOMPLETE, WZ_DEFAULTQUICKCOMPLETE); if (ppac) *ppac = pac; else pac->Release(); } } pomMulti->Release(); } punkACLMulti->Release(); } return hr; } /* Private functions */ //+------------------------------------------------------------------------- // Removes anything that we appended to the edit text //-------------------------------------------------------------------------- void CAutoComplete::_RemoveCompletion() { TraceMsg(AC_GENERAL, "CAutoComplete::_RemoveCompletion()"); if (m_fAppended) { // Remove any highlighted text that we displayed Edit_ReplaceSel(m_hwndEdit, TEXT("")); m_fAppended = FALSE; } } //+------------------------------------------------------------------------- // Updates the text in the edit control //-------------------------------------------------------------------------- void CAutoComplete::_SetEditText(LPCWSTR psz) { // // We set a flag so that we can distinguish between us setting the text // and someone else doing it. If someone else sets the text we hide our // dropdown. // m_fSettingText = TRUE; // Don't display our special wildcard search string if (psz[0] == CH_WILDCARD) { Edit_SetText(m_hwndEdit, L""); } else { Edit_SetText(m_hwndEdit, psz); } m_fSettingText = FALSE; } //+------------------------------------------------------------------------- // Removed anything that we appended to the edit text and then updates // m_pszCurrent with the current string. //-------------------------------------------------------------------------- void CAutoComplete::_GetEditText(void) { TraceMsg(AC_GENERAL, "CAutoComplete::_GetEditText()"); _RemoveCompletion(); // remove anything we added int iCurrent = GetWindowTextLength(m_hwndEdit); // // If the current buffer is too small, delete it. // if (m_pszCurrent && LocalSize(m_pszCurrent) <= (UINT)(iCurrent + 1) * sizeof(TCHAR)) { SetStr(&m_pszCurrent, NULL); } // // If there is no current buffer, try to allocate one // with some room to grow. // if (!m_pszCurrent) { m_pszCurrent = (LPTSTR)LocalAlloc(LPTR, (iCurrent + (MAX_URL_STRING / 2)) * SIZEOF(TCHAR)); } // // If we have a current buffer, get the text. // if (m_pszCurrent) { if (!GetWindowText(m_hwndEdit, m_pszCurrent, iCurrent + 1)) { *m_pszCurrent = L'\0'; } // On win9x GetWindowTextLength can return more than the # of characters m_iCurrent = lstrlen(m_pszCurrent); } else { m_iCurrent = 0; } } //+------------------------------------------------------------------------- // Updates the text in the edit control //-------------------------------------------------------------------------- void CAutoComplete::_UpdateText ( int iStartSel, // start location for selected int iEndSel, // end location of selected text LPCTSTR pszCurrent, // unselected text LPCTSTR pszNew // autocompleted (selected) text ) { TraceMsg(AC_GENERAL, "CAutoComplete::_UpdateText(iStart=%i; iEndSel = %i, pszCurrent=>%s<, pszNew=>%s<)", iStartSel, iEndSel, (pszCurrent ? pszCurrent : TEXT("(null)")), (pszNew ? pszNew : TEXT("(null)"))); // // Restore the old text. // _SetEditText(pszCurrent); // // Put the cursor at the insertion point. // Edit_SetSel(m_hwndEdit, iStartSel, iStartSel); // // Insert the new text. // Edit_ReplaceSel(m_hwndEdit, pszNew); // // Select the newly added text. // Edit_SetSel(m_hwndEdit, iStartSel, iEndSel); } //+------------------------------------------------------------------------- // If pwszQuickComplete is NULL, we will use our internal default. // pwszRegKeyValue can be NULL indicating that there is not a key. //-------------------------------------------------------------------------- BOOL CAutoComplete::_SetQuickCompleteStrings(LPCOLESTR pwszRegKeyPath, LPCOLESTR pwszQuickComplete) { TraceMsg(AC_GENERAL, "CAutoComplete::SetQuickCompleteStrings(pwszRegKeyPath=0x%x, pwszQuickComplete = 0x%x)", pwszRegKeyPath, pwszQuickComplete); if (pwszRegKeyPath) { lstrcpyn(m_szRegKeyPath, pwszRegKeyPath, ARRAYSIZE(m_szRegKeyPath)); } else { // can be empty m_szRegKeyPath[0] = TEXT('\0'); } if (pwszQuickComplete) { lstrcpyn(m_szQuickComplete, pwszQuickComplete, ARRAYSIZE(m_szQuickComplete)); } else { // use default value lstrcpyn(m_szQuickComplete, c_szAutoDefQuickComp, ARRAYSIZE(m_szQuickComplete)); } return TRUE; } //+------------------------------------------------------------------------- // Formats the current contents of the edit box with the appropriate prefix // and endfix and returns the completed string. //-------------------------------------------------------------------------- LPTSTR CAutoComplete::_QuickEnter() { // // If they shift-enter, then do the favorite pre/post-fix. // TCHAR szFormat[MAX_QUICK_COMPLETE_STRING]; TCHAR szNewText[MAX_URL_STRING]; int iLen; TraceMsg(AC_GENERAL, "CAutoComplete::_QuickEnter()"); if (NULL == m_pszCurrent) { return NULL; } lstrcpyn(szFormat, m_szQuickComplete, ARRAYSIZE(szFormat)); DWORD cb = sizeof(szFormat); SHGetValue(HKEY_CURRENT_USER, m_szRegKeyPath, TEXT("QuickComplete"), NULL, &szFormat, &cb); // // Remove preceeding and trailing white space // PathRemoveBlanks(m_pszCurrent); // // Make sure we don't GPF. // iLen = lstrlen(m_pszCurrent) + lstrlen(szFormat); if (iLen < ARRAYSIZE(szNewText)) { // If the quick complete is already present, don't add it again LPWSTR pszInsertion = StrStrI(szFormat, L"%s"); LPWSTR pszFormat = szFormat; if (pszInsertion) { // If prefix is already present, don't add it again. // (we could improve this to only add parts of the predfix that are missing) int iInsertion = (int)(pszInsertion - pszFormat); if (iInsertion == 0 || StrCmpNI(pszFormat, m_pszCurrent, iInsertion) == 0) { // Skip over prefix pszFormat = pszInsertion; } // If postfix is already present, don't add it again. LPWSTR pszPostFix = pszInsertion + ARRAYSIZE(L"%s") - 1; int cchCurrent = lstrlen(m_pszCurrent); int cchPostFix = lstrlen(pszPostFix); if (cchPostFix > 0 && cchPostFix < cchCurrent && StrCmpI(m_pszCurrent + (cchCurrent - cchPostFix), pszPostFix) == 0) { // Lop off postfix *pszPostFix = 0; } } wnsprintf(szNewText, ARRAYSIZE(szNewText), pszFormat, m_pszCurrent); SetStr(&m_pszCurrent, szNewText); } return m_pszCurrent; } BOOL CAutoComplete::_ResetSearch(void) { TraceMsg(AC_GENERAL, "CAutoComplete::_ResetSearch()"); m_dwFlags = ACF_RESET; return TRUE; } //+------------------------------------------------------------------------- // Returns TRUE if the char is a forward or backackwards slash //-------------------------------------------------------------------------- BOOL CAutoComplete::_IsWhack(TCHAR ch) { return (ch == TEXT('/')) || (ch == TEXT('\\')); } //+------------------------------------------------------------------------- // Returns TRUE if the string points to a character used to separate words //-------------------------------------------------------------------------- BOOL CAutoComplete::_IsBreakChar(WCHAR wch) { // Do a binary search in our table of break characters int iMin = 0; int iMax = ARRAYSIZE(g_szBreakChars) - 1; while (iMax - iMin >= 2) { int iTry = (iMax + iMin + 1) / 2; if (wch < g_szBreakChars[iTry]) iMax = iTry; else if (wch > g_szBreakChars[iTry]) iMin = iTry; else return TRUE; } return (wch == g_szBreakChars[iMin] || wch == g_szBreakChars[iMax]); } //+------------------------------------------------------------------------- // Returns TRUE if we want to append to the current edit box contents //-------------------------------------------------------------------------- BOOL CAutoComplete::_WantToAppendResults() { // // Users get annoyed if we append real text after a // slash, because they type "c:\" and we complete // it to "c:\windows" when they aren't looking. // // Also, it's annoying to have "\" autocompleted to "\\" // return (m_pszCurrent && (!(_IsWhack(m_pszCurrent[0]) && m_pszCurrent[1] == NULL) && !_IsWhack(m_pszCurrent[lstrlen(m_pszCurrent)-1]))); } #ifdef UNIX extern "C" BOOL MwTranslateUnixKeyBinding( HWND hwnd, DWORD message, WPARAM *pwParam, DWORD *pModifiers ); #endif //+------------------------------------------------------------------------- // Callback routine used by the edit window to determine where to break // words. We install this custom callback dor the ctl arrow keys // recognize our break characters. //-------------------------------------------------------------------------- int CALLBACK CAutoComplete::EditWordBreakProcW ( LPWSTR pszEditText, // pointer to edit text int ichCurrent, // index of starting point int cch, // length in characters of edit text int code // action to take ) { LPWSTR psz = pszEditText + ichCurrent; int iIndex; BOOL fFoundNonDelimiter = FALSE; static BOOL fRight = FALSE; // hack due to bug in USER switch (code) { case WB_ISDELIMITER: fRight = TRUE; // Simple case - is the current character a delimiter? iIndex = (int)_IsBreakChar(*psz); break; case WB_LEFT: // Move to the left to find the first delimiter. If we are // currently at a delimiter, then skip delimiters until we // find the first non-delimiter, then start from there. // // Special case for fRight - if we are currently at a delimiter // then just return the current word! while ((psz = CharPrev(pszEditText, psz)) != pszEditText) { if (_IsBreakChar(*psz)) { if (fRight || fFoundNonDelimiter) break; } else { fFoundNonDelimiter = TRUE; fRight = FALSE; } } iIndex = (int)(psz - pszEditText); // We are currently pointing at the delimiter, next character // is the beginning of the next word. if (iIndex > 0 && iIndex < cch) iIndex++; break; case WB_RIGHT: fRight = FALSE; // If we are not at a delimiter, then skip to the right until // we find the first delimiter. If we started at a delimiter, or // we have just finished scanning to the first delimiter, then // skip all delimiters until we find the first non delimiter. // // Careful - the string passed in to us may not be NULL terminated! fFoundNonDelimiter = !_IsBreakChar(*psz); if (psz != (pszEditText + cch)) { while ((psz = CharNext(psz)) != (pszEditText + cch)) { if (_IsBreakChar(*psz)) { fFoundNonDelimiter = FALSE; } else { if (!fFoundNonDelimiter) break; } } } // We are currently pointing at the next word. iIndex = (int) (psz - pszEditText); break; } return iIndex; } //+------------------------------------------------------------------------- // Returns the index of the next or previous break character in m_pszCurrent //-------------------------------------------------------------------------- int CAutoComplete::_JumpToNextBreak ( int iLoc, // current location DWORD dwFlags // direction (WB_RIGHT or WB_LEFT) ) { return EditWordBreakProcW(m_pszCurrent, iLoc, lstrlen(m_pszCurrent), dwFlags); } //+------------------------------------------------------------------------- // Handles Horizontal cursor movement. Returns TRUE if the message should // passed on to the OS. Note that we only call this on win9x. On NT we // use EM_SETWORDBREAKPROC to set a callback instead because it sets the // caret correctly. This callback can crash on win9x. //-------------------------------------------------------------------------- BOOL CAutoComplete::_CursorMovement ( WPARAM wParam // virtual key data from WM_KEYDOWN ) { BOOL fShift, fControl; DWORD dwKey = (DWORD)wParam; int iStart, iEnd; TraceMsg(AC_GENERAL, "CAutoComplete::_CursorMovement(wParam = 0x%x)", wParam); fShift = (0 > GetKeyState(VK_SHIFT)) ; fControl = (0 > GetKeyState(VK_CONTROL)); // We don't do anything special unless the SHIFT or CTRL // key is down so we don't want to mess up arrowing around // UNICODE character clusters. (INDIC o+d+j+d+k+w) if (!fShift && !fControl) return TRUE; // let OS handle because of UNICODE char clusters #ifdef UNIX { DWORD dwModifiers; dwModifiers = 0; if ( fShift ) { dwModifiers |= FSHIFT; } if ( fControl ) { dwModifiers |= FCONTROL; } MwTranslateUnixKeyBinding( m_hwndEdit, WM_KEYDOWN, (WPARAM*) &dwKey, &dwModifiers ); fShift = ( dwModifiers & FSHIFT ); fControl = ( dwModifiers & FCONTROL ); } #endif // get the current selection SendMessage(m_hwndEdit, EM_GETSEL, (WPARAM)&iStart, (LPARAM)&iEnd); // the user is editting the text, so this is now invalid. m_dwFlags = ACF_RESET; _GetEditText(); if (!m_pszCurrent) return TRUE; // we didn't handle it... let the default wndproc try // Determine the previous selection direction int dwSelectionDirection; if (iStart == iEnd) { // Nothing previously selected, so use new direction dwSelectionDirection = dwKey; } else { // Base the selection direction on whether the caret is positioned // at the beginning or the end of the selection POINT pt; int cchCaret = iEnd; if (GetCaretPos(&pt)) { cchCaret = (int)SendMessage(m_hwndEdit, EM_CHARFROMPOS, 0, (LPARAM)MAKELPARAM(pt.x, 0)); } dwSelectionDirection = (cchCaret >= iEnd) ? VK_RIGHT : VK_LEFT; } if (fControl) { if (dwKey == VK_RIGHT) { // did we orginally go to the left? if (dwSelectionDirection == VK_LEFT) { // yes...unselect iStart = _JumpToNextBreak(iStart, WB_RIGHT); // if (!iStart) // iStart = m_iCurrent; } else if (iEnd != m_iCurrent) { // select or "jump over" characters iEnd = _JumpToNextBreak(iEnd, WB_RIGHT); // if (!iEnd) // iEnd = m_iCurrent; } } else // dwKey == VK_LEFT { // did we orginally go to the right? if (dwSelectionDirection == VK_RIGHT) { // yes...unselect // int iRemember = iEnd; iEnd = _JumpToNextBreak(iEnd, WB_LEFT); } else if (iStart) // != 0 { // select or "jump over" characters iStart = _JumpToNextBreak(iStart, WB_LEFT); } } } else // if !fControl { // This code is benign if the SHIFT key isn't down // because it has to do with modifying the selection. if (dwKey == VK_RIGHT) { if (dwSelectionDirection == VK_LEFT) { iStart++; } else { iEnd++; } } else // dwKey == VK_LEFT { LPTSTR pszPrev; if (dwSelectionDirection == VK_RIGHT) { pszPrev = CharPrev(m_pszCurrent, &m_pszCurrent[iEnd]); iEnd = (int)(pszPrev - m_pszCurrent); } else { pszPrev = CharPrev(m_pszCurrent, &m_pszCurrent[iStart]); iStart = (int)(pszPrev - m_pszCurrent); } } } // Are we selecting or moving? if (!fShift) { // just moving... if (dwKey == VK_RIGHT) { iStart = iEnd; } else // pachi->dwSelectionDirection == VK_LEFT { iEnd = iStart; } } // // If we are selecting text to the left, we have to jump hoops // to get the caret on the left of the selection. Edit_SetSel // always places the caret on the right, and if we position the // caret ourselves the edit control still uses the old caret // position. So we have to send VK_LEFT messages to the edit // control to get it to select things properly. // if (fShift && dwSelectionDirection == VK_LEFT && iStart < iEnd) { // Temporarily reset the control key (yuk!) BYTE keyState[256]; if (fControl) { GetKeyboardState(keyState); keyState[VK_CONTROL] &= 0x7f; SetKeyboardState(keyState); } // Select the last character and select left // one character at a time. Arrrggg. SendMessage(m_hwndEdit, WM_SETREDRAW, FALSE, 0); Edit_SetSel(m_hwndEdit, iEnd, iEnd); while (iEnd > iStart) { DefSubclassProc(m_hwndEdit, WM_KEYDOWN, VK_LEFT, 0); --iEnd; } SendMessage(m_hwndEdit, WM_SETREDRAW, TRUE, 0); InvalidateRect(m_hwndEdit, NULL, FALSE); UpdateWindow(m_hwndEdit); // Restore the control key if (fControl) { keyState[VK_CONTROL] |= 0x80; SetKeyboardState(keyState); } } else { Edit_SetSel(m_hwndEdit, iStart, iEnd); } return FALSE; // we handled it } //+------------------------------------------------------------------------- // Process WM_KEYDOWN message. Returns TRUE if the message should be passed // to the original wndproc. //-------------------------------------------------------------------------- BOOL CAutoComplete::_OnKeyDown(WPARAM wParam) { WPARAM wParamTranslated; TraceMsg(AC_GENERAL, "CAutoComplete::_OnKeyDown(wParam = 0x%x)", wParam); if (m_pThread->IsDisabled()) { // // Let the original wndproc handle it. // return TRUE; } wParamTranslated = wParam; #ifdef UNIX // Don't pass in HWND as the edit control will and we don't // want translation to cause two SendMessages for the same // control DWORD dwModifiers; dwModifiers = 0; if (GetKeyState(VK_CONTROL) < 0) { dwModifiers |= FCONTROL; } MwTranslateUnixKeyBinding( NULL, WM_KEYDOWN, &wParamTranslated, &dwModifiers ); #endif switch (wParamTranslated) { case VK_RETURN: { #ifndef UNIX if (0 > GetKeyState(VK_CONTROL)) #else if (dwModifiers & FCONTROL) #endif { // // Ctrl-Enter does some quick formatting. // _GetEditText(); _SetEditText(_QuickEnter()); } else { // // Reset the search criteria. // _ResetSearch(); // // Highlight entire text. // Edit_SetSel(m_hwndEdit, 0, (LPARAM)-1); } // // Stop any searches that are going on. // _StopSearch(); // // For intelliforms, if the dropdown is visible and something // is selected in the dropdown, we simulate an activation event. // if (m_hwndList) { int iCurSel = ListView_GetNextItem(m_hwndList, -1, LVNI_SELECTED); if ((iCurSel != -1) && m_hwndDropDown && IsWindowVisible(m_hwndDropDown)) { WCHAR szBuf[MAX_URL_STRING]; _GetItem(iCurSel, szBuf, ARRAYSIZE(szBuf), FALSE); SendMessage(m_hwndEdit, m_uMsgItemActivate, 0, (LPARAM)szBuf); } } // // Hide the dropdown // _HideDropDown(); // bugbug: For some reason, the original windproc is ignoring the return key. // It should hide the dropdown! if (m_hwndCombo) { SendMessage(m_hwndCombo, CB_SHOWDROPDOWN, FALSE, 0); } // // Let the original wndproc handle it. // break; } case VK_ESCAPE: _StopSearch(); _HideDropDown(); // bugbug: For some reason, the original windproc is ignoring the enter key. // It should hide the dropdown! if (m_hwndCombo) { SendMessage(m_hwndCombo, CB_SHOWDROPDOWN, FALSE, 0); } break; case VK_LEFT: case VK_RIGHT: // We do our own cursor movement on win9x because EM_SETWORDBREAKPROC is broken. if (!g_fRunningOnNT) { return _CursorMovement(wParam); } break; case VK_PRIOR: case VK_UP: if (!(m_dwFlags & ACF_IGNOREUPDOWN) && !_IsComboboxDropped()) { // // If the dropdown is visible, the up-down keys navigate our list // if (m_hwndDropDown && IsWindowVisible(m_hwndDropDown)) { int iCurSel = ListView_GetNextItem(m_hwndList, -1, LVNI_SELECTED); if (iCurSel == 0) { // If at top, move back up into the edit box // Deselect the dropdown and select the edit box ListView_SetItemState(m_hwndList, 0, 0, 0x000f); if (m_pszCurrent) { // Restore original text if they arrow out of listview _SetEditText(m_pszCurrent); } Edit_SetSel(m_hwndEdit, MAX_URL_STRING, MAX_URL_STRING); } else if (iCurSel != -1) { // If in middle or at bottom, move up SendMessage(m_hwndList, WM_KEYDOWN, wParam, 0); SendMessage(m_hwndList, WM_KEYUP, wParam, 0); } else { int iSelect = ListView_GetItemCount(m_hwndList)-1; // If in edit box, move to bottom ListView_SetItemState(m_hwndList, iSelect, LVIS_SELECTED|LVIS_FOCUSED, 0x000f); ListView_EnsureVisible(m_hwndList, iSelect, FALSE); } return FALSE; } // // If Autosuggest drop-down enabled but not popped up then start a search // based on the current edit box contents. If the edit box is empty, // search for everything. // else if ((m_dwOptions & ACO_UPDOWNKEYDROPSLIST) && _IsAutoSuggestEnabled()) { // Ensure the background thread knows we have focus _GotFocus(); _StartCompletion(FALSE, TRUE); return FALSE; } // // Otherwise we see if we should append the completions in place // else if (_IsAutoAppendEnabled()) { if (_AppendPrevious(FALSE)) { return FALSE; } } } break; case VK_NEXT: case VK_DOWN: if (!(m_dwFlags & ACF_IGNOREUPDOWN) && !_IsComboboxDropped()) { // // If the dropdown is visible, the up-down keys navigate our list // if (m_hwndDropDown && IsWindowVisible(m_hwndDropDown)) { ASSERT(m_hdpa); ASSERT(DPA_GetPtrCount(m_hdpa) != 0); ASSERT(m_iFirstMatch != -1); int iCurSel = ListView_GetNextItem(m_hwndList, -1, LVNI_SELECTED); if (iCurSel == -1) { // If no item selected, first down arrow selects first item ListView_SetItemState(m_hwndList, 0, LVIS_SELECTED | LVIS_FOCUSED, 0x000f); ListView_EnsureVisible(m_hwndList, 0, FALSE); } else if (iCurSel == ListView_GetItemCount(m_hwndList)-1) { // If last item selected, down arrow goes into edit box ListView_SetItemState(m_hwndList, iCurSel, 0, 0x000f); if (m_pszCurrent) { // Restore original text if they arrow out of listview _SetEditText(m_pszCurrent); } Edit_SetSel(m_hwndEdit, MAX_URL_STRING, MAX_URL_STRING); } else { // If first or middle item selected, down arrow selects next item SendMessage(m_hwndList, WM_KEYDOWN, wParam, 0); SendMessage(m_hwndList, WM_KEYUP, wParam, 0); } return FALSE; } // // If Autosuggest drop-down enabled but not popped up then start a search // based on the current edit box contents. If the edit box is empty, // search for everything. // else if ((m_dwOptions & ACO_UPDOWNKEYDROPSLIST) && _IsAutoSuggestEnabled()) { // Ensure the background thread knows we have focus _GotFocus(); _StartCompletion(FALSE, TRUE); return FALSE; } // // Otherwise we see if we should append the completions in place // else if (_IsAutoAppendEnabled()) { if (_AppendNext(FALSE)) { return FALSE; } } } break; case VK_END: case VK_HOME: _ResetSearch(); break; case VK_BACK: // // Indicate that selection doesn't match m_psrCurrentlyDisplayed. // #ifndef UNIX if (0 > GetKeyState(VK_CONTROL)) #else if (dwModifiers & FCONTROL) #endif { // // Handle Ctrl-Backspace to delete word. // int iStart, iEnd; SendMessage(m_hwndEdit, EM_GETSEL, (WPARAM)&iStart, (LPARAM)&iEnd); // // Nothing else must be selected. // if (iStart == iEnd) { _GetEditText(); if (!m_pszCurrent) { // // We didn't handle it, let the // other wndprocs try. // return TRUE; } // // Erase the "word". // iStart = EditWordBreakProcW(m_pszCurrent, iStart, iStart+1, WB_LEFT); Edit_SetSel(m_hwndEdit, iStart, iEnd); Edit_ReplaceSel(m_hwndEdit, TEXT("")); } // // We handled it. // return FALSE; } break; } // // Let the original wndproc handle it. // return TRUE; } LRESULT CAutoComplete::_OnChar(WPARAM wParam, LPARAM lParam) { LRESULT lres = 0; // means nothing, but we handled the call TCHAR cKey = (TCHAR) wParam; if (wParam == VK_TAB) { // Ignore tab characters return 0; } // Ensure the background thread knows we have focus _GotFocus(); if (m_pThread->IsDisabled()) { // // Just follow the chain. // return DefSubclassProc(m_hwndEdit, WM_CHAR, wParam, lParam); } if (cKey != 127 && cKey != VK_ESCAPE && cKey != VK_RETURN && cKey != 0x0a) // control-backspace is ignored { // let the default edit wndproc do its thing first lres = DefSubclassProc(m_hwndEdit, WM_CHAR, wParam, lParam); // ctrl-c is generating a VK_CANCEL. Don't bring up autosuggest in this case. if (cKey != VK_CANCEL) { BOOL fAppend = (cKey != VK_BACK); _StartCompletion(fAppend); } } else { _StopSearch(); _HideDropDown(); } return lres; } //+------------------------------------------------------------------------- // Starts autocomplete based on the current editbox contents //-------------------------------------------------------------------------- void CAutoComplete::_StartCompletion ( BOOL fAppend, // Ok to append completion in edit box BOOL fEvenIfEmpty // = FALSE, Completes to everything if edit box is empty ) { // Get the text typed in WCHAR szCurrent[MAX_URL_STRING]; int cchCurrent = GetWindowText(m_hwndEdit, szCurrent, ARRAYSIZE(szCurrent)); // See if we want a wildcard search if (fEvenIfEmpty && cchCurrent == 0) { cchCurrent = 1; szCurrent[0] = CH_WILDCARD; szCurrent[1] = 0; } // If unchanged, we are done if (m_pszLastSearch && m_pszCurrent && StrCmpI(m_pszCurrent, szCurrent) == 0) { if (!(m_hwndDropDown && IsWindowVisible(m_hwndDropDown)) && (-1 != m_iFirstMatch) && _IsAutoSuggestEnabled() && // Don't show drop-down if only one exact match (IForms) (m_hdpa && ((m_iLastMatch != m_iFirstMatch) || (((CACString*)DPA_GetPtr(m_hdpa, m_iFirstMatch))->StrCmpI(szCurrent) != 0)))) { _ShowDropDown(); } return; } // Save the current text if (szCurrent[0] == CH_WILDCARD) { SetStr(&m_pszCurrent, szCurrent); } else { _GetEditText(); } // // Deselect the current selection in the dropdown // if (m_hwndList) { int iCurSel = ListView_GetNextItem(m_hwndList, -1, LVNI_SELECTED); if (iCurSel != -1) { ListView_SetItemState(m_hwndList, iCurSel, 0, 0x000f); } } // // If nothing typed in, stop any pending search // if (cchCurrent == 0) { if (m_pszCurrent) { _StopSearch(); if (m_pszCurrent) { SetStr(&m_pszCurrent, NULL); } // bugbug: Free last completion _HideDropDown(); } } // // See if we need to generate a new list // else { int iCompleted = m_pszLastSearch ? lstrlen(m_pszLastSearch) : 0; int iScheme; // Get length of common prefix (if any) int cchPrefix = IsFlagSet(m_dwOptions, ACO_FILTERPREFIXES) ? CACThread::GetSpecialPrefixLen(szCurrent) : 0; if ( // If no previous completion, start a new search (0 == iCompleted) || // If the list was truncated (reached limit), we need to refetch m_fNeedNewList || // We purge matches to common prefixes ("www.", "http://" etc). If the // last search may have resulted in items being filtered out, and the // new string will not, then we need to refetch. (cchPrefix > 0 && cchPrefix < cchCurrent && CACThread::MatchesSpecialPrefix(m_pszLastSearch)) || // If the portion we last completed to was altered, we need to refetch (StrCmpNI(m_pszLastSearch, szCurrent, iCompleted) != 0) || // If we have entered a new folder, we need to refetch (StrChrI(szCurrent + iCompleted, DIR_SEPARATOR_CHAR) != NULL) || // If we have entered a url folder, we need to refetch (ftp://shapitst/Bryanst/) ((StrChrI(szCurrent + iCompleted, URL_SEPARATOR_CHAR) != NULL) && (URL_SCHEME_FTP == (iScheme = GetUrlScheme(szCurrent)))) ) { // If the last search was truncated, make sure we try the next search with more characters int cchMin = cchPrefix + 1; if (m_fNeedNewList) { cchMin = iCompleted + 1; } // Find the last '\\' (or '/' for ftp) int i = cchCurrent - 1; while ((szCurrent[i] != DIR_SEPARATOR_CHAR) && !((szCurrent[i] == URL_SEPARATOR_CHAR) && (iScheme == URL_SCHEME_FTP)) && (i >= cchMin)) { --i; } // Start a new search szCurrent[i+1] = 0; if (_StartSearch(szCurrent)) SetStr(&m_pszLastSearch, szCurrent); } // Otherwise we can simply update from our last completion list else { // if (m_hdpa) { _UpdateCompletion(szCurrent, -1, fAppend); } else { // Awaiting completion, cache new match... } } } } //+------------------------------------------------------------------------- // Get the background thread to start a new search //-------------------------------------------------------------------------- BOOL CAutoComplete::_StartSearch(LPCWSTR pszSeatch) { // Empty the dropdown list. To minimize flash, we don't hide it unless // the search comes up empty if (m_hwndList) { ListView_SetItemCountEx(m_hwndList, 0, 0); } return m_pThread->StartSearch(pszSeatch, m_dwOptions); } //+------------------------------------------------------------------------- // Get the background thread to abort the last search //-------------------------------------------------------------------------- void CAutoComplete::_StopSearch() { SetStr(&m_pszLastSearch, NULL); m_pThread->StopSearch(); } //+------------------------------------------------------------------------- // Informs the background thread that we have focus. //-------------------------------------------------------------------------- void CAutoComplete::_GotFocus() { if (!m_pThread->HasFocus()) { m_pThread->GotFocus(); } } //+------------------------------------------------------------------------- // Message from background thread indicating that the search was completed //-------------------------------------------------------------------------- void CAutoComplete::_OnSearchComplete ( HDPA hdpa, // New completion list BOOL fLimitReached // if this is a partial list ) { _FreeDPAPtrs(m_hdpa); m_hdpa = hdpa; m_fNeedNewList = fLimitReached; // Was it a wildcard search? BOOL fWildCard = m_pszLastSearch && (m_pszLastSearch[0] == CH_WILDCARD) && (m_pszLastSearch[1] == L'\0'); // // See if we should add "Search for <stuff typed in>" to the end of // the list. // m_fSearchForAdded = FALSE; if (!fWildCard && (m_dwOptions & ACO_SEARCH)) { // Add "Search for <stuff typed in>" to the end of the list // First make sure we have a dpa if (m_hdpa == NULL) { m_hdpa = DPA_Create(AC_LIST_GROWTH_CONST); } if (m_hdpa) { // Create a bogus entry and add to the end of the list. This place // holder makes sure the drop-down does not go away when there are no // matching entries. CACString* pStr = CreateACString(L"", 0); if (DPA_AppendPtr(m_hdpa, pStr) == -1) { pStr->Release(); } else { m_fSearchForAdded = TRUE; } } } // If no search results, hide our dropdown if (NULL == m_hdpa || 0 == DPA_GetPtrCount(m_hdpa)) { _HideDropDown(); if (m_hwndList) { ListView_SetItemCountEx(m_hwndList, 0, 0); } m_iFirstMatch = -1; } else { if (m_pszCurrent) { // If we are still waiting for a completion, then update the completion list if (m_pszLastSearch) { _UpdateCompletion(m_pszCurrent, -1, TRUE); } } if (m_hwndDropDown && IsWindowVisible(m_hwndDropDown)) { _PositionDropDown(); // Resize based on number of hits _UpdateScrollbar(); } } } //+------------------------------------------------------------------------- // Returns the text for an item in the autocomplete list //-------------------------------------------------------------------------- BOOL CAutoComplete::_GetItem ( int iIndex, // zero-based index LPWSTR pszText, // location to return text int cchMax, // size of pszText buffer BOOL fDisplayName // TRUE = return name to display // FALSE = return name to go to edit box ) { // Check for special "Search for <typed in>" entry at end of the list if (m_fSearchFor && iIndex == m_iLastMatch - m_iFirstMatch) { ASSERT(NULL != m_pszCurrent); WCHAR szFormat[MAX_PATH]; int id = fDisplayName ? IDS_SEARCHFOR : IDS_SEARCHFORCMD; MLLoadString(id, szFormat, ARRAYSIZE(szFormat)); wnsprintf(pszText, cchMax, szFormat, m_pszCurrent); } // Normal list entry else { CACString* pStr = (CACString*)DPA_GetPtr(m_hdpa, iIndex + m_iFirstMatch); if (pStr) { StrCpyN(pszText, pStr->GetStr(), cchMax); } else if (cchMax >= 1) { pszText[0] = 0; } } return TRUE; } //+------------------------------------------------------------------------- // Frees an item in our autocomplete list //-------------------------------------------------------------------------- int CAutoComplete::_DPADestroyCallback(LPVOID p, LPVOID d) { ((CACString*)p)->Release(); return 1; } //+------------------------------------------------------------------------- // Frees our last completion list //-------------------------------------------------------------------------- void CAutoComplete::_FreeDPAPtrs(HDPA hdpa) { TraceMsg(AC_GENERAL, "CAutoComplete::_FreeDPAPtrs(hdpa = 0x%x)", hdpa); if (hdpa) { DPA_DestroyCallback(hdpa, _DPADestroyCallback, 0); } } //+------------------------------------------------------------------------- // Updates the matching completion //-------------------------------------------------------------------------- void CAutoComplete::_UpdateCompletion ( LPCWSTR pszTyped, // typed in string to match int iChanged, // char added since last update or -1 BOOL fAppend // ok to append completion ) { int iFirstMatch = -1; int iLastMatch = -1; int nChars = lstrlen(pszTyped); // Was it a wildcard search? BOOL fWildCard = pszTyped && (pszTyped[0] == CH_WILDCARD) && (pszTyped[1] == L'\0'); if (fWildCard && DPA_GetPtrCount(m_hdpa)) { // Everything matches iFirstMatch = 0; iLastMatch = DPA_GetPtrCount(m_hdpa) - 1; } else { // PERF: Special case where current == search string /* // // Find the first matching index // if (iChanged > 0) { // PERF: Get UC and LC versions of WC for compare below? WCHAR wc = pszTyped[iChanged]; // A character was added so search from current location for (int i = m_iFirstMatch; i < DPA_GetPtrCount(m_hdpa); ++i) { CACString* pStr; pStr = (CACString*)DPA_GetPtr(m_hdpa, i); ASSERT(pStr); if (pStr && pStr->GetLength() >= iChanged && ChrCmpI((*pStr)[iChanged], wc) == 0) { // This is the first match iFirstMatch = i; break; } } } else */ { // Damn, we have to search the whole list // PERF: Switch to a binary search. for (int i = 0; i < DPA_GetPtrCount(m_hdpa); ++i) { CACString* pStr; pStr = (CACString*)DPA_GetPtr(m_hdpa, i); ASSERT(pStr); if (pStr && (pStr->StrCmpNI(pszTyped, nChars) == 0)) { iFirstMatch = i; break; } } } if (-1 != iFirstMatch) { // // Find the last match // // PERF: Should we binary search up to the last end of list? for (iLastMatch = iFirstMatch; iLastMatch + 1 < DPA_GetPtrCount(m_hdpa); ++iLastMatch) { CACString* pStr; pStr = (CACString*)DPA_GetPtr(m_hdpa, iLastMatch + 1); ASSERT(pStr); if (NULL == pStr || (pStr->StrCmpNI(pszTyped, nChars) != 0)) { break; } } } } // // See if we should add "Search for <stuff typed in>" to the end of // the list. // int iSearchFor = 0; int nScheme; if (m_fSearchForAdded && // Not a drive letter (*pszTyped && pszTyped[1] != L':') && // Not a UNC path (pszTyped[0] != L'\\' && pszTyped[1] != L'\\') && // Not a known scheme ((nScheme = GetUrlScheme(pszTyped)) == URL_SCHEME_UNKNOWN || nScheme == URL_SCHEME_INVALID) && // Ignore anything theat begins with "www" !(pszTyped[0] == L'w' && pszTyped[1] == L'w' && pszTyped[2] == L'w') // Not a search keyword // !Is ) { // Add "Search for <stuff typed in>" iSearchFor = 1; } m_fSearchFor = iSearchFor; m_iLastMatch = iLastMatch + iSearchFor; m_iFirstMatch = iFirstMatch; if (iSearchFor && iFirstMatch == -1) { // There is one entry - the special "search for <>" entry m_iFirstMatch = 0; } if (_IsAutoSuggestEnabled()) { // Update our drop-down list if ((m_iFirstMatch == -1) || // Hide if there are no matches ((m_iLastMatch == m_iFirstMatch) && // Or if only one match which we've already typed (IForms) (((CACString*)DPA_GetPtr(m_hdpa, m_iFirstMatch))->StrCmpI(pszTyped) == 0))) { _HideDropDown(); } else { if (m_hwndList) { int cItems = m_iLastMatch - m_iFirstMatch + 1; ListView_SetItemCountEx(m_hwndList, cItems, 0); } _ShowDropDown(); _UpdateScrollbar(); } } if (_IsAutoAppendEnabled() && fAppend && m_iFirstMatch != -1 && !fWildCard) { // If caret is not at the end of the string, don't append DWORD dwSel = Edit_GetSel(m_hwndEdit); int iStartSel = LOWORD(dwSel); int iEndSel = HIWORD(dwSel); int iLen = lstrlen(pszTyped); if (iStartSel == iStartSel && iStartSel != iLen) { return; } // Bugbug: Should use the shortest match m_iAppended = -1; _AppendNext(TRUE); } } //+------------------------------------------------------------------------- // Appends the next completion to the current edit text. Returns TRUE if // successful. //-------------------------------------------------------------------------- BOOL CAutoComplete::_AppendNext ( BOOL fAppendToWhack // Apend to next whack (false = append entire match) ) { // Nothing to complete? if (NULL == m_hdpa || 0 == DPA_GetPtrCount(m_hdpa) || m_iFirstMatch == -1 || !_WantToAppendResults()) return FALSE; // // If nothing currently appended, init to the // last item so that we will wrap around to the // first item // if (m_iAppended == -1) { m_iAppended = m_iLastMatch; } int iAppend = m_iAppended; CACString* pStr; // // Loop through the items until we find one without a prefix // do { if (++iAppend > m_iLastMatch) { iAppend = m_iFirstMatch; } pStr = (CACString*)DPA_GetPtr(m_hdpa, iAppend); if (pStr && // Don't append if match has as www. prefix (pStr->PrefixLength() < 4 || StrCmpNI(pStr->GetStr() + pStr->PrefixLength() - 4, L"www.", 4) != 0) && // Ignore the "Search for" if present !(m_fSearchFor && iAppend == m_iLastMatch)) { // We found one so append it _Append(*pStr, fAppendToWhack); m_iAppended = iAppend; } } while (iAppend != m_iAppended); return TRUE; } //+------------------------------------------------------------------------- // Appends the previous completion to the current edit text. Returns TRUE // if successful. //-------------------------------------------------------------------------- BOOL CAutoComplete::_AppendPrevious ( BOOL fAppendToWhack // Append to next whack (false = append entire match) ) { // Nothing to complete? if (NULL == m_hdpa || 0 == DPA_GetPtrCount(m_hdpa) || m_iFirstMatch == -1 || !_WantToAppendResults()) return FALSE; // // If nothing currently appended, init to the // first item so that we will wrap around to the // last item // if (m_iAppended == -1) { m_iAppended = m_iFirstMatch; } int iAppend = m_iAppended; CACString* pStr; // // Loop through the items until we find one without a prefix // do { if (--iAppend < m_iFirstMatch) { iAppend = m_iLastMatch; } pStr = (CACString*)DPA_GetPtr(m_hdpa, iAppend); if (pStr && // Don't append if match has as www. prefix (pStr->PrefixLength() < 4 || StrCmpNI(pStr->GetStr() + pStr->PrefixLength() - 4, L"www.", 4) != 0) && // Ignore the "Search for" if present !(m_fSearchFor && iAppend == m_iLastMatch)) { // We found one so append it _Append(*pStr, fAppendToWhack); m_iAppended = iAppend; } } while (iAppend != m_iAppended); return TRUE; } //+------------------------------------------------------------------------- // Appends the completion to the current edit text //-------------------------------------------------------------------------- void CAutoComplete::_Append ( CACString& rStr, // item to append to the editbox text BOOL fAppendToWhack // Apend to next whack (false = append entire match) ) { ASSERT(_IsAutoAppendEnabled()); if (m_pszCurrent) { int cchCurrent = lstrlen(m_pszCurrent); LPCWSTR pszAppend = rStr.GetStrToCompare() + cchCurrent; int cchAppend; if (fAppendToWhack) { // // Advance to the whacks. // const WCHAR *pch = pszAppend; cchAppend = 0; while (*pch && !_IsWhack(*pch)) { ++cchAppend; pch++; } // // Advance past the whacks. // while (*pch && _IsWhack(*pch)) { ++cchAppend; pch++; } } else { // Append entire match cchAppend = lstrlen(pszAppend); } WCHAR szAppend[MAX_URL_STRING]; StrCpyN(szAppend, pszAppend, cchAppend + 1); _UpdateText(cchCurrent, cchCurrent + cchAppend, m_pszCurrent, szAppend); m_fAppended = TRUE; } } //+------------------------------------------------------------------------- // Hides the AutoSuggest dropdown //-------------------------------------------------------------------------- void CAutoComplete::_HideDropDown() { if (m_hwndDropDown) { ShowWindow(m_hwndDropDown, SW_HIDE); } } //+------------------------------------------------------------------------- // Shows and positions the autocomplete dropdown //-------------------------------------------------------------------------- void CAutoComplete::_ShowDropDown() { if (m_hwndDropDown && !_IsComboboxDropped() && !m_fImeCandidateOpen) { // If the edit window is visible, it better have focus! // (Intelliforms uses an invisible window that doesn't // get focus.) if (IsWindowVisible(m_hwndEdit) && m_hwndEdit != GetFocus()) { ShowWindow(m_hwndDropDown, SW_HIDE); return; } if (!IsWindowVisible(m_hwndDropDown)) { // It should not be possible to open a new dropdown while // another dropdown is visible! But to be safe we'll check ... if (s_hwndDropDown) { ASSERT(FALSE); ShowWindow(s_hwndDropDown, SW_HIDE); } s_hwndDropDown = m_hwndDropDown; // // Install a thread hook so that we can detect when something // happens that should hide the dropdown. // ENTERCRITICAL; if (s_hhookMouse) { // Should never happen because the hook is removed when the dropdown // is hidden. But we can't afford to orphan a hook so we check just // in case! ASSERT(FALSE); UnhookWindowsHookEx(s_hhookMouse); } s_hhookMouse = SetWindowsHookEx(WH_MOUSE, s_MouseHook, HINST_THISDLL, NULL); LEAVECRITICAL; // // Subclass the parent windows so that we can detect when something // happens that should hide the dropdown // _SubClassParent(m_hwndEdit); } _PositionDropDown(); } } //+------------------------------------------------------------------------- // Positions dropdown based on edit window position //-------------------------------------------------------------------------- void CAutoComplete::_PositionDropDown() { RECT rcEdit; GetWindowRect(m_hwndEdit, &rcEdit); int x = rcEdit.left; int y = rcEdit.bottom; // Don't resize if user already has if (!m_fDropDownResized) { #ifndef UNIX m_nDropHeight = 100; #else m_nDropHeight = 150; #endif MINMAXINFO mmi = {0}; SendMessage(m_hwndDropDown, WM_GETMINMAXINFO, 0, (LPARAM)&mmi); m_nDropWidth = max(RECTWIDTH(rcEdit), mmi.ptMinTrackSize.x); // Calculate dropdown height based on number of string matches if (m_hdpa) { /* int iDropDownHeight = m_nStatusHeight + ListView_GetItemSpacing(m_hwndList, FALSE) * DPA_GetPtrCount(m_hdpa); */ int iDropDownHeight = m_nStatusHeight - GetSystemMetrics(SM_CYBORDER) + HIWORD(ListView_ApproximateViewRect(m_hwndList, -1, -1, -1)); if (m_nDropHeight > iDropDownHeight) { m_nDropHeight = iDropDownHeight; } } } int w = m_nDropWidth; int h = m_nDropHeight; // // Make sure we don't go off the screen // HMONITOR hMonitor = MonitorFromWindow(m_hwndEdit, MONITOR_DEFAULTTONEAREST); MONITORINFO mi; mi.cbSize = sizeof(mi); GetMonitorInfo(hMonitor, &mi); RECT rcMon = mi.rcMonitor; int cxMax = rcMon.right - rcMon.left; if (w > cxMax) { w = cxMax; } /* if (x < rcMon.left) { // Off the left edge, so move right x += rcMon.left - x; } else if (x + w > rcMon.right) { // Off the right edge, so move left x -= (x + w - rcMon.right); } */ int cyMax = (RECTHEIGHT(rcMon) - RECTHEIGHT(rcEdit)); if (h > cyMax) { h = cyMax; } BOOL fDroppedUp = FALSE; if (y + h > rcMon.bottom #ifdef ALLOW_ALWAYS_DROP_UP || m_fAlwaysDropUp #endif ) { // Off the bottom of the screen, so see if there is more // room in the up direction if (rcEdit.top > rcMon.bottom - rcEdit.bottom) { // There's more room to pop up y = max(rcEdit.top - h, 0); h = rcEdit.top - y; fDroppedUp = TRUE; } else { // Don't let it go past the bottom h = rcMon.bottom - y; } } BOOL fFlipped = BOOLIFY(m_fDroppedUp) ^ BOOLIFY(fDroppedUp); m_fDroppedUp = fDroppedUp; SetWindowPos(m_hwndDropDown, HWND_TOP, x, y, w, h, SWP_SHOWWINDOW | SWP_NOACTIVATE); if (fFlipped) { _UpdateGrip(); } } //+------------------------------------------------------------------------- // Window procedure for the subclassed edit box //-------------------------------------------------------------------------- LRESULT CAutoComplete::_EditWndProc(UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { case WM_SETTEXT: // // If the text is changed programmatically, we hide the dropdown. // This fixed a bug in the dialog at: // // Internet Options\security\Local Intranet\Sites\Advanced // // - If you select something in the dropdown the press enter, // the enter key is intercepeted by the dialog which clears // the edit field, but the drop-down is not hidden. // if (!m_fSettingText) { _HideDropDown(); } break; case WM_GETDLGCODE: { // // If the auto-suggest drop-down if up, we process // the tab key. // BOOL fDropDownVisible = m_hwndDropDown && IsWindowVisible(m_hwndDropDown); if (wParam == VK_TAB && IsFlagSet(m_dwOptions, ACO_USETAB)) { #ifndef UNIX if ((GetKeyState(VK_CONTROL) < 0) || !fDropDownVisible) { break; } #else // // On unix, an unmodified tab key is processed even if autosuggest // is not visible. // if ((GetKeyState(VK_CONTROL) < 0) || ((GetKeyState(VK_SHIFT) < 0) && !fDropDownVisible)) { break; } if (!fDropDownVisible) { // // Make tab key autocomplete key if at end of edit control // UINT cchTotal = SendMessage(m_hwndEdit, EM_LINELENGTH, 0, 0L); DWORD ichMinSel; SendMessage(m_hwndEdit, EM_GETSEL, (WPARAM) &ichMinSel, 0L); if (ichMinSel == cchTotal) { break; } } #endif // UNIX // We want the tab key return DLGC_WANTTAB; } else if (wParam == VK_ESCAPE && fDropDownVisible) { // eat escape so that dialog boxes (e.g. File Open) are not closed return DLGC_WANTALLKEYS; } break; } case WM_KEYDOWN: if (wParam == VK_TAB) { BOOL fDropDownVisible = m_hwndDropDown && IsWindowVisible(m_hwndDropDown); #ifdef UNIX if (!fDropDownVisible && (GetKeyState(VK_CONTROL) >= 0) && (GetKeyState(VK_SHIFT) >= 0) ) { wParam = VK_END; } else #endif if (fDropDownVisible && GetKeyState(VK_CONTROL) >= 0) { // Map tab to down-arrow and shift-tab to up-arrow wParam = (GetKeyState(VK_SHIFT) >= 0) ? VK_DOWN : VK_UP; } else { return 0; } } // Ensure the background thread knows we have focus _GotFocus(); // ASSERT(m_hThread || m_pThread->IsDisabled()); // If this occurs then we didn't process a WM_SETFOCUS when we should have. BryanSt. if (_OnKeyDown(wParam) == 0) { // // We handled it. // return 0; } if (wParam == VK_DELETE) { LRESULT lRes = DefSubclassProc(m_hwndEdit, uMsg, wParam, lParam); _StartCompletion(FALSE); return lRes; } break; case WM_CHAR: return _OnChar(wParam, lParam); case WM_CUT: case WM_PASTE: case WM_CLEAR: { LRESULT lRet = DefSubclassProc(m_hwndEdit, uMsg, wParam, lParam); // See if we need to update the completion if (!m_pThread->IsDisabled()) { _GotFocus(); _StartCompletion(TRUE); } return lRet; } case WM_SETFOCUS: m_pThread->GotFocus(); break; case WM_KILLFOCUS: { HWND hwndGetFocus = (HWND)wParam; // Ignore focus change to ourselves if (m_hwndEdit != hwndGetFocus) { if (m_hwndDropDown && GetFocus() != m_hwndDropDown) { _HideDropDown(); } m_pThread->LostFocus(); } break; } case WM_DESTROY: { HWND hwndEdit = m_hwndEdit; TraceMsg(AC_GENERAL, "CAutoComplete::_WndProc(WM_DESTROY) releasing subclass."); RemoveWindowSubclass(hwndEdit, s_EditWndProc, 0); if (m_hwndDropDown) { DestroyWindow(m_hwndDropDown); m_hwndDropDown = NULL; m_hwndList = NULL; m_hwndScroll = NULL; m_hwndGrip = NULL; } m_pThread->SyncShutDownBGThread(); SAFERELEASE(m_pThread); Release(); // Release subclass Ref. // Pass it onto the old wndproc. return DefSubclassProc(hwndEdit, uMsg, wParam, lParam); } break; case WM_MOVE: { if (m_hwndDropDown && IsWindowVisible(m_hwndDropDown)) { // Follow edit window, for example when intelliforms window scrolls w/intellimouse _PositionDropDown(); } } break; /* case WM_COMMAND: if (m_pThread->IsDisabled()) { break; } return _OnCommand(wParam, lParam); */ /* case WM_CONTEXTMENU: if (m_pThread->IsDisabled()) { break; } return _ContextMenu(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)); */ #ifndef UNIX case WM_LBUTTONDBLCLK: { // // Bypass our word break routine. We only register this callback on NT because it // doesn't work right on win9x. // if (g_fRunningOnNT && IsWindowUnicode(m_hwndEdit)) { // // We break words at url delimiters for ctrl-left & ctrl-right, but // we want double-click to use standard word selection so that it is easy // to select the URL. // SendMessage(m_hwndEdit, EM_SETWORDBREAKPROC, 0, (DWORD_PTR)m_oldEditWordBreakProc); LRESULT lres = DefSubclassProc(m_hwndEdit, uMsg, wParam, lParam); // Restore our word-break callback SendMessage(m_hwndEdit, EM_SETWORDBREAKPROC, 0, (DWORD_PTR)EditWordBreakProcW); return lres; } break; } #endif // !UNIX case WM_SETFONT: { // If we have a dropdown, recreate it with the latest font if (m_hwndDropDown) { _StopSearch(); DestroyWindow(m_hwndDropDown); m_hwndDropDown = NULL; m_hwndList = NULL; m_hwndScroll = NULL; m_hwndGrip = NULL; _SeeWhatsEnabled(); } break; } case WM_IME_NOTIFY: { // We don't want autocomplete to obsure the IME candidate window DWORD dwCommand = (DWORD)wParam; if (dwCommand == IMN_OPENCANDIDATE) { m_fImeCandidateOpen = TRUE; _HideDropDown(); } else if (dwCommand == IMN_CLOSECANDIDATE) { m_fImeCandidateOpen = FALSE; } } break; default: // Handle registered messages if (uMsg == m_uMsgSearchComplete) { _OnSearchComplete((HDPA)lParam, (BOOL)wParam); return 0; } // Pass mouse wheel messages to the drop-down if it is visible else if ((uMsg == WM_MOUSEWHEEL || uMsg == g_msgMSWheel) && m_hwndDropDown && IsWindowVisible(m_hwndDropDown)) { SendMessage(m_hwndList, uMsg, wParam, lParam); return 0; } break; } return DefSubclassProc(m_hwndEdit, uMsg, wParam, lParam); } //+------------------------------------------------------------------------- // Static window procedure for the subclassed edit box //-------------------------------------------------------------------------- LRESULT CALLBACK CAutoComplete::s_EditWndProc ( HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam, UINT_PTR uIdSubclass, // always zero for us DWORD_PTR dwRefData // -> CAutoComplete ) { CAutoComplete* pac = (CAutoComplete*)dwRefData; ASSERT(pac); if (pac) { ASSERT(pac->m_hwndEdit == hwnd); return pac->_EditWndProc(uMsg, wParam, lParam); } else { return DefWindowProcWrap(hwnd, uMsg, wParam, lParam); } } //+------------------------------------------------------------------------- // Draws the sizing grip. We do this ourselves rather than call // DrawFrameControl because the standard API does not flip upside down on // all platforms. (NT and win98 seem to use a font and thus ignore the map // mode) //-------------------------------------------------------------------------- BOOL DrawGrip(register HDC hdc, LPRECT lprc, BOOL fEraseBackground) { int x, y; int xMax, yMax; int dMin; HBRUSH hbrOld; HPEN hpen, hpenOld; DWORD rgbHilight, rgbShadow; // // The grip is really a pattern of 4 repeating diagonal lines: // One glare // Two raised // One empty // These lines run from bottom left to top right, in the bottom right // corner of the square given by (lprc->left, lprc->top, dMin by dMin. // dMin = min(lprc->right-lprc->left, lprc->bottom-lprc->top); xMax = lprc->left + dMin; yMax = lprc->top + dMin; // // Setup colors // hbrOld = GetSysColorBrush(COLOR_3DFACE); rgbHilight = GetSysColor(COLOR_3DHILIGHT); rgbShadow = GetSysColor(COLOR_3DSHADOW); // // Fill in background of ENTIRE rect // if (fEraseBackground) { hbrOld = SelectBrush(hdc, hbrOld); PatBlt(hdc, lprc->left, lprc->top, lprc->right-lprc->left, lprc->bottom-lprc->top, PATCOPY); SelectBrush(hdc, hbrOld); } else { /* hpen = CreatePen(PS_SOLID, 1, GetSysColor(COLOR_WINDOW)); if (hpen == NULL) return FALSE; hpenOld = SelectPen(hdc, hpen); x = lprc->left - 1; y = lprc->top - 1; MoveToEx(hdc, x, yMax, NULL); LineTo(hdc, xMax, y); SelectPen(hdc, hpenOld); DeletePen(hpen); */ // // Draw background color directly under grip: // hpen = CreatePen(PS_SOLID, 1, GetSysColor(COLOR_3DFACE)); if (hpen == NULL) return FALSE; hpenOld = SelectPen(hdc, hpen); x = lprc->left + 3; y = lprc->top + 3; while (x < xMax) { // // Since dMin is the same horz and vert, x < xMax and y < yMax // are interchangeable... // MoveToEx(hdc, x, yMax, NULL); LineTo(hdc, xMax, y); // Skip 3 lines in between x += 4; y += 4; } SelectPen(hdc, hpenOld); DeletePen(hpen); } // // Draw glare with COLOR_3DHILIGHT: // Create proper pen // Select into hdc // Starting at lprc->left, draw a diagonal line then skip the // next 3 // Select out of hdc // hpen = CreatePen(PS_SOLID, 1, rgbHilight); if (hpen == NULL) return FALSE; hpenOld = SelectPen(hdc, hpen); x = lprc->left; y = lprc->top; while (x < xMax) { // // Since dMin is the same horz and vert, x < xMax and y < yMax // are interchangeable... // MoveToEx(hdc, x, yMax, NULL); LineTo(hdc, xMax, y); // Skip 3 lines in between x += 4; y += 4; } SelectPen(hdc, hpenOld); DeletePen(hpen); // // Draw raised part with COLOR_3DSHADOW: // Create proper pen // Select into hdc // Starting at lprc->left+1, draw 2 diagonal lines, then skip // the next 2 // Select outof hdc // hpen = CreatePen(PS_SOLID, 1, rgbShadow); if (hpen == NULL) return FALSE; hpenOld = SelectPen(hdc, hpen); x = lprc->left+1; y = lprc->top+1; while (x < xMax) { // // Draw two diagonal lines touching each other. // MoveToEx(hdc, x, yMax, NULL); LineTo(hdc, xMax, y); x++; y++; MoveToEx(hdc, x, yMax, NULL); LineTo(hdc, xMax, y); // // Skip 2 lines inbetween // x += 3; y += 3; } SelectPen(hdc, hpenOld); DeletePen(hpen); return TRUE; } //+------------------------------------------------------------------------- // Update the visible characteristics of the gripper depending on whether // the dropdown is "dropped up" or the scrollbar is visible //-------------------------------------------------------------------------- void CAutoComplete::_UpdateGrip() { if (m_hwndGrip) { // // If we have a scrollbar the gripper has a rectangular shape. // if (m_hwndScroll && IsWindowVisible(m_hwndScroll)) { SetWindowRgn(m_hwndGrip, NULL, FALSE); } // // Otherwise, give it a trinagular window region // else { int nWidth = GetSystemMetrics(SM_CXVSCROLL); int nHeight = GetSystemMetrics(SM_CYHSCROLL); POINT rgpt[3] = { {nWidth, 0}, {nWidth, nHeight}, {0, nHeight}, }; // // If dropped up, convert the "bottom-Right" tringle into // a "top-right" triangle // if (m_fDroppedUp) { rgpt[2].y = 0; } HRGN hrgn = CreatePolygonRgn(rgpt, ARRAYSIZE(rgpt), WINDING); if (hrgn && !SetWindowRgn(m_hwndGrip, hrgn, TRUE)) DeleteObject(hrgn); } InvalidateRect(m_hwndGrip, NULL, TRUE); } } //+------------------------------------------------------------------------- // Transfer the listview scroll info into our scrollbar control //-------------------------------------------------------------------------- void CAutoComplete::_UpdateScrollbar() { if (m_hwndScroll) { SCROLLINFO si; si.cbSize = sizeof(si); si.fMask = SIF_ALL; BOOL fScrollVisible = IsWindowVisible(m_hwndScroll); if (GetScrollInfo(m_hwndList, SB_VERT, &si)) { SetScrollInfo(m_hwndScroll, SB_CTL, &si, TRUE); UINT nRange = si.nMax - si.nMin; BOOL fShow = (nRange != 0) && (nRange != (UINT)(si.nPage - 1)); ShowScrollBar(m_hwndScroll, SB_CTL, fShow); if (BOOLIFY(fScrollVisible) ^ BOOLIFY(fShow)) { _UpdateGrip(); } } } } //+------------------------------------------------------------------------- // Window procedure for the AutoSuggest drop-down //-------------------------------------------------------------------------- LRESULT CAutoComplete::_DropDownWndProc(UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { case WM_NCCREATE: { // // Add a listview to the dropdown // m_hwndList = CreateWindowEx(0, WC_LISTVIEW, c_szAutoSuggestTitle, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | LVS_REPORT | LVS_NOCOLUMNHEADER | LVS_SINGLESEL | LVS_OWNERDATA | LVS_OWNERDRAWFIXED, 0, 0, 30000, 30000, m_hwndDropDown, NULL, HINST_THISDLL, NULL); if (m_hwndList) { // Subclass the listview window if (SetProp(m_hwndList, c_szAutoCompleteProp, this)) { // point it to our wndproc and save the old one m_pOldListViewWndProc = (WNDPROC)SetWindowLongPtr(m_hwndList, GWLP_WNDPROC, (LONG_PTR) &s_ListViewWndProc); } ListView_SetExtendedListViewStyle(m_hwndList, LVS_EX_FULLROWSELECT | LVS_EX_ONECLICKACTIVATE | LVS_EX_TRACKSELECT); LV_COLUMN lvColumn; lvColumn.mask = LVCF_FMT | LVCF_WIDTH; lvColumn.fmt = LVCFMT_LEFT; lvColumn.cx = LISTVIEW_COLUMN_WIDTH; ListView_InsertColumn(m_hwndList, 0, &lvColumn); // We'll get the default dimensions when we first show it m_nDropWidth = 0; m_nDropHeight = 0; // Add a scrollbar m_hwndScroll = CreateWindowEx(0, L"scrollbar", NULL, WS_CHILD | SBS_VERT | SBS_RIGHTALIGN, 0, 0, 20, 100, m_hwndDropDown, 0, HINST_THISDLL, NULL); // Add a sizebox m_hwndGrip = CreateWindowEx(0, L"scrollbar", NULL, WS_CHILD | WS_VISIBLE | SBS_SIZEBOX | SBS_SIZEBOXBOTTOMRIGHTALIGN, 0, 0, 20, 100, m_hwndDropDown, 0, HINST_THISDLL, NULL); if (m_hwndGrip) { SetWindowSubclass(m_hwndGrip, s_GripperWndProc, 0, (ULONG_PTR)this); _UpdateGrip(); } } return (m_hwndList != NULL); } case WM_DESTROY: { // // I'm paranoid - should happen when we're hidden // if (s_hwndDropDown != NULL && s_hwndDropDown == m_hwndDropDown) { // Should never happen, but we take extra care not to leak a window hook! ASSERT(FALSE); ENTERCRITICAL; if (s_hhookMouse) { UnhookWindowsHookEx(s_hhookMouse); s_hhookMouse = NULL; } LEAVECRITICAL; s_hwndDropDown = NULL; } _UnSubClassParent(m_hwndEdit); // Unsubclass this window SetWindowLongPtr(m_hwndDropDown, GWLP_USERDATA, (LONG_PTR)NULL); break; } case WM_SYSCOLORCHANGE: SendMessage(m_hwndList, uMsg, wParam, lParam); break; case WM_WININICHANGE: SendMessage(m_hwndList, uMsg, wParam, lParam); if (wParam == SPI_SETNONCLIENTMETRICS) { _UpdateGrip(); } break; case WM_GETMINMAXINFO: { // // Don't shrink smaller than the size of the gripper // LPMINMAXINFO pMmi = (LPMINMAXINFO)lParam; pMmi->ptMinTrackSize.x = GetSystemMetrics(SM_CXVSCROLL); pMmi->ptMinTrackSize.y = GetSystemMetrics(SM_CYHSCROLL); return 0; } case WM_MOVE: { // // Reposition the list view in case we switch between dropping-down // and dropping up. // RECT rc; GetClientRect(m_hwndDropDown, &rc); int nWidth = RECTWIDTH(rc); int nHeight = RECTHEIGHT(rc); int cxGrip = GetSystemMetrics(SM_CXVSCROLL); int cyGrip = GetSystemMetrics(SM_CYHSCROLL); if (m_fDroppedUp) { SetWindowPos(m_hwndGrip, HWND_TOP, nWidth - cxGrip, 0, cxGrip, cyGrip, SWP_NOACTIVATE); SetWindowPos(m_hwndScroll, HWND_TOP, nWidth - cxGrip, cyGrip, cxGrip, nHeight-cyGrip, SWP_NOACTIVATE); } else { SetWindowPos(m_hwndGrip, HWND_TOP, nWidth - cxGrip, nHeight - cyGrip, cxGrip, cyGrip, SWP_NOACTIVATE); SetWindowPos(m_hwndScroll, HWND_TOP, nWidth - cxGrip, 0, cxGrip, nHeight-cyGrip, SWP_NOACTIVATE); } break; } case WM_SIZE: { int nWidth = LOWORD(lParam); int nHeight = HIWORD(lParam); int cxGrip = GetSystemMetrics(SM_CXVSCROLL); int cyGrip = GetSystemMetrics(SM_CYHSCROLL); if (m_fDroppedUp) { SetWindowPos(m_hwndGrip, HWND_TOP, nWidth - cxGrip, 0, cxGrip, cyGrip, SWP_NOACTIVATE); SetWindowPos(m_hwndScroll, HWND_TOP, nWidth - cxGrip, cyGrip, cxGrip, nHeight-cyGrip, SWP_NOACTIVATE); } else { SetWindowPos(m_hwndGrip, HWND_TOP, nWidth - cxGrip, nHeight - cyGrip, cxGrip, cyGrip, SWP_NOACTIVATE); SetWindowPos(m_hwndScroll, HWND_TOP, nWidth - cxGrip, 0, cxGrip, nHeight-cyGrip, SWP_NOACTIVATE); } // Save the new dimensions m_nDropWidth = nWidth + 2*GetSystemMetrics(SM_CXBORDER); m_nDropHeight = nHeight + 2*GetSystemMetrics(SM_CYBORDER); MoveWindow(m_hwndList, 0, 0, LISTVIEW_COLUMN_WIDTH + 10*cxGrip, nHeight, TRUE); _UpdateScrollbar(); InvalidateRect(m_hwndList, NULL, FALSE); break; } case WM_NCHITTEST: { RECT rc; POINT pt = {GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)}; // If the in the grip, show the sizing cursor if (m_hwndGrip) { GetWindowRect(m_hwndGrip, &rc); if (PtInRect(&rc, pt)) { if(IS_WINDOW_RTL_MIRRORED(m_hwndDropDown)) { return (m_fDroppedUp) ? HTTOPLEFT : HTBOTTOMLEFT; } else { return (m_fDroppedUp) ? HTTOPRIGHT : HTBOTTOMRIGHT; } } } } break; case WM_SHOWWINDOW: { s_fNoActivate = FALSE; BOOL fShow = (BOOL)wParam; if (!fShow) { // // We are being hidden so we no longer need to // subclass the parent windows. // _UnSubClassParent(m_hwndEdit); // // Remove the mouse hook. We shouldn't need to protect this global with // a critical section because another dropdown cannot be shown // before we are hidden. But we don't want to chance orphaning a hook // so to be safe we protect write access to this variable. // ENTERCRITICAL; if (s_hhookMouse) { UnhookWindowsHookEx(s_hhookMouse); s_hhookMouse = NULL; } LEAVECRITICAL; s_hwndDropDown = NULL; // Deselect the current selection int iCurSel = ListView_GetNextItem(m_hwndList, -1, LVNI_SELECTED); if (iCurSel) { ListView_SetItemState(m_hwndList, iCurSel, 0, 0x000f); } } } break; case WM_MOUSEACTIVATE: // // We don't want mouse clicks to activate us and // take focus from the edit box. // return (LRESULT)MA_NOACTIVATE; case WM_NCLBUTTONDOWN: // // We don't want resizing to activate us and deactivate the app. // The WM_MOUSEACTIVATE message above prevents mouse downs from // activating us, but mouse up after a resize still activates us. // if (wParam == HTBOTTOMRIGHT || wParam == HTTOPRIGHT) { s_fNoActivate = TRUE; } break; case WM_VSCROLL: { ASSERT(m_hwndScroll); // // Pass the scroll messages from our control to the listview // WORD nScrollCode = LOWORD(wParam); if (nScrollCode == SB_THUMBTRACK || nScrollCode == SB_THUMBPOSITION) { // // The listview ignores the 16-bit position passed in and // queries the internal window scrollbar for the tracking // position. Since this returns the wrong track position, // we have to handle thumb tracking ourselves. // WORD nPos = HIWORD(wParam); SCROLLINFO si; si.cbSize = sizeof(si); si.fMask = SIF_ALL; if (GetScrollInfo(m_hwndScroll, SB_CTL, &si)) { // // The track position is always at the top of the list. // So, if we are scrolling up, make sure that the track // position is visible. Otherwise we need to ensure // that a full page is visible below the track positon. // int nEnsureVisible = si.nTrackPos; if (si.nTrackPos > si.nPos) { nEnsureVisible += si.nPage - 1; } SendMessage(m_hwndList, LVM_ENSUREVISIBLE, nEnsureVisible, FALSE); } } else { // Let listview handle it SendMessage(m_hwndList, uMsg, wParam, lParam); } _UpdateScrollbar(); return 0; } case WM_EXITSIZEMOVE: // // Resize operation is over so permit the app to lose acitvation // s_fNoActivate = FALSE; m_fDropDownResized = TRUE; return 0; case WM_DRAWITEM: { // // We need to draw the contents of the list view ourselves // so that we can show items in the selected state even // when the edit control has focus. // LPDRAWITEMSTRUCT pdis = (LPDRAWITEMSTRUCT)lParam; if (pdis->itemID != -1) { HDC hdc = pdis->hDC; RECT rc = pdis->rcItem; BOOL fTextHighlight = pdis->itemState & ODS_SELECTED; // Setup the dc before we use it. BOOL fRTLReading = GetWindowLong(pdis->hwndItem, GWL_EXSTYLE) & WS_EX_RTLREADING; UINT uiOldTextAlign; if (fRTLReading) { uiOldTextAlign = GetTextAlign(hdc); SetTextAlign(hdc, uiOldTextAlign | TA_RTLREADING); } SetBkColor(hdc, GetSysColor(fTextHighlight ? COLOR_HIGHLIGHT : COLOR_WINDOW)); SetTextColor(hdc, GetSysColor(fTextHighlight ? COLOR_HIGHLIGHTTEXT : COLOR_WINDOWTEXT)); // Center the string vertically within rc SIZE sizeText; WCHAR szText[MAX_URL_STRING]; _GetItem(pdis->itemID, szText, ARRAYSIZE(szText), TRUE); int cch = lstrlen(szText); GetTextExtentPoint(hdc, szText, cch, &sizeText); int yMid = (rc.top + rc.bottom) / 2; int yString = yMid - (sizeText.cy/2); int xString = 5; // // If this is a .url string, don't display the extension // if (cch > 4 && StrCmpNI(szText + cch - 4, L".url", 4) == 0) { cch -= 4; } ExtTextOut(hdc, xString, yString, ETO_OPAQUE | ETO_CLIPPED, &rc, szText, cch, NULL); // Restore the text align in the dc. if (fRTLReading) { SetTextAlign(hdc, uiOldTextAlign); } } break; } case WM_NOTIFY: { // // Respond to notification messages from the list view // LPNMHDR pnmhdr = (LPNMHDR)lParam; switch (pnmhdr->code) { case LVN_GETDISPINFO: { // // Return the text for an autosuggest item // ASSERT(pnmhdr->hwndFrom == m_hwndList); LV_DISPINFO* pdi = (LV_DISPINFO*)lParam; if (pdi->item.mask & LVIF_TEXT) { _GetItem(pdi->item.iItem, pdi->item.pszText, pdi->item.cchTextMax + 1, TRUE); } break; } case LVN_ITEMCHANGED: { // // When an item is selected in the list view, we transfer it to the // edit control. But only if the selection was not caused by the // mouse passing over an element (hot tracking). // if (!m_fInHotTracking) { LPNMLISTVIEW pnmv = (LPNMLISTVIEW)lParam; if ((pnmv->uChanged & LVIF_STATE) && (pnmv->uNewState & (LVIS_FOCUSED | LVIS_SELECTED))) { WCHAR szBuf[MAX_URL_STRING]; _GetItem(pnmv->iItem, szBuf, ARRAYSIZE(szBuf), FALSE); // Copy the selection to the edit box and place caret at the end _SetEditText(szBuf); int cch = lstrlen(szBuf); Edit_SetSel(m_hwndEdit, cch, cch); } } // // Update the scrollbar. Note that we have to post a message to do this // after returning from this function. Otherwise we get old info // from the listview about the scroll positon. // PostMessage(m_hwndDropDown, AM_UPDATESCROLLPOS, 0, 0); break; } case LVN_ITEMACTIVATE: { // // Someone activated an item in the listview. We want to make sure that // the items is selected (without hot tracking) so that the contents // are moved to the edit box, and then simulate and enter key press. // LPNMITEMACTIVATE lpnmia = (LPNMITEMACTIVATE)lParam; WCHAR szBuf[MAX_URL_STRING]; _GetItem(lpnmia->iItem, szBuf, ARRAYSIZE(szBuf), FALSE); // Copy the selection to the edit box and place caret at the end _SetEditText(szBuf); int cch = lstrlen(szBuf); Edit_SetSel(m_hwndEdit, cch, cch); // // Intelliforms don't want an enter key because this would submit the // form, so first we try sending a notification. // if (SendMessage(m_hwndEdit, m_uMsgItemActivate, 0, (LPARAM)szBuf) == 0) { // Not an intelliform, so simulate an enter key instead. SendMessage(m_hwndEdit, WM_KEYDOWN, VK_RETURN, 0); SendMessage(m_hwndEdit, WM_KEYUP, VK_RETURN, 0); } _HideDropDown(); break; } case LVN_HOTTRACK: { // // Select items as we mouse-over them // LPNMLISTVIEW lpnmlv = (LPNMLISTVIEW)lParam; LVHITTESTINFO lvh; lvh.pt = lpnmlv->ptAction; int iItem = ListView_HitTest(m_hwndList, &lvh); if (iItem != -1) { // Update the current selection. The m_fInHotTracking flag prevents the // edit box contents from being updated m_fInHotTracking = TRUE; ListView_SetItemState(m_hwndList, iItem, LVIS_SELECTED|LVIS_FOCUSED, 0x000f); SendMessage(m_hwndList, LVM_ENSUREVISIBLE, iItem, FALSE); m_fInHotTracking = FALSE; } // We processed this... return TRUE; } } break; } case AM_UPDATESCROLLPOS: { if (m_hwndScroll) { int nTop = ListView_GetTopIndex(m_hwndList); SetScrollPos(m_hwndScroll, SB_CTL, nTop, TRUE); } break; } case AM_BUTTONCLICK: { // // This message is sent by the thread hook when a mouse click is detected outside // the drop-down window. Unless the click occurred inside the combobox, we will // hide the dropdown. // MOUSEHOOKSTRUCT *pmhs = (MOUSEHOOKSTRUCT*)lParam; HWND hwnd = pmhs->hwnd; RECT rc; if (hwnd != m_hwndCombo && hwnd != m_hwndEdit && // See if we clicked within the bounds of the editbox. This is // necessary for intelliforms. // bugbug: This assumes that the editbox is entirely visible! GetWindowRect(m_hwndEdit, &rc) && !PtInRect(&rc, pmhs->pt)) { _HideDropDown(); } return 0; } } return DefWindowProcWrap(m_hwndDropDown, uMsg, wParam, lParam); } //+------------------------------------------------------------------------- // Static window procedure for the AutoSuggest drop-down //-------------------------------------------------------------------------- LRESULT CALLBACK CAutoComplete::s_DropDownWndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { CAutoComplete* pThis; if (uMsg == WM_NCCREATE) { pThis = (CAutoComplete*)((LPCREATESTRUCT)lParam)->lpCreateParams; SetWindowLongPtr(hwnd, GWLP_USERDATA, (LONG_PTR) pThis); pThis->m_hwndDropDown = hwnd; } else { pThis = (CAutoComplete*)GetWindowLongPtr(hwnd, GWLP_USERDATA); } if (pThis) { ASSERT(pThis->m_hwndDropDown == hwnd); return pThis->_DropDownWndProc(uMsg, wParam, lParam); } else { return DefWindowProcWrap(hwnd, uMsg, wParam, lParam); } } //+------------------------------------------------------------------------- // We subclass the listview to prevent it from activating the drop-down // when someone clicks on it. //-------------------------------------------------------------------------- LRESULT CAutoComplete::_ListViewWndProc(UINT uMsg, WPARAM wParam, LPARAM lParam) { LRESULT lRet; switch (uMsg) { case WM_LBUTTONDOWN: case WM_RBUTTONDOWN: case WM_MBUTTONDOWN: case WM_LBUTTONUP: case WM_RBUTTONUP: case WM_MBUTTONUP: // // Prevent mouse clicks from activating this view // s_fNoActivate = TRUE; lRet = CallWindowProc(m_pOldListViewWndProc, m_hwndList, uMsg, wParam, lParam); s_fNoActivate = FALSE; return 0; case WM_DESTROY: // Restore old wndproc. RemoveProp(m_hwndList, c_szAutoCompleteProp); if (m_pOldListViewWndProc) { SetWindowLongPtr(m_hwndList, GWLP_WNDPROC, (LONG_PTR) m_pOldListViewWndProc); lRet = CallWindowProc(m_pOldListViewWndProc, m_hwndList, uMsg, wParam, lParam); m_pOldListViewWndProc = NULL; } return 0; case WM_GETOBJECT: if (lParam == OBJID_CLIENT) { SAFERELEASE(m_pDelegateAccObj); if (SUCCEEDED(CreateStdAccessibleObject(m_hwndList, OBJID_CLIENT, IID_IAccessible, (void **)&m_pDelegateAccObj))) { return LresultFromObject(IID_IAccessible, wParam, SAFECAST(this, IAccessible *)); } } break; case WM_NCHITTEST: { RECT rc; POINT pt = {GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)}; // If in the grip area, let our parent handle it if (m_hwndGrip) { GetWindowRect(m_hwndGrip, &rc); if (PtInRect(&rc, pt)) { return HTTRANSPARENT; } } break; } } lRet = CallWindowProc(m_pOldListViewWndProc, m_hwndList, uMsg, wParam, lParam); return lRet; } //+------------------------------------------------------------------------- // Static window procedure for the subclassed listview //-------------------------------------------------------------------------- LRESULT CAutoComplete::s_ListViewWndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { CAutoComplete* pac = (CAutoComplete*)GetProp(hwnd, c_szAutoCompleteProp); ASSERT(pac); if (pac) { return pac->_ListViewWndProc(uMsg, wParam, lParam); } else { return DefWindowProcWrap(hwnd, uMsg, wParam, lParam); } } //+------------------------------------------------------------------------- // This message hook is only installed when the AutoSuggest dropdown // is visible. It hides the dropdown if you click on any window other than // the dropdown or associated editbox/combobox. //-------------------------------------------------------------------------- LRESULT CALLBACK CAutoComplete::s_MouseHook(int nCode, WPARAM wParam, LPARAM lParam) { if (nCode >= 0) { MOUSEHOOKSTRUCT *pmhs = (MOUSEHOOKSTRUCT*)lParam; ASSERT(pmhs); switch (wParam) { case WM_LBUTTONDOWN: case WM_MBUTTONDOWN: case WM_RBUTTONDOWN: case WM_NCLBUTTONDOWN: case WM_NCMBUTTONDOWN: case WM_NCRBUTTONDOWN: { HWND hwnd = pmhs->hwnd; // If the click was outside the edit/combobox/dropdown, then // hide the dropdown. if (hwnd != s_hwndDropDown) { // Ignore if the button was clicked in the dropdown RECT rc; if (GetWindowRect(s_hwndDropDown, &rc) && !PtInRect(&rc, pmhs->pt)) { // Inform the dropdown SendMessage(s_hwndDropDown, AM_BUTTONCLICK, 0, (LPARAM)pmhs); } } break; } } } return CallNextHookEx(s_hhookMouse, nCode, wParam, lParam); } //+------------------------------------------------------------------------- // Subclasses all of the parents of hwnd so we can determine when they // are moved, deactivated, or clicked on. We use these events to signal // the window that has focus to hide its autocomplete dropdown. This is // similar to the CB_SHOWDROPDOWN message sent to comboboxes, but we cannot // assume that we are autocompleting a combobox. //-------------------------------------------------------------------------- void CAutoComplete::_SubClassParent ( HWND hwnd // window to notify of events ) { // // Subclass all the parent windows because any of them could cause // the position of hwnd to change which should hide the dropdown. // HWND hwndParent = hwnd; DWORD dwThread = GetCurrentThreadId(); while (hwndParent = GetParent(hwndParent)) { // Only subclass if this window is owned by our thread if (dwThread == GetWindowThreadProcessId(hwndParent, NULL)) { SetWindowSubclass(hwndParent, s_ParentWndProc, 0, (ULONG_PTR)this); } } } //+------------------------------------------------------------------------- // Unsubclasses all of the parents of hwnd. We use the helper functions in // comctl32 to safely unsubclass a window even if someone else subclassed // the window after us. //-------------------------------------------------------------------------- void CAutoComplete::_UnSubClassParent ( HWND hwnd // window to notify of events ) { HWND hwndParent = hwnd; DWORD dwThread = GetCurrentThreadId(); while (hwndParent = GetParent(hwndParent)) { // Only need to unsubclass if this window is owned by our thread if (dwThread == GetWindowThreadProcessId(hwndParent, NULL)) { RemoveWindowSubclass(hwndParent, s_ParentWndProc, 0); } } } //+------------------------------------------------------------------------- // Subclassed window procedure of the parents ot the editbox being // autocompleted. This intecepts messages that should case the autocomplete // dropdown to be hidden. //-------------------------------------------------------------------------- LRESULT CALLBACK CAutoComplete::s_ParentWndProc ( HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam, UINT_PTR uIdSubclass, // always zero for us DWORD_PTR dwRefData // -> CParentWindow ) { CAutoComplete* pThis = (CAutoComplete*)dwRefData; if (!pThis) return DefSubclassProc(hwnd, uMsg, wParam, lParam); switch (uMsg) { case WM_WINDOWPOSCHANGED: { // // Check the elapsed time since this was last called. We want to avoid an infinite loop // with another window that also wants to be on top. // static DWORD s_dwTicks = 0; DWORD dwTicks = GetTickCount(); DWORD dwEllapsed = dwTicks - s_dwTicks; s_dwTicks = dwTicks; if (dwEllapsed > 100) { // Make sure our dropdown stays on top LPWINDOWPOS pwp = (LPWINDOWPOS)lParam; if (IsFlagClear(pwp->flags, SWP_NOZORDER) && IsWindowVisible(pThis->m_hwndDropDown)) { SetWindowPos(pThis->m_hwndDropDown, HWND_TOP, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE); } } break; } case WM_ACTIVATE: { // Ignore if we are not being deactivated WORD fActive = LOWORD(wParam); if (fActive != WA_INACTIVE) { break; } // Drop through } case WM_MOVING: case WM_SIZE: case WM_LBUTTONDOWN: case WM_RBUTTONDOWN: case WM_MBUTTONDOWN: pThis->_HideDropDown(); break; case WM_NCACTIVATE: // // While clicking on the autosuggest dropdown, we // want to prevent the dropdown from being activated. // if (s_fNoActivate) return FALSE; break; case WM_DESTROY: RemoveWindowSubclass(hwnd, s_ParentWndProc, 0); break; default: break; } return DefSubclassProc(hwnd, uMsg, wParam, lParam); } //+------------------------------------------------------------------------- // Subclassed window procedure fir the grip re-sizer control //-------------------------------------------------------------------------- LRESULT CALLBACK CAutoComplete::s_GripperWndProc ( HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam, UINT_PTR uIdSubclass, // always zero for us DWORD_PTR dwRefData // -> CParentWindow ) { CAutoComplete* pThis = (CAutoComplete*)dwRefData; if (!pThis) return DefSubclassProc(hwnd, uMsg, wParam, lParam); switch (uMsg) { case WM_NCHITTEST: return HTTRANSPARENT; case WM_PAINT: PAINTSTRUCT ps; BeginPaint(hwnd, &ps); EndPaint(hwnd, &ps); break; case WM_ERASEBKGND: { HDC hdc = (HDC)wParam; RECT rc; GetClientRect(hwnd, &rc); int nOldMapMode = 0; BOOL fScrollVisible = pThis->m_hwndScroll && IsWindowVisible(pThis->m_hwndScroll); // // See if we need to vertically flip the grip // if (pThis->m_fDroppedUp) { nOldMapMode = SetMapMode(hdc, MM_ANISOTROPIC); SetWindowOrgEx(hdc, 0, 0, NULL); SetWindowExtEx(hdc, 1, 1, NULL); SetViewportOrgEx(hdc, 0, GetSystemMetrics(SM_CYHSCROLL), NULL); SetViewportExtEx(hdc, 1, -1, NULL); } // The standard DrawFrameControl API does not draw upside down on all platforms // DrawFrameControl(hdc, &rc, DFC_SCROLL, DFCS_SCROLLSIZEGRIP); DrawGrip(hdc, &rc, fScrollVisible); if (nOldMapMode) { SetViewportOrgEx(hdc, 0, 0, NULL); SetViewportExtEx(hdc, 1, 1, NULL); SetMapMode(hdc, nOldMapMode); } return 1; } case WM_DESTROY: RemoveWindowSubclass(hwnd, s_GripperWndProc, 0); break; default: break; } return DefSubclassProc(hwnd, uMsg, wParam, lParam); }
[ "mehmetyilmaz3371@gmail.com" ]
mehmetyilmaz3371@gmail.com
421bbf5b78de8fa6349bad55384fb1c3e847822c
3d5e097599e1a3996ec66e366902a9af8abb36dc
/application/pagerank.cpp
dfd3b71f5d4bb9325523c9455e8e3a1e68015416
[]
no_license
Tecelecta/HIP-GSWITCH
4831fec64d84b20f23c30b943423a61a4be4e241
c1890201197f5bc57eff260a5936198843a3d6c5
refs/heads/master
2020-04-26T23:03:11.652855
2019-04-04T14:28:54
2019-04-04T14:28:54
173,890,847
0
0
null
null
null
null
UTF-8
C++
false
false
3,674
cpp
#include <hip/hip_runtime.h> #include <iostream> #include <algorithm> #include "gswitch.h" const float damp = 0.85f; const float eps = 0.01f; using G = device_graph_t<CSR, Empty>; // actors inspector_t inspector; selector_t selector; executor_t executor; feature_t fets; config_t conf; stat_t stats; struct PR:Functor<VC,float,float,Empty>{ __device__ Status filter(int vid, G g){ float* cache = wa_of(vid); float* pr = ra_of(vid); int od = g.get_out_degree(vid); float newpr = (*cache*damp + 1-damp); if(od) newpr /= od; float err = (newpr-*pr)/(*pr); *cache = 0; *pr = newpr; if(err > -eps && err < eps) return Inactive; return Active; } __device__ float emit(int vid, Empty *em, G g) { return *ra_of(vid); } __device__ bool comp(float* v, float newv, G g) { *v += newv;return true; } __device__ bool compAtomic(float* v, float newv, G g) { atomicAdd(v, newv);return true; } }; void validation(host_graph_t<CSR,Empty> hg, float* pr){ for(int i = 0; i<hg.nvertexs; ++i) if(hg.odegrees[i]) pr[i] *= hg.odegrees[i]; bool flag = true; for(int i=0;i<hg.nvertexs;++i){ int s = hg.start_pos[i]; int e = (i==hg.nvertexs-1)?hg.nedges:hg.start_pos[i+1]; float sum = 0; for(int j = s; j < e; ++ j){ int u = hg.adj_list[j]; sum += pr[u]/hg.odegrees[u]; } sum = sum*damp + 1-damp; float diff = (sum - pr[i])/sum; if(fabs(diff)<eps) flag&=true; else flag&=false; if(!flag){ puts("failed"); std::cout << "id: " << i << " "<< sum << " " << pr[i] << " " << hg.odegrees[i] << std::endl; break; } } if(flag) puts("passed"); if(cmd_opt.verbose){ std::sort(pr,pr+hg.nvertexs); std::cout << "top 10 pagerank:" << std::endl; for(int i=1;i<=10;++i){ std::cout << pr[hg.nvertexs-i] << std::endl; } } } template<typename G, typename F> double run_pagerank(G g, F f){ // step 1: initializing LOG(" -- Initializing\n"); active_set_t as = build_active_set(g.nvertexs, conf); as.init(ALL_ACTIVE); double s = mwtime(); // step 2: Execute Algorithm for(int level=0;;level++){ inspector.inspect(as, g, f, stats, fets, conf); if(as.finish(g,f,conf)) break; selector.select(stats, fets, conf); executor.filter(as, g, f, stats, fets, conf); g.update_level(); executor.expand(as, g, f, stats, fets, conf); if(as.finish(g,f,conf)) break; } double e = mwtime(); return e-s; } int main(int argc, char* argv[]){ parse_cmd(argc, argv, "PageRank"); // step 1 : set features fets.centric = VC; fets.pattern = ASSO; fets.fromall = true; fets.toall = true; // step 2 : init Graph & Algorithm auto g = build_graph<VC>(cmd_opt.path, fets, cmd_opt.with_header, cmd_opt.with_weight, cmd_opt.directed); PR f; f.data.build(g.hg.nvertexs); f.data.init_wa([](int i){ return 0; }); f.data.init_ra([g](int i){ if(g.hg.odegrees[i]) return (1-damp)/g.hg.odegrees[i]; else return (1-damp); }); f.data.set_zero(0.0f); init_conf(stats, fets, conf, g, f); // step 3 : execute Algorithm LOG(" -- Launching PageRank\n"); double time = run_pagerank(g.dg, f); // step 4 : validation f.data.sync_ra(); if(cmd_opt.validation){ validation(g.hg, f.data.h_ra); } LOG("GPU PageRank time: %.3f ms\n", time); std::cout << time << std::endl; //std::cout << fets.nvertexs << " " //<< fets.nedges << " " //<< fets.avg_deg << " " //<< fets.std_deg << " " //<< fets.range << " " //<< fets.GI << " " //<< fets.Her << " " //<< time << std::endl; return 0; }
[ "lmy@ncic.ac.cn" ]
lmy@ncic.ac.cn
79009a0dce2350c74cdd34c6a0030d6eaaedad4e
cef685715a413ec34b95004dd966a4263bbb23af
/fenlei_predict/dialog.h
23c8f277e332daaee95283bb17ac9fdde09107c5
[]
no_license
gangan1996/wps_fenlei
11f13a0830efe6c7c1d62495f7629cbc20826dc2
d3cebab92bf8c638f41a6de2b9174dba64904a90
refs/heads/master
2020-03-18T11:00:52.566293
2018-05-24T13:00:01
2018-05-24T13:00:01
134,645,544
0
0
null
null
null
null
UTF-8
C++
false
false
387
h
#ifndef DIALOG_H #define DIALOG_H #include <QDialog> #include <vector> #include <string> using namespace std; namespace Ui { class Dialog; } class Dialog : public QDialog { Q_OBJECT public: explicit Dialog(QWidget *parent = 0); ~Dialog(); public: void sendData(vector<string>v1,vector<string>v2,vector<int>v3); private: Ui::Dialog *ui; }; #endif // DIALOG_H
[ "18331129181@163.com" ]
18331129181@163.com
072738146856ae3d8dd5c330dde579fdf7d946c5
bd7d4c148df27f8be6649d313efb24f536b7cf34
/src/armnnCaffeParser/test/TestMultiInputsOutputs.cpp
ebda3ce1b8cea7a8332508d16f2237e72aed87ed
[ "MIT" ]
permissive
codeaudit/armnn
701e126a11720760ee8209cc866aa095554696c2
c577f2c6a3b4ddb6ba87a882723c53a248afbeba
refs/heads/master
2020-03-29T00:48:17.399665
2018-08-31T08:22:23
2018-08-31T08:22:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,174
cpp
// // Copyright © 2017 Arm Ltd. All rights reserved. // See LICENSE file in the project root for full license information. // #include <boost/test/unit_test.hpp> #include "armnnCaffeParser/ICaffeParser.hpp" #include "ParserPrototxtFixture.hpp" BOOST_AUTO_TEST_SUITE(CaffeParser) struct MultiInputsOutputsFixture : public armnnUtils::ParserPrototxtFixture<armnnCaffeParser::ICaffeParser> { MultiInputsOutputsFixture() { m_Prototext = R"( name: "MultiInputsOutputs" layer { name: "input1" type: "Input" top: "input1" input_param { shape: { dim: 1 } } } layer { name: "input2" type: "Input" top: "input2" input_param { shape: { dim: 1 } } } layer { bottom: "input1" bottom: "input2" top: "add1" name: "add1" type: "Eltwise" } layer { bottom: "input2" bottom: "input1" top: "add2" name: "add2" type: "Eltwise" } )"; Setup({ }, { "add1", "add2" }); } }; BOOST_FIXTURE_TEST_CASE(MultiInputsOutputs, MultiInputsOutputsFixture) { RunTest<1>({ { "input1",{ 12.0f } },{ "input2",{ 13.0f } } }, { { "add1",{ 25.0f } },{ "add2",{ 25.0f } } }); } BOOST_AUTO_TEST_SUITE_END()
[ "telmo.soares@arm.com" ]
telmo.soares@arm.com
7b182722038db0efdf27599810643da825138c65
70ecac44b229e4e35050fd93ccc8b8778dc94720
/Design pattern/Bridge pattern/ConcreteImplementorA.h
c9891b565c4bb5ddedaafcf51a96a1c5e33be4ab
[ "MIT" ]
permissive
t-mochizuki/cpp-study
5602661ee1ad118b93ee8993e006f84b85a10a8b
1f6eb99db765fd970f2a44f941610d9a79200953
refs/heads/main
2023-07-21T13:55:11.664199
2023-07-10T09:35:11
2023-07-10T09:35:11
92,583,299
2
0
null
null
null
null
UTF-8
C++
false
false
489
h
#ifndef CONCRETE_IMPLEMENTOR_A #define CONCRETE_IMPLEMENTOR_A 1 #include "Implementor.h" namespace design { #include <iostream> #include <string> using std::cout; using std::endl; using std::string; class ConcreteImplementorA : public Implementor { private: public: ConcreteImplementorA() {} virtual ~ConcreteImplementorA() {} void operation() override { cout << "ConcreteImplementorA" << endl; } }; } // namespace design #endif // CONCRETE_IMPLEMENTOR_A
[ "t-mochizuki@users.noreply.github.com" ]
t-mochizuki@users.noreply.github.com
7d2e496d2930b093f96c97268b020fdcfdea63a9
bd1fea86d862456a2ec9f56d57f8948456d55ee6
/000/097/790/CWE36_Absolute_Path_Traversal__wchar_t_listen_socket_ifstream_81_goodG2B.cpp
64328cc3c97584e9b73fce2f2828397993148bce
[]
no_license
CU-0xff/juliet-cpp
d62b8485104d8a9160f29213368324c946f38274
d8586a217bc94cbcfeeec5d39b12d02e9c6045a2
refs/heads/master
2021-03-07T15:44:19.446957
2020-03-10T12:45:40
2020-03-10T12:45:40
246,275,244
0
1
null
null
null
null
UTF-8
C++
false
false
1,180
cpp
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE36_Absolute_Path_Traversal__wchar_t_listen_socket_ifstream_81_goodG2B.cpp Label Definition File: CWE36_Absolute_Path_Traversal.label.xml Template File: sources-sink-81_goodG2B.tmpl.cpp */ /* * @description * CWE: 36 Absolute Path Traversal * BadSource: listen_socket Read data using a listen socket (server side) * GoodSource: Full path and file name * Sinks: ifstream * BadSink : Open the file named in data using ifstream::open() * Flow Variant: 81 Data flow: data passed in a parameter to an virtual method called via a reference * * */ #ifndef OMITGOOD #include "std_testcase.h" #include "CWE36_Absolute_Path_Traversal__wchar_t_listen_socket_ifstream_81.h" #include <fstream> using namespace std; namespace CWE36_Absolute_Path_Traversal__wchar_t_listen_socket_ifstream_81 { void CWE36_Absolute_Path_Traversal__wchar_t_listen_socket_ifstream_81_goodG2B::action(wchar_t * data) const { { ifstream inputFile; /* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */ inputFile.open((char *)data); inputFile.close(); } } } #endif /* OMITGOOD */
[ "frank@fischer.com.mt" ]
frank@fischer.com.mt
f25c7e1c4f1254f16558166bc6a20987401b1cc8
67611090dd9203fcac9febdaef32f1ab60d777b6
/c++/faster-than-wind/ftw-game/src/Engine/pathfinder.cpp
0cfb1123e4d9514f8b2045d9ebd79cdf9d295720
[]
no_license
Hopson97/Ancient-Projects
bdcb54a61b5722a479872961057367c96f98a950
bea4c7e5c1af3ce23994d88a199427ac2ce69139
refs/heads/master
2020-06-26T18:39:08.194914
2020-03-16T07:55:40
2020-03-16T07:55:40
199,717,112
4
2
null
null
null
null
UTF-8
C++
false
false
3,339
cpp
#include "pathfinder.h" #include "constants.h" //the A* algorithm was a bit much for me to take in, so I decided to do my own take on a "path finder" //Constructor is not possible due to the nature of the project, so the vectors have to be set up later (aka when they actually have stuff in them) void PathFinder::setUp( const std::vector<Room>& rooms, const std::vector<Unit>& units ) { this->rooms = &rooms; this->units = &units; } void PathFinder::createPath(const sf::Vector2f& _oldPos, const sf::Vector2f& _newPos) { currRoom = nullptr; oldPos = _oldPos; newPos = _newPos; convToBase40(oldPos); convToBase40(newPos); setCurrPos( oldPos ); while ( !positions.empty() ) { positions.pop(); } std::vector<sf::Vector2f> posChecked; detectCurrentRoom(); while ( true ) { checkCurrentTile(); } } void PathFinder::checkCurrentTile() { /* if ( goalFound() ) return; for ( auto& wall : currRoom->getWalls() ) { if( wall.getSprite().getLocalBounds().intersects( curr ) { rotCurr(); } } */ } bool PathFinder::goalFound() { return false; } void PathFinder::detectCurrentRoom() { curr.setRotation(0); sf::Vector2f temp ( curr.getPosition().x, curr.getPosition().y); convToBase40( temp ); curr.setPosition ( temp ); curr.move( -40, 0); for( unsigned int i = 0; i < rooms->size() ; i++ ) { if(curr.getLocalBounds().intersects( rooms->at(i).getSprite().getLocalBounds() ) ) { currRoom = &rooms->at(i); curr.move( 40, 0); return; } } } void PathFinder::rotCurr( ) { if ( curr.getRotation() == 270 ) curr.setRotation( 0 ); else { curr.rotate(90); } setCheckPos(); } void PathFinder::setCurrPos( const sf::Vector2f& pos) { curr.setPosition( pos.x + ship::TILE_SIZE / 2, pos.y + ship::TILE_SIZE / 2 ); setCheckPos(); } void PathFinder::setCheckPos() { int r = curr.getRotation(); if ( r == 0 ) { atPos = sf::Vector2f ( curr.getPosition().x + 40, curr.getPosition().y ); } else if ( r == 90 ) { atPos = sf::Vector2f ( curr.getPosition().x - 1, curr.getPosition().y + 39 ); } else if ( r == 180 ) { atPos = sf::Vector2f ( curr.getPosition().x - 40, curr.getPosition().y - 1); } else if ( r == 270 ) { atPos = sf::Vector2f ( curr.getPosition().x, curr.getPosition().y - 40 ); } } void PathFinder::convToBase40 ( sf::Vector2f& pos ) { if (( (int)pos.x % 40 != 0)){ //If pos.x divided by 40 does not have a remainder of 0: while ( (int)pos.x % 40 != 0){ //While pos.x divided by 40 does not have a remainder of 0: pos.x--; //Change the X position by 1 (until the above is true). } } if (( (int)pos.y % 40 != 0)){ //If pos.x divided by 40 does not have a remainder of 0: while ( (int)pos.y % 40 != 0){ //While pos.x divided by 40 does not have a remainder of 0: pos.y--; //Change the X position by 1 (until the above is true). } } }
[ "mhopson@hotmail.co.uk" ]
mhopson@hotmail.co.uk
b4f05ced4f0bbed81bc781250827cdf4a7ce5bfd
217dca16ad70fea9cc5af2e194b82194d64274af
/Bigger/Bigger.h
a1642149b47350950f0296d750eb65949c6c9785
[]
no_license
hoopizs1452/c-plus-plus-practice
5363b2438de9cca782316dca78908694da2d5d6e
60db283ebf212202f43e4b6594cf9fa911d4fe12
refs/heads/master
2020-12-03T11:24:44.642119
2020-03-20T12:23:57
2020-03-20T12:23:57
231,297,742
0
0
null
null
null
null
UTF-8
C++
false
false
125
h
//#pragma once #ifndef Bigger_H #define Bigger_H class Bigger { public: int num; Bigger(int); int getBigger(); }; #endif
[ "45253893+hoopizs1452@users.noreply.github.com" ]
45253893+hoopizs1452@users.noreply.github.com
489c06448fe7464bc295777772f66e07bbaf5e88
2f37b0b5ea900093ec3d06f835824270738c0556
/Leetcode/103_BinaryTreeZigzagLevelOrderTraversal.cc
c611f0c6688f42eee2fe8efa1de4fde57701539a
[]
no_license
yanglin526000/Wu-Algorithm
d0da3fdc92748c21c2a96b096a260a608f04adab
5259f8c81fc9a14ec35c5422d0edb9ec36304ae8
refs/heads/master
2021-09-11T12:41:48.195238
2018-04-07T04:48:17
2018-04-07T04:48:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,276
cc
#include<cstdlib> #include<vector> #include<queue> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; //还是类似于层次遍历,输出每一层,只不过偶数层是逆序输出 class Solution { public: vector<vector<int>> zigzagLevelOrder(TreeNode* root) { vector<vector<int>> result; if(root==NULL) return result; queue<TreeNode*> q1, q2;//两个队列,用来区分不同的层 q1.push(root); vector<int>temp; int countRows=1; do{ auto node=q1.front(); q1.pop(); temp.push_back(node->val); if(node->left) q2.push(node->left); if(node->right) q2.push(node->right); if(q1.empty()){ q1=q2; while(!q2.empty())//queue没有clear函数,手动清空q2 q2.pop(); if(countRows%2==0) reverse(temp.begin(),temp.end()); countRows++; result.push_back(temp); temp.clear(); } }while(!q1.empty()); return result; } };
[ "jt26wzz@icloud.com" ]
jt26wzz@icloud.com
694782c72dedff93c3b2ea23ed3440970bf5afd0
c2a4fbda71cbb2f56805221eb2348986fa36fc46
/Samples/Win7Samples/security/cryptoapi/VerifyKeyTrust/VerifyKeyTrust/VerifyKeyTrust.cpp
b2c250e61f8529c8403ef6bb57870af285c3bedb
[ "MIT" ]
permissive
databuwa/Windows-classic-samples
1803afb296283dd1fcf9765891df3ddd64e8302d
ebeeaf1e11eede00b2c416df33486885baac6a5b
refs/heads/master
2022-01-03T06:30:19.637493
2021-12-21T03:14:43
2021-12-21T03:14:43
184,238,236
0
0
NOASSERTION
2021-12-21T03:14:43
2019-04-30T10:00:59
null
UTF-8
C++
false
false
7,134
cpp
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // // Copyright (c) Microsoft Corporation. All rights reserved. /**************************************************************** Title: Verifying Publisher Key of a signed binary This sample demonstrates how Win32 applications can verify that a file with an Authenticode signature originates from a specific software publisher using WinVerifyTrust and associated helper APIs. The example demonstrates verifying a files signature, getting the publisher certificate from the signature, calculating a SHA1 hash of a publisher's signing key, and comparing it against a list of known good SHA1 hash values. ****************************************************************/ #include <windows.h> #include <wincrypt.h> #include <wintrust.h> #include <softpub.h> #define SHA1_HASH_LEN 20 //+------------------------------------------------------------------------- // SHA1 Key Identifiers of the publisher certificates // // The SHA1 Key Identifier hash is obtained by executing the following // command for each publisher*.cer file: // // >certutil -v contoso.cer // // X509 Certificate: // // ... // // // Key Id Hash(sha1): d9 48 12 73 f8 4e 89 90 64 47 bf 6b 85 5f b6 cb e2 3d 63 d6 // // DON'T USE: Key Id Hash(rfc-sha1): // //-------------------------------------------------------------------------- static const BYTE PublisherKeyList[][SHA1_HASH_LEN] = { // // The following is the sha1 key identifier for my publisher certificate // CN = Contoso // O = Contoso // L = Redmond // S = Washington // C = US // { 0xd9, 0x48, 0x12, 0x73, 0xf8, 0x4e, 0x89, 0x90, 0x64, 0x47, 0xbf, 0x6b, 0x85, 0x5f, 0xb6, 0xcb, 0xe2, 0x3d, 0x63, 0xd6 }, }; #define PUBLISHER_KEY_LIST_CNT (sizeof(PublisherKeyList) / sizeof(PublisherKeyList[0])) // // Checks if the certificate's public key matches one of the SHA1 key identifers // in the list. // static BOOL IsTrustedKey( PCCERT_CONTEXT pCertContext, const BYTE KeyList[][SHA1_HASH_LEN], DWORD KeyCount ) { BYTE rgbKeyId[SHA1_HASH_LEN]; DWORD cbKeyId; cbKeyId = SHA1_HASH_LEN; if (!CryptHashPublicKeyInfo( NULL, // hCryptProv CALG_SHA1, 0, // dwFlags X509_ASN_ENCODING, &pCertContext->pCertInfo->SubjectPublicKeyInfo, rgbKeyId, &cbKeyId) || SHA1_HASH_LEN != cbKeyId) { return FALSE; } for (DWORD i = 0; i < KeyCount; i++) { if (0 == memcmp(KeyList[i], rgbKeyId, SHA1_HASH_LEN)) { return TRUE; } } return FALSE; } // // Checks if the leaf certificate in the chain context matches // one of the publisher's SHA1 key identifiers. // static BOOL IsTrustedPublisherKey( PCCERT_CHAIN_CONTEXT pChainContext ) { PCERT_SIMPLE_CHAIN pChain; PCCERT_CONTEXT pCertContext; // // Get the first simple chain // pChain = pChainContext->rgpChain[0]; // // Check that the leaf certificate contains the public // key for one of my publisher certificates // pCertContext = pChain->rgpElement[0]->pCertContext; return IsTrustedKey(pCertContext, PublisherKeyList, PUBLISHER_KEY_LIST_CNT); } // // Checks that the file is authenticode signed by the publisher // BOOL IsFilePublisherTrusted( LPCWSTR pwszFileName ) { BOOL trusted = FALSE; DWORD lastError; GUID wvtProvGuid = WINTRUST_ACTION_GENERIC_VERIFY_V2; // // Initialize structure for WinVerifyTrust call // WINTRUST_DATA wtd = { 0 }; WINTRUST_FILE_INFO wtfi = { 0 }; wtd.cbStruct = sizeof(WINTRUST_DATA); wtd.pPolicyCallbackData = NULL; wtd.pSIPClientData = NULL; wtd.dwUIChoice = WTD_UI_NONE; wtd.fdwRevocationChecks = WTD_REVOKE_WHOLECHAIN; wtd.dwUnionChoice = WTD_CHOICE_FILE; wtd.pFile = &wtfi; wtd.dwStateAction = WTD_STATEACTION_VERIFY; wtd.hWVTStateData = NULL; wtd.pwszURLReference = NULL; wtd.dwProvFlags = WTD_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT; wtfi.cbStruct = sizeof(WINTRUST_FILE_INFO); wtfi.pcwszFilePath = pwszFileName; wtfi.hFile = NULL; wtfi.pgKnownSubject = NULL; // // Check the file's Authenticode signature // if (S_OK != WinVerifyTrust((HWND)INVALID_HANDLE_VALUE, &wvtProvGuid, &wtd)) { lastError = GetLastError(); goto Cleanup; } // // Get provider data // CRYPT_PROVIDER_DATA* pProvData = WTHelperProvDataFromStateData(wtd.hWVTStateData); if (NULL == pProvData) { lastError = GetLastError(); goto Cleanup; } // // Get the signer // CRYPT_PROVIDER_SGNR* pProvSigner = WTHelperGetProvSignerFromChain(pProvData, 0, FALSE, 0); if (NULL == pProvSigner) { lastError = GetLastError(); goto Cleanup; } // // Check for Publisher Key Trust // if (!IsTrustedPublisherKey(pProvSigner->pChainContext)) { goto Cleanup; } // // If we made it this far, we can trust the file // trusted = TRUE; Cleanup: // // Close the previously-opened state data handle // wtd.dwStateAction = WTD_STATEACTION_CLOSE; WinVerifyTrust((HWND)INVALID_HANDLE_VALUE, &wvtProvGuid, &wtd); return trusted; } // -------------------------------------------------------------------------- // // Command line test tool to call the above IsFilePublisherTrusted() function. // #include <stdlib.h> #include <stdio.h> #include <string.h> static void Usage(void) { printf("Usage: VerifyKeyTrust [options] <FileName>\n"); printf("Options are:\n"); printf(" -h - This message\n"); printf("\n"); } int _cdecl wmain(int argc, __in_ecount(argc) wchar_t * argv[]) { int status; BOOL trusted; LPCWSTR pwszFileName = NULL; // Not allocated while (--argc>0) { if (**++argv == '-') { switch(argv[0][1]) { case 'h': default: goto BadUsage; } } else { if (pwszFileName == NULL) pwszFileName = argv[0]; else { printf("Too many arguments\n"); goto BadUsage; } } } if (pwszFileName == NULL) { printf("missing FileName \n"); goto BadUsage; } wprintf(L"command line: %s\n", GetCommandLineW()); trusted = IsFilePublisherTrusted(pwszFileName); if (trusted) { printf("Passed :: Publisher Trusted File\n"); } else { printf("Failed :: NOT PUBLISHER TRUSTED File\n"); } status = 0; CommonReturn: return status; ErrorReturn: status = -1; printf("Failed\n"); goto CommonReturn; BadUsage: Usage(); goto ErrorReturn; }
[ "microsoft@user.noreply.github.com" ]
microsoft@user.noreply.github.com
133813b00fbcf4dd024fde390047bd71ebb877e5
a87832e55c616f8f8e8ef2f7070ee6126a439665
/Static/Identifiable.cpp
7042156f81eb3182524c1aec2ae8ba5268c6883f
[]
no_license
Villanelle-V/BCW4
99d2693a6ebb6106201731f5e095c54e18623a31
fe9d1b4c028ec4f4ee81ff329ebc6cc428fa3ccf
refs/heads/main
2023-06-23T10:20:44.185943
2021-07-23T13:19:14
2021-07-23T13:19:14
388,102,092
0
0
null
null
null
null
UTF-8
C++
false
false
225
cpp
#include "Identifiable.h" Identifiable::Identifiable() { count += 1; this->id = count; } int Identifiable::getId() const { return this->id; } int Identifiable::getCount() { return count; } int Identifiable::count = 0;
[ "82818489+Villanelle-V@users.noreply.github.com" ]
82818489+Villanelle-V@users.noreply.github.com
9aec5d9b95bd0ce6944553778745571724e40831
16de124171e4d3612967b760c3499ca14cef1021
/facePlus/stdafx.h
92788a69e62521cbeddcd728dcbae38615a8c2a9
[]
no_license
Tempal/facePlus
98f4739e9fa11cefbb9eda8af8d3d2966fa99550
2862b77778e6cd13a1ff7d4db646678721b78c0f
refs/heads/master
2020-09-11T22:50:03.615476
2019-11-17T08:09:12
2019-11-17T08:09:12
222,216,389
0
0
null
null
null
null
UTF-8
C++
false
false
1,987
h
 // stdafx.h : 标准系统包含文件的包含文件, // 或是经常使用但不常更改的 // 特定于项目的包含文件 #pragma once #ifndef VC_EXTRALEAN #define VC_EXTRALEAN // 从 Windows 头中排除极少使用的资料 #endif #include "targetver.h" #define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS // 某些 CString 构造函数将是显式的 // 关闭 MFC 对某些常见但经常可放心忽略的警告消息的隐藏 #define _AFX_ALL_WARNINGS #include <afxwin.h> // MFC 核心组件和标准组件 #include <afxext.h> // MFC 扩展 #include <afxdisp.h> // MFC 自动化类 #ifndef _AFX_NO_OLE_SUPPORT #include <afxdtctl.h> // MFC 对 Internet Explorer 4 公共控件的支持 #endif #ifndef _AFX_NO_AFXCMN_SUPPORT #include <afxcmn.h> // MFC 对 Windows 公共控件的支持 #endif // _AFX_NO_AFXCMN_SUPPORT #include <afxcontrolbars.h> // 功能区和控件条的 MFC 支持 #ifdef _UNICODE #if defined _M_IX86 #pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='x86' publicKeyToken='6595b64144ccf1df' language='*'\"") #elif defined _M_X64 #pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='amd64' publicKeyToken='6595b64144ccf1df' language='*'\"") #else #pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"") #endif #endif #define CURL_STATICLIB #pragma comment(lib,"libcurl.lib") #include "GdiPlus.h" #pragma comment(lib,"GDIPlus.lib") using namespace Gdiplus; #define WM_MSG WM_USER+0x01 _ACRTIMP_ALT FILE* __cdecl __acrt_iob_func(unsigned); #ifdef __cplusplus extern "C" #endif FILE* __cdecl __iob_func(unsigned i) { return __acrt_iob_func(i); }
[ "tempal@163.com" ]
tempal@163.com
6498bd7f0b4b1545924d1bb68bb03231f0bfc135
cff7d2396057005906f808977cb9f6a54152e70d
/command_processor.h
eb69eca246e182dc69faa92e23d761164b57ce58
[ "Apache-2.0" ]
permissive
F11GAR0/SandraVM
5e1460131f28f0b4dc8c3a51580c9fc06fea78ce
350a6e73338d002e46a23341046f5587f5fb5c14
refs/heads/master
2022-07-17T20:03:06.570237
2020-05-18T12:30:41
2020-05-18T12:30:41
258,647,980
8
0
null
null
null
null
UTF-8
C++
false
false
2,705
h
#ifndef COMMAND_PROCESSOR_H #define COMMAND_PROCESSOR_H #include "main.h" namespace command_processor { //typedef section typedef void(*func)(std::string argvs); std::vector<std::pair<std::string, func>> cmds; std::vector<func> just_buff_callbacks; void register_command(std::string cmd, func callback) { cmds.push_back(std::pair<std::string, func>(cmd, callback)); } void register_buffer_line_hook(func callback){ just_buff_callbacks.push_back(callback); } std::string remove_first(const std::string& in) { std::string ret; for (int i = 1, len = in.length(); i < len; i++) { ret += in[i]; } return ret; } std::string compress(const std::vector<std::string>& in) { std::string ret; for (int i = 0, len = in.size(); i < len; i++) { ret += in[i]; ret += " "; } return ret; } std::vector<std::string> split(std::string in, char splitter) { std::vector<std::string> ret; std::string temp; for (int i = 0; i < in.length(); i++) { if (in[i] == splitter) { if (temp.length() > 0) { ret.push_back(temp); temp.clear(); } } else { temp += in[i]; } } if (temp.length() > 0) { ret.push_back(temp); } return ret; } void buffer_proc() { auto show_cmds = [](std::string) { std::cout << "All registered commands:" << std::endl; for (int i = 0, size = cmds.size(); i < size; i++) { std::cout << cmds[i].first << std::endl; } }; register_command("cmds", show_cmds); while (true) { char* in = (char*)malloc(512); std::cin.getline(in, 512); #ifdef DEBUG printf("\ncommand entered: %s\n", in); #endif if (strlen(in) > 0) { if (in[0] == '/') { auto ret = split(in, ' '); std::string cmd = remove_first(ret[0]); ret.erase(ret.begin()); for (int i = 0; i < cmds.size(); i++) { if (cmds[i].first == cmd) { cmds[i].second(compress(ret)); } } } else { for(int i = 0; i < just_buff_callbacks.size(); i++){ just_buff_callbacks[i](in); } } } free(in); } } } #endif // COMMAND_PROCESSOR_H
[ "38394923+F11GAR0@users.noreply.github.com" ]
38394923+F11GAR0@users.noreply.github.com
c58372eece998ddc0e2ca4236d97819c97691a3d
b64b4a23d1451a5a169deacf04f5de7b827c079c
/Graphics/include/LightBuilder.h
b4a1840bbca1b8d5d8ef841d9adb98c68f61b0ef
[ "MIT" ]
permissive
MarcoLotto/ScaenaFramework
f67a49999a93a7dc6c9dfaed3f192680a49b0b71
533e5149a1580080e41bfb37d5648023b6e39f6f
refs/heads/master
2020-04-12T07:25:08.838449
2018-03-26T02:52:23
2018-03-26T02:52:23
65,083,660
2
0
null
null
null
null
UTF-8
C++
false
false
1,290
h
/********************************** * SCAENA FRAMEWORK * Author: Marco Andrés Lotto * License: MIT - 2016 **********************************/ #pragma once #include "ObjectLight.h" class Object; class LightBuilder{ private: LightBuilder(){}; static SceneLight* fillSceneLightDataStructure(vec3 pos, vec3 dir, vec3 intens, int type); static ObjectLight* fillObjectLightDataStructure(vec3 pos, vec3 dir, vec3 intens, int type); static vec3 normalizeWithZeroSafe(vec3 vectorToNormalize); public: static SceneLight* buildPointSceneLight(vec3 position, vec3 intensity); static SceneLight* buildOnlyDiffusePointSceneLight(vec3 position, vec3 intensity); static SceneLight* buildDireccionalSceneLight(vec3 direction, vec3 intensity); static SceneLight* buildSpotSceneLight(vec3 position, vec3 direction, vec3 intensity, float factor); static ObjectLight* buildPointObjectLight(Object* ownerObject, vec3 localPosition, vec3 intensity); static ObjectLight* buildOnlyDiffusePointObjectLight(Object* ownerObject, vec3 localPosition, vec3 intensity); static ObjectLight* buildDireccionalObjectLight(Object* ownerObject, vec3 direction, vec3 intensity); static ObjectLight* buildSpotObjectLight(Object* ownerObject, vec3 localPosition, vec3 direction, vec3 intensity, float factor); };
[ "marcol91@gmail.com" ]
marcol91@gmail.com
5847867876a0f9a9f34b5f9daee4651d1f5f2b11
8f421001634923dbfb032389ecd094d4880e958a
/modules/sfm/src/libmv_light/libmv/simple_pipeline/intersect.h
3a0ffa7418bfada245a57aaef0dd78e75bae5026
[ "Apache-2.0" ]
permissive
opencv/opencv_contrib
ccf47a2a97022e20d936eb556aa9bc63bc9bdb90
9e134699310c81ea470445b4888fce5c9de6abc7
refs/heads/4.x
2023-08-22T05:58:21.266673
2023-08-11T16:28:20
2023-08-11T16:28:20
12,756,992
8,611
6,099
Apache-2.0
2023-09-14T17:35:22
2013-09-11T13:28:04
C++
UTF-8
C++
false
false
3,394
h
// Copyright (c) 2011 libmv authors. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. #ifndef LIBMV_SIMPLE_PIPELINE_INTERSECT_H #define LIBMV_SIMPLE_PIPELINE_INTERSECT_H #include "libmv/base/vector.h" #include "libmv/simple_pipeline/tracks.h" #include "libmv/simple_pipeline/reconstruction.h" namespace libmv { /*! Estimate the 3D coordinates of a track by intersecting rays from images. This takes a set of markers, where each marker is for the same track but different images, and reconstructs the 3D position of that track. Each of the frames for which there is a marker for that track must have a corresponding reconstructed camera in \a *reconstruction. \a markers should contain all \l Marker markers \endlink belonging to tracks visible in all frames. \a reconstruction should contain the cameras for all frames. The new \l Point points \endlink will be inserted in \a reconstruction. \note This assumes a calibrated reconstruction, e.g. the markers are already corrected for camera intrinsics and radial distortion. \note This assumes an outlier-free set of markers. \sa EuclideanResect */ bool EuclideanIntersect(const vector<Marker> &markers, EuclideanReconstruction *reconstruction); /*! Estimate the homogeneous coordinates of a track by intersecting rays. This takes a set of markers, where each marker is for the same track but different images, and reconstructs the homogeneous 3D position of that track. Each of the frames for which there is a marker for that track must have a corresponding reconstructed camera in \a *reconstruction. \a markers should contain all \l Marker markers \endlink belonging to tracks visible in all frames. \a reconstruction should contain the cameras for all frames. The new \l Point points \endlink will be inserted in \a reconstruction. \note This assumes that radial distortion is already corrected for, but does not assume that e.g. focal length and principal point are accounted for. \note This assumes an outlier-free set of markers. \sa Resect */ bool ProjectiveIntersect(const vector<Marker> &markers, ProjectiveReconstruction *reconstruction); } // namespace libmv #endif // LIBMV_SIMPLE_PIPELINE_INTERSECT_H
[ "edgar.riba@gmail.com" ]
edgar.riba@gmail.com
008e574d3bfefb1cd4ef607be24a2e7e8b0aac30
7aa27f0a05d60f9eb60c193af9622bef1c816af6
/sjasm/errors.h
7b511a356a8a10b9c340d91f138328c824edce95
[]
no_license
MSXALL/sjasmplus
3f2f87b2300ad8cd7fca71b3ae244d6a4a93e76e
7be51ad74960e613a50ffc42f11fafb6a2cc3ea4
refs/heads/master
2021-09-08T05:03:38.984435
2017-12-23T21:14:14
2017-12-23T21:14:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
868
h
// // Error handling // #ifndef SJASMPLUS_ERRORS_H #define SJASMPLUS_ERRORS_H #include <string> #include <iostream> #include <stack> using namespace std::string_literals; using std::cout; using std::cerr; using std::endl; using std::flush; using std::stack; extern std::string ErrorStr; extern int PreviousErrorLine; extern int WarningCount; enum EStatus { ALL, PASS1, PASS2, PASS3, FATAL, CATCHALL, SUPPRESS }; enum EReturn { END, ELSE, ENDIF, ENDTEXTAREA, ENDM }; void Error(const char *, const char *, int = PASS2); void Error(const std::string &fout, const std::string &bd, int type = PASS2); void Warning(const char *, const char *, int = PASS2); void Warning(const std::string &fout, const std::string &bd, int type = PASS2); // output #define _COUT cout << #define _CMDL << #define _ENDL << endl #define _END ; #endif //SJASMPLUS_ERRORS_H
[ "koloberdin@gmail.com" ]
koloberdin@gmail.com
f5c10ffca1126c9728082729a38bda2a503a99a7
301f6391c9050a9f8bb4dfcd1d04bb6968b2f63c
/validityform.cpp
cad6dd03858ca5874d8c3737d36b0fcad9ac3e16
[]
no_license
awais987123/Library-Management-system-GUI
d764a9fd895d047a4b87e025e74c8fec745b6a8d
fc5e03d08ed6445c2216efd4ce3a3fea94c79c05
refs/heads/master
2023-07-14T12:19:06.938472
2021-08-16T07:13:17
2021-08-16T07:13:17
396,652,679
0
0
null
null
null
null
UTF-8
C++
false
false
27
cpp
#include "validityform.h"
[ "muhammadawais987123@gmail.com" ]
muhammadawais987123@gmail.com
e90094715f1466fbf7d19eaf796bab6885be9ecd
206fd5b039197de0d59a1ccb9b50f6c053c3bf5b
/src/caffe/solver.cpp
afad6a2ac71c43beeaeb75d830830d2d0b608450
[ "LicenseRef-scancode-generic-cla", "BSD-2-Clause", "BSD-3-Clause", "LicenseRef-scancode-public-domain" ]
permissive
LiJianfei06/caffe-master-ljf
8d99c311c396d4be0c6c96efee1f67e286dc4dce
02902fda8252306803ce34167cfab40a224c68c2
refs/heads/master
2020-03-18T15:55:04.001845
2019-04-14T13:58:51
2019-04-14T13:58:51
134,936,903
1
1
null
null
null
null
UTF-8
C++
false
false
29,542
cpp
#include <cstdio> #include <string> #include <vector> #include "boost/algorithm/string.hpp" #include "caffe/solver.hpp" #include "caffe/util/format.hpp" #include "caffe/util/hdf5.hpp" #include "caffe/util/io.hpp" #include "caffe/util/upgrade_proto.hpp" namespace caffe { /***************************************************************** *Function: SetActionFunction *Description: 传入能传递消息的函数指针 *Calls: *Called By: ./tools/caffe.cpp: train() *Input: ActionCallback ActionCallback; *Output: *Return: *Others: *****************************************************************/ template<typename Dtype> void Solver<Dtype>::SetActionFunction(ActionCallback func) { action_request_function_ = func; } /***************************************************************** *Function: GetRequestedAction *Description: 返回传入的消息 *Calls: *Called By: 多处 *Input: *Output: *Return: typedef boost::function<SolverAction::Enum()> ActionCallback; *Others: *****************************************************************/ template<typename Dtype> SolverAction::Enum Solver<Dtype>::GetRequestedAction() { if (action_request_function_) { // If the external request function has been set, call it. return action_request_function_(); } return SolverAction::NONE; } /***************************************************************** *Function: Solver *Description: 构造函数 这个初始化的时候会调用的 *Calls: Init()方法 *Called By: *Input: 从solver.prototxt解析出来的参数 *Output: *Return: *Others: 确认开始会进入 *****************************************************************/ template <typename Dtype> Solver<Dtype>::Solver(const SolverParameter& param) : net_(), callbacks_(), requested_early_exit_(false) { // 这几个初始化列表 //LOG(FATAL) <<"Solver() "<<" "<< "lijianfei debug!!!!!!!!!!"; //确认开始会进入 Init(param); // 调用Init()方法进行初始化 } /***************************************************************** *Function: Solver *Description: 构造函数 *Calls: Init()方法 *Called By: *Input: 从solver.prototxt解析出来string的参数 *Output: *Return: *Others: 不会进入 *****************************************************************/ template <typename Dtype> Solver<Dtype>::Solver(const string& param_file) : net_(), callbacks_(), requested_early_exit_(false) { //LOG(FATAL) <<"Solver(string) "<<" "<< "lijianfei debug!!!!!!!!!!";// 不会进入 SolverParameter param; ReadSolverParamsFromTextFileOrDie(param_file, &param); Init(param); } /***************************************************************** *Function: Init *Description: 初始化函数 *Calls: InitTrainNet() 、InitTestNets() *Called By: 构造函数 *Input: 从solver.prototxt解析出来的参数 *Output: *Return: *Others: *****************************************************************/ template <typename Dtype> void Solver<Dtype>::Init(const SolverParameter& param) { LOG_IF(INFO, Caffe::root_solver()) << "Initializing solver from parameters: " << std::endl << param.DebugString(); param_ = param; CHECK_GE(param_.average_loss(), 1) << "average_loss should be non-negative."; CheckSnapshotWritePermissions(); if (param_.random_seed() >= 0) { Caffe::set_random_seed(param_.random_seed() + Caffe::solver_rank()); // 设置随机数种子 } // Scaffolding code InitTrainNet(); // 初始化训练网络 InitTestNets(); // 初始化测试网络 if (Caffe::root_solver()) // 在common.hpp中 判断当前solver线程是否为root线程 { LOG(INFO) << "Solver scaffolding done."; } iter_ = 0; current_step_ = 0; } /***************************************************************** *Function: LoadNetWeights *Description: 加载caffemodel模型into the train and test nets. *Calls: InitTrainNet() 、InitTestNets() *Called By: *Input: 1. Net类指针 2.模型名称 *Output: *Return: *Others: --WEIGHT parameter *****************************************************************/ // Load weights from the caffemodel(s) specified in "weights" solver parameter // into the train and test nets. template <typename Dtype> void LoadNetWeights(shared_ptr<Net<Dtype> > net, const std::string& model_list) { std::vector<std::string> model_names; boost::split(model_names, model_list, boost::is_any_of(",")); for (int i = 0; i < model_names.size(); ++i) { boost::trim(model_names[i]); LOG(INFO) << "Finetuning from " << model_names[i]; net->CopyTrainedLayersFrom(model_names[i]); // 从caffemodel里面载入参数 } } /***************************************************************** *Function: InitTrainNet *Description: 初始化训练网络 *Calls: ReadNetParamsFromTextFileOrDie() 、Net类 *Called By: *Input: *Output: *Return: *Others: *****************************************************************/ template <typename Dtype> void Solver<Dtype>::InitTrainNet() { const int num_train_nets = param_.has_net() + param_.has_net_param() + param_.has_train_net() + param_.has_train_net_param(); const string& field_names = "net, net_param, train_net, train_net_param"; //LOG(FATAL)<<num_train_nets; // 通常为1 CHECK_GE(num_train_nets, 1) << "SolverParameter must specify a train net " << "using one of these fields: " << field_names; CHECK_LE(num_train_nets, 1) << "SolverParameter must not contain more than " << "one of these fields specifying a train_net: " << field_names; NetParameter net_param; if (param_.has_train_net_param()) { LOG_IF(INFO, Caffe::root_solver()) << "Creating training net specified in train_net_param."; net_param.CopyFrom(param_.train_net_param()); } else if (param_.has_train_net()) { LOG_IF(INFO, Caffe::root_solver()) << "Creating training net from train_net file: " << param_.train_net(); ReadNetParamsFromTextFileOrDie(param_.train_net(), &net_param); // 加载信息 } if (param_.has_net_param()) { LOG_IF(INFO, Caffe::root_solver()) << "Creating training net specified in net_param."; net_param.CopyFrom(param_.net_param()); } if (param_.has_net()) { LOG_IF(INFO, Caffe::root_solver()) << "Creating training net from net file: " << param_.net(); ReadNetParamsFromTextFileOrDie(param_.net(), &net_param); // 加载信息 } // Set the correct NetState. We start with the solver defaults (lowest // precedence); then, merge in any NetState specified by the net_param itself; // finally, merge in any NetState specified by the train_state (highest // precedence). NetState net_state; net_state.set_phase(TRAIN); net_state.MergeFrom(net_param.state()); net_state.MergeFrom(param_.train_state()); net_param.mutable_state()->CopyFrom(net_state); net_.reset(new Net<Dtype>(net_param)); //调用模板类的构造函数,进行net的初始化 for (int w_idx = 0; w_idx < param_.weights_size(); ++w_idx) { LoadNetWeights(net_, param_.weights(w_idx)); } } /***************************************************************** *Function: InitTestNets *Description: 初始化测试网络 *Calls: ReadNetParamsFromTextFileOrDie() 、Net类 *Called By: *Input: *Output: *Return: *Others: *****************************************************************/ template <typename Dtype> void Solver<Dtype>::InitTestNets() { const bool has_net_param = param_.has_net_param(); const bool has_net_file = param_.has_net(); const int num_generic_nets = has_net_param + has_net_file; //需要注意的是TestNet可以有多个,而TrainNet只能有一个 CHECK_LE(num_generic_nets, 1) << "Both net_param and net_file may not be specified."; const int num_test_net_params = param_.test_net_param_size(); const int num_test_net_files = param_.test_net_size(); const int num_test_nets = num_test_net_params + num_test_net_files; if (num_generic_nets) { CHECK_GE(param_.test_iter_size(), num_test_nets) << "test_iter must be specified for each test network."; } else { CHECK_EQ(param_.test_iter_size(), num_test_nets) << "test_iter must be specified for each test network."; } // If we have a generic net (specified by net or net_param, rather than // test_net or test_net_param), we may have an unlimited number of actual // test networks -- the actual number is given by the number of remaining // test_iters after any test nets specified by test_net_param and/or test_net // are evaluated. const int num_generic_net_instances = param_.test_iter_size() - num_test_nets; const int num_test_net_instances = num_test_nets + num_generic_net_instances; if (param_.test_state_size()) { CHECK_EQ(param_.test_state_size(), num_test_net_instances) << "test_state must be unspecified or specified once per test net."; } if (num_test_net_instances) { CHECK_GT(param_.test_interval(), 0); } int test_net_id = 0; vector<string> sources(num_test_net_instances); vector<NetParameter> net_params(num_test_net_instances); for (int i = 0; i < num_test_net_params; ++i, ++test_net_id) { sources[test_net_id] = "test_net_param"; net_params[test_net_id].CopyFrom(param_.test_net_param(i)); } for (int i = 0; i < num_test_net_files; ++i, ++test_net_id) { sources[test_net_id] = "test_net file: " + param_.test_net(i); ReadNetParamsFromTextFileOrDie(param_.test_net(i), &net_params[test_net_id]); } const int remaining_test_nets = param_.test_iter_size() - test_net_id; if (has_net_param) { for (int i = 0; i < remaining_test_nets; ++i, ++test_net_id) { sources[test_net_id] = "net_param"; net_params[test_net_id].CopyFrom(param_.net_param()); } } if (has_net_file) { for (int i = 0; i < remaining_test_nets; ++i, ++test_net_id) { sources[test_net_id] = "net file: " + param_.net(); ReadNetParamsFromTextFileOrDie(param_.net(), &net_params[test_net_id]); } } test_nets_.resize(num_test_net_instances); for (int i = 0; i < num_test_net_instances; ++i) { // Set the correct NetState. We start with the solver defaults (lowest // precedence); then, merge in any NetState specified by the net_param // itself; finally, merge in any NetState specified by the test_state // (highest precedence). NetState net_state; net_state.set_phase(TEST); net_state.MergeFrom(net_params[i].state()); if (param_.test_state_size()) { net_state.MergeFrom(param_.test_state(i)); } net_params[i].mutable_state()->CopyFrom(net_state); LOG(INFO) << "Creating test net (#" << i << ") specified by " << sources[i]; test_nets_[i].reset(new Net<Dtype>(net_params[i])); test_nets_[i]->set_debug_info(param_.debug_info()); for (int w_idx = 0; w_idx < param_.weights_size(); ++w_idx) { LoadNetWeights(test_nets_[i], param_.weights(w_idx)); } } } /***************************************************************** *Function: Step *Description: 核心函数 *Calls: *Called By: Solve() *Input: *Output: *Return: *Others: *****************************************************************/ template <typename Dtype> void Solver<Dtype>::Step(int iters) { //设置开始的迭代次数(如果是从之前的snapshot恢复的,那iter_等于snapshot时的迭代次数)和结束的迭代次数 const int start_iter = iter_; const int stop_iter = iter_ + iters; // 输出的loss为前average_loss次loss的平均值,在solver.prototxt里设置,默认为1 // losses存储之前的average_loss个loss,smoothed_loss为最后要输出的均值 int average_loss = this->param_.average_loss(); losses_.clear(); smoothed_loss_ = 0; iteration_timer_.Start(); //迭代 while (iter_ < stop_iter) { // zero-init the params net_->ClearParamDiffs(); // 清空上一次所有参数的梯度 if (param_.test_interval() && iter_ % param_.test_interval() == 0 && (iter_ > 0 || param_.test_initialization())) // 判断是否需要测试 { if (Caffe::root_solver()) { TestAll(); } if (requested_early_exit_) { // Break out of the while loop because stop was requested while testing. break; } } for (int i = 0; i < callbacks_.size(); ++i) { callbacks_[i]->on_start(); // 暂时不知道 } const bool display = param_.display() && iter_ % param_.display() == 0; net_->set_debug_info(display && param_.debug_info()); // iter_size也是在solver.prototxt里设置,实际上的batch_size=iter_size*网络定义里的batch_size, // 因此每一次迭代的loss是iter_size次迭代的和,再除以iter_size,这个loss是通过调用`Net::ForwardBackward`函数得到的 // 这个设置我的理解是在GPU的显存不够的时候使用,比如我本来想把batch_size设置为128,但是会out_of_memory, // 借助这个方法,可以设置batch_size=32,iter_size=4,那实际上每次迭代还是处理了128个数据 // accumulate the loss and gradient Dtype loss = 0; for (int i = 0; i < param_.iter_size(); ++i) { loss += net_->ForwardBackward(); } loss /= param_.iter_size(); // average the loss across iterations for smoothed reporting // 计算要输出的smoothed_loss,如果losses里还没有存够average_loss个loss则将当前的loss插入, // 如果已经存够了,则将之前的替换掉 // 这个函数主要做Loss的平滑。由于Caffe的训练方式是SGD,我们无法把所有的数据同时 // 放入模型进行训练,那么部分数据产生的Loss就可能会和全样本的平均Loss不同,在必要 // 时候将Loss和历史过程中更新的Loss求平均就可以减少Loss的震荡问题。 UpdateSmoothedLoss(loss, start_iter, average_loss); //输出当前迭代的信息 if (display) { float lapse = iteration_timer_.Seconds(); float per_s = (iter_ - iterations_last_) / (lapse ? lapse : 1); LOG_IF(INFO, Caffe::root_solver()) << "Iteration " << iter_ << " (" << per_s << " iter/s, " << lapse << "s/" << param_.display() << " iters), loss = " << smoothed_loss_; iteration_timer_.Start(); iterations_last_ = iter_; const vector<Blob<Dtype>*>& result = net_->output_blobs(); int score_index = 0; for (int j = 0; j < result.size(); ++j) { const Dtype* result_vec = result[j]->cpu_data(); const string& output_name = net_->blob_names()[net_->output_blob_indices()[j]]; const Dtype loss_weight = net_->blob_loss_weights()[net_->output_blob_indices()[j]]; for (int k = 0; k < result[j]->count(); ++k) { ostringstream loss_msg_stream; if (loss_weight) { loss_msg_stream << " (* " << loss_weight << " = " << loss_weight * result_vec[k] << " loss)"; } LOG_IF(INFO, Caffe::root_solver()) << " Train net output #" << score_index++ << ": " << output_name << " = " << result_vec[k] << loss_msg_stream.str(); } } } for (int i = 0; i < callbacks_.size(); ++i) { callbacks_[i]->on_gradients_ready(); } ApplyUpdate();// 执行梯度的更新,这个函数在基类`Solver`中没有实现,会调用每个子类自己的实现。(sgd_solver.cpp中) // Increment the internal iter_ counter -- its value should always indicate // the number of times the weights have been updated. ++iter_; // 调用GetRequestedAction,实际是通过action_request_function_函数指针调用之前设置好(通过`SetRequestedAction`)的 // signal_handler的`CheckForSignals`函数,这个函数的作用是 // 会根据之前是否遇到系统信号以及信号的类型和我们设置(或者默认)的方式返回处理的方式 SolverAction::Enum request = GetRequestedAction(); // 如果request为`STOP`则修改`requested_early_exit_`为true,之后就会提前结束迭代 // Save a snapshot if needed. if ((param_.snapshot() && iter_ % param_.snapshot() == 0 && Caffe::root_solver()) || (request == SolverAction::SNAPSHOT)) { Snapshot(); } if (SolverAction::STOP == request) { requested_early_exit_ = true; // Break out of training loop. break; } } } /***************************************************************** *Function: Solve *Description: 核心函数,对整个网络进行训练 *Calls: Step() \ TestAll() *Called By: train() *Input: *Output: *Return: *Others: *****************************************************************/ template <typename Dtype> void Solver<Dtype>::Solve(const char* resume_file) { CHECK(Caffe::root_solver()); LOG(INFO) << "Solving " << net_->name(); //LOG(FATAL)<<resume_file; // 从头训就是空,否则又之前的信息 LOG(INFO) << "Learning Rate Policy: " << param_.lr_policy(); // Initialize to false every time we start solving. requested_early_exit_ = false; if (resume_file) { //判断`resume_file`这个指针是否NULL,如果不是则需要从resume_file存储的路径里读取之前训练的状态 LOG(INFO) << "Restoring previous solver status from " << resume_file; Restore(resume_file); } // For a network that is trained by the solver, no bottom or top vecs // should be given, and we will just provide dummy vecs. int start_iter = iter_; Step(param_.max_iter() - iter_); //这个函数执行了实际迭代训练过程 核心 // If we haven't already, save a snapshot after optimization, unless // overridden by setting snapshot_after_train := false //迭代结束或者遇到系统信号提前结束后,判断是否需要在训练结束之后snapshot //这个可以在solver.prototxt里设置 if (param_.snapshot_after_train() && (!param_.snapshot() || iter_ % param_.snapshot() != 0)) { Snapshot(); } // 如果在`Step`函数的迭代过程中遇到了系统信号,且我们的处理方式设置为`STOP`, // 那么`requested_early_exit_`会被修改为true,迭代提前结束,输出相关信息 if (requested_early_exit_) { LOG(INFO) << "Optimization stopped early."; return; } // After the optimization is done, run an additional train and test pass to // display the train and test loss/outputs if appropriate (based on the // display and test_interval settings, respectively). Unlike in the rest of // training, for the train net we only run a forward pass as we've already // updated the parameters "max_iter" times -- this final pass is only done to // display the loss, which is computed in the forward pass. // 判断是否需要输出最后的loss if (param_.display() && iter_ % param_.display() == 0) { int average_loss = this->param_.average_loss(); Dtype loss; net_->Forward(&loss); UpdateSmoothedLoss(loss, start_iter, average_loss);/*更新并且平滑损失*/ LOG(INFO) << "Iteration " << iter_ << ", loss = " << smoothed_loss_; } //判断是否需要最后Test if (param_.test_interval() && iter_ % param_.test_interval() == 0) { TestAll(); } LOG(INFO) << "Optimization Done."; } /***************************************************************** *Function: TestAll() *Description: 前向一遍测试集 *Calls: Test() *Called By: Step() *Input: *Output: *Return: *Others: *****************************************************************/ template <typename Dtype> void Solver<Dtype>::TestAll() { for (int test_net_id = 0; test_net_id < test_nets_.size() && !requested_early_exit_; ++test_net_id) { Test(test_net_id); } } /***************************************************************** *Function: Test() *Description: 前向测试一个测试网络 *Calls: test_net->Forward() *Called By: TestAll() *Input: *Output: *Return: *Others: *****************************************************************/ template <typename Dtype> void Solver<Dtype>::Test(const int test_net_id) { CHECK(Caffe::root_solver()); LOG(INFO) << "Iteration " << iter_ << ", Testing net (#" << test_net_id << ")"; CHECK_NOTNULL(test_nets_[test_net_id].get())-> ShareTrainedLayersWith(net_.get()); vector<Dtype> test_score; vector<int> test_score_output_id; const shared_ptr<Net<Dtype> >& test_net = test_nets_[test_net_id]; Dtype loss = 0; for (int i = 0; i < param_.test_iter(test_net_id); ++i){ // 循环多少次,外部设置 SolverAction::Enum request = GetRequestedAction(); // 获得信号 // Check to see if stoppage of testing/training has been requested. while (request != SolverAction::NONE) { if (SolverAction::SNAPSHOT == request){ // 如果传入信号是保存快照 Snapshot(); } else if (SolverAction::STOP == request) { // 如果是stop则退出 requested_early_exit_ = true; } request = GetRequestedAction(); // 不停地接收信号 } if (requested_early_exit_) { // break out of test loop. break; } Dtype iter_loss; const vector<Blob<Dtype>*>& result = test_net->Forward(&iter_loss); // 执行前向传播测试图片 if (param_.test_compute_loss()) { // 默认 false loss += iter_loss; // 累加损失便于后续统计 } if (i == 0) { for (int j = 0; j < result.size(); ++j) { const Dtype* result_vec = result[j]->cpu_data(); for (int k = 0; k < result[j]->count(); ++k) { test_score.push_back(result_vec[k]); test_score_output_id.push_back(j); // 保存结果 } } } else { int idx = 0; for (int j = 0; j < result.size(); ++j) { const Dtype* result_vec = result[j]->cpu_data(); for (int k = 0; k < result[j]->count(); ++k) { test_score[idx++] += result_vec[k]; // 保存结果 } } } } if (requested_early_exit_) { LOG(INFO) << "Test interrupted."; return; } if (param_.test_compute_loss()) { loss /= param_.test_iter(test_net_id); LOG(INFO) << "Test loss: " << loss; } for (int i = 0; i < test_score.size(); ++i) { // 一些测试结果打印 const int output_blob_index = test_net->output_blob_indices()[test_score_output_id[i]]; const string& output_name = test_net->blob_names()[output_blob_index]; const Dtype loss_weight = test_net->blob_loss_weights()[output_blob_index]; ostringstream loss_msg_stream; const Dtype mean_score = test_score[i] / param_.test_iter(test_net_id); if (loss_weight) { loss_msg_stream << " (* " << loss_weight << " = " << loss_weight * mean_score << " loss)"; } LOG(INFO) << " Test net output #" << i << ": " << output_name << " = " << mean_score << loss_msg_stream.str(); // 输出精度 static Dtype Max_acc=0; static Dtype Best_iter=0; if((output_name=="prob")&&(iter_>1000)) // 会保存最好的模型 { if(Max_acc < mean_score) { Max_acc = mean_score; Best_iter=iter_; Snapshot(); } LOG(INFO)<<" Max_acc: "<<Max_acc<<" with iter: "<< Best_iter; } } } /***************************************************************** *Function: Snapshot() *Description: 保存快照函数 *Calls: SnapshotToBinaryProto() / SnapshotToHDF5() *Called By: Solve() *Input: *Output: *Return: *Others: *****************************************************************/ template <typename Dtype> void Solver<Dtype>::Snapshot() { CHECK(Caffe::root_solver()); string model_filename; switch (param_.snapshot_format()) { case caffe::SolverParameter_SnapshotFormat_BINARYPROTO: model_filename = SnapshotToBinaryProto(); // 要么保存到二进制文件 break; case caffe::SolverParameter_SnapshotFormat_HDF5: // 要么保存到HDF5文件 model_filename = SnapshotToHDF5(); break; default: LOG(FATAL) << "Unsupported snapshot format."; } SnapshotSolverState(model_filename); } /***************************************************************** *Function: CheckSnapshotWritePermissions() *Description: 检查对应目录下是否有保存快照文件的权限 *Calls: *Called By: Init() *Input: *Output: *Return: *Others: *****************************************************************/ template <typename Dtype> void Solver<Dtype>::CheckSnapshotWritePermissions() { if (Caffe::root_solver() && param_.snapshot()) { CHECK(param_.has_snapshot_prefix()) << "In solver params, snapshot is specified but snapshot_prefix is not"; string probe_filename = SnapshotFilename(".tempfile"); std::ofstream probe_ofs(probe_filename.c_str()); if (probe_ofs.good()) { probe_ofs.close(); std::remove(probe_filename.c_str()); } else { LOG(FATAL) << "Cannot write to snapshot prefix '" << param_.snapshot_prefix() << "'. Make sure " << "that the directory exists and is writeable."; } } } /***************************************************************** *Function: SnapshotFilename() *Description: 生成快照的名称 *Calls: *Called By: SnapshotToHDF5() /SnapshotToBinaryProto() *Input: *Output: *Return: *Others: *****************************************************************/ template <typename Dtype> string Solver<Dtype>::SnapshotFilename(const string extension) { return param_.snapshot_prefix() + "_iter_" + caffe::format_int(iter_) + extension; } /***************************************************************** *Function: SnapshotToBinaryProto() *Description: 快照以二进制proto文件形式保存 *Calls: *Called By: Snapshot() *Input: *Output: *Return: *Others: *****************************************************************/ template <typename Dtype> string Solver<Dtype>::SnapshotToBinaryProto() { string model_filename = SnapshotFilename(".caffemodel"); LOG(INFO) << "Snapshotting to binary proto file " << model_filename; NetParameter net_param; net_->ToProto(&net_param, param_.snapshot_diff()); // 调用网络ToProto函数,再调用层的ToProto函数将每数据保存到proto对象中 WriteProtoToBinaryFile(net_param, model_filename); // 写到具体文件 return model_filename; } /***************************************************************** *Function: SnapshotToHDF5() *Description: 快照以HDF5文件形式保存 *Calls: *Called By: Snapshot() *Input: *Output: *Return: *Others: *****************************************************************/ template <typename Dtype> string Solver<Dtype>::SnapshotToHDF5() { string model_filename = SnapshotFilename(".caffemodel.h5"); LOG(INFO) << "Snapshotting to HDF5 file " << model_filename; net_->ToHDF5(model_filename, param_.snapshot_diff()); // 调用网络的ToHDF5函数,网络的ToHDF5函数再调用ToHDF5的库函数保存参数 return model_filename; } /***************************************************************** *Function: Restore() *Description: 存储函数实现如何存储solver到快照模型中 *Calls: *Called By: Solve() *Input: *Output: *Return: *Others: *****************************************************************/ template <typename Dtype> void Solver<Dtype>::Restore(const char* state_file) { string state_filename(state_file); if (state_filename.size() >= 3 && state_filename.compare(state_filename.size() - 3, 3, ".h5") == 0) { RestoreSolverStateFromHDF5(state_filename); // 调用具体的Solver的RestoreSolverStateFromHDF5来实现, 从HDF5文件来保存快照 } else { RestoreSolverStateFromBinaryProto(state_filename); // 调用具体的Solver的RestoreSolverStateFromBinaryProto来实现, 从二进制文件来保存快照 } } /***************************************************************** *Function: UpdateSmoothedLoss() *Description: 更新平滑损失 *Calls: *Called By: Solve() / Step() *Input: *Output: *Return: *Others: *****************************************************************/ template <typename Dtype> void Solver<Dtype>::UpdateSmoothedLoss(Dtype loss, int start_iter, int average_loss) { if (losses_.size() < average_loss) { losses_.push_back(loss); int size = losses_.size(); smoothed_loss_ = (smoothed_loss_ * (size - 1) + loss) / size; } else { int idx = (iter_ - start_iter) % average_loss; smoothed_loss_ += (loss - losses_[idx]) / average_loss; losses_[idx] = loss; } } INSTANTIATE_CLASS(Solver); } // namespace caffe
[ "976491174@qq.com" ]
976491174@qq.com
23f310daaf003202e15cf9e71d5f984e9e55280f
feef868891ae2c7dc46bec2181d2ce52e4713372
/src/main_window.cpp
407517938483190e897a032a6bb6b21584c5b0e8
[]
no_license
hajunsong/mobile_robot
e978b2420e39ebb34cbd020bdceaafd7e7a9fc55
7a7f83355b946ceb46ff2e63cb9556b5f9092e07
refs/heads/master
2022-01-08T11:33:01.949392
2019-07-02T07:22:44
2019-07-02T07:22:44
170,284,902
0
0
null
null
null
null
UTF-8
C++
false
false
27,876
cpp
/** * @file /src/main_window.cpp * * @brief Implementation for the qt gui. * * @date February 2011 **/ /***************************************************************************** ** Includes *****************************************************************************/ #include <QtGui> #include <QMessageBox> #include <iostream> #include "../include/mobile_robot/main_window.hpp" double init_pose[4] = {0.004, -0.042, 0.048, 0.999}; const int wp_size1 = 1; double path1[wp_size1][4] = { -0.596, -0.259, 0.939, -0.343 }; uint wp_indx1 = 0; const int wp_size2 = 1; double path2[wp_size2][4] = { -0.004, -0.042, 0.048, 0.999 }; uint wp_indx2 = 0; const uint wp_size3 = 1; double path3[wp_size3][4] = { -0.004, -0.042, 0.048, 0.999 }; uint wp_indx3 = 0; const double D2R = M_PI / 180.0; const double des_ang1 = -173 * D2R; const double des_ang2 = 110 * D2R; const double des_ang3 = -160 * D2R; const double des_ang4 = 30 * D2R; /***************************************************************************** ** Namespaces *****************************************************************************/ namespace MobileRobot { using namespace Qt; /***************************************************************************** ** Implementation [MainWindow] *****************************************************************************/ MainWindow::MainWindow(int argc, char **argv, QWidget *parent) : QMainWindow(parent), qnode(argc, argv), ui(new Ui::MainWindowDesign) { ui->setupUi(this); m_Rviz = new CreateRviz(); if (DEBUG_ENABLED) qDebug() << "m_Rviz Class"; m_RosLaunch = new RosLaunchClass(); if (DEBUG_ENABLED) qDebug() << "m_RosLaunch Class"; m_TopicUpdate = new TopicGuiUpdateClass(); if (DEBUG_ENABLED) qDebug() << "m_TopicUpdate Class"; modelMain = new QStandardItemModel(5, 5, this); m_TopicUpdate->Initialize(ui, modelMain); QObject::connect(ui->actionAbout_Qt, SIGNAL(triggered(bool)), qApp, SLOT(aboutQt())); // qApp is a global variable for the application ReadSettings(); setWindowIcon(QIcon(":/images/icon.png")); ui->tab_manager->setCurrentIndex(0); // ensure the first tab is showing - qt-designer should have this already hardwired, but often loses it (settings?). QObject::connect(&qnode, SIGNAL(rosShutdown()), this, SLOT(close())); /********************* ** Logging **********************/ ui->view_logging->setModel(qnode.loggingModel()); QObject::connect(&qnode, SIGNAL(loggingUpdated()), this, SLOT(updateLoggingView())); /********************* ** Auto Start **********************/ if (ui->checkbox_remember_settings->isChecked()) { on_button_connect_clicked(true); } timerUIUpdate = new QTimer(this); connect(timerUIUpdate, SIGNAL(timeout()), this, SLOT(UiUpdate())); timerUIUpdate->start(100); connect(ui->btnConnectServer, SIGNAL(clicked()), this, SLOT(btnConnectServerClicked())); connect(ui->btnGuest, SIGNAL(clicked()), this, SLOT(btnGuestClicked())); connect(ui->btnHome, SIGNAL(clicked()), this, SLOT(btnHomeClicked())); timerScenario = new QTimer(this); connect(timerScenario, SIGNAL(timeout()), this, SLOT(scenarioUpdate())); guestCome = false; event_flag = 0; connectServer = false; m_Client = new TcpClient(this); connect(m_Client->socket, SIGNAL(connected()), this, SLOT(onConnectServer())); connect(m_Client->socket, SIGNAL(readyRead()), this, SLOT(readMessage())); enableDxl = false; connect(ui->cbEnableDxl, SIGNAL(stateChanged(int)), this, SLOT(cbEnableDxlStateChanged(int))); connect(ui->btnRunDxl, SIGNAL(clicked()), this, SLOT(btnRunDxlClicked())); dxlControl = new DxlControl(); connect(ui->btnDocking, SIGNAL(clicked()), this, SLOT(btnDockingClicked())); init_flag = false; timerTurning = new QTimer(this); connect(timerTurning, SIGNAL(timeout()), this, SLOT(turning())); timerTurning->setInterval(50); timerDocking = new QTimer(this); connect(timerDocking, SIGNAL(timeout()), this, SLOT(docking())); timerDocking->setInterval(500); countDocking = 0; backgroundWidget = new QWidget(this); backgroundWidget->setFixedSize(1280, 800); backgroundWidget->setGeometry(0, 0, 1280, 800); backgroundWidget->hide(); serviceImage = new QLabel(backgroundWidget); serviceImage->setGeometry(backgroundWidget->rect()); flag = false; // AutoDockingROS autoDocking("mobile_robot"); autoDocking = new AutoDockingROS("mobile_robot"); ros::NodeHandle n; autoDocking->init(n); timerTcpWait = new QTimer(this); timerTcpWait->setInterval(2 * 60000); connect(timerTcpWait, SIGNAL(timeout()), this, SLOT(tcpWaitTimeout())); timerTcpWait->start(); AutoDriveFlag = false; // bumper_subscriber = n.subscribe("mobile_base/events/bumper", 1000, &QNode::BumperCallback, this); timerBumper = new QTimer(this); timerBumper->setInterval(10); connect(timerBumper, SIGNAL(timeout()), this, SLOT(bumperCheck())); qnode.m_TopicPacket.m_BumperState = false; timerJoystick = new QTimer(this); timerJoystick->setInterval(10); connect(timerJoystick, SIGNAL(timeout()), this, SLOT(joystickTimeout())); joystick = new Joystick("/dev/input/js0"); connect(ui->btnJoystickConnect, SIGNAL(clicked()), timerJoystick, SLOT(start())); move_direction = 0; on_button_connect_clicked(true); btnConnectServerClicked(); } MainWindow::~MainWindow() { timerUIUpdate->stop(); timerScenario->stop(); timerTurning->stop(); delete m_Client; if (enableDxl) delete dxlControl; delete timerUIUpdate; delete timerScenario; delete timerTurning; delete timerDocking; delete serviceImage; delete backgroundWidget; delete autoDocking; delete m_Rviz; delete m_RosLaunch; delete m_TopicUpdate; delete joystick; delete ui; } /***************************************************************************** ** Implementation [Slots] *****************************************************************************/ void MainWindow::UiUpdate() { switch (ui->tab_manager->currentIndex()) { case 0: m_TopicUpdate->UIUpdate(ui, modelMain, &qnode); break; } } void MainWindow::showNoMasterMessage() { QMessageBox msgBox; msgBox.setText("Couldn't find the ros master."); msgBox.exec(); close(); } /* * These triggers whenever the button is clicked, regardless of whether it * is already checked or not. */ void MainWindow::on_button_connect_clicked(bool check) { if (ui->checkbox_use_environment->isChecked()) { if (!qnode.init()) { showNoMasterMessage(); } else { ui->button_connect->setEnabled(false); } } else { if (!qnode.init(ui->line_edit_master->text().toStdString(), ui->line_edit_host->text().toStdString())) { showNoMasterMessage(); } else { ui->button_connect->setEnabled(false); ui->line_edit_master->setReadOnly(true); ui->line_edit_host->setReadOnly(true); ui->line_edit_topic->setReadOnly(true); } } m_Rviz->Rviz_Init(ui); } void MainWindow::on_checkbox_use_environment_stateChanged(int state) { bool enabled; if (state == 0) { enabled = true; } else { enabled = false; } ui->line_edit_master->setEnabled(enabled); ui->line_edit_host->setEnabled(enabled); //ui->line_edit_topic->setEnabled(enabled); } /***************************************************************************** ** Implemenation [Slots][manually connected] *****************************************************************************/ /** * This function is signalled by the underlying model. When the model changes, * this will drop the cursor down to the last line in the QListview to ensure * the user can always see the latest log message. */ void MainWindow::updateLoggingView() { ui->view_logging->scrollToBottom(); } /***************************************************************************** ** Implementation [Menu] *****************************************************************************/ void MainWindow::on_actionAbout_triggered() { QMessageBox::about(this, tr("About ..."), tr("<h2>PACKAGE_NAME Test Program 0.10</h2><p>Copyright Yujin Robot</p><p>This package needs an about description.</p>")); } /***************************************************************************** ** Implementation [Configuration] *****************************************************************************/ void MainWindow::ReadSettings() { // QSettings settings("Qt-Ros Package", "robomap"); // restoreGeometry(settings.value("geometry").toByteArray()); // restoreState(settings.value("windowState").toByteArray()); // QString master_url = settings.value("master_url", QString("http://192.168.1.2:11311/")).toString(); // QString host_url = settings.value("host_url", QString("192.168.1.3")).toString(); // //QString topic_name = settings.value("topic_name", QString("/chatter")).toString(); // ui->line_edit_master->setText(master_url); // ui->line_edit_host->setText(host_url); // //ui->line_edit_topic->setText(topic_name); // bool remember = settings.value("remember_settings", false).toBool(); // ui->checkbox_remember_settings->setChecked(remember); // bool checked = settings.value("use_environment_variables", false).toBool(); // ui->checkbox_use_environment->setChecked(checked); // if (checked) // { // ui->line_edit_master->setEnabled(false); // ui->line_edit_host->setEnabled(false); // //ui->line_edit_topic->setEnabled(false); // } } void MainWindow::WriteSettings() { // QSettings settings("Qt-Ros Package", "robomap"); // settings.setValue("master_url", ui->line_edit_master->text()); // settings.setValue("host_url", ui->line_edit_host->text()); // //settings.setValue("topic_name",ui->line_edit_topic->text()); // settings.setValue("use_environment_variables", QVariant(ui->checkbox_use_environment->isChecked())); // settings.setValue("geometry", saveGeometry()); // settings.setValue("windowState", saveState()); // settings.setValue("remember_settings", QVariant(ui->checkbox_remember_settings->isChecked())); } void MainWindow::closeEvent(QCloseEvent *event) { WriteSettings(); QMainWindow::closeEvent(event); } void MainWindow::btnConnectServerClicked() { qDebug() << "Try connect server"; m_Client->setIpAddress(ui->ipAddress->text()); m_Client->setPortNum(ui->portNum->text()); emit m_Client->connectToServer(); } void MainWindow::onConnectServer() { m_Client->socket->write("Server-MobileRobot Connection success"); ui->btnConnectServer->setDisabled(true); ui->ipAddress->setDisabled(true); ui->portNum->setDisabled(true); enableDxl = true; dxlControl->dxl_init(); ui->cbEnableDxl->setChecked(enableDxl); timerJoystick->start(); connectServer = true; on_btnSetInitialPose_clicked(); } void MainWindow::readMessage() { timerTcpWait->stop(); QByteArray rxData = m_Client->socket->readAll(); if (rxData.length() > 0) { qDebug() << "Receive Data(Frome Server) : " + rxData; char rxHead = 0x02, rxHeadSub = 0x05; QList<QByteArray> rxDataList = rxData.split(rxHead); int len = rxDataList.length(); for (int i = 0; i < len; i++) { QList<QByteArray> rxDataListSub = rxDataList[i].split(rxHeadSub); int len_sub = rxDataListSub.length(); if (len_sub > 1) { for (int j = 0; j < len_sub; j++) { if (rxDataListSub[j].length() > 0 && AutoDriveFlag) { int data = rxDataListSub[j].at(0); qDebug() << data; switch (data) { case 0: ROS_INFO("Guest leaved"); viewImageWink(); btnHomeClicked(); break; case 1: if (countDocking > 0) { timerDocking->stop(); docking_ac->cancelGoal(); countDocking = 0; delete docking_ac; on_btnSetInitialPose_clicked(); } btnGuestClicked(); break; case 3: viewImageWait(); break; case 6: timerTcpWait->start(); break; case 7: ROS_INFO("Guest leaved"); viewImageSmile(); btnHomeClicked(); break; case 8: // ROS_INFO("No Guest"); // event_flag = 9; // scenarioCnt = 0; // timerScenario->start(50); default: break; } } } } } } } void MainWindow::on_btnSetInitialPose_clicked() { double yaw = atan2(2.0 * (init_pose[Rw] * init_pose[Rz]), 1.0 - 2.0 * (init_pose[Rz] * init_pose[Rz])); m_Rviz->SetInitialPose(init_pose[Px], init_pose[Py], yaw); wp_indx1 = 0; wp_indx2 = 0; wp_indx3 = 0; if (init_flag == false) { m_Rviz->SetGoalPose(init_pose[Px], init_pose[Py], yaw); init_flag = true; } timerScenario->stop(); timerTurning->stop(); timerDocking->stop(); flag = true; viewImageSleep(); countDocking = 0; AutoDriveFlag = true; timerBumper->start(); } void MainWindow::btnGuestClicked() { viewImageSmile(); if (enableDxl) { dxlControl->moveDxl(); dxlControl->setHomePosition(); } event_flag = 1; scenarioCnt = 0; timerScenario->start(50); } void MainWindow::goGuest() { wp_indx1 = 0; double yaw = atan2(2.0 * (path1[0][Rw] * path1[0][Rz]), 1.0 - 2.0 * (path1[0][Rz] * path1[0][Rz])); m_Rviz->SetGoalPose(path1[0][Px], path1[0][Py], yaw); event_flag = 3; timerScenario->start(100); } void MainWindow::btnHomeClicked() { viewImageSmile(); if (enableDxl) { dxlControl->moveDxl(); dxlControl->setHomePosition(); } event_flag = 7; des_ang = des_ang4; turn_direct = RIGHT; timerTurning->start(); } void MainWindow::goEnd() { wp_indx2 = 0; double yaw = atan2(2.0 * (path2[0][Rw] * path2[0][Rz]), 1.0 - 2.0 * (path2[0][Rz] * path2[0][Rz])); m_Rviz->SetGoalPose(path2[0][Px], path2[0][Py], yaw); event_flag = 6; timerScenario->start(10); } void MainWindow::goHome() { wp_indx3 = 0; // ROS_INFO("========================================== 1"); double yaw = atan2(2.0 * (path3[0][Rw] * path3[0][Rz]), 1.0 - 2.0 * (path3[0][Rz] * path3[0][Rz])); // ROS_INFO("========================================== 2"); m_Rviz->SetGoalPose(path3[0][Px], path3[0][Py], yaw); // ROS_INFO("========================================== 3"); event_flag = 8; timerScenario->start(10); } void MainWindow::scenarioUpdate() { switch (event_flag) { case 1: { qnode.KobukiMove(-0.1, 0.0, 0.0, 0.0, 0.0, 0.0); scenarioCnt++; if (scenarioCnt > 25) { timerScenario->stop(); event_flag = 2; des_ang = des_ang1; turn_direct = LEFT; timerTurning->start(); } break; } case 3: { double dist = sqrt(pow(qnode.m_TopicPacket.m_AmclPx - path1[wp_indx1][Px], 2) + pow(qnode.m_TopicPacket.m_AmclPy - path1[wp_indx1][Py], 2)); if (dist <= 0.6) { wp_indx1++; if (wp_indx1 < wp_size1) { double yaw = atan2(2.0 * (path1[wp_indx1][Rw] * path1[wp_indx1][Rz]), 1.0 - 2.0 * (path1[wp_indx1][Rz] * path1[wp_indx1][Rz])); m_Rviz->SetGoalPose(path1[wp_indx1][Px], path1[wp_indx1][Py], yaw); } } if (wp_indx1 >= wp_size1) { if (qnode.m_TopicPacket.m_GoalReached) { timerScenario->stop(); event_flag = 4; des_ang = des_ang2; turn_direct = RIGHT; timerTurning->start(); } wp_indx1--; } break; } case 6: { double dist = sqrt(pow(qnode.m_TopicPacket.m_AmclPx - path2[wp_indx2][Px], 2) + pow(qnode.m_TopicPacket.m_AmclPy - path2[wp_indx2][Py], 2)); if (dist <= 0.6) { wp_indx2++; if (wp_indx2 < wp_size2) { double yaw = atan2(2.0 * (path2[wp_indx2][Rw] * path2[wp_indx2][Rz]), 1.0 - 2.0 * (path2[wp_indx2][Rz] * path2[wp_indx2][Rz])); m_Rviz->SetGoalPose(path2[wp_indx2][Px], path2[wp_indx2][Py], yaw); } } if (wp_indx2 >= wp_size2) { if (qnode.m_TopicPacket.m_GoalReached) { timerScenario->stop(); event_flag = 7; des_ang = des_ang4; turn_direct = RIGHT; timerTurning->start(); } wp_indx2--; } break; } case 8: { double dist = sqrt(pow(qnode.m_TopicPacket.m_AmclPx - path3[wp_indx3][Px], 2) + pow(qnode.m_TopicPacket.m_AmclPy - path3[wp_indx3][Py], 2)); if (dist <= 0.6) { wp_indx3++; if (wp_indx3 < wp_size3) { double yaw = atan2(2.0 * (path3[wp_indx3][Rw] * path3[wp_indx3][Rz]), 1.0 - 2.0 * (path3[wp_indx3][Rz] * path3[wp_indx3][Rz])); m_Rviz->SetGoalPose(path3[wp_indx3][Px], path3[wp_indx3][Py], yaw); } } if (wp_indx3 >= wp_size3) { // ROS_INFO("wp_indx3 : [%d]", wp_indx3); sleep(1); if (qnode.m_TopicPacket.m_GoalReached) { timerScenario->stop(); btnDockingClicked(); if (connectServer) { QByteArray txData; txData.append(QByteArray::fromRawData("\x02\x05", 2)); txData.append(QByteArray::fromRawData("\x05", 1)); txData.append(QByteArray::fromRawData("\x0D\x05", 2)); m_Client->socket->write(txData); } } wp_indx3--; } break; } case 9: { qnode.KobukiMove(-0.1, 0.0, 0.0, 0.0, 0.0, 0.2); scenarioCnt++; if (scenarioCnt > 50) { timerScenario->stop(); btnHomeClicked(); } break; } default: break; } } void MainWindow::turning() { double yaw = qnode.m_TopicPacket.m_ImuYaw; double err = yaw - des_ang; // ROS_INFO("yaw =: [%f], des =: [%f], err =: [%f]", yaw, des_ang, err); if (abs(err) >= 0.05) { qnode.KobukiMove(0.0, 0.0, 0.0, 0.0, 0.0, turn_direct == LEFT ? 1.0 : -1.0); } else { qnode.KobukiMove(0.0, 0.0, 0.0, 0.0, 0.0, 0.0); timerTurning->stop(); if (event_flag == 2) { goGuest(); } else if (event_flag == 4) { if (connectServer) { QByteArray txData; txData.append(QByteArray::fromRawData("\x02\x05", 2)); txData.append(QByteArray::fromRawData("\x02", 1)); txData.append(QByteArray::fromRawData("\x0D\x05", 2)); m_Client->socket->write(txData); } viewImageWink(); // btnHomeClicked(); } else if (event_flag == 5) { ROS_INFO("kobuki go End"); goEnd(); } else if (event_flag == 7) { ROS_INFO("kobuki go Home"); goHome(); } } } void MainWindow::cbEnableDxlStateChanged(int state) { if (state == 2) { enableDxl = true; dxlControl->dxl_init(); } else { enableDxl = false; dxlControl->dxl_deinit(); } } void MainWindow::btnRunDxlClicked() { if (enableDxl) { dxlControl->moveDxl(); dxlControl->setHomePosition(); } } void MainWindow::btnDockingClicked() { // docking(); ROS_INFO("docking start"); // Create the client // actionlib::SimpleActionClient<kobuki_msgs::AutoDockingAction> docking_ac("dock_drive_action", true); docking_ac = new actionlib::SimpleActionClient<kobuki_msgs::AutoDockingAction>("dock_drive_action", true); docking_ac->waitForServer(); // Create goal object kobuki_msgs::AutoDockingGoal goal; // Send the goal docking_ac->sendGoal(goal); countDocking = 0; timerDocking->start(); } void MainWindow::docking() { // int dock_state = autoDocking->spin(); // Assign initial state actionlib::SimpleClientGoalState dock_state = actionlib::SimpleClientGoalState::LOST; dock_state = docking_ac->getState(); ROS_INFO("%d Docking status: %s", countDocking, dock_state.toString().c_str()); countDocking++; if (dock_state == actionlib::SimpleClientGoalState::SUCCEEDED) { ROS_INFO("Docking complete."); on_btnSetInitialPose_clicked(); qnode.ResetOdom(); } else { if (countDocking >= 30) { docking_ac->cancelGoal(); qnode.KobukiMove(0.0, 0.0, 0.0, 0.0, 0.0, 0.0); on_btnSetInitialPose_clicked(); } } } void MainWindow::viewImageSmile() { ui->centralwidget->hide(); ui->dock_status->close(); backgroundWidget->show(); labelDrawImage( serviceImage, "/root/catkin_ws/src/mobile_robot/resources/images/smile.png", 1.5); } void MainWindow::viewImageWink() { ui->centralwidget->hide(); ui->dock_status->close(); backgroundWidget->show(); labelDrawImage( serviceImage, "/root/catkin_ws/src/mobile_robot/resources/images/wink.jpg", 2.0); } void MainWindow::viewImageSleep() { ui->centralwidget->hide(); ui->dock_status->close(); backgroundWidget->show(); labelDrawImage( serviceImage, "/root/catkin_ws/src/mobile_robot/resources/images/sleep.jpg", 1.0); } void MainWindow::viewImageWait() { ui->centralwidget->hide(); ui->dock_status->close(); backgroundWidget->show(); QMovie *movie = new QMovie("/root/catkin_ws/src/mobile_robot/resources/images/wait.gif"); QSize movieSize; movieSize.setWidth(serviceImage->width() * 0.5); movieSize.setHeight(serviceImage->height() * 0.8); movie->setScaledSize(movieSize); serviceImage->setAlignment(Qt::AlignmentFlag::AlignCenter); serviceImage->setMovie(movie); movie->start(); } void MainWindow::labelDrawImage(QLabel *label, QString imagePath, double scale) { QImage *image = new QImage(); QPixmap *buffer = new QPixmap(); if (image->load(imagePath)) { *buffer = QPixmap::fromImage(*image); *buffer = buffer->scaled(image->width() * scale, image->height() * scale); } label->setAlignment(Qt::AlignmentFlag::AlignCenter); label->setPixmap(*buffer); } void MainWindow::tcpWaitTimeout() { btnConnectServerClicked(); } void MainWindow::bumperCheck() { if (qnode.m_TopicPacket.m_BumperState && countDocking == 0) { ROS_INFO("Occurred Bumper Event"); emergencyStop(); } } void MainWindow::emergencyStop() { timerUIUpdate->stop(); timerScenario->stop(); timerTurning->stop(); timerDocking->stop(); timerTcpWait->stop(); qnode.CancelGoal(); AutoDriveFlag = false; qnode.KobukiMove(0.0, 0.0, 0.0, 0.0, 0.0, 0.0); timerBumper->stop(); } void MainWindow::joystickTimeout(){ if (joystick->isFound()){ // Attempt to sample an event from the joystick JoystickEvent event; if (joystick->sample(&event)) { if (event.isButton()) { switch(event.number){ case 0: // Button A ROS_INFO("Button A is %s\n", event.value == 0 ? "up" : "down"); move_direction = 3; break; case 1: // Button B ROS_INFO("Button B is %s\n", event.value == 0 ? "up" : "down"); move_direction = 2; break; case 3: // Button X ROS_INFO("Button X is %s\n", event.value == 0 ? "up" : "down"); move_direction = 1; break; case 4: // Button Y ROS_INFO("Button Y is %s\n", event.value == 0 ? "up" : "down"); move_direction = 4; break; case 10: // Button SELCET ROS_INFO("Button SELECT is %s\n", event.value == 0 ? "up" : "down"); emergencyStop(); move_direction = 0; AutoDriveFlag = false; break; case 11: // Button START ROS_INFO("Button START is %s\n", event.value == 0 ? "up" : "down"); move_direction = -1; AutoDriveFlag = true; if (connectServer) { QByteArray txData; txData.append(QByteArray::fromRawData("\x02\x05", 2)); txData.append(QByteArray::fromRawData("\x05", 1)); txData.append(QByteArray::fromRawData("\x0D\x05", 2)); m_Client->socket->write(txData); } on_btnSetInitialPose_clicked(); break; default : break; } } // else if (event.isAxis()) // { // ROS_INFO("Axis %u is at position %d\n", event.number, event.value); // } } if (!AutoDriveFlag){ // cout << move_direction; switch(move_direction){ case 0: qnode.KobukiMove(0.0, 0.0, 0.0, 0.0, 0.0, 0.0); break; case 1: qnode.KobukiMove(0.07, 0.0, 0.0, 0.0, 0.0, 0.0); break; case 2: qnode.KobukiMove(-0.07, 0.0, 0.0, 0.0, 0.0, 0.0); break; case 3: qnode.KobukiMove(0.0, 0.0, 0.0, 0.0, 0.0, -0.5); break; case 4: qnode.KobukiMove(0.0, 0.0, 0.0, 0.0, 0.0, 0.5); break; default: break; } } } else{ // ROS_INFO("Joystick not connected"); delete joystick; joystick = new Joystick("/dev/input/js0"); } } } // namespace MobileRobot
[ "hajunsong90@gmail.com" ]
hajunsong90@gmail.com
5d59dc48eda4d3633199c66e99368eae0db62744
a8bee14fb5461e7c0478ae651296cda01298bebc
/AlienAIDemo/Source/AlienAIDemo/Private/Controller/EnemyController.cpp
e341505d6a32c067dedcc636c209a8fb55d8b46b
[ "MIT" ]
permissive
Rodolfo377/AlienAIDemo
19ffc1da4ba2ac75336420642172f7b1619921df
5a2efb29820b2b488ecbd1bd89a06362d834e888
refs/heads/master
2022-12-09T10:25:36.053190
2020-10-01T16:31:02
2020-10-01T16:31:02
284,100,410
0
0
null
null
null
null
UTF-8
C++
false
false
135
cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "../../Public/Controller/EnemyController.h"
[ "rodolfo.fava@protonmail.com" ]
rodolfo.fava@protonmail.com
a7e1ef78267e56d55104b1f728dfc44ef1f25d07
d8e7a11322f6d1b514c85b0c713bacca8f743ff5
/7.6.00.32/V76_00_32/MaxDB_ORG/sys/src/SAPDB/Container/Container_AVLTree.hpp
770c8fa081922dd67684f77905358f74ef710746
[]
no_license
zhaonaiy/MaxDB_GPL_Releases
a224f86c0edf76e935d8951d1dd32f5376c04153
15821507c20bd1cd251cf4e7c60610ac9cabc06d
refs/heads/master
2022-11-08T21:14:22.774394
2020-07-07T00:52:44
2020-07-07T00:52:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
33,393
hpp
/*!************************************************************************** module : Container_ALVTree.hpp responsible : Dirk Thomsen created : 2003-01-24 last changed: 2003-02-13 copyright: Copyright (c) 2003-2005 SAP AG description : Class declaration and definition for template ALVTree ========== licence begin GPL Copyright (c) 2003-2005 SAP AG 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 2 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, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. ========== licence end *****************************************************************************/ #ifndef CONTAINER_AVLTREE_HPP #define CONTAINER_AVLTREE_HPP #include "SAPDBCommon/MemoryManagement/SAPDBMem_IRawAllocator.hpp" #include "SAPDBCommon/MemoryManagement/SAPDBMem_NewDestroy.hpp" #include "geo00.h" /*-----------------------------------------------------------------------------*/ enum Container_AVLTreeError { AVLTree_Ok = 0, AVLTree_NotFound = -1, AVLTree_DuplicateKey = -2, AVLTree_OutOfMemory = -8 }; enum Container_AVLTreeIterDirection { AVLTree_ASCENDING, AVLTree_DESCENDING }; /// Definition of Container_AVLNodeComparator */ template <class T> class Container_AVLNodeComparator { public : /*! Ths method compares the key of some node (NodeKey) with the key searched for (SearchKey). For some applications the order of arguments may be important, so Container_AVLTree must pay attention to it!!! */ inline int Compare(const T& NodeKey, const T& SearchKey) { if (NodeKey < SearchKey) return -1; if (SearchKey < NodeKey) return 1; return 0; } }; /// Definition of Container_AVLNode */ template <class KEY, class CMP> class Container_AVLNode { typedef Container_AVLNode<KEY,CMP>* Container_AVLNodePtr; // protected: KEY m_Key; // Container_AVLNodePtr m_LeftSon; Container_AVLNodePtr m_RightSon; Container_AVLNodePtr m_Parent; int m_Balance; // public: // Container_AVLNode( const KEY& k ); virtual ~Container_AVLNode( void ) {} // must be virtual! // inline const KEY* GetKey( void ) const; // inline int& Balance( void ); inline SAPDB_Bool Balanced( void ) const; inline void Delete_RR( Container_AVLNodePtr& p, SAPDB_Bool& balance ); inline void Delete_LL( Container_AVLNodePtr& p, SAPDB_Bool& balance ); inline SAPDB_Bool LeftDeeper( void ) const; inline Container_AVLNodePtr& LeftSon( void ) { return m_LeftSon; } inline SAPDB_Bool RightDeeper( void ) const; inline Container_AVLNodePtr& RightSon( void ) { return m_RightSon; } inline void SetLeftSon( Container_AVLNodePtr son ); inline void SetRightSon( Container_AVLNodePtr son ); inline Container_AVLNodePtr& Parent( void ) { return m_Parent; } inline void Rotate_LL( Container_AVLNodePtr& p ); inline void Rotate_LR( Container_AVLNodePtr& p ); inline void Rotate_RL( Container_AVLNodePtr& p ); inline void Rotate_RR( Container_AVLNodePtr& p ); inline void SetBalanced( void ); inline void SetRightDeeper( void ); inline void SetLeftDeeper( void ); virtual void CleanUp( SAPDBMem_IRawAllocator& alloc, CMP& cmp ) {}; }; template <class KEY, class CONTENT, class CMP> class Container_AVLContentNode : public Container_AVLNode<KEY,CMP> { typedef Container_AVLContentNode<KEY,CONTENT,CMP>* Container_AVLContentNodePtr; // public: // Container_AVLContentNode( const KEY& k ) : Container_AVLNode<KEY,CMP>(k), m_Content() { } // Container_AVLContentNode( const KEY& k, const CONTENT& d ) : Container_AVLNode<KEY,CMP>(k), m_Content(d) { } // virtual ~Container_AVLContentNode( void ) {} // must be virtual as otherwise m_Content will not be destructed when AVLTree.DeleteNode is called // inline const CONTENT* GetContent( void ) const { return &m_Content; } // inline const CONTENT* SetContent( const CONTENT& d ) { m_Content = d; return &m_Content; } // virtual void DeleteSelf( SAPDBMem_IRawAllocator& alloc, CMP& cmp ) {}; // private: CONTENT m_Content; // }; /// Definition of Container_AVLTree */ template<class NODE, class KEY, class CMP> class Container_AVLTree { #if defined(AIX) || defined(SUN) || defined(HPUX) || defined(SOLARIS) public : #endif typedef Container_AVLNode<KEY,CMP>* Container_AVLNodePtr; // public : // Container_AVLTree(CMP* c, SAPDBMem_IRawAllocator* a) : m_Root(NULL), mAllocatorPtr(a), mCmp(c), m_NodeCount(0), m_ChangeCount(0) { } // Container_AVLTree() : m_Root(NULL), mAllocatorPtr(NULL), mCmp(NULL), m_NodeCount(0), m_ChangeCount(0) { } // virtual ~Container_AVLTree( void ) { DeleteAll(); } // inline void AdviseAllocator( SAPDBMem_IRawAllocator* a ) { mAllocatorPtr = a; } // inline SAPDBMem_IRawAllocator* GetAllocator( void ) { return mAllocatorPtr; } // inline SAPDB_ULong GetMaxSize ( void ) { return 0; // return mAllocatorPtr.??? // D.T. } // inline void AdviseCompare( CMP* c ) { mCmp = c; } // inline NODE* Insert( const KEY& key, Container_AVLTreeError& rc ) { return InsertIntoTree(key, rc); } // inline NODE* Find( const KEY& key ) const { return FindNode(key); } // inline NODE* InsertNode( const KEY& key, Container_AVLNodePtr& p, const Container_AVLNodePtr& parent, SAPDB_Bool& balance, Container_AVLTreeError& rc ); // inline NODE* FindNode( const KEY& key ) const; // inline NODE* InsertIntoTree( const KEY& key, Container_AVLTreeError& rc ) { SAPDB_Bool dummy = SAPDB_FALSE; rc = AVLTree_Ok; return InsertNode(key, m_Root, NULL, dummy, rc); } // inline Container_AVLTreeError Delete( const KEY& key ) { SAPDB_Bool balance = SAPDB_FALSE; return DeleteNode (key, *REINTERPRET_CAST(Container_AVLNodePtr*, &m_Root), balance); } // inline void DeleteAll( void ) { DeleteSubtree(m_Root); m_Root = NULL; } // inline SAPDB_ULong GetSize( void ) const { return m_NodeCount; } // inline SAPDB_ULong GetChanges( void ) const { return m_ChangeCount; } // inline SAPDB_Bool CheckTree( void ) const { return (CheckSubTree(m_Root) >= 0); } #if !defined(AIX) && !(defined(SUN) || defined(SOLARIS)) && !defined(HPUX) private : #endif #define STACK_SIZE 128 class Stack { public : int m_Bottom; int m_Top; Container_AVLNodePtr m_Stack[STACK_SIZE]; Stack() : m_Bottom(0), m_Top(0) {}; inline void Push( Container_AVLNodePtr p ) { ++m_Top; if (STACK_SIZE == m_Top) m_Top = 0; m_Stack[m_Top] = p; if (m_Top == m_Bottom) { ++m_Bottom; if (STACK_SIZE == m_Bottom) m_Bottom = 0; } } inline SAPDB_Bool IsEmpty( void ) { return (m_Bottom == m_Top); } inline Container_AVLNodePtr Pop( void ) { if (!IsEmpty()) { Container_AVLNodePtr p = m_Stack[m_Top]; --m_Top; if (m_Top < 0) m_Top = STACK_SIZE - 1; return p; } return NULL; } inline void Reset ( void ) { while (!IsEmpty()) { Pop(); } } }; private : inline int CheckSubTree ( Container_AVLNodePtr p ) const; inline void BalanceLeft ( Container_AVLNodePtr& p, SAPDB_Bool& balance ); inline void BalanceRight ( Container_AVLNodePtr& p, SAPDB_Bool& balance ); inline void Del ( Container_AVLNodePtr& p, Container_AVLNodePtr& deleted, SAPDB_Bool& balance ); inline void DeleteBalanceLeft ( Container_AVLNodePtr& p, SAPDB_Bool& balance ); inline void DeleteBalanceRight ( Container_AVLNodePtr& p, SAPDB_Bool& balance ); inline Container_AVLTreeError DeleteNode ( const KEY& key, Container_AVLNodePtr& p, SAPDB_Bool& doBalance ); inline void DeleteSubtree( Container_AVLNodePtr p ); /// Container_AVLNodePtr m_Root; /// SAPDBMem_IRawAllocator* mAllocatorPtr; CMP* mCmp; /// Number of nodes within the tree SAPDB_ULong m_NodeCount; /// This counter is incremented every time an update operation takes place on the tree /// and thereby it is used to validate iterators if necessary. SAPDB_ULong m_ChangeCount; public : class Iterator; friend class Iterator; /// Local class to iterate over all entries stored in the avl-tree class Iterator { /// Pointer to the current node Container_AVLNodePtr m_curNode; public : /// Pointer to the corresponding avl-tree Container_AVLTree* m_AVLTree; /// Direction iterator is moving if element is deleted Container_AVLTreeIterDirection m_direction; /*! * When starting the iterator this counter is set to the value * of the change counter of the corresponding avl-tree. Before * increment or decrement it is checked, that these two * counters are still the same and if they differ, then an * exception is thrown, as the structure of the tree might * have changed. */ SAPDB_ULong m_startCount; /// ctor 1 Iterator( void ) : m_AVLTree(NULL), m_curNode(NULL), m_direction(AVLTree_ASCENDING), m_startCount(0) { } /// ctor 1 Iterator( const Iterator& iter ) : m_AVLTree(iter.m_AVLTree), m_curNode(iter.m_curNode), m_direction(iter.m_direction), m_startCount(iter.m_startCount) { } /// cast operator inline operator SAPDB_Bool( void ) { return m_curNode != NULL; } /// Increment Iterator (Prefix variant). inline void operator++( void ) { //if (m_StartCount!= m_AVLTree->m_ChangeCount){ // The structure might has been changed by an update operation // on the tree // Throwing of exception not possible, as this class is used in the kernel. //} if (m_curNode == NULL) { return; } if (m_curNode->RightSon() == NULL) { // Ascent from leaf node or right child node. Container_AVLNodePtr p = m_curNode; while (m_curNode != NULL) { m_curNode = m_curNode->Parent(); if ((m_curNode != NULL) && (m_curNode->RightSon()) != p) break; p = m_curNode; } } else { // Descent to leftmost leaf in right subtree m_curNode = m_curNode->RightSon(); while (NULL != m_curNode->LeftSon()) { m_curNode = m_curNode->LeftSon(); } } } /// Increment iterator (Postfix variant. Parameter is only used to /// distinguish from prefix variant) inline void operator++( int i ) { operator++(); } /// Decrement iterator. (Prefix variant) inline void operator--( void ) { //if (m_StartCount != m_AVLTree->m_ChangeCount){ // The structure might has been changed by an update operation // on the tree. // Throwing of exception not possible, as this class is used in the kernel. //} if (m_curNode == NULL) { return; } if (m_curNode->LeftSon() == NULL) { // Ascent from leave node or left child node. Container_AVLNodePtr p = m_curNode; while (m_curNode != NULL) { m_curNode = m_curNode->Parent(); if ((m_curNode != NULL) && (m_curNode->LeftSon()) != p) break; p = m_curNode; } } else { // Descent to rightmost leave in left subtree m_curNode = m_curNode->LeftSon(); while (NULL != m_curNode->RightSon()) { m_curNode = m_curNode->RightSon(); } } } /// Decrement iterator (Postfix variant. Parameter is only used to /// distinguish from prefix variant) inline void operator--( int i ) { operator--(); } /// deref op inline NODE* operator()() { return (NODE*) GetNodePtr(); } /// deref const op inline const NODE* operator()() const { return (NODE*) GetNodePtr(); } /// returns a node in the tree inline Container_AVLNodePtr GetNodePtr( void ) const { return m_curNode; } /// Iterator is invalid, if there was an update operation on the /// corresponding avl-tree since the start of the iterator. inline SAPDB_Bool IsValid( void ) const { return (m_curNode != NULL) && (m_startCount == m_AVLTree->m_ChangeCount); } /// set to last node inline void SetLast( void ) { m_curNode = m_AVLTree->GetRoot(); while ((NULL != m_curNode) && (NULL != m_curNode->RightSon())) { m_curNode = m_curNode->RightSon(); } m_startCount = m_AVLTree->m_ChangeCount; } /// set to first node inline void SetFirst( void ) { m_curNode = m_AVLTree->GetRoot(); while ((NULL != m_curNode) && (NULL != m_curNode->LeftSon())) { m_curNode = m_curNode->LeftSon(); } m_startCount = m_AVLTree->m_ChangeCount; } /// set to specific location void SetLocation(Container_AVLNodePtr& p) { m_curNode = p; m_startCount = m_AVLTree->m_ChangeCount; } }; /// delete an entry Container_AVLTreeError Delete( Iterator& iter ) { Container_AVLNodePtr node = iter.GetNodePtr(); if ( node == 0 ) return AVLTree_NotFound; const KEY& key = *iter()->GetKey(); if (iter.m_direction == AVLTree_ASCENDING) ++iter; else --iter; Container_AVLTreeError rc = Delete (key); if (rc == AVLTree_Ok) iter.m_startCount = this->m_ChangeCount; return rc; } /// returns pointer to first element Iterator First( void ); /// returns pointer to last element Iterator Last( void ); /// search element Iterator Locate( KEY, Container_AVLTreeIterDirection direction=AVLTree_ASCENDING ); /// get root node Container_AVLNodePtr GetRoot( void ) { return m_Root; } }; /*-----------------------------------------------------------------------------*/ /* Definition of Container_AVLContentTree */ /*-----------------------------------------------------------------------------*/ template<class NODE, class KEY, class CONTENT, class CMP> class Container_AVLContentTree : public Container_AVLTree<NODE,KEY,CMP> { typedef Container_AVLContentNode<KEY,CONTENT,CMP>* Container_AVLNodePtr; // public : // Container_AVLContentTree( CMP* c, SAPDBMem_IRawAllocator* a ) : Container_AVLTree<NODE,KEY,CMP>(c, a) { }; // Container_AVLContentTree( void ) : Container_AVLTree<NODE,KEY,CMP>() { }; // inline const NODE* Insert( const KEY& key, const CONTENT& data, Container_AVLTreeError& rc ) { NODE* N = (NODE*) InsertIntoTree(key, rc); if (N) N->SetContent(data); return N; } // inline const NODE* Insert( const KEY& key, Container_AVLTreeError& rc ) { NODE* N = InsertIntoTree(key, rc); if (N) N->SetContent(CONTENT()); return N; } // inline const NODE* Find( const KEY& key ) const { return (NODE*) FindNode(key); } // inline const CONTENT* FindContent( const KEY& key ) const { if (const NODE* N = Find(key)) return N->GetContent(); else return 0; } // }; /*-----------------------------------------------------------------------------*/ /* Implementation of Container_AVLNode */ /*-----------------------------------------------------------------------------*/ template<class KEY, class CMP> Container_AVLNode<KEY,CMP>::Container_AVLNode(const KEY& k) : m_Key(k), m_LeftSon(NULL), m_RightSon(NULL), m_Balance(0) { } template<class KEY, class CMP> inline const KEY* Container_AVLNode<KEY,CMP>::GetKey() const { return &m_Key; } template<class KEY, class CMP> inline SAPDB_Bool Container_AVLNode<KEY,CMP>::Balanced() const { return (0 == m_Balance); } template<class KEY, class CMP> inline void Container_AVLNode<KEY,CMP>::Delete_LL (Container_AVLNodePtr& p, SAPDB_Bool& balance) { p->SetLeftSon( this->RightSon() ); this->SetRightSon( p ); if (this->Balanced()) { p->SetLeftDeeper(); this->SetRightDeeper(); balance = SAPDB_FALSE; } else { this->SetBalanced(); p->SetBalanced(); } p = this; } template<class KEY, class CMP> inline void Container_AVLNode<KEY,CMP>::Delete_RR (Container_AVLNodePtr& p, SAPDB_Bool& balance) { p->SetRightSon( this->LeftSon() ); this->SetLeftSon( p ); if (this->Balanced()) { p->SetRightDeeper(); this->SetLeftDeeper(); balance = SAPDB_FALSE; } else { this->SetBalanced(); p->SetBalanced(); } p = this; } template<class KEY, class CMP> inline SAPDB_Bool Container_AVLNode<KEY,CMP>::LeftDeeper() const { return (-1 == m_Balance); } template<class KEY, class CMP> inline SAPDB_Bool Container_AVLNode<KEY,CMP>::RightDeeper() const { return (1 == m_Balance); } template<class KEY, class CMP> inline void Container_AVLNode<KEY,CMP>::Rotate_LL (Container_AVLNodePtr& p) { this->Parent() = p->Parent(); p->SetLeftSon( this->RightSon() ); this->SetRightSon( p ); p->SetBalanced(); p = this; } template<class KEY, class CMP> inline void Container_AVLNode<KEY,CMP>::Rotate_LR (Container_AVLNodePtr& p) { Container_AVLNodePtr right = RightSon(); right->Parent() = p->Parent(); this->SetRightSon( right->LeftSon() ); right->SetLeftSon( this ); p->SetLeftSon( right->RightSon() ); right->SetRightSon( p ); if (right->LeftDeeper()) p->SetRightDeeper(); else p->SetBalanced(); if (right->RightDeeper()) this->SetLeftDeeper(); else this->SetBalanced(); p = right; p->SetBalanced(); } template<class KEY, class CMP> inline void Container_AVLNode<KEY,CMP>::Rotate_RL (Container_AVLNodePtr& p) { Container_AVLNodePtr left = LeftSon(); left->Parent() = p->Parent(); this->SetLeftSon( left->RightSon() ); left->SetRightSon( this ); p->SetRightSon( left->LeftSon() ); left->SetLeftSon( p ); if (left->RightDeeper()) p->SetLeftDeeper(); else p->SetBalanced(); if (left->LeftDeeper()) this->SetRightDeeper(); else this->SetBalanced(); p = left; p->SetBalanced(); } template<class KEY, class CMP> inline void Container_AVLNode<KEY,CMP>::Rotate_RR (Container_AVLNodePtr& p) { this->Parent() = p->Parent(); p->SetRightSon( this->LeftSon() ); this->SetLeftSon( p ); p->SetBalanced(); p = this; } template<class KEY, class CMP> inline void Container_AVLNode<KEY,CMP>::SetBalanced() { m_Balance = 0; } template<class KEY, class CMP> inline void Container_AVLNode<KEY,CMP>::SetRightDeeper() { m_Balance = 1; } template<class KEY, class CMP> inline void Container_AVLNode<KEY,CMP>::SetLeftDeeper() { m_Balance = -1; } template<class KEY, class CMP> inline int& Container_AVLNode<KEY,CMP>::Balance() { return m_Balance; } /*-----------------------------------------------------------------------------*/ /* Implementation of Container_AVLTree */ /*-----------------------------------------------------------------------------*/ template<class NODE, class KEY, class CMP> inline void Container_AVLTree<NODE,KEY,CMP>::BalanceLeft (Container_AVLNodePtr& p, SAPDB_Bool& balance) { if (p->RightDeeper()) { p->SetBalanced(); balance = SAPDB_FALSE; } else { if (p->Balanced()) { p->SetLeftDeeper(); } else { Container_AVLNodePtr left = p->LeftSon(); if (left->LeftDeeper()) left->Rotate_LL (p); else left->Rotate_LR(p); p->SetBalanced(); balance = SAPDB_FALSE; } } } template<class NODE, class KEY, class CMP> inline void Container_AVLTree<NODE,KEY,CMP>::BalanceRight(Container_AVLNodePtr& p, SAPDB_Bool& balance) { if (p->LeftDeeper()) { p->SetBalanced(); balance = SAPDB_FALSE; } else { if (p->Balanced()) { p->SetRightDeeper(); } else { Container_AVLNodePtr right = p->RightSon(); if (right->RightDeeper()) right->Rotate_RR (p); else right->Rotate_RL(p); p->SetBalanced(); balance = SAPDB_FALSE; } } } template<class NODE, class KEY, class CMP> inline int Container_AVLTree<NODE,KEY,CMP>::CheckSubTree(Container_AVLNodePtr p) const { if (0 == p) return 0; int l = CheckSubTree(p->LeftSon()); int r = CheckSubTree(p->RightSon()); if (l < r) { if (!p->RightDeeper()) return -1; return (r + 1); } if (l > r) { if (!p->LeftDeeper()) return -1; return (l + 1); } if (!p->Balanced()) return -1; return (l + 1); } template<class NODE, class KEY, class CMP> inline void Container_AVLTree<NODE,KEY,CMP>::Del(Container_AVLNodePtr& p, Container_AVLNodePtr& deletedNode, SAPDB_Bool& balance) { if (NULL != p->RightSon()) { Del (p->RightSon(), deletedNode, balance); p->SetRightSon(p->RightSon()); // fix parent entry of rightSon if (balance) DeleteBalanceRight (p, balance); } else { deletedNode = p; p = p->LeftSon(); balance = SAPDB_TRUE; } } template<class NODE, class KEY, class CMP> inline void Container_AVLTree<NODE,KEY,CMP>::DeleteBalanceLeft(Container_AVLNodePtr& p, SAPDB_Bool& balance) { if (p->LeftDeeper()) { p->SetBalanced(); } else { if (p->Balanced()) { p->SetRightDeeper(); balance = SAPDB_FALSE; } else { Container_AVLNodePtr right = p->RightSon(); if (!right->LeftDeeper()) { right->Parent() = p->Parent(); right->Delete_RR (p, balance); } else right->Rotate_RL(p); } } } template<class NODE, class KEY, class CMP> inline void Container_AVLTree<NODE,KEY,CMP>::DeleteBalanceRight (Container_AVLNodePtr& p, SAPDB_Bool& balance) { if (p->RightDeeper()) { p->SetBalanced(); } else { if (p->Balanced()) { p->SetLeftDeeper(); balance = SAPDB_FALSE; } else { Container_AVLNodePtr left = p->LeftSon(); if (!left->RightDeeper()) { left->Parent() = p->Parent(); left->Delete_LL (p, balance); } else left->Rotate_LR(p); } } } template<class NODE, class KEY, class CMP> inline Container_AVLTreeError Container_AVLTree<NODE,KEY,CMP>::DeleteNode ( const KEY& key, Container_AVLNodePtr& p, SAPDB_Bool& balance ) { Container_AVLTreeError rc = AVLTree_Ok; if (NULL == p) { rc = AVLTree_NotFound; balance = SAPDB_FALSE; } else { switch (mCmp->Compare(*p->GetKey(), key)) { case 1 : rc = DeleteNode (key, p->LeftSon(), balance); if (balance) DeleteBalanceLeft(p, balance); break; case -1 : rc = DeleteNode (key, p->RightSon(), balance); if (balance) DeleteBalanceRight (p, balance); break; case 0 : Container_AVLNodePtr curr = p; if (NULL == curr->RightSon()) { if (curr->LeftSon() != NULL) curr->LeftSon()->Parent() = p->Parent(); p = curr->LeftSon(); balance = SAPDB_TRUE; } else { if (NULL == curr->LeftSon()) { if (curr->RightSon() != NULL) curr->RightSon()->Parent() = p->Parent(); p = curr->RightSon(); balance = SAPDB_TRUE; } else { Container_AVLNodePtr deleted; Del (curr->LeftSon(), deleted, balance); deleted->Parent() = curr->Parent(); deleted->SetLeftSon( p->LeftSon() ); deleted->SetRightSon( p->RightSon() ); deleted->Balance() = p->Balance(); p = deleted; if (balance) DeleteBalanceLeft(p, balance); } } curr->CleanUp(*mAllocatorPtr, *mCmp); destroy(curr, *mAllocatorPtr); --m_NodeCount; ++m_ChangeCount; break; } } return rc; } template<class NODE, class KEY, class CMP> inline void Container_AVLTree<NODE,KEY,CMP>::DeleteSubtree(Container_AVLNodePtr p) { if (NULL != p) { DeleteSubtree(p->LeftSon()); DeleteSubtree(p->RightSon()); p->CleanUp(*mAllocatorPtr, *mCmp); destroy(p, *mAllocatorPtr); --m_NodeCount; ++m_ChangeCount; } } template<class NODE, class KEY, class CMP> inline NODE* Container_AVLTree<NODE,KEY,CMP>::InsertNode(const KEY& key, Container_AVLNodePtr& p, const Container_AVLNodePtr& parent, SAPDB_Bool& balance, Container_AVLTreeError& rc) { Container_AVLNodePtr pInserted = NULL; if (NULL == p) { p = new(*mAllocatorPtr) NODE(key); if (!p) { rc = AVLTree_OutOfMemory; balance = SAPDB_FALSE; return NULL; } else { rc = AVLTree_Ok; ++m_NodeCount; ++m_ChangeCount; pInserted = p; p->Parent() = parent; balance = SAPDB_TRUE; } } else { switch (mCmp->Compare(*p->GetKey(), key)) { case 1 : pInserted = InsertNode (key, p->LeftSon(), p, balance, rc); if (pInserted && balance) BalanceLeft(p, balance); break; case -1 : pInserted = InsertNode (key, p->RightSon(), p, balance, rc); if (pInserted && balance) BalanceRight(p, balance); break; case 0 : rc = AVLTree_DuplicateKey; break; } } return (NODE*) pInserted; } template<class NODE, class KEY, class CMP> inline NODE* Container_AVLTree<NODE,KEY,CMP>::FindNode (const KEY& key) const { Container_AVLNodePtr curr = m_Root; while (NULL != curr) { switch (mCmp->Compare(*curr->GetKey(), key)) { case 1 : curr = curr->LeftSon(); break; case -1 : curr = curr->RightSon(); break; case 0 : return (NODE*) curr; break; } } return NULL; } /*-----------------------------------------------------------------------------*/ /* Implementation of Container_AVLTree:Iterator */ /*-----------------------------------------------------------------------------*/ template<class NODE, class KEY, class CMP> inline TYPENAME_MEO00 Container_AVLTree<NODE,KEY,CMP>::Iterator Container_AVLTree<NODE,KEY,CMP>::First( void ) { Iterator iter; iter.m_AVLTree = this; iter.SetFirst(); return iter; } template<class NODE, class KEY, class CMP> inline TYPENAME_MEO00 Container_AVLTree<NODE,KEY,CMP>::Iterator Container_AVLTree<NODE,KEY,CMP>::Last( void ) { Iterator iter; iter.m_AVLTree = this; iter->SetLast(); return iter; } template<class NODE, class KEY, class CMP> inline TYPENAME_MEO00 Container_AVLTree<NODE,KEY,CMP>::Iterator Container_AVLTree<NODE,KEY,CMP>::Locate( KEY key, Container_AVLTreeIterDirection direction ) { Iterator iter; iter.m_AVLTree = this; iter.m_direction = direction; int cmpResult = 1; Container_AVLNodePtr p = m_Root; Container_AVLNodePtr lastGoodNode = NULL; while (NULL != p && cmpResult != 0) { lastGoodNode = p; cmpResult = mCmp->Compare(*p->GetKey(), key); if (cmpResult == 1) { p = p->LeftSon(); } else { if (cmpResult == -1) p = p->RightSon(); } } if (NULL != p) iter.SetLocation(p); else iter.SetLocation(lastGoodNode); if (cmpResult != 0 && iter) { // There is no object with the specified key. Dependend on the parameter // position pointer either on the next largest resp. next smallest object. if (direction == AVLTree_ASCENDING && cmpResult == -1) { ++iter; } else { if (direction == AVLTree_DESCENDING && cmpResult == 1) --iter; } } return iter; } template <class KEY, class CMP> inline void Container_AVLNode<KEY, CMP>::SetRightSon( typename Container_AVLNode<KEY, CMP>::Container_AVLNodePtr son) { this->RightSon() = son; if (son != NULL) son->Parent() = this; } template <class KEY, class CMP> inline void Container_AVLNode<KEY, CMP>::SetLeftSon( typename Container_AVLNode<KEY, CMP>::Container_AVLNodePtr son) { this->LeftSon() = son; if (son != NULL) son->Parent() = this; } #endif
[ "gunter.mueller@gmail.com" ]
gunter.mueller@gmail.com
2ff2138acb764de1811dbcdd883b395a04a35079
a782e8b77eb9a32ffb2c3f417125553693eaee86
/src/developer/debug/shared/regex.cc
3cc9ccf8fd4cb6047c432999757823221945459c
[ "BSD-3-Clause" ]
permissive
xyuan/fuchsia
9e5251517e88447d3e4df12cf530d2c3068af290
db9b631cda844d7f1a1b18cefed832a66f46d56c
refs/heads/master
2022-06-30T17:53:09.241350
2020-05-13T12:28:17
2020-05-13T12:28:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,198
cc
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/developer/debug/shared/regex.h" #include "src/lib/fxl/logging.h" namespace debug_ipc { Regex::Regex() = default; Regex::~Regex() { if (handle_.has_value()) regfree(&handle_.value()); } Regex::Regex(Regex&& other) : handle_(std::move(other.handle_)) { other.handle_.reset(); } Regex& Regex::operator=(Regex&& other) { if (this == &other) return *this; handle_ = std::move(other.handle_); other.handle_.reset(); return *this; } bool Regex::Init(const std::string& regexp, Regex::CompareType compare_type) { if (valid()) return false; regex_t r; int flags = REG_EXTENDED; if (compare_type == Regex::CompareType::kCaseInsensitive) flags |= REG_ICASE; int status = regcomp(&r, regexp.c_str(), flags); if (status) { return false; } handle_ = r; return true; } bool Regex::Match(const std::string& candidate) const { FX_DCHECK(valid()); int status = regexec(&handle_.value(), candidate.c_str(), 0, nullptr, 0); return status == 0; } } // namespace debug_ipc
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
ba4c952b0890ba6f014b9d50023cc51b4a139c6b
1f0ee61ba80c7a09b916ab74837878e6dfe18f5f
/nica/hls/axi_data.hpp
06f134335dab2f512ac8dac7cff58a9346ab8f57
[ "BSD-2-Clause" ]
permissive
lastweek/nica
0c955ea049532e944cc1ef3b7f1c2f331ba9a354
c3067cf487b7615318a5e057363f42c4888bcebe
refs/heads/master
2020-08-04T01:26:25.811021
2019-08-20T11:04:13
2019-08-20T11:11:05
211,953,166
1
0
null
2019-09-30T20:43:07
2019-09-30T20:43:07
null
UTF-8
C++
false
false
1,555
hpp
// // Copyright (c) 2016-2019 Haggai Eran, Gabi Malka, Lior Zeno, Maroun Tork // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // #pragma once #include <ntl/axi_data.hpp> namespace hls_ik { using ntl::axi_data; typedef hls::stream<ap_uint<axi_data::width> > data_stream; }
[ "haggai.eran@gmail.com" ]
haggai.eran@gmail.com
34410163a74ad96902f02d05bf13178397b7b5fc
7456a002dc9806f7b3bc61423db34262124a616b
/Sort.h
282470460dd25c8f9978777facbc515c526169db
[]
no_license
veamirr/sem3_lab1
5cf36b3c2f8b9916873e92e1b24e6bdb58742f91
3badd4818a1df3fd557880ad5ae2256e2ec72663
refs/heads/main
2023-02-10T08:09:36.419331
2020-12-26T09:22:27
2020-12-26T09:22:27
324,519,787
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
2,341
h
#pragma once #include <iostream> #include "Sequence.h" #include "ArraySequence.h" template <class T> class Sort { public: void shakeSort(Sequence<T>* seq, bool (*cmp)(T, T)); void insertSort(Sequence<T>* seq, bool (*cmp)(T, T)); void SelectionSort(Sequence<T>* seq, bool (*cmp)(T, T)); }; template <class T> void Sort<T>::shakeSort(Sequence<T>* seq, bool (*cmp)(T, T)) { int left = 0, right = seq->getLength() - 1; int flag = 1; T a, b; while ((left < right) && flag > 0) { flag = 0; for (int i = left; i < right; i++) { a = seq->get(i); b = seq->get(i + 1); //if (a > b) if (cmp(a,b)==true) { T t = a; seq->insertAt(i, b); seq->insertAt(i + 1, t); flag = 1; } } right--; for (int i = right; i > left; i--) { a = seq->get(i - 1); b = seq->get(i); //if (a > b) if (cmp(a,b)==true) { T t = b; seq->insertAt(i, a); seq->insertAt(i - 1, t); flag = 1; } } left++; } } template <class T> void Sort<T>::insertSort(Sequence<T>* seq, bool (*cmp)(T, T)) { T key; int j; for (int i = 1; i < seq->getLength(); i++) { key = seq->get(i); j = i - 1; while (j >= 0 && cmp(seq->get(j),key)==true) { seq->insertAt(j + 1, seq->get(j)); j = j - 1; } seq->insertAt(j + 1, key); } } template <class T> void Sort<T>::SelectionSort(Sequence<T>* seq, bool (*cmp)(T, T))//не работает для списка так как insertAt работает со сдвигом { T max, x; int maxnum; for (int i = seq->getLength(); i > 1; i--) { max = seq->getFirst(); maxnum = 0; for (int j = 1; j < i; j++) { if (cmp(seq->get(j), max) == true) { max = seq->get(j); maxnum = j; } }; seq->insertAt(maxnum, seq->get(i - 1)); seq->insertAt(i - 1, max); } }
[ "noreply@github.com" ]
noreply@github.com
d8c9eccfdd543d89fa7d3d88858901938055c750
2c5b430f058c50d6f782b93f4d9f8a41216ddf9b
/Motor2D/Emmiter.cpp
fd04b9054cbd49a3ac5794510479b91931dfa372
[ "MIT" ]
permissive
Dawn-of-gods/Final-Fantasy-Dawn-of-Gods
3cea7ff58a173f0ff5678287120b209aa42fa7f8
b5dcdd0aa548900b3b2279cd4c6d4220f5869c08
refs/heads/master
2022-02-21T22:57:56.423810
2019-07-11T12:04:46
2019-07-11T12:04:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,523
cpp
#include "Emmiter.h" #include "j1EntityFactory.h" #include "j1Render.h" Emmiter::Emmiter(fPoint pos, const j1Entity * owner) :Projectile(pos, { 0.F,0.F }, 0u, owner, "EmmiterArrows", PROJECTILE_TYPE::EMMITER) { SetPivot(150, 112); size.create(300, 225); position -= pivot; engine.seed(rd()); lifeTimer.Start(); createArrowsTimer.Start(); dieTimer.Start(); //currentAnimation = &anim; rang.x = 100; rang.y = 40; lifeTime = 4u; createArrowsSpeed = 75u; dieTime = 6u; constantHeigth = App->render->camera->h; /*App->audio->PlayFx(App->entityFactory->strech_Shoot, 0);*/ } Emmiter::~Emmiter() { } bool Emmiter::PreUpdate() { if (lifeTimer.ReadSec() > lifeTime) { to_explode = true; } return true; } bool Emmiter::Update(float dt) { if (!to_explode) { if (createArrowsTimer.Read() > createArrowsSpeed) { CreateArrow(); createArrowsTimer.Start(); } } return true; } bool Emmiter::PostUpdate() { if (to_explode) { if (dieTime < dieTimer.ReadSec()) { to_delete = true; } } return true; } void Emmiter::CreateArrow() { float posY = RandomValue(-rang.y, rang.y); posY += position.y + size.y / 2; float posX = RandomValue(-rang.x, rang.x); posX += position.x + size.x / 2; App->entityFactory->CreateArrow({ posX, posY - 350 }, { posX, posY + 100 }, 200, App->entityFactory->player->GetShara(), PROJECTILE_TYPE::EMMITER_ARROWS, 2); } float Emmiter::RandomValue(int min, int max) { std::uniform_int_distribution<int> range(min, max); return range(rd); }
[ "36155703+GerardClotet@users.noreply.github.com" ]
36155703+GerardClotet@users.noreply.github.com
b89acf71e7dce6bbfa693a4a9d748a18e89f4004
c66a861bca14245583e32875c6cc91dee10b4987
/Berkeley_socket/Berkeley_socket.cpp
07a36785c64a5f9ae43d9d0b87864bc7a962080d
[]
no_license
gustavohfc/Messenger
39005e3915504d77b7ed768d271af4e2fc6d69e6
29977a17f8dd109edd6fbc03f7d2ded7f460dc9a
refs/heads/master
2017-12-29T17:51:56.827523
2016-10-30T02:38:52
2016-10-30T02:38:52
72,234,521
0
0
null
null
null
null
UTF-8
C++
false
false
234
cpp
#include "Berkeley_socket.h" using namespace std; berkeley_socket::berkeley_socket(socket_engine_communication* engine_communication) { this->engine_communication = engine_communication; } berkeley_socket::~berkeley_socket() { }
[ "gustavohfcarvalho@gmail.com" ]
gustavohfcarvalho@gmail.com
303544b4d697297e82acd2040c2f3b0103052b99
dc6013d9d3f486be1a2a9c4dfe7254848232423f
/src/content_source.cc
cee766ab4a2eab4bc17a6c3051d9bf837f50da47
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
kwiberg/frz
d2a5fcfc13b3abc87b4e57124070892a5d73ffdc
8661247c70e89a671b2b412c8c4f4c3f329ef98d
refs/heads/main
2023-05-30T19:58:01.528635
2021-07-07T09:36:17
2021-07-07T09:36:17
341,926,362
0
0
null
null
null
null
UTF-8
C++
false
false
9,286
cc
/* Copyright 2021 Karl Wiberg 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. */ #include "content_source.hh" #include <absl/container/flat_hash_map.h> #include <filesystem> #include <functional> #include <memory> #include <optional> #include "content_store.hh" #include "exceptions.hh" #include "file_stream.hh" #include "hash.hh" #include "hasher.hh" #include "log.hh" #include "stream.hh" namespace frz { namespace { // A content source based on a directory tree of files. Starts out knowing only // the set of files and their file sizes (which can be obtained by a relatively // quick directory traversal), and lazily computes content hashes as necessary. // In particular, since callers ask for content by hash *and size*, this // content source is able to avoid computing hashes for any files that don't // have the requested file size. template <int HashBits> class DirectoryContentSource final : public ContentSource<HashBits> { public: DirectoryContentSource( const std::filesystem::path& dir, bool read_only, Streamer& streamer, std::function<std::unique_ptr<Hasher<256>>()> create_hasher) : dir_(dir), read_only_(read_only), streamer_(streamer), create_hasher_(std::move(create_hasher)) {} std::optional<std::filesystem::path> Fetch( Log& log, const HashAndSize<HashBits>& hs, ContentStore& content_store) override try { ListFiles(log); std::optional<FindFileResult> r = FindFile(log, hs, read_only_ ? &content_store : nullptr); if (!r.has_value()) { // Couldn't find the requested content. return std::nullopt; } else if (r->already_inserted) { // FindFile() inserted the content for us. return r->path; } else { // FindFile() found the content, and we need to insert it. return read_only_ ? content_store.CopyInsert(r->path, streamer_) : content_store.MoveInsert(r->path, streamer_); } } catch (const Error& e) { log.Important("When fetching %s: %s", hs.ToBase32(), e.what()); return std::nullopt; } private: // Traverse the directory tree and populate files_by_size_. void ListFiles(Log& log) { if (files_listed_) { return; } auto progress = log.Progress("Listing files in %s", dir_); auto file_counter = progress.AddCounter("files"); for (const std::filesystem::directory_entry& dent : std::filesystem::recursive_directory_iterator(dir_)) { if (std::filesystem::is_regular_file(dent.symlink_status())) { // A regular file (not a symlink to one). files_by_size_[dent.file_size()].push_back(dent.path()); file_counter.Increment(1); } } files_listed_ = true; } // Locate a file with the given hash+size, and return its path---or // nullopt, if it cannot be found. In the process, move file paths from // `files_by_size_` to `files_by_hash_` as their hashes become known. In // case it's efficient to do so, stream-insert the file to `content_store` // as part of the search. struct FindFileResult { // The path where the requested file can be found. std::filesystem::path path; // Did we insert the file into the content store? bool already_inserted; }; std::optional<FindFileResult> FindFile(Log& log, const HashAndSize<HashBits>& hs, ContentStore* const content_store) { auto hash_it = files_by_hash_.find(hs); if (hash_it != files_by_hash_.end()) { return FindFileResult{.path = hash_it->second, .already_inserted = false}; } auto size_it = files_by_size_.find(hs.GetSize()); if (size_it == files_by_size_.end()) { return std::nullopt; } FRZ_ASSERT(!size_it->second.empty()); auto progress = log.Progress("Hashing files"); auto file_counter = progress.AddCounter("files"); auto byte_counter = progress.AddCounter("bytes", hs.GetSize() * size_it->second.size()); while (!size_it->second.empty()) { std::filesystem::path p = std::move(size_it->second.back()); size_it->second.pop_back(); try { auto source = CreateFileSource(p); SizeHasher hasher(create_hasher_()); std::optional<HashAndSize<256>> p_hs; std::optional<std::filesystem::path> inserted_path; if (content_store == nullptr) { streamer_.Stream(*source, hasher, [&](int num_bytes) { byte_counter.Increment(num_bytes); }); p_hs = hasher.Finish(); } else { inserted_path = content_store->StreamInsert( [&](StreamSink& content_sink) { // Stream the file contents to both the hasher and // the content store. We wait for the secondary // transfer to finish iff the hash was the one we // were looking for. auto kFinish = Streamer::SecondaryStreamDecision::kFinish; auto kAbandon = Streamer::SecondaryStreamDecision::kAbandon; streamer_.ForkedStream( {.source = *source, .primary_sink = hasher, .secondary_sink = content_sink, .primary_done = [&] { p_hs = hasher.Finish(); return p_hs == hs ? kFinish : kAbandon; }, .primary_progress = [&](int num_bytes) { byte_counter.Increment(num_bytes); }, .secondary_progress = [](int /*num_bytes*/) {}}); return p_hs == hs; // keep the inserted content iff // the hash matched }); } FRZ_ASSERT(p_hs.has_value()); auto [it, inserted] = files_by_hash_.insert({*p_hs, std::move(p)}); if (p_hs == hs) { if (size_it->second.empty()) { files_by_size_.erase(size_it); } return FindFileResult{ .path = inserted_path.value_or(it->second), .already_inserted = inserted_path.has_value()}; } } catch (const Error& e) { log.Important("When reading %s: %s", p, e.what()); } file_counter.Increment(1); } FRZ_ASSERT(size_it->second.empty()); files_by_size_.erase(size_it); return std::nullopt; } // Map from content hash+size to the path of a file with that hash+size. absl::flat_hash_map<HashAndSize<HashBits>, std::filesystem::path> files_by_hash_; // Map from file size to vector of paths of files of that size. Only files // not listed in `files_by_hash_` are listed here. Vectors are never empty. absl::flat_hash_map<std::uintmax_t, std::vector<std::filesystem::path>> files_by_size_; // Have we traversed the directory tree and populated files_by_size_? (We // do this the first time we need it rather than in the constructor, in // order to save time if no one ever calls us asking for any content.) bool files_listed_ = false; const std::filesystem::path dir_; const bool read_only_; Streamer& streamer_; const std::function<std::unique_ptr<Hasher<256>>()> create_hasher_; }; } // namespace template <int HashBits> std::unique_ptr<ContentSource<HashBits>> ContentSource<HashBits>::Create( const std::filesystem::path& dir, bool read_only, Streamer& streamer, std::function<std::unique_ptr<Hasher<HashBits>>()> create_hasher) { return std::make_unique<DirectoryContentSource<HashBits>>( dir, read_only, streamer, std::move(create_hasher)); } template class ContentSource<256>; } // namespace frz
[ "k@w5.se" ]
k@w5.se
af791c89388c8b0396f3885324514f6bf11a26b4
249b8ac66022cef45f1e5fd8d594b76ee0cb3ad4
/Working/finalShockTube/0.075/particle/fD
c156f66db1468e2cfe57f35efbfcea4484f66c48
[]
no_license
Anthony-Gay/HPC_workspace
2a3da1d599a562f2820269cc36a997a2b16fcbb8
41ef65d7ed3977418f360a52c2d8ae681e1b3971
refs/heads/master
2021-07-13T17:36:50.352775
2021-02-08T05:59:49
2021-02-08T05:59:49
232,433,074
0
1
null
null
null
null
UTF-8
C++
false
false
964
/*--------------------------------*- C++ -*----------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Version: 7 \\/ M anipulation | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volVectorField; location "0.075/particle"; object fD; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [1 -1 -2 0 0 0 0]; internalField uniform (0 0 0); boundaryField { partSide { type symmetry; } partBound { type zeroGradient; } nullDims { type empty; } } // ************************************************************************* //
[ "anthonygay1812@yahoo.com" ]
anthonygay1812@yahoo.com
a1fa9c272fb78ae4cd308bcad273c024ee6b6e05
4fd512ca271222db6a230d1b8a42db9f21e53e0a
/CodeGenerator/Game/CodeCondition.cpp
2104227a697fb52226083eeddae0b17ccf397063
[]
no_license
li5414/GameEditor
2ca2305c2e56842af8389ca2e1923719cf272f7d
c8d2f463c334560f698016ddd985689278615f97
refs/heads/master
2022-07-05T09:29:36.389703
2022-05-26T15:21:39
2022-05-26T15:21:39
230,262,151
1
0
null
2019-12-26T12:40:52
2019-12-26T12:40:51
null
GB18030
C++
false
false
10,540
cpp
#include "CodeCondition.h" void CodeCondition::generate() { string cppHeaderPath = cppGamePath + "ConditionManager/"; string cppConditionFilePath = cppHeaderPath + "Condition/"; string cppConditionEnumPath = cppGamePath + "Common/"; string csRegisterPath = csHotfixGamePath + "ConditionManager/"; string csConditionFilePath = csRegisterPath + "Condition/"; string csConditionEnumPath = csHotfixGamePath + "Common/"; string conditionFile; openTxtFile("Condition.txt", conditionFile); if (conditionFile.length() == 0) { ERROR("未找文件Condition.txt"); return; } myVector<string> conditionLineList; split(conditionFile.c_str(), "\r\n", conditionLineList); myVector<pair<string, string>> conditionList; FOR_VECTOR(conditionLineList) { myVector<string> splitResult; split(conditionLineList[i].c_str(), "\t", splitResult); if (splitResult.size() != 2) { ERROR("条件文件解析错误:" + conditionLineList[i]); } conditionList.push_back(make_pair(splitResult[0], splitResult[1])); } END(conditionLineList); if (cppGamePath.length() > 0) { // c++ // 生成ConditionHeader.h文件 generateCppHeaderFile(conditionList, cppHeaderPath); // 生成ConditionRegister.h文件 generateCppRegisterFile(conditionList, cppHeaderPath); // 生成CONDITION枚举 generateCppConditionEnum(conditionList, cppConditionEnumPath); FOR_VECTOR(conditionList) { generateCppConditionFile(conditionList[i].first, cppConditionFilePath); } END(conditionList); } if (csHotfixGamePath.length() > 0) { // cs // 生成ConditionRegister.cs文件 generateCSRegisterFile(conditionList, csRegisterPath); // 生成CONDITION枚举 generateCSConditionEnum(conditionList, csConditionEnumPath); FOR_VECTOR(conditionList) { generateCSConditionFile(conditionList[i].first, csConditionFilePath); } END(conditionList); } } // ConditionHeader.h文件 void CodeCondition::generateCppHeaderFile(const myVector<pair<string, string>>& conditionList, const string& headerPath) { string str0; line(str0, "#ifndef _CONDITION_HEADER_H_"); line(str0, "#define _CONDITION_HEADER_H_"); line(str0, ""); uint count = conditionList.size(); FOR_I(count) { line(str0, "#include \"" + conditionList[i].first + ".h\""); } line(str0, ""); line(str0, "#endif", false); writeFile(headerPath + "ConditionHeader.h", ANSIToUTF8(str0.c_str(), true)); } // ConditionRegister.h文件 void CodeCondition::generateCppRegisterFile(const myVector<pair<string, string>>& conditionList, const string& filePath) { string str0; line(str0, "#include \"GameHeader.h\""); line(str0, ""); line(str0, "#define CONDITION_FACTORY(classType, type) mConditionFactoryManager->addFactory<classType>(type);"); line(str0, ""); line(str0, "void ConditionRegister::registeAll()"); line(str0, "{"); uint count = conditionList.size(); FOR_I(count) { const string& conditionName = conditionList[i].first; string conditionEnum = nameToUpper(conditionName.substr(strlen("Condition")), false); line(str0, "\tCONDITION_FACTORY(" + conditionName + ", CONDITION::" + conditionEnum + ");"); } line(str0, "}", false); writeFile(filePath + "ConditionRegister.cpp", ANSIToUTF8(str0.c_str(), true)); } // CONDITION枚举 void CodeCondition::generateCppConditionEnum(const myVector<pair<string, string>>& conditionList, const string& filePath) { myVector<string> preContent; myVector<string> endContent; findCppPreAndEndContent(filePath + "GameEnum.h", preContent, endContent); string str0; FOR_VECTOR(preContent) { line(str0, preContent[i]); } END(preContent); line(str0, "\tNONE,"); FOR_VECTOR_CONST(conditionList) { string conditionEnum = nameToUpper(conditionList[i].first.substr(strlen("Condition")), false); string lineStr = "\t" + conditionEnum + ","; uint needTableCount = generateAlignTableCount(lineStr, 24); FOR_J(needTableCount) { lineStr += "\t"; } lineStr += conditionList[i].second; line(str0, lineStr); } line(str0, "\tMAX,"); FOR_VECTOR(endContent) { line(str0, endContent[i], i != endContent.size() - 1); } END(endContent); writeFile(filePath + "GameEnum.h", ANSIToUTF8(str0.c_str(), true)); } // Condition.h和Condition.cpp void CodeCondition::generateCppConditionFile(const string& conditionName, const string& conditionPath) { string headerFullPath = conditionPath + conditionName + ".h"; if (!isFileExist(headerFullPath)) { string header; string marcoName = nameToUpper(conditionName) + "_H_"; string typeStr = nameToUpper(conditionName.substr(strlen("Condition")), false); line(header, "#ifndef " + marcoName); line(header, "#define " + marcoName); line(header, ""); line(header, "#include \"Condition.h\""); line(header, ""); line(header, "class " + conditionName + " : public Condition"); line(header, "{"); line(header, "\tBASE_CLASS(Condition);"); line(header, "public:"); line(header, "\t" + conditionName + "()"); line(header, "\t{"); line(header, "\t}"); line(header, "\tvoid setCharacter(CharacterGame* character) override;"); line(header, "\tvoid resetProperty() override"); line(header, "\t{"); line(header, "\t\tbase::resetProperty();"); line(header, "\t}"); line(header, "\tvoid setParam0(const string& param) override"); line(header, "\t{"); line(header, "\t}"); line(header, "protected:"); line(header, "};"); line(header, ""); line(header, "#endif", false); writeFile(headerFullPath, ANSIToUTF8(header.c_str(), true)); } string sourceFullPath = conditionPath + conditionName + ".cpp"; if (!isFileExist(sourceFullPath)) { string source; line(source, "#include \"GameHeader.h\""); line(source, ""); line(source, "void " + conditionName + "::setCharacter(CharacterGame* character)"); line(source, "{"); line(source, "\tbase::setCharacter(character);"); line(source, "}"); writeFile(sourceFullPath, ANSIToUTF8(source.c_str(), true)); } } void CodeCondition::generateCSRegisterFile(const myVector<pair<string, string>>& conditionList, const string& filePath) { string str0; line(str0, "using UnityEngine;"); line(str0, "using System;"); line(str0, "using System.Collections.Generic;"); line(str0, ""); line(str0, "public class ConditionRegister : GB"); line(str0, "{"); line(str0, "\tpublic static void registeAll()"); line(str0, "\t{"); uint count = conditionList.size(); FOR_I(count) { const string& conditionName = conditionList[i].first; string conditionEnum = nameToUpper(conditionName.substr(strlen("Condition")), false); line(str0, "\t\tregiste<" + conditionName + ">(CONDITION." + conditionEnum + ");"); } line(str0, ""); line(str0, "\t\tmConditionManager.checkConditionTypeCount((int)CONDITION.MAX - 1);"); line(str0, "\t}"); line(str0, "\t//--------------------------------------------------------------------------------------------------------------------------"); line(str0, "\tprotected static void registe<T>(CONDITION type) where T : Condition"); line(str0, "\t{"); line(str0, "\t\tmConditionManager.registe(typeof(T), type);"); line(str0, "\t}"); line(str0, "}", false); writeFile(filePath + "ConditionRegister.cs", ANSIToUTF8(str0.c_str(), true)); } void CodeCondition::generateCSConditionEnum(const myVector<pair<string, string>>& conditionList, const string& filePath) { myVector<string> preContent; myVector<string> endContent; findCSPreAndEndContent(filePath + "GameEnum.cs", preContent, endContent); string str0; FOR_VECTOR(preContent) { line(str0, preContent[i]); } END(preContent); line(str0, "\tNONE,"); FOR_VECTOR_CONST(conditionList) { string conditionEnum = nameToUpper(conditionList[i].first.substr(strlen("Condition")), false); string lineStr = "\t" + conditionEnum + ","; uint needTableCount = generateAlignTableCount(lineStr, 24); FOR_J(needTableCount) { lineStr += "\t"; } lineStr += conditionList[i].second; line(str0, lineStr); } line(str0, "\tMAX,"); FOR_VECTOR(endContent) { line(str0, endContent[i], i != endContent.size() - 1); } END(endContent); writeFile(filePath + "GameEnum.cs", ANSIToUTF8(str0.c_str(), true)); } void CodeCondition::generateCSConditionFile(const string& conditionName, const string& conditionPath) { string csFullPath = conditionPath + conditionName + ".cs"; if (!isFileExist(csFullPath)) { string str; line(str, "using UnityEngine;"); line(str, "using System;"); line(str, "using System.Collections.Generic;"); line(str, ""); line(str, "public class " + conditionName + " : Condition"); line(str, "{"); line(str, "\tpublic override void init(TDConditionDetail data, CharacterGame character)"); line(str, "\t{"); line(str, "\t\tbase.init(data, character);"); line(str, "\t}"); line(str, "\tpublic override void resetProperty()"); line(str, "\t{"); line(str, "\t\tbase.resetProperty();"); line(str, "\t}"); line(str, "\tpublic override void setParam0(string param) {}"); line(str, "\tpublic override void setValue(int value){}"); line(str, "}", false); writeFile(csFullPath, ANSIToUTF8(str.c_str(), true)); } } void CodeCondition::findCppPreAndEndContent(const string& fullPath, myVector<string>& preContent, myVector<string>& endContent) { // 0表示正在查找前段部分的代码 // 1表示正在查找条件枚举的代码 // 2表示正在查找后段部分的代码 int state = 0; myVector<string> allLines; openTxtFileLines(fullPath, allLines); FOR_VECTOR(allLines) { if (state == 0) { preContent.push_back(allLines[i]); } else if (state == 2) { endContent.push_back(allLines[i]); } if (i > 0 && allLines[i - 1] == "enum class CONDITION : byte") { state = 1; continue; } if (state == 1 && i + 1 < allLines.size() && allLines[i + 1] == "};") { state = 2; continue; } } END(allLines); } void CodeCondition::findCSPreAndEndContent(const string& fullPath, myVector<string>& preContent, myVector<string>& endContent) { // 0表示正在查找前段部分的代码 // 1表示正在查找条件枚举的代码 // 2表示正在查找后段部分的代码 int state = 0; myVector<string> allLines; openTxtFileLines(fullPath, allLines); FOR_VECTOR(allLines) { if (state == 0) { preContent.push_back(allLines[i]); } else if (state == 2) { endContent.push_back(allLines[i]); } if (i > 0 && allLines[i - 1] == "public enum CONDITION : byte") { state = 1; continue; } if (state == 1 && i + 1 < allLines.size() && allLines[i + 1] == "};") { state = 2; continue; } } END(allLines); }
[ "785130190@qq.com" ]
785130190@qq.com
46c4fd7e878fc97a1efa5bb98de07543a46058dd
e6642884e2baceb47ee8a4e4b338d622e21680fe
/程序设计与算法/《计算导论与C语言基础》/week6/大象喝水.cpp
057803ba11d8d33240443bd12df94bf9ef480d5c
[]
no_license
mulongfu/Coursera
9eb8a8724110ace588b7814e05b7fe5b0adecbbd
9ada6c94b0e788514fe722db4223338033bbd8e8
refs/heads/master
2021-10-19T06:16:08.149075
2019-02-18T13:44:22
2019-02-18T13:44:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
268
cpp
#include <iostream> #define PI 3.14159 using namespace std; int main() { int h, r, count = 0; double bucket, need = 20000; cin >> h >> r; bucket = PI * r * r * h; while (need - bucket > 0) { need -= bucket; count++; } count++; cout << count; return 0; }
[ "k134563@gmail.com" ]
k134563@gmail.com
dbac83032267879838d0bdfb3c906ee39e561783
70d681bcdc41f6838d0f1d8defa3571528cf56eb
/18.Delete Duplicated Node in List.cpp
279b0e2d46df641cf2fd9ed7d1b657d4bbeb4746
[]
no_license
VoidShooter/CodingInterview
21abfdfd1062a371c926181c3798b2e2e4fa7aff
7d40cdbbe02ac08198d02f79522315ef3a1fa701
refs/heads/master
2020-04-24T15:55:22.692433
2020-01-12T14:30:50
2020-01-12T14:30:50
172,087,890
0
0
null
null
null
null
UTF-8
C++
false
false
1,116
cpp
#include <iostream> using namespace std; struct ListNode { int val; struct ListNode *next; explicit ListNode(int x) : val(x), next(NULL) { } }; class Solution { public: ListNode* deleteDuplication(ListNode* pHead) { if(pHead==nullptr) return nullptr; if(pHead->next== nullptr) return pHead; ListNode* current; if(pHead->next->val == pHead->val){ current = pHead->next->next; while(current!= nullptr && current->val == pHead->val) current = current->next; return deleteDuplication(current); }else{ current = pHead->next; pHead->next = deleteDuplication(current); return pHead; } } }; int main() { ListNode n1(1), n2(2), n3(3), n4(3), n5(4), n6(4), n7(5); n1.next = &n2; n2.next = &n3; n3.next = &n4; n4.next = &n5; n5.next = &n6; n6.next = &n7; ListNode* pNode = Solution().deleteDuplication(&n1); while(pNode!= nullptr){ cout<<pNode->val<<endl; pNode = pNode->next; } return 0; }
[ "noreply@github.com" ]
noreply@github.com
3a4bbf1649120dd6fe3a284e5956050492d6494d
2752a042a4839d93976aae46d8a37bf550323083
/NeoEfx_BasicAlt201.ino
6d4f5a487ae73970f1b63a3cbc8bb96f8ad85e5d
[]
no_license
dkonha01/NeoPixelAlexaDemo
e74e82d243d633bffb9deff1ad2012b33b6e4b03
da9afbb2b0fcebec322deea9ed10448a88dba3e9
refs/heads/master
2020-04-13T13:50:34.086469
2018-12-27T03:40:35
2018-12-27T03:40:35
163,243,718
0
0
null
null
null
null
UTF-8
C++
false
false
2,391
ino
#include <NeoEffects.h> #include <NeoStrip.h> #include <NeoWindow.h> #include <Adafruit_NeoPixel.h> #define SMALL_NEORING_SIZE 16 #define STRIP_PIN 6 const int RING_1_START = 0; const int RING_2_START = 0; const int RING_3_START = 0; const int RING_4_START = 0; const int RING_5_START = 0; const int RING_6_START = 0; const int numRings = 6; NeoStrip strip1 = NeoStrip(SMALL_NEORING_SIZE * numRings, STRIP_PIN, NEO_GRB + NEO_KHZ800); NeoWindow ring1 = NeoWindow(&strip1, RING_1_START, SMALL_NEORING_SIZE); NeoWindow ring2 = NeoWindow(&strip1, RING_2_START, SMALL_NEORING_SIZE); NeoWindow ring3 = NeoWindow(&strip1, RING_3_START, SMALL_NEORING_SIZE); NeoWindow ring4 = NeoWindow(&strip1, RING_4_START, SMALL_NEORING_SIZE); NeoWindow ring5 = NeoWindow(&strip1, RING_4_START, SMALL_NEORING_SIZE); NeoWindow ring6 = NeoWindow(&strip1, RING_4_START, SMALL_NEORING_SIZE); // pin for input int switchPinA = 5; int switchPinB = 9; int switchPinC = 10; int switchPinD = 11; int switchPinE = 12; int switchPinF = 13; const uint32_t aNicePurple = strip1.Color(128, 0, 50); const uint32_t redRed = strip1.Color(128, 0, 0); const uint32_t soBlue = strip1.Color(0, 0, 128); void setup() { // use serial line for debugging output Serial.begin(115200); delay(500); Serial.println("Starting NeoEffects Test"); strip1.begin(); ring1.setCircleEfx(redRed, 117); ring2.setSparkleEfx(aNicePurple, 7, 47, 77); ring3.setBlinkEfx(soBlue, 250, 10); ring4.setRainbowEfx( 3, 7 ); ring5.setWipeEfx(redRed,187 ); Serial.println("Setup Done"); } void loop() { // grab the current time using the class method. thus it is only called once, regardless of # windows NeoWindow::updateTime(); if( digitalRead(switchPinA) == true ) { ring5.updateWindow(); ring1.updateWindow(); } else if( digitalRead(switchPinB) == true ) { ring2.updateWindow(); } else if( digitalRead(switchPinC) == true ) { ring3.updateWindow(); } else if( digitalRead(switchPinD) == true ) { ring4.updateWindow(); } else if(digitalRead(switchPinE) == true ) { ring5.updateWindow(); } else if( digitalRead(switchPinF) == true ) { ring6.updateWindow(); } else strip1.fillStrip(Adafruit_NeoPixel::Color(0,0,0)); //delay(10) // if the strip changed, send commands out to it. strip1.show(); }
[ "dkonhauser@gmail.com" ]
dkonhauser@gmail.com
36979916c5b003085575c84687696df27ecdee1d
d7c94f4a713aaf0fbb3dbb9b56c9f6945e0479c1
/URI Online Judge/uri1379.cpp
e45f471d920f10faefb154cf6d3d5558241bc507
[]
no_license
fonte-nele/Competitive-Programming
2dabb4aab6ce2e6dc552885464fefdd485f9218c
faf0c6077ae0115f121968f7b70f4d68f9ce922b
refs/heads/master
2021-06-28T09:24:07.708562
2020-12-27T14:45:15
2020-12-27T14:45:15
193,268,717
3
0
null
null
null
null
UTF-8
C++
false
false
313
cpp
#include <bits/stdc++.h> int min (int x, int y) { return x < y ? x : y; } int max (int x, int y) { return x > y ? x : y; } int main () { int x, y; while (1) { scanf("%d%d", &x, &y); if (x == 0 and y == 0) break; printf("%d\n", 2*min(x,y)-max(x,y)); } return 0; }
[ "felipephontinelly@hotmail.com" ]
felipephontinelly@hotmail.com
e1d0d33681a28d6d6f092429a1e31915a6b473fe
7a3acc9c0e43cceef6294c6e898a515b13c0903e
/include/operon/interpreter/dispatch_table.hpp
681f1b92c52dbae1d9534c2d4d5184734bbaf8b5
[ "MIT" ]
permissive
chensh236/operon
55b58d7dcf89d599de61189c43a044caa6cfcee9
24c3714c4356cc8c4f6341d26dea5fab7769c347
refs/heads/master
2023-07-28T10:27:59.073206
2021-09-14T16:52:48
2021-09-14T16:52:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,838
hpp
// SPDX-License-Identifier: MIT // SPDX-FileCopyrightText: Copyright 2019-2021 Heal Research #ifndef OPERON_EVAL_DETAIL #define OPERON_EVAL_DETAIL #include "core/node.hpp" #include "core/types.hpp" #include "interpreter/functions.hpp" #include "robin_hood.h" #include <Eigen/Dense> #include <fmt/core.h> #include <tuple> namespace Operon { namespace detail { // this should be good enough - tests show 512 is about optimal template<typename T> struct batch_size { static const size_t value = 512 / sizeof(T); }; template<typename T> using eigen_t = typename Eigen::Array<T, batch_size<T>::value, Eigen::Dynamic, Eigen::ColMajor>; template<typename T> using eigen_ref = Eigen::Ref<eigen_t<T>, Eigen::Unaligned, Eigen::Stride<batch_size<T>::value, 1>>; // dispatching mechanism // compared to the simple/naive way of evaluating n-ary symbols, this method has the following advantages: // 1) improved performance: the naive method accumulates into the result for each argument, leading to unnecessary assignments // 2) minimizing the number of intermediate steps which might improve floating point accuracy of some operations // if arity > 4, one accumulation is performed every 4 args template<NodeType Type, typename T> inline void dispatch_op_nary(eigen_t<T>& m, Operon::Vector<Node> const& nodes, size_t parentIndex, size_t /* row number - not used */) { static_assert(Type < NodeType::Aq); auto result = m.col(parentIndex); const auto f = [](bool cont, decltype(result) res, auto&&... args) { if (cont) { ContinuedFunction<Type>{}(res, std::forward<decltype(args)>(args)...); } else { Function<Type>{}(res, std::forward<decltype(args)>(args)...); } }; const auto nextArg = [&](size_t i) { return i - (nodes[i].Length + 1); }; auto arg1 = parentIndex - 1; bool continued = false; int arity = nodes[parentIndex].Arity; while (arity > 0) { switch (arity) { case 1: { f(continued, result, m.col(arg1)); arity = 0; break; } case 2: { auto arg2 = nextArg(arg1); f(continued, result, m.col(arg1), m.col(arg2)); arity = 0; break; } case 3: { auto arg2 = nextArg(arg1), arg3 = nextArg(arg2); f(continued, result, m.col(arg1), m.col(arg2), m.col(arg3)); arity = 0; break; } default: { auto arg2 = nextArg(arg1), arg3 = nextArg(arg2), arg4 = nextArg(arg3); f(continued, result, m.col(arg1), m.col(arg2), m.col(arg3), m.col(arg4)); arity -= 4; arg1 = nextArg(arg4); break; } } continued = true; } } template<NodeType Type, typename T> inline void dispatch_op_unary(eigen_t<T>& m, Operon::Vector<Node> const&, size_t i, size_t /* row number - not used */) { static_assert(Type < NodeType::Constant && Type > NodeType::Pow); Function<Type>{}(m.col(i), m.col(i - 1)); } template<NodeType Type, typename T> inline void dispatch_op_binary(eigen_t<T>& m, Operon::Vector<Node> const& nodes, size_t i, size_t /* row number - not used */) { static_assert(Type < NodeType::Log && Type > NodeType::Div); auto j = i - 1; auto k = j - nodes[j].Length - 1; Function<Type>{}(m.col(i), m.col(j), m.col(k)); } template<NodeType Type, typename T> inline void dispatch_op_simple_unary_or_binary(eigen_t<T>& m, Operon::Vector<Node> const& nodes, size_t parentIndex, size_t /* row number - not used */) { auto r = m.col(parentIndex); size_t i = parentIndex - 1; size_t arity = nodes[parentIndex].Arity; Function<Type> f{}; if (arity == 1) { f(r, m.col(i)); } else { auto j = i - (nodes[i].Length + 1); f(r, m.col(i), m.col(j)); } } template<NodeType Type, typename T> inline void dispatch_op_simple_nary(eigen_t<T>& m, Operon::Vector<Node> const& nodes, size_t parentIndex, size_t /* row number - not used */) { auto r = m.col(parentIndex); size_t arity = nodes[parentIndex].Arity; auto i = parentIndex - 1; Function<Type> f{}; if (arity == 1) { f(r, m.col(i)); } else { r = m.col(i); for (size_t k = 1; k < arity; ++k) { i -= nodes[i].Length + 1; f(r, m.col(i)); } } } struct noop { template<typename... Args> void operator()(Args&&...) {} }; template<typename X, typename Tuple> class tuple_index; template<typename X, typename... T> class tuple_index<X, std::tuple<T...>> { template<std::size_t... idx> static constexpr ssize_t find_idx(std::index_sequence<idx...>) { return -1 + ((std::is_same<X, T>::value ? idx + 1 : 0) + ...); } public: static constexpr ssize_t value = find_idx(std::index_sequence_for<T...>{}); }; template<typename T> using Callable = typename std::function<void(detail::eigen_t<T>&, Operon::Vector<Node> const&, size_t, size_t)>; template<NodeType Type, typename T> static constexpr Callable<T> MakeCall() { if constexpr (Type < NodeType::Aq) { // nary: add, sub, mul, div return Callable<T>(detail::dispatch_op_nary<Type, T>); } else if constexpr (Type < NodeType::Log) { // binary: aq, pow return Callable<T>(detail::dispatch_op_binary<Type, T>); } else if constexpr (Type < NodeType::Constant) { // unary: exp, log, sin, cos, tan, tanh, sqrt, cbrt, square, dynamic return Callable<T>(detail::dispatch_op_unary<Type, T>); } } template<NodeType Type, typename... Ts, std::enable_if_t<sizeof...(Ts) != 0, bool> = true> static constexpr auto MakeTuple() { return std::tuple(MakeCall<Type, Ts>()...); }; template<typename F, typename... Ts, std::enable_if_t<sizeof...(Ts) != 0 && (std::is_invocable_r_v<void, F, detail::eigen_t<Ts>&, Vector<Node> const&, size_t, size_t> && ...), bool> = true> static constexpr auto MakeTuple(F&& f) { return std::tuple(Callable<Ts>(std::forward<F&&>(f))...); } template<typename F, typename... Ts, std::enable_if_t<sizeof...(Ts) != 0 && (std::is_invocable_r_v<void, F, detail::eigen_t<Ts>&, Vector<Node> const&, size_t, size_t> && ...), bool> = true> static constexpr auto MakeTuple(F const& f) { return std::tuple(Callable<Ts>(f)...); } template<NodeType Type> static constexpr auto MakeDefaultTuple() { return MakeTuple<Type, Operon::Scalar, Operon::Dual>(); } template<typename F, std::enable_if_t< std::is_invocable_r_v< void, F, detail::eigen_t<Operon::Scalar>&, Operon::Vector<Node> const&, size_t, size_t > && std::is_invocable_r_v< void, F, detail::eigen_t<Operon::Dual>&, Operon::Vector<Node> const&, size_t, size_t >, bool> = true> static constexpr auto MakeDefaultTuple(F&& f) { return MakeTuple<F, Operon::Scalar, Operon::Dual>(std::forward<F&&>(f)); } } // namespace detail struct DispatchTable { template<typename T> using Callable = detail::Callable<T>; using Tuple = std::tuple<Callable<Operon::Scalar>, Callable<Operon::Dual>>; using Map = robin_hood::unordered_flat_map<Operon::Hash, Tuple>; using Pair = robin_hood::pair<Operon::Hash, Tuple>; DispatchTable() { InitializeMap(); } DispatchTable(DispatchTable const& other) : map(other.map) { } DispatchTable(DispatchTable &&other) : map(std::move(other.map)) { } void InitializeMap() { const auto hash = [](auto t) { return Node(t).HashValue; }; map = Map{ { hash(NodeType::Add), detail::MakeDefaultTuple<NodeType::Add>() }, { hash(NodeType::Sub), detail::MakeDefaultTuple<NodeType::Sub>() }, { hash(NodeType::Mul), detail::MakeDefaultTuple<NodeType::Mul>() }, { hash(NodeType::Sub), detail::MakeDefaultTuple<NodeType::Sub>() }, { hash(NodeType::Div), detail::MakeDefaultTuple<NodeType::Div>() }, { hash(NodeType::Aq), detail::MakeDefaultTuple<NodeType::Aq>() }, { hash(NodeType::Pow), detail::MakeDefaultTuple<NodeType::Pow>() }, { hash(NodeType::Log), detail::MakeDefaultTuple<NodeType::Log>() }, { hash(NodeType::Exp), detail::MakeDefaultTuple<NodeType::Exp>() }, { hash(NodeType::Sin), detail::MakeDefaultTuple<NodeType::Sin>() }, { hash(NodeType::Cos), detail::MakeDefaultTuple<NodeType::Cos>() }, { hash(NodeType::Tan), detail::MakeDefaultTuple<NodeType::Tan>() }, { hash(NodeType::Tanh), detail::MakeDefaultTuple<NodeType::Tanh>() }, { hash(NodeType::Sqrt), detail::MakeDefaultTuple<NodeType::Sqrt>() }, { hash(NodeType::Cbrt), detail::MakeDefaultTuple<NodeType::Cbrt>() }, { hash(NodeType::Square), detail::MakeDefaultTuple<NodeType::Square>() }, /* constants and variables not needed here */ }; }; template<typename T> inline Callable<T>& Get(Operon::Hash const h) { constexpr ssize_t idx = detail::tuple_index<Callable<T>, Tuple>::value; static_assert(idx >= 0, "Tuple does not contain type T"); if (auto it = map.find(h); it != map.end()) { return std::get<static_cast<size_t>(idx)>(it->second); } throw std::runtime_error(fmt::format("Hash value {} is not in the map\n", h)); } template<typename T> inline Callable<T> const& Get(Operon::Hash const h) const { constexpr ssize_t idx = detail::tuple_index<Callable<T>, Tuple>::value; static_assert(idx >= 0, "Tuple does not contain type T"); if (auto it = map.find(h); it != map.end()) { return std::get<static_cast<size_t>(idx)>(it->second); } throw std::runtime_error(fmt::format("Hash value {} is not in the map\n", h)); } template<typename F, std::enable_if_t<std::is_invocable_r_v<void, F, detail::eigen_t<Operon::Dual>&, Vector<Node> const&, size_t, size_t>, bool> = true> void RegisterCallable(Operon::Hash hash, F const& f) { map[hash] = detail::MakeTuple<F, Operon::Scalar, Operon::Dual>(f); } private: Map map; }; } // namespace Operon #endif
[ "bogdan.burlacu@pm.me" ]
bogdan.burlacu@pm.me
35ba7817229f9a235d0fefef66b0437167b938e7
675861e17bd0a61639bc72641ed802c2253ef857
/src/DetectionEngine/big_data_ac_test/levelAc.cpp
0ef0c1fe86ae489ec838cf9561ae92684cc4c5a3
[]
no_license
cjqhenry14/Real-Time-Network-Data-Analysis-System
dd9d80042034c1ba09ae4efd13a6f2c245b7dc71
9fe61b63f7c630c43159bb320f230ab57186c754
refs/heads/master
2020-05-18T02:02:17.979482
2015-04-15T00:23:00
2015-04-15T00:23:00
30,944,369
1
0
null
null
null
null
UTF-8
C++
false
false
21,983
cpp
/*** level arr->avl g++ -o levelAc.o levelAc.cpp ***/ #include <stdio.h> #include <malloc.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <unistd.h> /*#define keyFile "bigkey.txt" #define stringFile "string.txt" #define LineMax 6 #define queMax 30//½ÚµãÊý #define keyNum 5*/ #define keyFile "bigKey.txt" #define stringFile "bigString.txt" #define LineMax 20 #define queMax 400005//1799536 43533 #define keyNum 20000//20000 40000 60000 80000 100000 #define arrQueMax 60000 #define charSize 256 #define avlStartLevel 2 //<avlStartLevel ֮ǰ¶ŒÊÇarray²ã //======================== struct ACVL { struct ACVL *avlFail; struct arrnode *avlToArrFail; //avl->arrayµÄʧ°ÜÖžÕë struct ACVL *avlRoot; int count; int level;//²ãºÅ,0¿ªÊŒ int data; int bf; struct ACVL *lchild; struct ACVL *rchild; }; typedef struct ACVL ACNODE,*BST; BST buildAvl(int index,BST T,BST newnode); BST stepAvlNext(BST T,int index); int queryAvlExist(BST T,int index); int input; BST R = NULL; //================= struct arrnode { struct arrnode *fail; //ʧ°ÜÖžÕë struct arrnode *next[charSize];//Ò»žöœÚµãÓµÓеÄ×Ӝڵã struct ACVL *arrToAvlNext[charSize];//ÖžÏò¶ù×ÓÊÇavlÊ÷œá¹¹ int count; //ÊÇ·ñΪžÃµ¥ŽÊ×îºóÒ»žöµã£»1±íÊŸÊÇ×îºóÒ»žöµã£¬0±íÊŸ³õÊŒ»¯£¬£­1±íÊŸÒÑŸ­Í³ŒÆ¹ý int level;//²ãºÅ,0¿ªÊŒ }; typedef struct arrnode arrNode; arrNode *keyque[arrQueMax];//¹ØŒüŽÊÿÐÐ50žöŽÊ£¬¹²10000ÐÐ ACNODE *avlKeyQue[queMax];//avl que int *keyword;//¹ØŒüŽÊ int head,tail;//¶ÓÁеÄÍ·¡¢Î²ÖžÕë //--------------------- ACNODE *avlStartTemp,*avltemp; arrNode *arrtemp; void printEach(arrNode *nn); //-------------------- /*²åÈëœÚµãµœ×ÖµäÊ÷ÖÐ*/ void insert(int * str,arrNode *root,int num) { arrNode *arrtemp = root; int i = 0, index,j; for(i=0; i<num; i++) { //printf("%c\n",str[i]);//eeceb deace index = str[i]; if(i<avlStartLevel)//֮ǰ¶ŒÊÇarray²ã { if (arrtemp->next[index] == NULL)/*Èç¹û²»ŽæÔÚÄÇžöœÚµã£¬Ê×ÏÈµÃŽŽœšœÚµã*/ { arrNode *newArrNode = (arrNode *)malloc(sizeof(arrNode)); for (j = 0; j < charSize; j++) { newArrNode->next[j] = NULL; newArrNode->arrToAvlNext[j]=NULL; } newArrNode->count = 0; newArrNode->level=i;//²ãºÅž³Öµ arrtemp->next[index] = newArrNode; } arrtemp = arrtemp->next[index]; } //------------------------------------------ else if(i==avlStartLevel)//ŒÇÂŒavl²ã¿ªÍ·µÚÒ»žö { if (arrtemp->arrToAvlNext[index] == NULL)//ÏÖÔÚŽŠÓÚ¹ý¶Èœ×¶Î { ACNODE * newAvlNode = (ACNODE *)malloc(sizeof(ACNODE)); newAvlNode->lchild=NULL; newAvlNode->rchild=NULL; newAvlNode->avlFail=NULL; newAvlNode->avlToArrFail=NULL; newAvlNode->bf=0; newAvlNode->data=index; newAvlNode->count = 0; newAvlNode->level = i; newAvlNode->avlRoot=NULL; arrtemp->arrToAvlNext[index] = newAvlNode; } avltemp=arrtemp->arrToAvlNext[index];//Ï൱ÓÚp=stepAvlNext(p->avlRoot,index); }//end if i==avlStartLevel else { if (queryAvlExist(avltemp->avlRoot,index)==0)//avlœ×¶Î { ACNODE * newAvlNode2 = (ACNODE *)malloc(sizeof(ACNODE)); newAvlNode2->lchild=NULL; newAvlNode2->rchild=NULL; newAvlNode2->avlFail=NULL; newAvlNode2->avlToArrFail=NULL; newAvlNode2->bf=0; newAvlNode2->data=index; newAvlNode2->count = 0; newAvlNode2->level = i; newAvlNode2->avlRoot=NULL; avltemp->avlRoot= buildAvl(index,avltemp->avlRoot,newAvlNode2); } // printf("\n ==== %c",i,str[i]); avltemp=stepAvlNext(avltemp->avlRoot,index); } }//end for avltemp->count = 1;//IMPORTANT!!±íÊŸŽËœÚµãΪ×îºóÒ»žöŽÊ,ÊÇavlÀàÐ͵ÄÖžÕë,ÒòΪ²ãÊý×îºóÊÇavl,±ä³€ºÍlistÐèÒªÁíÍ⿌ÂÇ } /*ʧ°ÜÖžÕëµÄœšÁ¢*/ void build_fail(arrNode *root) { int i,m; root->fail = NULL;/*ÈÃrootµÄʧ°ÜÖžÕëÖžÏòNULL£¬×÷ΪһÖÖÌõŒþÅжÏ*/ keyque[head++] = root;//++ Ö®ºóhead=1 while (head != tail)/*µ±±éÀúÍêËùÓеĜڵãºó£¬head==tail*/ { if(keyque[tail]->level==(avlStartLevel-1)) break;//Èç¹ûÓöµœ¹ý¶È²ã-1.ÔòÌø³ö arrNode *temp = keyque[tail++];/*Ê×ÏÈÈÃÖžÕëÖžÏòroot£¬keyqueµÄ×÷ÓÃÏ൱ÓÚ¹ã¶ÈËÑË÷ÀïÃæŒÇÂŒ¶ù×ӵĶÓÁÐ*/ arrNode *p = NULL; for (i=0; i < charSize; i++)//±éÀúÒ»žöœÚµãµÄ¶ù×Ó { if (temp->next[i] != NULL)/*ÕÒµœŽæÔڵĜڵ㣬ÓõÄÊDZéÀúµÄ·œ·š*/ { if (temp == root) { temp->next[i]->fail = root;/*rootËùÓÐÏÂÒ»Œ¶œÚµãµÄʧ°ÜÖžÕëÈ«²¿ÖžÏòroot*/ } else { p = temp->fail;/*ÕÒµœÊ§ÅäµãžžœÚµãµÄʧ°ÜÖžÕë,ÆäžžœÚµãµÄ×Ö·ûÓëžÃʧ°ÜÖžÕëÖžÏò×Ö·ûÏàµÈ*/ while (p != NULL) { if (p->next[i] != NULL)/*Èç¹ûp->next[i]ÓМڵ㣬ÔÚp->next[i]ŸÍÊÇtemp->next[i]ʧ°ÜÖžÕëλÖÃ*/ { temp->next[i]->fail = p->next[i]; break; } p = p->fail;/*Èç¹ûÉÏÒ»žöif²»³ÉÁ¢£¬ÔòŒÌÐøÏòÉϲéÕÒ*/ } if (p == NULL) { temp->next[i]->fail = root;/*Èç¹ûûÓÐÕÒµœ£¬ÄÇÃŽœ«Ê§°ÜÖžÕëÖžÏòroot*/ } }//end else keyque[head++] = temp->next[i];//Óжù×Ó,ŸÍhead++,Žæ·Å¶ù×Ӝڵ㣬ÒÔ±ž¹ã¶ÈËÑË÷Ìø×ª } }// end for }//end while1 for array ÏÖÔÚnum=2²ãµÄfail¶ŒÒÑŸ­œšºÃ //-------------µÚÈý²ã¿ªÊŒ-------------------------- //µÚÈý²ãÍøÉÏÕÒžžÇ×µÄʱºòÖ»ÄÜÊÇarrayÀàÐÍ¡£ arrNode *arrToAvlp = NULL; int avlHead=0, avlTail=0; for(m=tail; m<head; m++) //µ¥¶ÀœšµÚÈý²ãµÄʧ°ÜÖžÕ룬œ«µÚËIJã¶ù×ÓŽæÈëavlKeyQue[]; { for (i=0; i < charSize; i++)//±éÀúÒ»žöœÚµãµÄ¶ù×Ó { if (keyque[m]->arrToAvlNext[i] != NULL)/*ÕÒµœŽæÔڵĜڵ㣬ÓõÄÊDZéÀúµÄ·œ·š*/ { arrToAvlp= keyque[m]->fail; while (arrToAvlp != NULL) { if (arrToAvlp->next[i] != NULL) { keyque[m]->arrToAvlNext[i]->avlToArrFail = arrToAvlp->next[i]; break; } arrToAvlp = arrToAvlp->fail; } if (arrToAvlp == NULL) { keyque[m]->arrToAvlNext[i]->avlToArrFail = root; } avlKeyQue[avlHead++] = keyque[m]->arrToAvlNext[i];//œ«µÚ3²ãŽæÈëavlKeyQue } } } //printf(" *********************** %d\n", head); /* for(m=0;m<5;m++){ printf("\n *%c level:%d",avlKeyQue[m]->data,avlKeyQue[m]->avlToArrFail->level); }*/ //-------------µÚÈý²ãover-------------------------- //-------------ºóÐøavl²ã¿ªÊŒ-------------------------- while (avlHead != avlTail)/*µ±±éÀúÍêËùÓеĜڵãºó£¬head==tail*/ { ACNODE *avltemp = avlKeyQue[avlTail++];/*Ê×ÏÈÈÃÖžÕëÖžÏòroot£¬keyqueµÄ×÷ÓÃÏ൱ÓÚ¹ã¶ÈËÑË÷ÀïÃæŒÇÂŒ¶ù×ӵĶÓÁÐ*/ ACNODE *avlp = NULL; arrNode *arrp = NULL; for (i=0; i < charSize; i++)//±éÀúÒ»žöœÚµãµÄ¶ù×Ó { if(queryAvlExist(avltemp->avlRoot,i)==1)/*ÕÒµœŽæÔڵĜڵ㣬ÓõÄÊDZéÀúµÄ·œ·š*/ { avlp=avltemp->avlFail;//·Ö2ÖÖÇé¿ö,žžÇ×ÊÇarrayºÍavl£¬avltempµÄfail±Ø¶šÒÑŸ­œšÁ¢ arrp=avltemp->avlToArrFail; if(avlp!=NULL) //con1.žžÇלڵãµÄfailÖžÏòavl { while (avlp != NULL) { if (queryAvlExist(avlp->avlRoot,i)==1)/*Èç¹ûp->next[i]ÓМڵ㣬ÔÚp->next[i]ŸÍÊÇtemp->next[i]ʧ°ÜÖžÕëλÖÃ*/ { //avltemp->next[i]->fail = avlp->next[i]; stepAvlNext(avltemp->avlRoot,i)->avlFail=stepAvlNext(avlp->avlRoot,i); break; } if(avlp->level==avlStartLevel)// { arrp = avlp->avlToArrFail;/*Èç¹ûÉÏÒ»žöif²»³ÉÁ¢£¬ÔòŒÌÐøÏòÉϲéÕÒ*/ break; } else if(avlp->level>avlStartLevel) { avlp = avlp->avlFail; } } if (avlp == NULL) { stepAvlNext(avltemp->avlRoot,i)->avlToArrFail = root; } }//end con1 if(arrp!=NULL) //con2.žžÇלڵãµÄfailÖžÏòarray { while (arrp != NULL) { if(arrp->level<(avlStartLevel-1)) //Ž¿array { if (arrp->next[i] != NULL) { stepAvlNext(avltemp->avlRoot,i)->avlToArrFail = arrp->next[i]; break; } arrp = arrp->fail; } else //×ÔŒºÊÇarray, ¶ù×ÓÊÇavl { if (arrp->arrToAvlNext[i] != NULL) { stepAvlNext(avltemp->avlRoot,i)->avlFail = arrp->arrToAvlNext[i];//failÖžÏòarrp¶ù×Ó,±Ø¶šÊÇavl break; } arrp = arrp->fail; } } if (arrp == NULL) { stepAvlNext(avltemp->avlRoot,i)->avlToArrFail = root;/*Èç¹ûûÓÐÕÒµœ£¬ÄÇÃŽœ«Ê§°ÜÖžÕëÖžÏòroot*/ } }//end con2 avlKeyQue[avlHead++] = stepAvlNext(avltemp->avlRoot,i);//Óжù×Ó,ŸÍhead++,Žæ·Å¶ù×Ӝڵ㣬ÒÔ±ž¹ã¶ÈËÑË÷Ìø×ª } }// end for }//end while // printf(" *********************** %d\n", avlHead); } /*œšÁ¢¹ØŒü×ÖÊ÷*/ void build_keyword(arrNode *root) { FILE *fp; int i=0,j=0; if ((fp=fopen(keyFile, "r"))==NULL) { printf("open keyword.txt file error!!\n"); return; } for(i=0; i<keyNum; i++) { for(j=0; j<LineMax; j++) { keyword[j]=fgetc(fp); } keyword[j]='\0'; insert(keyword,root,j);//žùŸÝkeywordœšÁ¢×ÖµäÊ÷ } } //======================================= int queryStr(arrNode *root) { FILE *fp; int cnt = 0, index; int avlSwitch=0, u=0;//avlSwitch 0¿ªÊŒŽÓarrayœÚµã¿ªÊŒÕÒ£¬1ŽÓavlœÚµã¿ªÊŒÕÒ arrNode *arrQueryP = root;/*ŽÓroot¿ªÊŒÆ¥Åä*/ ACNODE *avlQueryP = NULL; if ((fp=fopen(stringFile, "r"))==NULL) { printf("open string.txt file error!!\n"); return 0; } while(!feof(fp)) { index=fgetc(fp); while(1) { if(avlSwitch==0) { if(arrQueryP->level<(avlStartLevel-1))//1.Ž¿array { while(arrQueryP->next[index]==NULL&&arrQueryP!=root) { arrQueryP = arrQueryP->fail; } arrQueryP = arrQueryP->next[index];//ÏÖÔÚ¿ÉÄܵœŽïÁ˹ý¶É²ã£¬œøÐÐÏÂÒ»žöif avlSwitch=0; if (arrQueryP == NULL) { arrQueryP = root; } break; } //------------------------------------------ else if(arrQueryP->level==(avlStartLevel-1)) //2.¹ý¶É²ã { if(arrQueryP->arrToAvlNext[index]==NULL) { arrQueryP = arrQueryP->fail; while(arrQueryP->next[index]==NULL&&arrQueryP!=root) { arrQueryP = arrQueryP->fail; }//ŒÌÐøµœÉϲãarrayÕÒfail arrQueryP = arrQueryP->next[index]; } else { avlQueryP=arrQueryP->arrToAvlNext[index]; avlSwitch=1; } if (arrQueryP == NULL) { arrQueryP = root; avlSwitch=0; } break; } }//switch = 0 end //------------------------------------------ else if (avlSwitch==1) { //if (avlQueryP->level == 3) // printf("\n 3: %c",avlQueryP->data); while(queryAvlExist(avlQueryP->avlRoot,index)!=1) { //printf("eee");//ËÀÑ­»· if(avlQueryP->avlFail!=NULL) //avlµÄfailÖžÏòavl { avlQueryP=avlQueryP->avlFail; } else if(avlQueryP->avlToArrFail!=NULL) //avlµÄfailÖžÏòarray { arrQueryP=avlQueryP->avlToArrFail; avlSwitch=0; break; } } if(queryAvlExist(avlQueryP->avlRoot,index)==1) //ÊôÓÚÕý³£Ìø³ö£¬ÕÒµœÁËavlµÄnext { //if (avlQueryP->level == 3) //printf(" && %c && ",avlQueryP->data); avlQueryP=stepAvlNext(avlQueryP->avlRoot,index); //if (avlQueryP->level == 4) //printf(" ++ %c ++ ",avlQueryP->data); avlSwitch=1; break; } if (avlQueryP == NULL) { arrQueryP = root; avlSwitch=0; break; } }//end avlSwitch==1 }//end while //---------------------------- if (avlSwitch==1)//Èç¹ûÊÇarray²ãÓМáÊø×Ö·û£¬ÐèÒªœøÒ»²œžÄœø { ACNODE *avlCntTemp = avlQueryP; arrNode *arrCntTemp2 =NULL; while (avlCntTemp->count != -1) { cnt+=avlCntTemp->count; avlCntTemp->count = -1; if(avlCntTemp->avlFail!=NULL) avlCntTemp = avlCntTemp ->avlFail; else if (avlCntTemp->avlToArrFail!=NULL) { arrCntTemp2=avlCntTemp->avlToArrFail; // break; }//end while while (arrCntTemp2 != NULL && arrCntTemp2 != root && arrCntTemp2->count != -1) { cnt+=arrCntTemp2->count; arrCntTemp2->count = -1; arrCntTemp2 = arrCntTemp2 ->fail; }//ŒÆÆ¥Å䵜µÄ¹ØŒü×Ö } } } return cnt; } void printEach(arrNode *nn) { int j; for (j = 0; j < charSize; j++) if(nn->next[j]!=NULL) printf("%c",j); } void printEachArrToAvl(arrNode *nn) { int j; for (j = 0; j < charSize; j++) if(nn->arrToAvlNext[j]!=NULL) printf("%c",j); } void printAvlFail(ACNODE *avln) { int j; if(avln->avlFail!=NULL) printf("%d",avln->avlFail->level); if(avln->avlToArrFail!=NULL) { printf("%d",avln->avlToArrFail->level); } } //======================================= int main() { avlStartTemp = (ACNODE *)malloc(sizeof(ACNODE)); arrtemp = (arrNode *)malloc(sizeof(arrNode)); avltemp = (ACNODE *)malloc(sizeof(ACNODE)); //======== printf("=================levelAc start==================\n"); clock_t start,finish,middle; double exeTime,preTime; start = clock(); keyword=(int*)malloc(LineMax*sizeof(int)); int i; head = tail = 0; arrNode *root = (arrNode *)malloc(sizeof(arrNode)); for (i = 0; i < charSize; i++) root->next[i] = NULL; root->count = 0; root->level=-1; build_keyword(root); build_fail(root);//œšÁ¢Ê§°ÜÖžÕë //showTrie(root); //Ô€ŽŠÀíʱŒä middle = clock(); preTime= (double)(middle - start) / CLOCKS_PER_SEC; printf(" preTime :%f\n",preTime); printf(" arrToAvl %d\n",queryStr(root)); finish = clock(); exeTime = (double)(finish - middle) / CLOCKS_PER_SEC; printf(" exeTime :%f\n",exeTime); printf("=================levelAc end==================\n"); //sleep(3); return 0; } int Height(BST T) { if (T == NULL) return -1; else return T->bf; } int Max(int A, int B) { return ((A > B) ? A:B); } BST SingleRotateWithRight(BST K2,BST K1) { K1 = K2->rchild; K2->rchild = K1->lchild; K1->lchild = K2; K2->bf = Max(Height(K2->lchild), Height(K2->rchild)) + 1; K1->bf = Max(Height(K1->lchild), Height(K1->rchild)) + 1; return K1; } BST SingleRotateWithLeft(BST K2,BST K1) { K1 = K2->lchild; K2->lchild = K1->rchild; K1->rchild = K2; K2->bf = Max(Height(K2->lchild), Height(K2->rchild)) + 1; K1->bf = Max(Height(K1->lchild), Height(K1->rchild)) + 1; return K1; } BST DoubleRotateWithLeft(BST K3,BST newnode) { K3->lchild = SingleRotateWithRight(K3->lchild,newnode); return SingleRotateWithLeft(K3,newnode); } BST DoubleRotateWithRight(BST K3,BST newnode) { K3->rchild = SingleRotateWithLeft(K3->rchild,newnode); return SingleRotateWithRight(K3,newnode); } BST AVLInsert(BST T,BST newnode) { if (T == NULL) { newnode->bf = Max(Height(newnode->lchild), Height(newnode->rchild)) + 1; return newnode; } else if (input < T->data) { T->lchild = AVLInsert(T->lchild,newnode); if (Height(T->lchild) - Height(T->rchild) == 2) { if (input < T->lchild->data) { T = SingleRotateWithLeft(T,newnode); } else { T = DoubleRotateWithLeft(T,newnode); } } } else if (input > T->data) { T->rchild = AVLInsert(T->rchild,newnode); if (Height(T->rchild) - Height(T->lchild) == 2) { if (input > T->rchild->data) { T = SingleRotateWithRight(T,newnode); } else { T = DoubleRotateWithRight(T,newnode); } } } T->bf = Max(Height(T->lchild), Height(T->rchild)) + 1; return T; } int queryAvlExist(BST T,int index) { while(T!=NULL) { if(T->data==index) return 1; else if(T->data>index) { T=T->lchild; } else if(T->data<index) { T=T->rchild; } } return 0; } BST stepAvlNext(BST T,int index) { while(T!=NULL) { if(T->data==index) { return T; } else if(T->data>index) T=T->lchild; else T=T->rchild; } return NULL; } BST buildAvl(int index,BST T,BST newnode) { input=index; R = AVLInsert(T,newnode); return R; }
[ "cjqhenry@gmail.com" ]
cjqhenry@gmail.com
8e4ff4aea2d2aa8e5cb9055b209e6b2d6a4a8d71
975d45994f670a7f284b0dc88d3a0ebe44458a82
/servidor/Testes/Comunicação/Comunicação/Comunicação/includes/dreamServer.cpp
6d7e1b3d50a4cee930a0a64c66a009c2632411e6
[]
no_license
phabh/warbugs
2b616be17a54fbf46c78b576f17e702f6ddda1e6
bf1def2f8b7d4267fb7af42df104e9cdbe0378f8
refs/heads/master
2020-12-25T08:51:02.308060
2010-11-15T00:37:38
2010-11-15T00:37:38
60,636,297
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
10,340
cpp
/****************************************************************************************** Funções da classe dreamServer *******************************************************************************************/ #include "dreamServer.h" #include "dreamSock.h" #include "dreamClient.h" #include "dreamMessage.h" dreamServer::dreamServer() { _init = false; _port = 0; _runningIndex = 1; _socket = 0; _clientList = NULL; } dreamServer::~dreamServer() { dreamClient *list = _clientList; dreamClient *next; while(list != NULL) { next = list->_next; if(list) { free(list); } list = next; } _clientList = NULL; dreamSock_CloseSocket(_socket); } int dreamServer::initialize(char *localIP, int serverPort) { // Initialize dreamSock if it is not already initialized dreamSock_Initialize(); // Store the server IP and port for later use _port = serverPort; // Create server socket _socket = dreamSock_OpenUDPSocket(localIP, _port); if(_socket == DREAMSOCK_INVALID_SOCKET) { return DREAMSOCK_SERVER_ERROR; } _init = true; return 0; } void dreamServer::uninitialize(void) { dreamSock_CloseSocket(_socket); _init = false; } void dreamServer::sendAddClient(dreamClient *newClient) { // Send connection confirmation newClient->_message.init(newClient->_message._outgoingData, sizeof(newClient->_message._outgoingData)); //-101 = DREAMSOCK_MES_CONNECT newClient->_message.writeByte(-101); // type newClient->sendPacket(); // Send 'Add client' message to every client dreamClient *client = _clientList; // First inform the new client of the other clients for(; client != NULL; client = client->_next) { newClient->_message.init(newClient->_message._outgoingData, sizeof(newClient->_message._outgoingData)); //-103 = DREAMSOCK_MES_ADDCLIENT newClient->_message.writeByte(-103); // type if(client == newClient) { newClient->_message.writeByte(1); // local client newClient->_message.writeByte(client->getIndex()); newClient->_message.writeString(client->getName()); } else { newClient->_message.writeByte(0); // not local client newClient->_message.writeByte(client->getIndex()); newClient->_message.writeString(client->getName()); } newClient->sendPacket(); } // Then tell the others about the new client for(client = _clientList; client != NULL; client = client->_next) { if(client == newClient) continue; client->_message.init(client->_message._outgoingData, sizeof(client->_message._outgoingData)); //-103 = DREAMSOCK_MES_ADDCLIENT client->_message.writeByte(-103); // type client->_message.writeByte(0); client->_message.writeByte(newClient->getIndex()); client->_message.writeString(newClient->getName()); client->sendPacket(); } } void dreamServer::sendRemoveClient(dreamClient *client) { int index = client->getIndex(); // Send 'Remove client' message to every client dreamClient *list = _clientList; for(; list != NULL; list = list->_next) { list->_message.init(list->_message._outgoingData, sizeof(list->_message._outgoingData)); //-104 = DREAMSOCK_MES_REMOVECLIENT list->_message.writeByte(-104); // type list->_message.writeByte(index); // index } sendPackets(); // Send disconnection confirmation client->_message.init(client->_message._outgoingData, sizeof(client->_message._outgoingData)); //-102 = DREAMSOCK_MES_DISCONNECT client->_message.writeByte(-102); client->sendPacket(); } void dreamServer::sendPing(void) { // Send ping message to every client dreamClient *list = _clientList; for(; list != NULL; list = list->_next) { list->sendPing(); } } void dreamServer::addClient(struct sockaddr *address, char *name) { // First get a pointer to the beginning of client list dreamClient *list = _clientList; dreamClient *prev; dreamClient *newClient; //LogString("LIB: Adding client, index %d", _runningIndex); // No clients yet, adding the first one if(_clientList == NULL) { // LogString("LIB: Server: Adding first client"); _clientList = (dreamClient *) calloc(1, sizeof(dreamClient)); _clientList->setSocket(_socket); _clientList->setSocketAddress(address); _clientList->setConnectionState(DREAMSOCK_CONNECTING); _clientList->setOutgoingSequence(1); _clientList->setIncomingSequence(0); _clientList->setIncomingAcknowledged(0); _clientList->setIndex(_runningIndex); _clientList->setName(name); _clientList->_next = NULL; newClient = _clientList; } else { // LogString("LIB: Server: Adding another client"); prev = list; list = _clientList->_next; while(list != NULL) { prev = list; list = list->_next; } list = (dreamClient *) calloc(1, sizeof(dreamClient)); list->setSocket(_socket); list->setSocketAddress(address); list->setConnectionState(DREAMSOCK_CONNECTING); list->setOutgoingSequence(1); list->setIncomingSequence(0); list->setIncomingAcknowledged(0); list->setIndex(_runningIndex); list->setName(name); list->_next = NULL; prev->_next = list; newClient = list; } _runningIndex++; sendAddClient(newClient); } void dreamServer::removeClient(dreamClient *client) { dreamClient *list = NULL; dreamClient *prev = NULL; dreamClient *next = NULL; int index = client->getIndex(); //LogString("LIB: Removing client with index %d", index); sendRemoveClient(client); for(list = _clientList; list != NULL; list = list->_next) { if(client == list) { if(prev != NULL) { prev->_next = client->_next; } break; } prev = list; } if(client == _clientList) { // LogString("LIB: Server: removing first client in list"); if(list) next = list->_next; if(client) free(client); client = NULL; _clientList = next; } else { // LogString("LIB: Server: removing a client"); if(list) next = list->_next; if(client) free(client); client = next; } } void dreamServer::parsePacket(dreamMessage *mes, struct sockaddr *address) { mes->beginReading(); int type = mes->readByte(); // Find the correct client by comparing addresses dreamClient *clList = _clientList; // If we do not have clients yet, skip to message type checking if(clList != NULL) { for(; clList != NULL; clList = clList->_next) { if(memcmp(clList->getSocketAddress(), address, sizeof(address)) == 0) { break; } } if(clList != NULL) { clList->setLastMessageTime(dreamSock_GetCurrentSystemTime()); // Check if the type is a positive number-> is the packet sequenced if(type > 0) { unsigned short sequence = mes->readShort(); unsigned short sequenceAck = mes->readShort(); if(sequence <= clList->getIncomingSequence()) { // LogString("LIB: Server: Sequence mismatch(sequence: %ld <= incoming seq: %ld)", sequence, clList->getIncomingSequence()); } clList->setDroppedPackets(sequence - (clList->getIncomingSequence() -1)); clList->setIncomingSequence(sequence); clList->setIncomingAcknowledged(sequenceAck); } // Wait for one message before setting state to connected if(clList->getConnectionState() == DREAMSOCK_CONNECTING) clList->setConnectionState(DREAMSOCK_CONNECTED); } } // Parse through the system messages switch(type) { //-101 = DREAMSOCK_MES_CONNECT case -101: addClient(address, mes->readString()); // LogString("LIBRARY: Server: a client connected successfully"); break; //-102 = DREAMSOCK_MES_DISCONNECT case -102: if(clList == NULL) break; removeClient(clList); // LogString("LIBRARY: Server: a client disconnected"); break; //-105 = DREAMSOCK_MES_PING case -105: //clList->setPing((dreamSock_GetCurrentSystemTime() – clList->getPingSent())); clList->setPing(dreamSock_GetCurrentSystemTime() - clList->getPingSent()); break; } } int dreamServer::checkForTimeout(char *data, struct sockaddr *from) { int currentTime = dreamSock_GetCurrentSystemTime(); dreamClient *clList = _clientList; dreamClient *next; for(; clList != NULL;) { next = clList->_next; // Don't timeout when connecting if(clList->getConnectionState() == DREAMSOCK_CONNECTING) { clList = next; continue; } // Check if the client has been silent for 30 seconds // If yes, assume crashed and remove the client if((currentTime - clList->getLastMessageTime()) > 30000) { // LogString("Client timeout, disconnecting (%d – %d = %d)", currentTime, clList->getLastMessageTime(), currentTime – clList->getLastMessageTime()); // Build a 'fake' message so the application will also // receive notification of a client disconnecting dreamMessage mes; mes.init(data, sizeof(data)); //-102 = DREAMSOCK_MES_DISCONNECT mes.writeByte(-102); *(struct sockaddr *) from = *clList->getSocketAddress(); removeClient(clList); return mes.getSize(); } clList = next; } return 0; } int dreamServer::getPacket(char *data, struct sockaddr *from) { // Check if the server is set up if(!_socket) return 0; // Check for timeout int timeout = checkForTimeout(data, from); if(timeout) return timeout; // Wait for a while or incoming data int maxfd = _socket; fd_set allset; struct timeval waittime; waittime.tv_sec = 10 / 1000; waittime.tv_usec = (10 % 1000) * 1000; FD_ZERO(&allset); FD_SET(_socket, &allset); fd_set reading = allset; int nready = select(maxfd + 1, &reading, NULL, NULL, &waittime); if(!nready) return 0; // Read data of the socket int ret = 0; dreamMessage mes; mes.init(data, sizeof(data)); ret = dreamSock_GetPacket(_socket, mes._data, from); if(ret <= 0) return 0; mes.setSize(ret); // Parse system messages parsePacket(&mes, from); return ret; } void dreamServer::sendPackets(void) { // Check if the server is set up if(!socket) return; dreamClient *clList = _clientList; for(; clList != NULL; clList = clList->_next) { if(clList->_message.getSize() == 0) continue; clList->sendPacket(); } }
[ "phabh@users.noreply.github.com" ]
phabh@users.noreply.github.com
ad76b112ece589483fdb7d39da30d3ca61d0c4af
dff4d070ec9aefd3801a65e585c3f4bc4ee599aa
/resources/3d-program/cubeTransformations.cpp
460e22860e1a487e42e3c449a052c867a0eb9641
[ "Apache-2.0" ]
permissive
jaykay12/Large-Volume-Data-Visualization
e171d0521b9cf6896f8ec54e73ee04bfe127c343
a434197ce1e1b24b24f350304268da2c443ea701
refs/heads/master
2022-07-07T10:00:33.691700
2020-05-16T06:05:57
2020-05-16T06:05:57
101,227,722
6
1
null
null
null
null
UTF-8
C++
false
false
6,102
cpp
#include <GL/gl.h> #include <GL/glut.h> #include <GL/glu.h> GLfloat xRotated=0.0, yRotated=0.0, zRotated=0.0; GLfloat xTranslate=0.0, yTranslate=0.0, zTranslate=0.0; GLfloat xScale=1.0, yScale=1.0, zScale=1.0; int iShape = 1; void init(void) { glClearColor(0,0,0,0); } void DrawCube(void) { glMatrixMode(GL_MODELVIEW); // clear the drawing buffer. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); glTranslatef(0.0+xTranslate, 0.0+yTranslate, -10.5+ zTranslate); glRotatef(xRotated,1.0,0.0,0.0); // rotation about Y axis glRotatef(yRotated,0.0,1.0,0.0); // rotation about Z axis glRotatef(zRotated,0.0,0.0,1.0); glScalef(xScale,yScale,zScale); glBegin(GL_QUADS); // Draw The Cube Using quads glColor3f(0.0f,1.0f,0.0f); // Color Blue glVertex3f( 1.0f, 1.0f,-1.0f); // Top Right Of The Quad (Top) glVertex3f(-1.0f, 1.0f,-1.0f); // Top Left Of The Quad (Top) glVertex3f(-1.0f, 1.0f, 1.0f); // Bottom Left Of The Quad (Top) glVertex3f( 1.0f, 1.0f, 1.0f); // Bottom Right Of The Quad (Top) glColor3f(1.0f,0.5f,0.0f); // Color Orange glVertex3f( 1.0f,-1.0f, 1.0f); // Top Right Of The Quad (Bottom) glVertex3f(-1.0f,-1.0f, 1.0f); // Top Left Of The Quad (Bottom) glVertex3f(-1.0f,-1.0f,-1.0f); // Bottom Left Of The Quad (Bottom) glVertex3f( 1.0f,-1.0f,-1.0f); // Bottom Right Of The Quad (Bottom) glColor3f(1.0f,0.0f,0.0f); // Color Red glVertex3f( 1.0f, 1.0f, 1.0f); // Top Right Of The Quad (Front) glVertex3f(-1.0f, 1.0f, 1.0f); // Top Left Of The Quad (Front) glVertex3f(-1.0f,-1.0f, 1.0f); // Bottom Left Of The Quad (Front) glVertex3f( 1.0f,-1.0f, 1.0f); // Bottom Right Of The Quad (Front) glColor3f(1.0f,1.0f,0.0f); // Color Yellow glVertex3f( 1.0f,-1.0f,-1.0f); // Top Right Of The Quad (Back) glVertex3f(-1.0f,-1.0f,-1.0f); // Top Left Of The Quad (Back) glVertex3f(-1.0f, 1.0f,-1.0f); // Bottom Left Of The Quad (Back) glVertex3f( 1.0f, 1.0f,-1.0f); // Bottom Right Of The Quad (Back) glColor3f(0.0f,0.0f,1.0f); // Color Blue glVertex3f(-1.0f, 1.0f, 1.0f); // Top Right Of The Quad (Left) glVertex3f(-1.0f, 1.0f,-1.0f); // Top Left Of The Quad (Left) glVertex3f(-1.0f,-1.0f,-1.0f); // Bottom Left Of The Quad (Left) glVertex3f(-1.0f,-1.0f, 1.0f); // Bottom Right Of The Quad (Left) glColor3f(1.0f,0.0f,1.0f); // Color Violet glVertex3f( 1.0f, 1.0f,-1.0f); // Top Right Of The Quad (Right) glVertex3f( 1.0f, 1.0f, 1.0f); // Top Left Of The Quad (Right) glVertex3f( 1.0f,-1.0f, 1.0f); // Bottom Left Of The Quad (Right) glVertex3f( 1.0f,-1.0f,-1.0f); // Bottom Right Of The Quad (Right) glEnd(); // End Drawing The Cube glFlush(); } /*void animation(void) { yRotated += 0.01; xRotated += 0.02; DrawCube(); }*/ void ProcessMenu(int value) { iShape = value; switch(iShape) { case 1: xRotated += 90.0; break; case 2: yRotated += 90.0; break; case 3: zRotated += 90.0; break; case 4: xTranslate += 2.0; break; case 5: xTranslate += -2.0; break; case 6: yTranslate += 2.0; break; case 7: yTranslate += -2.0; break; case 8: zTranslate += 2.0; break; case 9: zTranslate += -2.0; break; case 10: xScale += 0.5; yScale += 0.5; zScale += 0.5; break; case 11: xScale -= 0.5; yScale -= 0.5; zScale -= 0.5; break; default: xRotated += 0.0; } // Restore transformations glPopMatrix(); // Flush drawing commands glutSwapBuffers(); glutPostRedisplay(); } void reshape(int x, int y) { if (y == 0 || x == 0) return; //Nothing is visible then, so return //Set a new projection matrix glMatrixMode(GL_PROJECTION); glLoadIdentity(); //Angle of view:40 degrees //Near clipping plane distance: 0.5 //Far clipping plane distance: 20.0 gluPerspective(40.0,(GLdouble)x/(GLdouble)y,0.5,20.0); glMatrixMode(GL_MODELVIEW); glViewport(0,0,x,y); //Use the whole window for rendering } int main(int argc, char* argv[]) { int nTransformationMenu, nRotateMenu, nTranslateMenu, nScaleMenu; glutInit(&argc, argv); //we initizlilze the glut. functions glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB); glutInitWindowPosition(100, 100); glutCreateWindow("Cube"); nRotateMenu = glutCreateMenu(ProcessMenu); glutAddMenuEntry("90 degree along x-axis",1); glutAddMenuEntry("90 degree along y-axis",2); glutAddMenuEntry("90 degree along z-axis",3); nTranslateMenu = glutCreateMenu(ProcessMenu); glutAddMenuEntry("2 units along positive x-axis",4); glutAddMenuEntry("2 units along negative x-axis",5); glutAddMenuEntry("2 units along positive y-axis",6); glutAddMenuEntry("2 units along negative y-axis",7); glutAddMenuEntry("2 units along positive z-axis",8); glutAddMenuEntry("2 units along negative z-axis",9); nScaleMenu = glutCreateMenu(ProcessMenu); glutAddMenuEntry("Zoom In",10); glutAddMenuEntry("Zoom Out",11); nTransformationMenu = glutCreateMenu(ProcessMenu); glutAddSubMenu("Rotate",nRotateMenu); glutAddSubMenu("Translate",nTranslateMenu); glutAddSubMenu("Scale",nScaleMenu); glutAttachMenu(GLUT_RIGHT_BUTTON); init(); glutDisplayFunc(DrawCube); glutReshapeFunc(reshape); //Set the function for the animation. //glutIdleFunc(); glutMainLoop(); return 0; } //- See more at: http://www.codemiles.com/c-opengl-examples/draw-3d-cube-using-opengl-t9018.html#sthash.TGrdK6Sq.dpuf
[ "jalazkumar1208@gmail.com" ]
jalazkumar1208@gmail.com
78d92ee4585b4b11184b8fe325dddb023e1a8b93
09e5cfe06e437989a2ccf2aeecb9c73eb998a36c
/modules/clipper/clipper/minimol/container_minimol.cpp
875b66f7de71822d305d976614ddaf1635253748
[ "LGPL-2.1-only", "BSD-3-Clause" ]
permissive
jorgediazjr/dials-dev20191018
b81b19653624cee39207b7cefb8dfcb2e99b79eb
77d66c719b5746f37af51ad593e2941ed6fbba17
refs/heads/master
2020-08-21T02:48:54.719532
2020-01-25T01:41:37
2020-01-25T01:41:37
216,089,955
0
1
BSD-3-Clause
2020-01-25T01:41:39
2019-10-18T19:03:17
Python
UTF-8
C++
false
false
3,983
cpp
/* container_minimol.cpp: atomic model types */ //C Copyright (C) 2000-2004 Kevin Cowtan and University of York //C Copyright (C) 2000-2005 Kevin Cowtan and University of York //L //L This library is free software and is distributed under the terms //L and conditions of version 2.1 of the GNU Lesser General Public //L Licence (LGPL) with the following additional clause: //L //L `You may also combine or link a "work that uses the Library" to //L produce a work containing portions of the Library, and distribute //L that work under terms of your choice, provided that you give //L prominent notice with each copy of the work that the specified //L version of the Library is used in it, and that you include or //L provide public access to the complete corresponding //L machine-readable source code for the Library including whatever //L changes were used in the work. (i.e. If you make changes to the //L Library you must distribute those, but you do not need to //L distribute source or object code to those portions of the work //L not covered by this licence.)' //L //L Note that this clause grants an additional right and does not impose //L any additional restriction, and so does not affect compatibility //L with the GNU General Public Licence (GPL). If you wish to negotiate //L other terms, please contact the maintainer. //L //L You can redistribute it and/or modify the library under the terms of //L the GNU Lesser General Public License as published by the Free Software //L Foundation; either version 2.1 of the License, or (at your option) any //L later version. //L //L This library is distributed in the hope that it will be useful, but //L WITHOUT ANY WARRANTY; without even the implied warranty of //L MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU //L Lesser General Public License for more details. //L //L You should have received a copy of the CCP4 licence and/or GNU //L Lesser General Public License along with this library; if not, write //L to the CCP4 Secretary, Daresbury Laboratory, Warrington WA4 4AD, UK. //L The GNU Lesser General Public can also be obtained by writing to the //L Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, //L MA 02111-1307 USA #include "container_minimol.h" namespace clipper { // CMiniMol /*! The object is constructed at the given location in the hierarchy. An attempt is made to initialise the object using information from its parents in the hierarchy. \param parent An object in the hierarchy (usually the parent of the new object). \param name The path from \c parent to the new object (usually just the name of the new object). */ CMiniMol::CMiniMol( Container& parent, const String name ) : Container( parent, name ) { init( NullSpacegroup, NullCell ); } /*! An attempt is made to initialise the object using information from the supplied parameters, or if they are Null, from its parents in the hierarchy. \param spacegroup The spacegroup for the model. \param name The cell for the model. */ void CMiniMol::init( const Spacegroup& spacegroup, const Cell& cell ) { // use supplied values by default const Spacegroup* sp = &spacegroup; // use pointers so we can reassign const Cell* cp = &cell; // otherwise get them from the tree if ( sp->is_null() ) sp = parent_of_type_ptr<const Spacegroup>(); if ( cp->is_null() ) cp = parent_of_type_ptr<const Cell>(); // initialise if ( sp != NULL && cp != NULL ) if ( !sp->is_null() && !cp->is_null() ) MiniMol::init( *sp, *cp ); Container::update(); } /*! Hierarchical update. If this object is uninitialised, an attempt is made to initialise the object using information from its parents in the hierarchy. The childen of the object are then updated. */ void CMiniMol::update() { if ( CMiniMol::is_null() ) init( NullSpacegroup, NullCell ); else Container::update(); } } // namespace clipper
[ "jorge7soccer@gmail.com" ]
jorge7soccer@gmail.com
eb5f8f12880705631d00f46cbcd1553c8135d8eb
d932716790743d0e2ae7db7218fa6d24f9bc85dc
/components/security_interstitials/content/security_interstitial_controller_client.cc
87d0789a3912da7f940726d322303a7f59526e8d
[ "BSD-3-Clause" ]
permissive
vade/chromium
c43f0c92fdede38e8a9b858abd4fd7c2bb679d9c
35c8a0b1c1a76210ae000a946a17d8979b7d81eb
refs/heads/Syphon
2023-02-28T00:10:11.977720
2017-05-24T16:38:21
2017-05-24T16:38:21
80,049,719
19
3
null
2017-05-24T19:05:34
2017-01-25T19:31:53
null
UTF-8
C++
false
false
3,371
cc
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/security_interstitials/content/security_interstitial_controller_client.h" #include <utility> #include "components/prefs/pref_service.h" #include "components/safe_browsing/common/safe_browsing_prefs.h" #include "components/security_interstitials/core/metrics_helper.h" #include "content/public/browser/interstitial_page.h" #include "content/public/browser/web_contents.h" #include "content/public/common/referrer.h" using content::Referrer; namespace security_interstitials { SecurityInterstitialControllerClient::SecurityInterstitialControllerClient( content::WebContents* web_contents, std::unique_ptr<MetricsHelper> metrics_helper, PrefService* prefs, const std::string& app_locale, const GURL& default_safe_page) : ControllerClient(std::move(metrics_helper)), web_contents_(web_contents), interstitial_page_(nullptr), prefs_(prefs), app_locale_(app_locale), default_safe_page_(default_safe_page) {} SecurityInterstitialControllerClient::~SecurityInterstitialControllerClient() {} void SecurityInterstitialControllerClient::set_interstitial_page( content::InterstitialPage* interstitial_page) { interstitial_page_ = interstitial_page; } content::InterstitialPage* SecurityInterstitialControllerClient::interstitial_page() { return interstitial_page_; } void SecurityInterstitialControllerClient::GoBack() { interstitial_page_->DontProceed(); } bool SecurityInterstitialControllerClient::CanGoBack() { return web_contents_->GetController().CanGoBack(); } void SecurityInterstitialControllerClient::GoBackAfterNavigationCommitted() { // If the offending entry has committed, go back or to a safe page without // closing the error page. This error page will be closed when the new page // commits. if (web_contents_->GetController().CanGoBack()) { web_contents_->GetController().GoBack(); } else { web_contents_->GetController().LoadURL( default_safe_page_, content::Referrer(), ui::PAGE_TRANSITION_AUTO_TOPLEVEL, std::string()); } } void SecurityInterstitialControllerClient::Proceed() { interstitial_page_->Proceed(); } void SecurityInterstitialControllerClient::Reload() { web_contents_->GetController().Reload(content::ReloadType::NORMAL, true); } void SecurityInterstitialControllerClient::OpenUrlInCurrentTab( const GURL& url) { content::OpenURLParams params(url, Referrer(), WindowOpenDisposition::CURRENT_TAB, ui::PAGE_TRANSITION_LINK, false); web_contents_->OpenURL(params); } const std::string& SecurityInterstitialControllerClient::GetApplicationLocale() const { return app_locale_; } PrefService* SecurityInterstitialControllerClient::GetPrefService() { return prefs_; } const std::string SecurityInterstitialControllerClient::GetExtendedReportingPrefName() const { return safe_browsing::GetExtendedReportingPrefName(*prefs_); } bool SecurityInterstitialControllerClient::CanLaunchDateAndTimeSettings() { NOTREACHED(); return false; } void SecurityInterstitialControllerClient::LaunchDateAndTimeSettings() { NOTREACHED(); } } // namespace security_interstitials
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
1e4e0a5657b9727cf94fecab47260393d4e7b57a
149e184a66dca507ed8730f7b0e34a08567f820e
/cantestmmainwindow.h
b268d405f66c192eed718981f0c8c530b03b5087
[]
no_license
pjzuuuuu/CANTest
1d06e1da3b6283e6b5486566b61f420ca3cac63f
d2e01e0f79beab84a37cefa02359e512f004eda1
refs/heads/master
2020-09-08T19:54:15.930973
2019-11-12T14:10:54
2019-11-12T14:10:54
221,230,353
0
0
null
null
null
null
UTF-8
C++
false
false
477
h
#ifndef CANTESTMMAINWINDOW_H #define CANTESTMMAINWINDOW_H #include <QMainWindow> #include "can_tcpdlg.h" namespace Ui { class CANTestmMainWindow; } class CANTestmMainWindow : public QMainWindow { Q_OBJECT public: explicit CANTestmMainWindow(QWidget *parent = 0); ~CANTestmMainWindow(); protected: private: CAN_TCPdlg* TCPdlg; private: Ui::CANTestmMainWindow *ui; signals: private slots: void CreatDialog(); }; #endif // CANTESTMMAINWINDOW_H
[ "pangjingze1997@gmail.com" ]
pangjingze1997@gmail.com
2346e95507d17119fc82d9ef3884523ba57255c2
4ecbb1fd6ca57cd920b546f8a3a9a4c6691ac17c
/PrzekierowaniaRuchu/ArcFlagsCreator.h
f6fbc056648eaf495c6341053372299040da2a75
[]
no_license
adrianwawryczuk/PrzekierowaniaRuchu
5ab2596d6c83d43fd82a1f671e356b5527df064e
6c6ad69a91f775ba2f1fb1c569bdf6a28322397a
refs/heads/master
2021-09-15T13:39:38.958219
2017-01-18T22:08:11
2017-01-18T22:08:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
150
h
#pragma once #include "Dijkstra.h" #include "MySqlConnection.h" #include <boost/thread.hpp> class ArcFlagsCreator { public: ArcFlagsCreator(); };
[ "adrianek3276@gmail.com" ]
adrianek3276@gmail.com
8ff98b4bb29f178f3690871e4cd54035d1d3c2d1
67bf93cfae8f8153e65601fd3bc5442349ee665c
/Chapter4/pe4-1.cpp
56845f493cbc4f2bfb05df6ec71abcb78d179e03
[]
no_license
Ali-Fawzi-Lateef/C-PrimerPlus
ce86c880dc3a2b6b4eda6a277463563136c1cc00
f53bca85c36dffb768aa18a15d0446dd766fe309
refs/heads/master
2023-08-02T02:38:05.418154
2021-09-23T18:06:47
2021-09-23T18:06:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
906
cpp
// pe4-1.cpp -- this program requests and displays information // This is exercise 1 of chapter 4 in C++ Primer Plus by Stephen Prata #include<iostream> int main(void) { using namespace std; cout << "What is your first name? "; char first_name[20]; cin.getline(first_name, 20); // we can see that cin does not leave a new line character after reading text first_name[19] = '\0'; //cin.get(); // This is unnecessary because the member function getline() does not leave a newline character in the input cout << "What is your last name? "; char last_name[20]; cin.getline(last_name, 20); last_name[19] = '\0'; cout << "What letter grade do you deserve? "; char grade; cin >> grade; cout << "What is your age? "; int age; cin >> age; cout << "Name: " << last_name << ", " << first_name << endl << "Grade: " << char (grade + 1) << endl << "Age: " << age << endl; return 0; }
[ "nruderman.s@gmail.com" ]
nruderman.s@gmail.com
98ef0fa5b101d04e87c056ccc6712ed01a13361a
ce71ba08e9094a4d76c8cc1e0cc7891ae016ff60
/Lib/Chip/CM0+/Freescale/MKM34ZA5/PORTC.hpp
599428947203f5a5f71542f8e70d794de47ad8f8
[ "Apache-2.0" ]
permissive
operativeF/Kvasir
9bfe25e1844d41ffefe527f16117c618af50cde9
dfbcbdc9993d326ef8cc73d99129e78459c561fd
refs/heads/master
2020-04-06T13:12:59.381009
2019-01-25T18:43:17
2019-01-25T18:43:17
157,489,295
0
0
Apache-2.0
2018-11-14T04:12:05
2018-11-14T04:12:04
null
UTF-8
C++
false
false
55,097
hpp
#pragma once #include <Register/Utility.hpp> namespace Kvasir { //Pin Control and Interrupts namespace PortcGpclr{ ///<Global Pin Control Low Register using Addr = Register::Address<0x40048080,0x00000000,0x00000000,unsigned>; ///Global Pin Write Data constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> gpwd{}; ///Global Pin Write Enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,16),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> gpwe{}; } namespace PortcGpchr{ ///<Global Pin Control High Register using Addr = Register::Address<0x40048084,0x00000000,0x00000000,unsigned>; ///Global Pin Write Data constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,0),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> gpwd{}; ///Global Pin Write Enable constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,16),Register::Access<Register::AccessType::writeOnly,Register::ReadActionType::normal,Register::ModifiedWriteValueType::normal>,unsigned> gpwe{}; } namespace PortcIsfr{ ///<Interrupt Status Flag Register using Addr = Register::Address<0x400480a0,0x00000000,0x00000000,unsigned>; ///Interrupt Status Flag constexpr Register::FieldLocation<Addr,Register::maskFromRange(31,0),Register::ReadWriteAccess,unsigned> isf{}; } namespace PortcPcr0{ ///<Pin Control Register n using Addr = Register::Address<0x40048000,0xfef078f8,0x00000000,unsigned>; ///Pull Select enum class PsVal { v0=0x00000000, ///<Internal pulldown resistor is enabled on the corresponding pin, if the corresponding Port Pull Enable field is set. v1=0x00000001, ///<Internal pullup resistor is enabled on the corresponding pin, if the corresponding Port Pull Enable field is set. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,PsVal> ps{}; namespace PsValC{ constexpr Register::FieldValue<decltype(ps)::Type,PsVal::v0> v0{}; constexpr Register::FieldValue<decltype(ps)::Type,PsVal::v1> v1{}; } ///Pull Enable enum class PeVal { v0=0x00000000, ///<Internal pullup or pulldown resistor is not enabled on the corresponding pin. v1=0x00000001, ///<Internal pullup or pulldown resistor is enabled on the corresponding pin, if the pin is configured as a digital input. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,PeVal> pe{}; namespace PeValC{ constexpr Register::FieldValue<decltype(pe)::Type,PeVal::v0> v0{}; constexpr Register::FieldValue<decltype(pe)::Type,PeVal::v1> v1{}; } ///Slew Rate Enable enum class SreVal { v0=0x00000000, ///<Fast slew rate is configured on the corresponding pin, if the pin is configured as a digital output. v1=0x00000001, ///<Slow slew rate is configured on the corresponding pin, if the pin is configured as a digital output. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,SreVal> sre{}; namespace SreValC{ constexpr Register::FieldValue<decltype(sre)::Type,SreVal::v0> v0{}; constexpr Register::FieldValue<decltype(sre)::Type,SreVal::v1> v1{}; } ///Pin Mux Control enum class MuxVal { v000=0x00000000, ///<Pin disabled (analog). v001=0x00000001, ///<Alternative 1 (GPIO). v010=0x00000002, ///<Alternative 2 (chip-specific). v011=0x00000003, ///<Alternative 3 (chip-specific). v100=0x00000004, ///<Alternative 4 (chip-specific). v101=0x00000005, ///<Alternative 5 (chip-specific). v110=0x00000006, ///<Alternative 6 (chip-specific). v111=0x00000007, ///<Alternative 7 (chip-specific). }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,8),Register::ReadWriteAccess,MuxVal> mux{}; namespace MuxValC{ constexpr Register::FieldValue<decltype(mux)::Type,MuxVal::v000> v000{}; constexpr Register::FieldValue<decltype(mux)::Type,MuxVal::v001> v001{}; constexpr Register::FieldValue<decltype(mux)::Type,MuxVal::v010> v010{}; constexpr Register::FieldValue<decltype(mux)::Type,MuxVal::v011> v011{}; constexpr Register::FieldValue<decltype(mux)::Type,MuxVal::v100> v100{}; constexpr Register::FieldValue<decltype(mux)::Type,MuxVal::v101> v101{}; constexpr Register::FieldValue<decltype(mux)::Type,MuxVal::v110> v110{}; constexpr Register::FieldValue<decltype(mux)::Type,MuxVal::v111> v111{}; } ///Lock Register enum class LkVal { v0=0x00000000, ///<Pin Control Register fields [15:0] are not locked. v1=0x00000001, ///<Pin Control Register fields [15:0] are locked and cannot be updated until the next system reset. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,LkVal> lk{}; namespace LkValC{ constexpr Register::FieldValue<decltype(lk)::Type,LkVal::v0> v0{}; constexpr Register::FieldValue<decltype(lk)::Type,LkVal::v1> v1{}; } ///Interrupt Configuration enum class IrqcVal { v0000=0x00000000, ///<Interrupt/DMA request disabled. v0001=0x00000001, ///<DMA request on rising edge. v0010=0x00000002, ///<DMA request on falling edge. v0011=0x00000003, ///<DMA request on either edge. v1000=0x00000008, ///<Interrupt when logic zero. v1001=0x00000009, ///<Interrupt on rising edge. v1010=0x0000000a, ///<Interrupt on falling edge. v1011=0x0000000b, ///<Interrupt on either edge. v1100=0x0000000c, ///<Interrupt when logic one. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,16),Register::ReadWriteAccess,IrqcVal> irqc{}; namespace IrqcValC{ constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v0000> v0000{}; constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v0001> v0001{}; constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v0010> v0010{}; constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v0011> v0011{}; constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v1000> v1000{}; constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v1001> v1001{}; constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v1010> v1010{}; constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v1011> v1011{}; constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v1100> v1100{}; } ///Interrupt Status Flag enum class IsfVal { v0=0x00000000, ///<Configured interrupt is not detected. v1=0x00000001, ///<Configured interrupt is detected. If the pin is configured to generate a DMA request, then the corresponding flag will be cleared automatically at the completion of the requested DMA transfer. Otherwise, the flag remains set until a logic one is written to the flag. If the pin is configured for a level sensitive interrupt and the pin remains asserted, then the flag is set again immediately after it is cleared. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,IsfVal> isf{}; namespace IsfValC{ constexpr Register::FieldValue<decltype(isf)::Type,IsfVal::v0> v0{}; constexpr Register::FieldValue<decltype(isf)::Type,IsfVal::v1> v1{}; } } namespace PortcPcr1{ ///<Pin Control Register n using Addr = Register::Address<0x40048004,0xfef078f8,0x00000000,unsigned>; ///Pull Select enum class PsVal { v0=0x00000000, ///<Internal pulldown resistor is enabled on the corresponding pin, if the corresponding Port Pull Enable field is set. v1=0x00000001, ///<Internal pullup resistor is enabled on the corresponding pin, if the corresponding Port Pull Enable field is set. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,PsVal> ps{}; namespace PsValC{ constexpr Register::FieldValue<decltype(ps)::Type,PsVal::v0> v0{}; constexpr Register::FieldValue<decltype(ps)::Type,PsVal::v1> v1{}; } ///Pull Enable enum class PeVal { v0=0x00000000, ///<Internal pullup or pulldown resistor is not enabled on the corresponding pin. v1=0x00000001, ///<Internal pullup or pulldown resistor is enabled on the corresponding pin, if the pin is configured as a digital input. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,PeVal> pe{}; namespace PeValC{ constexpr Register::FieldValue<decltype(pe)::Type,PeVal::v0> v0{}; constexpr Register::FieldValue<decltype(pe)::Type,PeVal::v1> v1{}; } ///Slew Rate Enable enum class SreVal { v0=0x00000000, ///<Fast slew rate is configured on the corresponding pin, if the pin is configured as a digital output. v1=0x00000001, ///<Slow slew rate is configured on the corresponding pin, if the pin is configured as a digital output. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,SreVal> sre{}; namespace SreValC{ constexpr Register::FieldValue<decltype(sre)::Type,SreVal::v0> v0{}; constexpr Register::FieldValue<decltype(sre)::Type,SreVal::v1> v1{}; } ///Pin Mux Control enum class MuxVal { v000=0x00000000, ///<Pin disabled (analog). v001=0x00000001, ///<Alternative 1 (GPIO). v010=0x00000002, ///<Alternative 2 (chip-specific). v011=0x00000003, ///<Alternative 3 (chip-specific). v100=0x00000004, ///<Alternative 4 (chip-specific). v101=0x00000005, ///<Alternative 5 (chip-specific). v110=0x00000006, ///<Alternative 6 (chip-specific). v111=0x00000007, ///<Alternative 7 (chip-specific). }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,8),Register::ReadWriteAccess,MuxVal> mux{}; namespace MuxValC{ constexpr Register::FieldValue<decltype(mux)::Type,MuxVal::v000> v000{}; constexpr Register::FieldValue<decltype(mux)::Type,MuxVal::v001> v001{}; constexpr Register::FieldValue<decltype(mux)::Type,MuxVal::v010> v010{}; constexpr Register::FieldValue<decltype(mux)::Type,MuxVal::v011> v011{}; constexpr Register::FieldValue<decltype(mux)::Type,MuxVal::v100> v100{}; constexpr Register::FieldValue<decltype(mux)::Type,MuxVal::v101> v101{}; constexpr Register::FieldValue<decltype(mux)::Type,MuxVal::v110> v110{}; constexpr Register::FieldValue<decltype(mux)::Type,MuxVal::v111> v111{}; } ///Lock Register enum class LkVal { v0=0x00000000, ///<Pin Control Register fields [15:0] are not locked. v1=0x00000001, ///<Pin Control Register fields [15:0] are locked and cannot be updated until the next system reset. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,LkVal> lk{}; namespace LkValC{ constexpr Register::FieldValue<decltype(lk)::Type,LkVal::v0> v0{}; constexpr Register::FieldValue<decltype(lk)::Type,LkVal::v1> v1{}; } ///Interrupt Configuration enum class IrqcVal { v0000=0x00000000, ///<Interrupt/DMA request disabled. v0001=0x00000001, ///<DMA request on rising edge. v0010=0x00000002, ///<DMA request on falling edge. v0011=0x00000003, ///<DMA request on either edge. v1000=0x00000008, ///<Interrupt when logic zero. v1001=0x00000009, ///<Interrupt on rising edge. v1010=0x0000000a, ///<Interrupt on falling edge. v1011=0x0000000b, ///<Interrupt on either edge. v1100=0x0000000c, ///<Interrupt when logic one. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,16),Register::ReadWriteAccess,IrqcVal> irqc{}; namespace IrqcValC{ constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v0000> v0000{}; constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v0001> v0001{}; constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v0010> v0010{}; constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v0011> v0011{}; constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v1000> v1000{}; constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v1001> v1001{}; constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v1010> v1010{}; constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v1011> v1011{}; constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v1100> v1100{}; } ///Interrupt Status Flag enum class IsfVal { v0=0x00000000, ///<Configured interrupt is not detected. v1=0x00000001, ///<Configured interrupt is detected. If the pin is configured to generate a DMA request, then the corresponding flag will be cleared automatically at the completion of the requested DMA transfer. Otherwise, the flag remains set until a logic one is written to the flag. If the pin is configured for a level sensitive interrupt and the pin remains asserted, then the flag is set again immediately after it is cleared. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,IsfVal> isf{}; namespace IsfValC{ constexpr Register::FieldValue<decltype(isf)::Type,IsfVal::v0> v0{}; constexpr Register::FieldValue<decltype(isf)::Type,IsfVal::v1> v1{}; } } namespace PortcPcr2{ ///<Pin Control Register n using Addr = Register::Address<0x40048008,0xfef078f8,0x00000000,unsigned>; ///Pull Select enum class PsVal { v0=0x00000000, ///<Internal pulldown resistor is enabled on the corresponding pin, if the corresponding Port Pull Enable field is set. v1=0x00000001, ///<Internal pullup resistor is enabled on the corresponding pin, if the corresponding Port Pull Enable field is set. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,PsVal> ps{}; namespace PsValC{ constexpr Register::FieldValue<decltype(ps)::Type,PsVal::v0> v0{}; constexpr Register::FieldValue<decltype(ps)::Type,PsVal::v1> v1{}; } ///Pull Enable enum class PeVal { v0=0x00000000, ///<Internal pullup or pulldown resistor is not enabled on the corresponding pin. v1=0x00000001, ///<Internal pullup or pulldown resistor is enabled on the corresponding pin, if the pin is configured as a digital input. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,PeVal> pe{}; namespace PeValC{ constexpr Register::FieldValue<decltype(pe)::Type,PeVal::v0> v0{}; constexpr Register::FieldValue<decltype(pe)::Type,PeVal::v1> v1{}; } ///Slew Rate Enable enum class SreVal { v0=0x00000000, ///<Fast slew rate is configured on the corresponding pin, if the pin is configured as a digital output. v1=0x00000001, ///<Slow slew rate is configured on the corresponding pin, if the pin is configured as a digital output. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,SreVal> sre{}; namespace SreValC{ constexpr Register::FieldValue<decltype(sre)::Type,SreVal::v0> v0{}; constexpr Register::FieldValue<decltype(sre)::Type,SreVal::v1> v1{}; } ///Pin Mux Control enum class MuxVal { v000=0x00000000, ///<Pin disabled (analog). v001=0x00000001, ///<Alternative 1 (GPIO). v010=0x00000002, ///<Alternative 2 (chip-specific). v011=0x00000003, ///<Alternative 3 (chip-specific). v100=0x00000004, ///<Alternative 4 (chip-specific). v101=0x00000005, ///<Alternative 5 (chip-specific). v110=0x00000006, ///<Alternative 6 (chip-specific). v111=0x00000007, ///<Alternative 7 (chip-specific). }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,8),Register::ReadWriteAccess,MuxVal> mux{}; namespace MuxValC{ constexpr Register::FieldValue<decltype(mux)::Type,MuxVal::v000> v000{}; constexpr Register::FieldValue<decltype(mux)::Type,MuxVal::v001> v001{}; constexpr Register::FieldValue<decltype(mux)::Type,MuxVal::v010> v010{}; constexpr Register::FieldValue<decltype(mux)::Type,MuxVal::v011> v011{}; constexpr Register::FieldValue<decltype(mux)::Type,MuxVal::v100> v100{}; constexpr Register::FieldValue<decltype(mux)::Type,MuxVal::v101> v101{}; constexpr Register::FieldValue<decltype(mux)::Type,MuxVal::v110> v110{}; constexpr Register::FieldValue<decltype(mux)::Type,MuxVal::v111> v111{}; } ///Lock Register enum class LkVal { v0=0x00000000, ///<Pin Control Register fields [15:0] are not locked. v1=0x00000001, ///<Pin Control Register fields [15:0] are locked and cannot be updated until the next system reset. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,LkVal> lk{}; namespace LkValC{ constexpr Register::FieldValue<decltype(lk)::Type,LkVal::v0> v0{}; constexpr Register::FieldValue<decltype(lk)::Type,LkVal::v1> v1{}; } ///Interrupt Configuration enum class IrqcVal { v0000=0x00000000, ///<Interrupt/DMA request disabled. v0001=0x00000001, ///<DMA request on rising edge. v0010=0x00000002, ///<DMA request on falling edge. v0011=0x00000003, ///<DMA request on either edge. v1000=0x00000008, ///<Interrupt when logic zero. v1001=0x00000009, ///<Interrupt on rising edge. v1010=0x0000000a, ///<Interrupt on falling edge. v1011=0x0000000b, ///<Interrupt on either edge. v1100=0x0000000c, ///<Interrupt when logic one. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,16),Register::ReadWriteAccess,IrqcVal> irqc{}; namespace IrqcValC{ constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v0000> v0000{}; constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v0001> v0001{}; constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v0010> v0010{}; constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v0011> v0011{}; constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v1000> v1000{}; constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v1001> v1001{}; constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v1010> v1010{}; constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v1011> v1011{}; constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v1100> v1100{}; } ///Interrupt Status Flag enum class IsfVal { v0=0x00000000, ///<Configured interrupt is not detected. v1=0x00000001, ///<Configured interrupt is detected. If the pin is configured to generate a DMA request, then the corresponding flag will be cleared automatically at the completion of the requested DMA transfer. Otherwise, the flag remains set until a logic one is written to the flag. If the pin is configured for a level sensitive interrupt and the pin remains asserted, then the flag is set again immediately after it is cleared. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,IsfVal> isf{}; namespace IsfValC{ constexpr Register::FieldValue<decltype(isf)::Type,IsfVal::v0> v0{}; constexpr Register::FieldValue<decltype(isf)::Type,IsfVal::v1> v1{}; } } namespace PortcPcr3{ ///<Pin Control Register n using Addr = Register::Address<0x4004800c,0xfef078f8,0x00000000,unsigned>; ///Pull Select enum class PsVal { v0=0x00000000, ///<Internal pulldown resistor is enabled on the corresponding pin, if the corresponding Port Pull Enable field is set. v1=0x00000001, ///<Internal pullup resistor is enabled on the corresponding pin, if the corresponding Port Pull Enable field is set. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,PsVal> ps{}; namespace PsValC{ constexpr Register::FieldValue<decltype(ps)::Type,PsVal::v0> v0{}; constexpr Register::FieldValue<decltype(ps)::Type,PsVal::v1> v1{}; } ///Pull Enable enum class PeVal { v0=0x00000000, ///<Internal pullup or pulldown resistor is not enabled on the corresponding pin. v1=0x00000001, ///<Internal pullup or pulldown resistor is enabled on the corresponding pin, if the pin is configured as a digital input. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,PeVal> pe{}; namespace PeValC{ constexpr Register::FieldValue<decltype(pe)::Type,PeVal::v0> v0{}; constexpr Register::FieldValue<decltype(pe)::Type,PeVal::v1> v1{}; } ///Slew Rate Enable enum class SreVal { v0=0x00000000, ///<Fast slew rate is configured on the corresponding pin, if the pin is configured as a digital output. v1=0x00000001, ///<Slow slew rate is configured on the corresponding pin, if the pin is configured as a digital output. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,SreVal> sre{}; namespace SreValC{ constexpr Register::FieldValue<decltype(sre)::Type,SreVal::v0> v0{}; constexpr Register::FieldValue<decltype(sre)::Type,SreVal::v1> v1{}; } ///Pin Mux Control enum class MuxVal { v000=0x00000000, ///<Pin disabled (analog). v001=0x00000001, ///<Alternative 1 (GPIO). v010=0x00000002, ///<Alternative 2 (chip-specific). v011=0x00000003, ///<Alternative 3 (chip-specific). v100=0x00000004, ///<Alternative 4 (chip-specific). v101=0x00000005, ///<Alternative 5 (chip-specific). v110=0x00000006, ///<Alternative 6 (chip-specific). v111=0x00000007, ///<Alternative 7 (chip-specific). }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,8),Register::ReadWriteAccess,MuxVal> mux{}; namespace MuxValC{ constexpr Register::FieldValue<decltype(mux)::Type,MuxVal::v000> v000{}; constexpr Register::FieldValue<decltype(mux)::Type,MuxVal::v001> v001{}; constexpr Register::FieldValue<decltype(mux)::Type,MuxVal::v010> v010{}; constexpr Register::FieldValue<decltype(mux)::Type,MuxVal::v011> v011{}; constexpr Register::FieldValue<decltype(mux)::Type,MuxVal::v100> v100{}; constexpr Register::FieldValue<decltype(mux)::Type,MuxVal::v101> v101{}; constexpr Register::FieldValue<decltype(mux)::Type,MuxVal::v110> v110{}; constexpr Register::FieldValue<decltype(mux)::Type,MuxVal::v111> v111{}; } ///Lock Register enum class LkVal { v0=0x00000000, ///<Pin Control Register fields [15:0] are not locked. v1=0x00000001, ///<Pin Control Register fields [15:0] are locked and cannot be updated until the next system reset. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,LkVal> lk{}; namespace LkValC{ constexpr Register::FieldValue<decltype(lk)::Type,LkVal::v0> v0{}; constexpr Register::FieldValue<decltype(lk)::Type,LkVal::v1> v1{}; } ///Interrupt Configuration enum class IrqcVal { v0000=0x00000000, ///<Interrupt/DMA request disabled. v0001=0x00000001, ///<DMA request on rising edge. v0010=0x00000002, ///<DMA request on falling edge. v0011=0x00000003, ///<DMA request on either edge. v1000=0x00000008, ///<Interrupt when logic zero. v1001=0x00000009, ///<Interrupt on rising edge. v1010=0x0000000a, ///<Interrupt on falling edge. v1011=0x0000000b, ///<Interrupt on either edge. v1100=0x0000000c, ///<Interrupt when logic one. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,16),Register::ReadWriteAccess,IrqcVal> irqc{}; namespace IrqcValC{ constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v0000> v0000{}; constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v0001> v0001{}; constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v0010> v0010{}; constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v0011> v0011{}; constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v1000> v1000{}; constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v1001> v1001{}; constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v1010> v1010{}; constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v1011> v1011{}; constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v1100> v1100{}; } ///Interrupt Status Flag enum class IsfVal { v0=0x00000000, ///<Configured interrupt is not detected. v1=0x00000001, ///<Configured interrupt is detected. If the pin is configured to generate a DMA request, then the corresponding flag will be cleared automatically at the completion of the requested DMA transfer. Otherwise, the flag remains set until a logic one is written to the flag. If the pin is configured for a level sensitive interrupt and the pin remains asserted, then the flag is set again immediately after it is cleared. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,IsfVal> isf{}; namespace IsfValC{ constexpr Register::FieldValue<decltype(isf)::Type,IsfVal::v0> v0{}; constexpr Register::FieldValue<decltype(isf)::Type,IsfVal::v1> v1{}; } } namespace PortcPcr4{ ///<Pin Control Register n using Addr = Register::Address<0x40048010,0xfef078f8,0x00000000,unsigned>; ///Pull Select enum class PsVal { v0=0x00000000, ///<Internal pulldown resistor is enabled on the corresponding pin, if the corresponding Port Pull Enable field is set. v1=0x00000001, ///<Internal pullup resistor is enabled on the corresponding pin, if the corresponding Port Pull Enable field is set. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,PsVal> ps{}; namespace PsValC{ constexpr Register::FieldValue<decltype(ps)::Type,PsVal::v0> v0{}; constexpr Register::FieldValue<decltype(ps)::Type,PsVal::v1> v1{}; } ///Pull Enable enum class PeVal { v0=0x00000000, ///<Internal pullup or pulldown resistor is not enabled on the corresponding pin. v1=0x00000001, ///<Internal pullup or pulldown resistor is enabled on the corresponding pin, if the pin is configured as a digital input. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,PeVal> pe{}; namespace PeValC{ constexpr Register::FieldValue<decltype(pe)::Type,PeVal::v0> v0{}; constexpr Register::FieldValue<decltype(pe)::Type,PeVal::v1> v1{}; } ///Slew Rate Enable enum class SreVal { v0=0x00000000, ///<Fast slew rate is configured on the corresponding pin, if the pin is configured as a digital output. v1=0x00000001, ///<Slow slew rate is configured on the corresponding pin, if the pin is configured as a digital output. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,SreVal> sre{}; namespace SreValC{ constexpr Register::FieldValue<decltype(sre)::Type,SreVal::v0> v0{}; constexpr Register::FieldValue<decltype(sre)::Type,SreVal::v1> v1{}; } ///Pin Mux Control enum class MuxVal { v000=0x00000000, ///<Pin disabled (analog). v001=0x00000001, ///<Alternative 1 (GPIO). v010=0x00000002, ///<Alternative 2 (chip-specific). v011=0x00000003, ///<Alternative 3 (chip-specific). v100=0x00000004, ///<Alternative 4 (chip-specific). v101=0x00000005, ///<Alternative 5 (chip-specific). v110=0x00000006, ///<Alternative 6 (chip-specific). v111=0x00000007, ///<Alternative 7 (chip-specific). }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,8),Register::ReadWriteAccess,MuxVal> mux{}; namespace MuxValC{ constexpr Register::FieldValue<decltype(mux)::Type,MuxVal::v000> v000{}; constexpr Register::FieldValue<decltype(mux)::Type,MuxVal::v001> v001{}; constexpr Register::FieldValue<decltype(mux)::Type,MuxVal::v010> v010{}; constexpr Register::FieldValue<decltype(mux)::Type,MuxVal::v011> v011{}; constexpr Register::FieldValue<decltype(mux)::Type,MuxVal::v100> v100{}; constexpr Register::FieldValue<decltype(mux)::Type,MuxVal::v101> v101{}; constexpr Register::FieldValue<decltype(mux)::Type,MuxVal::v110> v110{}; constexpr Register::FieldValue<decltype(mux)::Type,MuxVal::v111> v111{}; } ///Lock Register enum class LkVal { v0=0x00000000, ///<Pin Control Register fields [15:0] are not locked. v1=0x00000001, ///<Pin Control Register fields [15:0] are locked and cannot be updated until the next system reset. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,LkVal> lk{}; namespace LkValC{ constexpr Register::FieldValue<decltype(lk)::Type,LkVal::v0> v0{}; constexpr Register::FieldValue<decltype(lk)::Type,LkVal::v1> v1{}; } ///Interrupt Configuration enum class IrqcVal { v0000=0x00000000, ///<Interrupt/DMA request disabled. v0001=0x00000001, ///<DMA request on rising edge. v0010=0x00000002, ///<DMA request on falling edge. v0011=0x00000003, ///<DMA request on either edge. v1000=0x00000008, ///<Interrupt when logic zero. v1001=0x00000009, ///<Interrupt on rising edge. v1010=0x0000000a, ///<Interrupt on falling edge. v1011=0x0000000b, ///<Interrupt on either edge. v1100=0x0000000c, ///<Interrupt when logic one. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,16),Register::ReadWriteAccess,IrqcVal> irqc{}; namespace IrqcValC{ constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v0000> v0000{}; constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v0001> v0001{}; constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v0010> v0010{}; constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v0011> v0011{}; constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v1000> v1000{}; constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v1001> v1001{}; constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v1010> v1010{}; constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v1011> v1011{}; constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v1100> v1100{}; } ///Interrupt Status Flag enum class IsfVal { v0=0x00000000, ///<Configured interrupt is not detected. v1=0x00000001, ///<Configured interrupt is detected. If the pin is configured to generate a DMA request, then the corresponding flag will be cleared automatically at the completion of the requested DMA transfer. Otherwise, the flag remains set until a logic one is written to the flag. If the pin is configured for a level sensitive interrupt and the pin remains asserted, then the flag is set again immediately after it is cleared. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,IsfVal> isf{}; namespace IsfValC{ constexpr Register::FieldValue<decltype(isf)::Type,IsfVal::v0> v0{}; constexpr Register::FieldValue<decltype(isf)::Type,IsfVal::v1> v1{}; } } namespace PortcPcr5{ ///<Pin Control Register n using Addr = Register::Address<0x40048014,0xfef078f8,0x00000000,unsigned>; ///Pull Select enum class PsVal { v0=0x00000000, ///<Internal pulldown resistor is enabled on the corresponding pin, if the corresponding Port Pull Enable field is set. v1=0x00000001, ///<Internal pullup resistor is enabled on the corresponding pin, if the corresponding Port Pull Enable field is set. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,PsVal> ps{}; namespace PsValC{ constexpr Register::FieldValue<decltype(ps)::Type,PsVal::v0> v0{}; constexpr Register::FieldValue<decltype(ps)::Type,PsVal::v1> v1{}; } ///Pull Enable enum class PeVal { v0=0x00000000, ///<Internal pullup or pulldown resistor is not enabled on the corresponding pin. v1=0x00000001, ///<Internal pullup or pulldown resistor is enabled on the corresponding pin, if the pin is configured as a digital input. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,PeVal> pe{}; namespace PeValC{ constexpr Register::FieldValue<decltype(pe)::Type,PeVal::v0> v0{}; constexpr Register::FieldValue<decltype(pe)::Type,PeVal::v1> v1{}; } ///Slew Rate Enable enum class SreVal { v0=0x00000000, ///<Fast slew rate is configured on the corresponding pin, if the pin is configured as a digital output. v1=0x00000001, ///<Slow slew rate is configured on the corresponding pin, if the pin is configured as a digital output. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,SreVal> sre{}; namespace SreValC{ constexpr Register::FieldValue<decltype(sre)::Type,SreVal::v0> v0{}; constexpr Register::FieldValue<decltype(sre)::Type,SreVal::v1> v1{}; } ///Pin Mux Control enum class MuxVal { v000=0x00000000, ///<Pin disabled (analog). v001=0x00000001, ///<Alternative 1 (GPIO). v010=0x00000002, ///<Alternative 2 (chip-specific). v011=0x00000003, ///<Alternative 3 (chip-specific). v100=0x00000004, ///<Alternative 4 (chip-specific). v101=0x00000005, ///<Alternative 5 (chip-specific). v110=0x00000006, ///<Alternative 6 (chip-specific). v111=0x00000007, ///<Alternative 7 (chip-specific). }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,8),Register::ReadWriteAccess,MuxVal> mux{}; namespace MuxValC{ constexpr Register::FieldValue<decltype(mux)::Type,MuxVal::v000> v000{}; constexpr Register::FieldValue<decltype(mux)::Type,MuxVal::v001> v001{}; constexpr Register::FieldValue<decltype(mux)::Type,MuxVal::v010> v010{}; constexpr Register::FieldValue<decltype(mux)::Type,MuxVal::v011> v011{}; constexpr Register::FieldValue<decltype(mux)::Type,MuxVal::v100> v100{}; constexpr Register::FieldValue<decltype(mux)::Type,MuxVal::v101> v101{}; constexpr Register::FieldValue<decltype(mux)::Type,MuxVal::v110> v110{}; constexpr Register::FieldValue<decltype(mux)::Type,MuxVal::v111> v111{}; } ///Lock Register enum class LkVal { v0=0x00000000, ///<Pin Control Register fields [15:0] are not locked. v1=0x00000001, ///<Pin Control Register fields [15:0] are locked and cannot be updated until the next system reset. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,LkVal> lk{}; namespace LkValC{ constexpr Register::FieldValue<decltype(lk)::Type,LkVal::v0> v0{}; constexpr Register::FieldValue<decltype(lk)::Type,LkVal::v1> v1{}; } ///Interrupt Configuration enum class IrqcVal { v0000=0x00000000, ///<Interrupt/DMA request disabled. v0001=0x00000001, ///<DMA request on rising edge. v0010=0x00000002, ///<DMA request on falling edge. v0011=0x00000003, ///<DMA request on either edge. v1000=0x00000008, ///<Interrupt when logic zero. v1001=0x00000009, ///<Interrupt on rising edge. v1010=0x0000000a, ///<Interrupt on falling edge. v1011=0x0000000b, ///<Interrupt on either edge. v1100=0x0000000c, ///<Interrupt when logic one. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,16),Register::ReadWriteAccess,IrqcVal> irqc{}; namespace IrqcValC{ constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v0000> v0000{}; constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v0001> v0001{}; constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v0010> v0010{}; constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v0011> v0011{}; constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v1000> v1000{}; constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v1001> v1001{}; constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v1010> v1010{}; constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v1011> v1011{}; constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v1100> v1100{}; } ///Interrupt Status Flag enum class IsfVal { v0=0x00000000, ///<Configured interrupt is not detected. v1=0x00000001, ///<Configured interrupt is detected. If the pin is configured to generate a DMA request, then the corresponding flag will be cleared automatically at the completion of the requested DMA transfer. Otherwise, the flag remains set until a logic one is written to the flag. If the pin is configured for a level sensitive interrupt and the pin remains asserted, then the flag is set again immediately after it is cleared. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,IsfVal> isf{}; namespace IsfValC{ constexpr Register::FieldValue<decltype(isf)::Type,IsfVal::v0> v0{}; constexpr Register::FieldValue<decltype(isf)::Type,IsfVal::v1> v1{}; } } namespace PortcPcr6{ ///<Pin Control Register n using Addr = Register::Address<0x40048018,0xfef078f8,0x00000000,unsigned>; ///Pull Select enum class PsVal { v0=0x00000000, ///<Internal pulldown resistor is enabled on the corresponding pin, if the corresponding Port Pull Enable field is set. v1=0x00000001, ///<Internal pullup resistor is enabled on the corresponding pin, if the corresponding Port Pull Enable field is set. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,PsVal> ps{}; namespace PsValC{ constexpr Register::FieldValue<decltype(ps)::Type,PsVal::v0> v0{}; constexpr Register::FieldValue<decltype(ps)::Type,PsVal::v1> v1{}; } ///Pull Enable enum class PeVal { v0=0x00000000, ///<Internal pullup or pulldown resistor is not enabled on the corresponding pin. v1=0x00000001, ///<Internal pullup or pulldown resistor is enabled on the corresponding pin, if the pin is configured as a digital input. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,PeVal> pe{}; namespace PeValC{ constexpr Register::FieldValue<decltype(pe)::Type,PeVal::v0> v0{}; constexpr Register::FieldValue<decltype(pe)::Type,PeVal::v1> v1{}; } ///Slew Rate Enable enum class SreVal { v0=0x00000000, ///<Fast slew rate is configured on the corresponding pin, if the pin is configured as a digital output. v1=0x00000001, ///<Slow slew rate is configured on the corresponding pin, if the pin is configured as a digital output. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,SreVal> sre{}; namespace SreValC{ constexpr Register::FieldValue<decltype(sre)::Type,SreVal::v0> v0{}; constexpr Register::FieldValue<decltype(sre)::Type,SreVal::v1> v1{}; } ///Pin Mux Control enum class MuxVal { v000=0x00000000, ///<Pin disabled (analog). v001=0x00000001, ///<Alternative 1 (GPIO). v010=0x00000002, ///<Alternative 2 (chip-specific). v011=0x00000003, ///<Alternative 3 (chip-specific). v100=0x00000004, ///<Alternative 4 (chip-specific). v101=0x00000005, ///<Alternative 5 (chip-specific). v110=0x00000006, ///<Alternative 6 (chip-specific). v111=0x00000007, ///<Alternative 7 (chip-specific). }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,8),Register::ReadWriteAccess,MuxVal> mux{}; namespace MuxValC{ constexpr Register::FieldValue<decltype(mux)::Type,MuxVal::v000> v000{}; constexpr Register::FieldValue<decltype(mux)::Type,MuxVal::v001> v001{}; constexpr Register::FieldValue<decltype(mux)::Type,MuxVal::v010> v010{}; constexpr Register::FieldValue<decltype(mux)::Type,MuxVal::v011> v011{}; constexpr Register::FieldValue<decltype(mux)::Type,MuxVal::v100> v100{}; constexpr Register::FieldValue<decltype(mux)::Type,MuxVal::v101> v101{}; constexpr Register::FieldValue<decltype(mux)::Type,MuxVal::v110> v110{}; constexpr Register::FieldValue<decltype(mux)::Type,MuxVal::v111> v111{}; } ///Lock Register enum class LkVal { v0=0x00000000, ///<Pin Control Register fields [15:0] are not locked. v1=0x00000001, ///<Pin Control Register fields [15:0] are locked and cannot be updated until the next system reset. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,LkVal> lk{}; namespace LkValC{ constexpr Register::FieldValue<decltype(lk)::Type,LkVal::v0> v0{}; constexpr Register::FieldValue<decltype(lk)::Type,LkVal::v1> v1{}; } ///Interrupt Configuration enum class IrqcVal { v0000=0x00000000, ///<Interrupt/DMA request disabled. v0001=0x00000001, ///<DMA request on rising edge. v0010=0x00000002, ///<DMA request on falling edge. v0011=0x00000003, ///<DMA request on either edge. v1000=0x00000008, ///<Interrupt when logic zero. v1001=0x00000009, ///<Interrupt on rising edge. v1010=0x0000000a, ///<Interrupt on falling edge. v1011=0x0000000b, ///<Interrupt on either edge. v1100=0x0000000c, ///<Interrupt when logic one. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,16),Register::ReadWriteAccess,IrqcVal> irqc{}; namespace IrqcValC{ constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v0000> v0000{}; constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v0001> v0001{}; constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v0010> v0010{}; constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v0011> v0011{}; constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v1000> v1000{}; constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v1001> v1001{}; constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v1010> v1010{}; constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v1011> v1011{}; constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v1100> v1100{}; } ///Interrupt Status Flag enum class IsfVal { v0=0x00000000, ///<Configured interrupt is not detected. v1=0x00000001, ///<Configured interrupt is detected. If the pin is configured to generate a DMA request, then the corresponding flag will be cleared automatically at the completion of the requested DMA transfer. Otherwise, the flag remains set until a logic one is written to the flag. If the pin is configured for a level sensitive interrupt and the pin remains asserted, then the flag is set again immediately after it is cleared. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,IsfVal> isf{}; namespace IsfValC{ constexpr Register::FieldValue<decltype(isf)::Type,IsfVal::v0> v0{}; constexpr Register::FieldValue<decltype(isf)::Type,IsfVal::v1> v1{}; } } namespace PortcPcr7{ ///<Pin Control Register n using Addr = Register::Address<0x4004801c,0xfef078f8,0x00000000,unsigned>; ///Pull Select enum class PsVal { v0=0x00000000, ///<Internal pulldown resistor is enabled on the corresponding pin, if the corresponding Port Pull Enable field is set. v1=0x00000001, ///<Internal pullup resistor is enabled on the corresponding pin, if the corresponding Port Pull Enable field is set. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(0,0),Register::ReadWriteAccess,PsVal> ps{}; namespace PsValC{ constexpr Register::FieldValue<decltype(ps)::Type,PsVal::v0> v0{}; constexpr Register::FieldValue<decltype(ps)::Type,PsVal::v1> v1{}; } ///Pull Enable enum class PeVal { v0=0x00000000, ///<Internal pullup or pulldown resistor is not enabled on the corresponding pin. v1=0x00000001, ///<Internal pullup or pulldown resistor is enabled on the corresponding pin, if the pin is configured as a digital input. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(1,1),Register::ReadWriteAccess,PeVal> pe{}; namespace PeValC{ constexpr Register::FieldValue<decltype(pe)::Type,PeVal::v0> v0{}; constexpr Register::FieldValue<decltype(pe)::Type,PeVal::v1> v1{}; } ///Slew Rate Enable enum class SreVal { v0=0x00000000, ///<Fast slew rate is configured on the corresponding pin, if the pin is configured as a digital output. v1=0x00000001, ///<Slow slew rate is configured on the corresponding pin, if the pin is configured as a digital output. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(2,2),Register::ReadWriteAccess,SreVal> sre{}; namespace SreValC{ constexpr Register::FieldValue<decltype(sre)::Type,SreVal::v0> v0{}; constexpr Register::FieldValue<decltype(sre)::Type,SreVal::v1> v1{}; } ///Pin Mux Control enum class MuxVal { v000=0x00000000, ///<Pin disabled (analog). v001=0x00000001, ///<Alternative 1 (GPIO). v010=0x00000002, ///<Alternative 2 (chip-specific). v011=0x00000003, ///<Alternative 3 (chip-specific). v100=0x00000004, ///<Alternative 4 (chip-specific). v101=0x00000005, ///<Alternative 5 (chip-specific). v110=0x00000006, ///<Alternative 6 (chip-specific). v111=0x00000007, ///<Alternative 7 (chip-specific). }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(10,8),Register::ReadWriteAccess,MuxVal> mux{}; namespace MuxValC{ constexpr Register::FieldValue<decltype(mux)::Type,MuxVal::v000> v000{}; constexpr Register::FieldValue<decltype(mux)::Type,MuxVal::v001> v001{}; constexpr Register::FieldValue<decltype(mux)::Type,MuxVal::v010> v010{}; constexpr Register::FieldValue<decltype(mux)::Type,MuxVal::v011> v011{}; constexpr Register::FieldValue<decltype(mux)::Type,MuxVal::v100> v100{}; constexpr Register::FieldValue<decltype(mux)::Type,MuxVal::v101> v101{}; constexpr Register::FieldValue<decltype(mux)::Type,MuxVal::v110> v110{}; constexpr Register::FieldValue<decltype(mux)::Type,MuxVal::v111> v111{}; } ///Lock Register enum class LkVal { v0=0x00000000, ///<Pin Control Register fields [15:0] are not locked. v1=0x00000001, ///<Pin Control Register fields [15:0] are locked and cannot be updated until the next system reset. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(15,15),Register::ReadWriteAccess,LkVal> lk{}; namespace LkValC{ constexpr Register::FieldValue<decltype(lk)::Type,LkVal::v0> v0{}; constexpr Register::FieldValue<decltype(lk)::Type,LkVal::v1> v1{}; } ///Interrupt Configuration enum class IrqcVal { v0000=0x00000000, ///<Interrupt/DMA request disabled. v0001=0x00000001, ///<DMA request on rising edge. v0010=0x00000002, ///<DMA request on falling edge. v0011=0x00000003, ///<DMA request on either edge. v1000=0x00000008, ///<Interrupt when logic zero. v1001=0x00000009, ///<Interrupt on rising edge. v1010=0x0000000a, ///<Interrupt on falling edge. v1011=0x0000000b, ///<Interrupt on either edge. v1100=0x0000000c, ///<Interrupt when logic one. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(19,16),Register::ReadWriteAccess,IrqcVal> irqc{}; namespace IrqcValC{ constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v0000> v0000{}; constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v0001> v0001{}; constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v0010> v0010{}; constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v0011> v0011{}; constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v1000> v1000{}; constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v1001> v1001{}; constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v1010> v1010{}; constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v1011> v1011{}; constexpr Register::FieldValue<decltype(irqc)::Type,IrqcVal::v1100> v1100{}; } ///Interrupt Status Flag enum class IsfVal { v0=0x00000000, ///<Configured interrupt is not detected. v1=0x00000001, ///<Configured interrupt is detected. If the pin is configured to generate a DMA request, then the corresponding flag will be cleared automatically at the completion of the requested DMA transfer. Otherwise, the flag remains set until a logic one is written to the flag. If the pin is configured for a level sensitive interrupt and the pin remains asserted, then the flag is set again immediately after it is cleared. }; constexpr Register::FieldLocation<Addr,Register::maskFromRange(24,24),Register::ReadWriteAccess,IsfVal> isf{}; namespace IsfValC{ constexpr Register::FieldValue<decltype(isf)::Type,IsfVal::v0> v0{}; constexpr Register::FieldValue<decltype(isf)::Type,IsfVal::v1> v1{}; } } }
[ "holmes.odin@gmail.com" ]
holmes.odin@gmail.com
4a15aef41a1aad55094cc0b530cfaf5fde861e11
c9652f71a8f295607e84c67332ca5717571efa3a
/cc/random_lines/main.cc
9ef3777e970fa5c7783cc44316c6b102a19cc9ac
[]
no_license
valhakis/master
f34d46a7de39bf1627ea1dd15556efda4f756201
2ae80f86fef749abcac85782c542a6cd8f2e7d77
refs/heads/master
2021-01-20T13:37:31.348837
2017-11-18T12:43:01
2017-11-18T12:43:01
90,505,495
0
0
null
null
null
null
UTF-8
C++
false
false
1,489
cc
#include <GLFW/glfw3.h> #include <time.h> #include <stdio.h> #include <math.h> // make 100 random lines // make one line // random number between -1 and 1 static void keyboard(GLFWwindow* window, int key, int scancode, int action, int mods) { if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) { glfwSetWindowShouldClose(window, true); } } int main(void) { srand(time(NULL)); GLFWwindow* window; /* Initialize the library */ if (!glfwInit()) return -1; glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); /* Create a windowed mode window and its OpenGL context */ window = glfwCreateWindow(640, 480, "Hello World", NULL, NULL); if (!window) { glfwTerminate(); return -1; } /* Make the window's context current */ glfwMakeContextCurrent(window); glfwSetKeyCallback(window, keyboard); /* Loop until the user closes the window */ while (!glfwWindowShouldClose(window)) { /* Render here */ glClear(GL_COLOR_BUFFER_BIT); float x1 = ((float)(rand() % 200) - 100) / 100.0f; float y1 = ((float)(rand() % 200) - 100) / 100.0f; float x2 = ((float)(rand() % 200) - 100) / 100.0f; float y2 = ((float)(rand() % 200) - 100) / 100.0f; /* draws the circle */ glBegin(GL_LINES); glVertex3f(x1, y1, 0.0f); glVertex3f(x2, y2, 0.0f); glEnd(); /* Swap front and back buffers */ glfwSwapBuffers(window); /* Poll for and process events */ glfwPollEvents(); } glfwTerminate(); return 0; }
[ "william.valhakis@gmail.com" ]
william.valhakis@gmail.com
59aa6ed84ab0f484c390b1df1bb134793cc853f3
5e8d200078e64b97e3bbd1e61f83cb5bae99ab6e
/main/source/src/protocols/task_operations/RestrictIdentitiesOperation.hh
e05131f736e1c51df2dae8d96dc8ca9838aed011
[]
no_license
MedicaicloudLink/Rosetta
3ee2d79d48b31bd8ca898036ad32fe910c9a7a28
01affdf77abb773ed375b83cdbbf58439edd8719
refs/heads/master
2020-12-07T17:52:01.350906
2020-01-10T08:24:09
2020-01-10T08:24:09
232,757,729
2
6
null
null
null
null
UTF-8
C++
false
false
2,700
hh
// -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*- // vi: set ts=2 noet: // // (c) Copyright Rosetta Commons Member Institutions. // (c) This file is part of the Rosetta software suite and is made available under license. // (c) The Rosetta software is developed by the contributing members of the Rosetta Commons. // (c) For more information, see http://www.rosettacommons.org. Questions about this can be // (c) addressed to University of Washington CoMotion, email: license@uw.edu. /// @file devel/matdes/RestrictIdentitiesOperation.hh /// @brief TaskOperation class that restricts a vector of Size defined residues to repacking /// when parsed, it takes in a string and splits by "," /// @author Neil King (neilking@uw.edu) #ifndef INCLUDED_protocols_task_operations_RestrictIdentitiesOperation_hh #define INCLUDED_protocols_task_operations_RestrictIdentitiesOperation_hh // Unit Headers #include <protocols/task_operations/RestrictIdentitiesOperation.fwd.hh> #include <protocols/task_operations/RestrictIdentitiesOperationCreator.hh> #include <core/pack/task/operation/TaskOperation.hh> // Project Headers #include <core/pose/Pose.fwd.hh> #include <core/pack/task/PackerTask.fwd.hh> #include <utility/tag/Tag.fwd.hh> #include <utility/tag/XMLSchemaGeneration.fwd.hh> // Utility Headers #include <core/types.hh> #include <utility/vector1.hh> // C++ Headers #include <string> namespace protocols { namespace task_operations { /// @details this class is a TaskOperation to prevent repacking of residues not near an interface. class RestrictIdentitiesOperation : public core::pack::task::operation::TaskOperation { public: RestrictIdentitiesOperation(); RestrictIdentitiesOperation( utility::vector1 < std::string > const & identities, bool prevent_repacking ); virtual core::pack::task::operation::TaskOperationOP clone() const; virtual ~RestrictIdentitiesOperation(); // @brief getters utility::vector1< std::string > identities() const; bool prevent_repacking() const; // @brief setters void identities( utility::vector1 < std::string > residues_vec ); void prevent_repacking( bool const prevent_repacking); virtual void apply( core::pose::Pose const &, core::pack::task::PackerTask & ) const; virtual void parse_tag( TagCOP, DataMap & ); static void provide_xml_schema( utility::tag::XMLSchemaDefinition & xsd ); static std::string keyname() { return "RestrictIdentities"; } private: std::string unparsed_identities_; utility::vector1 < std::string > identities_; bool prevent_repacking_; }; } //namespace task_operations } //namespace protocols #endif // INCLUDED_devel_matdes_RestrictIdentitiesOperation_HH
[ "36790013+MedicaicloudLink@users.noreply.github.com" ]
36790013+MedicaicloudLink@users.noreply.github.com
7221fe798fef358a36b37f8b1f1591ad75e439bc
78918391a7809832dc486f68b90455c72e95cdda
/boost_lib/boost/hof/decorate.hpp
dc182367cc6741f54a2ff9758670538c5e40005b
[ "MIT" ]
permissive
kyx0r/FA_Patcher
50681e3e8bb04745bba44a71b5fd04e1004c3845
3f539686955249004b4483001a9e49e63c4856ff
refs/heads/master
2022-03-28T10:03:28.419352
2020-01-02T09:16:30
2020-01-02T09:16:30
141,066,396
2
0
null
null
null
null
UTF-8
C++
false
false
6,010
hpp
/*============================================================================= Copyright (c) 2015 Paul Fultz II decorate.h Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) ==============================================================================*/ #ifndef BOOST_HOF_GUARD_DECORATE_H #define BOOST_HOF_GUARD_DECORATE_H /// decorate /// ======== /// /// Description /// ----------- /// /// The `decorate` function adaptor helps create simple function decorators. /// /// A function adaptor takes a function and returns a new functions whereas a /// decorator takes some parameters and returns a function adaptor. The /// `decorate` function adaptor will return a decorator that returns a /// function adaptor. Eventually, it will invoke the function with the user- /// provided parameter and function. /// /// Synopsis /// -------- /// /// template<class F> /// constexpr decorate_adaptor<F> decorate(F f); /// /// Semantics /// --------- /// /// assert(decorate(f)(x)(g)(xs...) == f(x, g, xs...)); /// /// Requirements /// ------------ /// /// F must be: /// /// * [ConstInvocable](ConstInvocable) /// * MoveConstructible /// /// Example /// ------- /// /// #include <boost/hof.hpp> /// #include <cassert> /// #include <iostream> /// #include <string> /// using namespace boost::hof; /// /// struct logger_f /// { /// template<class F, class... Ts> /// auto operator()(const std::string& message, F&& f, Ts&&... xs) const /// -> decltype(f(std::forward<Ts>(xs)...)) /// { /// // Message to print out when the function is called /// std::cout << message << std::endl; /// // Call the function /// return f(std::forward<Ts>(xs)...); /// } /// }; /// // The logger decorator /// BOOST_HOF_STATIC_FUNCTION(logger) = boost::hof::decorate(logger_f()); /// /// struct sum_f /// { /// template<class T, class U> /// T operator()(T x, U y) const /// { /// return x+y; /// } /// }; /// /// BOOST_HOF_STATIC_FUNCTION(sum) = sum_f(); /// int main() { /// // Use the logger decorator to print "Calling sum" when the function is called /// assert(3 == logger("Calling sum")(sum)(1, 2)); /// } /// #include <boost/hof/reveal.hpp> #include <boost/hof/detail/delegate.hpp> #include <boost/hof/detail/move.hpp> #include <boost/hof/detail/make.hpp> #include <boost/hof/detail/callable_base.hpp> #include <boost/hof/detail/static_const_var.hpp> #include <boost/hof/detail/compressed_pair.hpp> namespace boost { namespace hof { namespace detail { template<class D, class T, class F> struct decorator_invoke // : compressed_pair<compressed_pair<F, T>, D> : compressed_pair<compressed_pair<D, T>, F> { // typedef compressed_pair<F, T> base; typedef compressed_pair<compressed_pair<D, T>, F> base; BOOST_HOF_INHERIT_CONSTRUCTOR(decorator_invoke, base) template<class... Ts> constexpr const compressed_pair<D, T>& get_pair(Ts&&... xs) const noexcept { return this->first(xs...); } template<class... Ts> constexpr const F& base_function(Ts&&... xs) const noexcept { return this->second(xs...); } template<class... Ts> constexpr const D& get_decorator(Ts&&... xs) const noexcept { return this->get_pair(xs...).first(xs...); } template<class... Ts> constexpr const T& get_data(Ts&&... xs) const noexcept { return this->get_pair(xs...).second(xs...); } BOOST_HOF_RETURNS_CLASS(decorator_invoke); struct decorator_invoke_failure { template<class Failure> struct apply { template<class... Ts> struct of : Failure::template of<const T&, const F&, Ts...> {}; }; }; struct failure : failure_map<decorator_invoke_failure, D> {}; template<class... Ts> constexpr BOOST_HOF_SFINAE_RESULT(const D&, id_<const T&>, id_<const F&>, id_<Ts>...) operator()(Ts&&... xs) const BOOST_HOF_SFINAE_RETURNS ( BOOST_HOF_MANGLE_CAST(const D&)(BOOST_HOF_CONST_THIS->get_decorator(xs...))( BOOST_HOF_MANGLE_CAST(const T&)(BOOST_HOF_CONST_THIS->get_data(xs...)), BOOST_HOF_MANGLE_CAST(const F&)(BOOST_HOF_CONST_THIS->base_function(xs...)), BOOST_HOF_FORWARD(Ts)(xs)... ) ); }; template<class D, class T> struct decoration : compressed_pair<D, T> { typedef compressed_pair<D, T> base; BOOST_HOF_INHERIT_CONSTRUCTOR(decoration, base) template<class... Ts> constexpr const D& get_decorator(Ts&&... xs) const noexcept { return this->first(xs...); } template<class... Ts> constexpr const T& get_data(Ts&&... xs) const noexcept { return this->second(xs...); } template<class F> constexpr decorator_invoke<D, T, detail::callable_base<F>> operator()(F f) const BOOST_HOF_NOEXCEPT(BOOST_HOF_IS_NOTHROW_CONSTRUCTIBLE(decorator_invoke<D, T, detail::callable_base<F>>, compressed_pair<D, T>, detail::callable_base<F>&&)) { return decorator_invoke<D, T, detail::callable_base<F>>( *this, static_cast<detail::callable_base<F>&&>(f) ); } }; } template<class F> struct decorate_adaptor : detail::callable_base<F> { typedef decorate_adaptor fit_rewritable1_tag; typedef detail::callable_base<F> base; BOOST_HOF_INHERIT_CONSTRUCTOR(decorate_adaptor, detail::callable_base<F>) template<class... Ts> constexpr const base& base_function(Ts&&... xs) const noexcept { return boost::hof::always_ref(*this)(xs...); } // TODO: Add predicate for constraints template<class T> constexpr detail::decoration<base, T> operator()(T x) const BOOST_HOF_NOEXCEPT(BOOST_HOF_IS_NOTHROW_CONSTRUCTIBLE(base, const base&) && BOOST_HOF_IS_NOTHROW_CONSTRUCTIBLE(T, T&&)) { return detail::decoration<base, T>(this->base_function(x), static_cast<T&&>(x)); } }; BOOST_HOF_DECLARE_STATIC_VAR(decorate, detail::make<decorate_adaptor>); } } // namespace boost::hof #endif
[ "k.melekhin@gmail.com" ]
k.melekhin@gmail.com
d32d479b2b22a4272ea758937f28cfb2c3399956
78060487b80999f4445bf8ba33c55435b9c57e13
/include/LogManager.h
182cf8f54750afda9f5604a5d2201497af70a754
[]
no_license
Inphinitii/TyrEngine
bae171835bb7712ea35321eed76ca529a3ab2dd5
122ee08554ae311017522e88dafe1d4baf27e92b
refs/heads/master
2016-08-12T21:10:35.825638
2015-10-30T22:15:35
2015-10-30T22:15:35
45,278,497
1
0
null
null
null
null
UTF-8
C++
false
false
707
h
#ifndef LOGMANAGER_H #define LOGMANAGER_H #include <stdio.h> #include <string> #pragma clang diagnostic ignored "-Wc++98-compat" //TODO INCLUDE TIMESTAMPS class Log { public: enum PRIORITY { URGENT, WARNING, SUCCESS, INFO}; const char* PriorityString[4] = {"URGENT", "WARNING", "SUCCESS", "INFO"}; bool Open(const char* _mode); bool Write(std::string _toWrite, PRIORITY _type); bool Close(); virtual ~Log(); Log(std::string _fileName); private: FILE* m_file; std::string m_fileName; std::string m_logDirectory = "./Logs/"; std::string m_pathName; }; class LogManager { public: LogManager(); ~LogManager(); protected: private: }; #endif // LOGMANAGER_H
[ "tremazki@hotmail.com" ]
tremazki@hotmail.com
398e07c85341abb0c4d5c3fc8ad24ef5ecc2f802
30a77bd87fcaef83692fa7f40f737c73072cdcbf
/includes/input/reader.h
e15567062bce572454d0f9edf15548dc3e6e9953
[]
no_license
lgarciaag89/tomocomd_mpi
930ef179966b207d506b34cfe0fbd5dc92bb06f9
03f207ad6f4c9eb99bb0f1a77187a59b02b0454d
refs/heads/master
2020-04-11T01:15:08.272154
2018-12-17T22:02:25
2018-12-17T22:02:25
161,408,138
0
0
null
null
null
null
UTF-8
C++
false
false
853
h
// // Created by potter on 2/12/18. // #ifndef TOMOCOMD_MPI_READER_H #define TOMOCOMD_MPI_READER_H #endif //TOMOCOMD_MPI_READER_H #include <iostream> #include <string> #include <vector> #include <fstream> #include <cstdio> #include <cstring> #include <stdexcept> #include <algorithm> #include <boost/filesystem.hpp> #include <openbabel/obconversion.h> #include <openbabel/mol.h> #define MOLS_FOLDER "mols" #define SDFS_FOLDER "sdfs" #define PROJECTS_FOLDER "projects" using namespace OpenBabel; class Reader{ private: std::string basedir; std::vector<std::string> sdfs; std::vector<std::string> mols; std::vector<std::string> projects; void split_sdfs(); void split_sdfs(std::string file_sdf); public: Reader(std::string base); void read_mols(); void read_sdfs(); void read_project(); void show(); };
[ "lgarciaag89@gmail.com" ]
lgarciaag89@gmail.com
99bb2301885ac681c5efeb100c5dd0529be687d4
4be99d76023f6f07f8b4387fd52d673e366c281d
/hiho/1494.cpp
72c993d444f53f9e757d0a48ce4273dce6ba4ccc
[]
no_license
allisterke/cpp-training-lab
8298f5a9af9b0f496f124fe8e2feb55ca9603e2f
b83142b3efcc8cf57b0282dc2a1d89dd8ee9b156
refs/heads/master
2021-01-21T16:00:17.138044
2017-11-09T07:23:13
2017-11-09T07:23:13
91,868,138
0
0
null
null
null
null
UTF-8
C++
false
false
953
cpp
#include <bits/stdc++.h> using namespace std; class Solution { private: unordered_map<int, int> edges; int levels; public: void clear() { levels = 0; edges.clear(); } void addBricks(vector<int> &bricks) { ++ levels; int offset = 0; for(int i = 0; i+1 < bricks.size(); ++ i) { offset += bricks[i]; ++ edges[offset]; } } int bestPos() { int maxd = 0; for(auto it = edges.begin(); it != edges.end(); ++ it) { maxd = max(maxd, it->second); } return levels - maxd; } }; int main() { Solution s; int N, C; vector<int> bricks; cin >> N; s.clear(); for(int i = 0; i < N; ++ i) { cin >> C; bricks.resize(C); for(int j = 0; j < C; ++ j) { cin >> bricks[j]; } s.addBricks(bricks); } cout << s.bestPos() << endl; return 0; }
[ "allisterke@gmail.com" ]
allisterke@gmail.com
e9ccdb88d7b8fd98c05bbbbb957a8746a64058fb
b3ff614159b3e0abedc7b6e9792b86145639994b
/general-techniques/binary-search/binary-search-on-solution/dinner_party.cpp
0c3f09cdc977e3a06bd6083a045a0d0ff98b265d
[]
no_license
s-nandi/contest-problems
828b66e1ce4c9319033fdc78140dd2c240f40cd4
d4caa7f19bf51794e4458f5a61c50f23594d50a7
refs/heads/master
2023-05-01T06:17:01.181487
2023-04-26T00:42:52
2023-04-26T00:42:52
113,280,133
0
0
null
2018-02-09T18:44:26
2017-12-06T06:51:11
C++
UTF-8
C++
false
false
1,742
cpp
// binary search on answer (not obvious), recover array given circular prefix sums // https://dmoj.ca/problem/dmopc19c7p2 #include <bits/stdc++.h> using namespace std; using ll = long long; using ld = long double; using vi = vector<int>; #define rep(i, a, b) for(auto i = (a); i < (b); ++i) #define trav(a, x) for(auto& a : x) #define all(x) begin(x), end(x) #define sz(x) (int)(x).size() #define PB push_back struct edge{int to;}; using graph = vector<vector<edge>>; int next(int i, int n){return i + 1 < n ? i + 1 : 0;} const int INF = 1231231234; int simulate(const auto& a, int i, int val, vi* out = nullptr) { vi b(sz(a)); b[i] = val; int j = next(i, sz(a)); int prev = val; do { b[j] = a[j] - prev; if (b[j] < 0) return INF; prev = b[j]; j = next(j, sz(a)); } while (j != i); int need = a[i] - prev; if (out != nullptr) *out = b; return need; } int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); int n; cin >> n; vi a(n); trav(i, a) cin >> i; auto min_pos = min_element(all(a)) - begin(a); int lo = 0, hi = a[min_pos]; int choice = -1; while (lo <= hi) { int mid = (lo + hi) / 2; auto res = simulate(a, min_pos, mid); if (res < mid) { hi = mid - 1; } else if (res > mid) { lo = mid + 1; } else { choice = mid; break; } } if (choice == -1) { cout << "NO" << '\n'; } else { vi res; simulate(a, min_pos, choice, &res); cout << "YES" << '\n'; vector<pair<int, int>> construct; rep(i, 0, sz(a)) { rep(it, 0, res[i]) { construct.PB({i, next(i, sz(a))}); } } cout << sz(construct) << '\n'; for (auto [a, b]: construct) cout << a << " " << b << '\n'; } }
[ "noreply@github.com" ]
noreply@github.com
6cddaea4be3522ccf41ca2abcdc36d7e81b81798
731e75bf82242f74b6aaf0fff440628d817ab9bd
/hw6-1/simple_account.h
5730dfa23fe1585135c28fca9c3baa3fa771b2d0
[]
no_license
ydk1104/ITE1015
547b7fa42ca237ba41456b2ed28df358e7bf0911
fedeae736cfd5ca60d2dff5f7262840e7099d35a
refs/heads/master
2022-04-02T15:40:17.554502
2019-12-05T04:45:37
2019-12-28T17:50:29
230,643,290
0
1
null
null
null
null
UTF-8
C++
false
false
353
h
class account{ public: int id, balance; }; class accountManager{ private: int N = 0; account arr[10]; long long int MAX = 1000000; public: void menu(char); void create_new_account(); void deposit(int id, int money); void withdraw(int id, int money); void transfer(int id_from, int id_to, int money); void print_money(int id); };
[ "ydk1104@hanyang.ac.kr" ]
ydk1104@hanyang.ac.kr
1ae4da47fd4f74575aa85b8145bd62b3f71c72bf
52d90eb640e2d7d5a9ac7f43c49eed952284613b
/Dynamic Programming/Frog 1 Atcoder.cpp
8ad8776f41869576414935a6d2c08567b3f09cf9
[ "MIT" ]
permissive
rohittuli5/Competitive-and-Interview-Practice-Questions
11381d0f1ab24bfff91c35569de8a9e9d2434926
54349c7336eb7384c333b4e415b2cd762d57c0f5
refs/heads/master
2020-12-19T23:54:21.411865
2020-01-23T21:48:53
2020-01-23T21:48:53
235,890,444
0
0
null
null
null
null
UTF-8
C++
false
false
488
cpp
#include<bits/stdc++.h> #define ll long long int using namespace std; int main(){ ll n; cin>>n; ll arr[n]={0},dp[n]={0}; for (int i = 0; i < n; i++) { cin>>arr[i]; } dp[0]=0; dp[1]=abs(arr[1]-arr[0]); for(int i=2;i<n;i++) { ll first=abs(arr[i-1]-arr[i])+dp[i-1]; ll second=abs(arr[i-2]-arr[i])+dp[i-2]; dp[i]= first<=second ? first:second; } cout<<dp[n-1]<<endl; return 0; }
[ "noreply@github.com" ]
noreply@github.com
3d79d27ea5f862d5456d1ef40f9bd31ae617c517
7dbc7f1ed2e181232b32beda07596a9e809220d7
/lib/grammar/Field.cpp
4baa3e011989f5e4330124fe463f60d55774b00c
[]
no_license
rajatkb/Sharp
63d96b563b55cf68d0e1e6b2ddf888a8df946bf6
44a1239457e077379ab164abbc02b130cdcec80e
refs/heads/master
2020-03-12T19:57:28.876420
2017-03-31T02:03:28
2017-03-31T02:03:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
259
cpp
// // Created by BraxtonN on 2/2/2017. // #include "Field.h" #include "ClassObject.h" bool Field::operator==(const Field& f) { if(nf == fnof) return klass != NULL && klass->match(f.klass); else return (nf == f.nf) && name == f.name; }
[ "braxtonnunnally@gmail.com" ]
braxtonnunnally@gmail.com
d1459e14ebd9e39f85787e70775cae0d969e413f
b257bd5ea374c8fb296dbc14590db56cb7e741d8
/Extras/DevExpress VCL/Library/RS17/cxFilterDialog.hpp
4b343d90271110fdf1a03fed77e3a840b0e14aeb
[]
no_license
kitesoft/Roomer-PMS-1
3d362069e3093f2a49570fc1677fe5682de3eabd
c2f4ac76b4974e4a174a08bebdb02536a00791fd
refs/heads/master
2021-09-14T07:13:32.387737
2018-05-04T12:56:58
2018-05-04T12:56:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,144
hpp
// CodeGear C++Builder // Copyright (c) 1995, 2012 by Embarcadero Technologies, Inc. // All rights reserved // (DO NOT EDIT: machine generated header) 'cxFilterDialog.pas' rev: 24.00 (Win32) #ifndef CxfilterdialogHPP #define CxfilterdialogHPP #pragma delphiheader begin #pragma option push #pragma option -w- // All warnings off #pragma option -Vx // Zero-length empty class member #pragma pack(push,8) #include <System.hpp> // Pascal unit #include <SysInit.hpp> // Pascal unit #include <System.Variants.hpp> // Pascal unit #include <Winapi.Windows.hpp> // Pascal unit #include <System.Classes.hpp> // Pascal unit #include <Vcl.Controls.hpp> // Pascal unit #include <Vcl.Graphics.hpp> // Pascal unit #include <Vcl.ExtCtrls.hpp> // Pascal unit #include <Vcl.Forms.hpp> // Pascal unit #include <Vcl.StdCtrls.hpp> // Pascal unit #include <System.SysUtils.hpp> // Pascal unit #include <cxButtonEdit.hpp> // Pascal unit #include <cxButtons.hpp> // Pascal unit #include <cxContainer.hpp> // Pascal unit #include <cxControls.hpp> // Pascal unit #include <cxDataStorage.hpp> // Pascal unit #include <cxDropDownEdit.hpp> // Pascal unit #include <cxEdit.hpp> // Pascal unit #include <cxFilter.hpp> // Pascal unit #include <cxFilterConsts.hpp> // Pascal unit #include <cxFilterControlUtils.hpp> // Pascal unit #include <cxLookAndFeels.hpp> // Pascal unit #include <cxMaskEdit.hpp> // Pascal unit #include <cxTextEdit.hpp> // Pascal unit #include <cxLookAndFeelPainters.hpp> // Pascal unit #include <cxRadioGroup.hpp> // Pascal unit #include <cxGraphics.hpp> // Pascal unit #include <Vcl.Menus.hpp> // Pascal unit #include <cxLabel.hpp> // Pascal unit //-- user supplied ----------------------------------------------------------- namespace Cxfilterdialog { //-- type declarations ------------------------------------------------------- typedef System::TMetaClass* TcxFilterDialogClass; class DELPHICLASS TcxFilterDialog; class PASCALIMPLEMENTATION TcxFilterDialog : public Vcl::Forms::TForm { typedef Vcl::Forms::TForm inherited; __published: Cxlabel::TcxLabel* lblTitle; Cxlabel::TcxLabel* lblColumnCaption; Cxlabel::TcxLabel* lblSingle; Cxlabel::TcxLabel* lblSeries; Cxbuttons::TcxButton* btnOK; Cxbuttons::TcxButton* btnCancel; Cxdropdownedit::TcxComboBox* cbOperator1; Cxdropdownedit::TcxComboBox* cbOperator2; Cxradiogroup::TcxRadioButton* rbAnd; Cxradiogroup::TcxRadioButton* rbOr; Vcl::Stdctrls::TLabel* lblEdit1PlaceHolder; Vcl::Stdctrls::TLabel* lblEdit2PlaceHolder; void __fastcall FormCloseQuery(System::TObject* Sender, bool &CanClose); void __fastcall cbOperator1Click(System::TObject* Sender); void __fastcall cbOperator2PropertiesChange(System::TObject* Sender); private: Cxfilter::TcxFilterCriteria* FCriteria; Vcl::Controls::TCaption FDisplayValue1; Vcl::Controls::TCaption FDisplayValue2; Cxedit::TcxCustomEdit* FEdit1; Cxedit::TcxCustomEdit* FEdit2; Cxedit::TcxCustomEditProperties* FEditProperties; Cxfiltercontrolutils::TcxCustomFilterEditHelperClass FFilterEditHelper; System::TObject* FItemLink; System::Variant FValue1; System::Variant FValue2; Cxdatastorage::TcxValueTypeClass FValueTypeClass; protected: void __fastcall AddFilterItem(Cxfilter::TcxFilterCriteriaItemList* AParent, Cxdropdownedit::TcxComboBox* AComboBox, const System::Variant &AValue, System::UnicodeString ADisplayValue); void __fastcall CheckWildcardDescriptionVisibility(void); virtual void __fastcall CreateParams(Vcl::Controls::TCreateParams &Params); void __fastcall GetFilterValues(Cxedit::TcxCustomEdit* AEdit, System::Variant &AValue, Vcl::Controls::TCaption &ADisplayValue); virtual Cxdropdownedit::TcxComboBox* __fastcall GetOperatorComboBox(Cxedit::TcxCustomEdit* AEdit); virtual Cxfiltercontrolutils::TcxFilterControlOperators __fastcall GetSupportedOperators(void); virtual void __fastcall InitControls(const System::UnicodeString ACriteriaItemCaption); virtual void __fastcall InitControlValues(void); void __fastcall InitEdits(Cxdropdownedit::TcxComboBox* AComboBox, Cxedit::TcxCustomEdit* AEdit, Cxfilter::TcxFilterCriteriaItem* AItem); virtual void __fastcall InitLookAndFeel(Cxlookandfeels::TcxLookAndFeel* ALookAndFeel); void __fastcall SetEditValidChars(Cxedit::TcxCustomEdit* AEdit); void __fastcall ValidateValue(Cxedit::TcxCustomEdit* AEdit, System::Variant &AValue); __property Vcl::Controls::TCaption DisplayValue1 = {read=FDisplayValue1}; __property Vcl::Controls::TCaption DisplayValue2 = {read=FDisplayValue2}; __property Cxedit::TcxCustomEdit* Edit1 = {read=FEdit1}; __property Cxedit::TcxCustomEdit* Edit2 = {read=FEdit2}; __property Cxfiltercontrolutils::TcxCustomFilterEditHelperClass FilterEditHelper = {read=FFilterEditHelper}; __property Cxfiltercontrolutils::TcxFilterControlOperators SupportedOperators = {read=GetSupportedOperators}; __property System::Variant Value1 = {read=FValue1}; __property System::Variant Value2 = {read=FValue2}; public: __fastcall virtual TcxFilterDialog(Cxfilter::TcxFilterCriteria* ACriteria, System::TObject* AItemLink, Cxedit::TcxCustomEditProperties* AEditProperties, const System::UnicodeString ACriteriaItemCaption, Cxdatastorage::TcxValueTypeClass AValueTypeClass, Cxlookandfeels::TcxLookAndFeel* ALookAndFeel, Vcl::Graphics::TFont* AFont); virtual void __fastcall ApplyChanges(void); __classmethod Cxfiltercontrolutils::TcxCustomFilterEditHelperClass __fastcall GetFilterEditHelper(Cxedit::TcxCustomEditProperties* AEditProperties); __property Cxfilter::TcxFilterCriteria* Criteria = {read=FCriteria}; __property Cxedit::TcxCustomEditProperties* EditProperties = {read=FEditProperties}; __property System::TObject* ItemLink = {read=FItemLink}; __property Cxdatastorage::TcxValueTypeClass ValueTypeClass = {read=FValueTypeClass}; public: /* TCustomForm.CreateNew */ inline __fastcall virtual TcxFilterDialog(System::Classes::TComponent* AOwner, int Dummy) : Vcl::Forms::TForm(AOwner, Dummy) { } /* TCustomForm.Destroy */ inline __fastcall virtual ~TcxFilterDialog(void) { } public: /* TWinControl.CreateParented */ inline __fastcall TcxFilterDialog(HWND ParentWindow) : Vcl::Forms::TForm(ParentWindow) { } }; //-- var, const, procedure --------------------------------------------------- extern PACKAGE TcxFilterDialogClass cxFilterDialogClass; extern PACKAGE bool __fastcall IsFilterControlDialogNeeded(Cxfilter::TcxFilterCriteria* ACriteria); extern PACKAGE bool __fastcall ShowFilterDialog(Cxfilter::TcxFilterCriteria* ACriteria, System::TObject* AItemLink, Cxedit::TcxCustomEditProperties* AEditProperties, const System::UnicodeString ACriteriaItemCaption, Cxdatastorage::TcxValueTypeClass AValueTypeClass, Cxlookandfeels::TcxLookAndFeel* ALookAndFeel = (Cxlookandfeels::TcxLookAndFeel*)(0x0), Vcl::Graphics::TFont* AFont = (Vcl::Graphics::TFont*)(0x0)); } /* namespace Cxfilterdialog */ #if !defined(DELPHIHEADER_NO_IMPLICIT_NAMESPACE_USE) && !defined(NO_USING_NAMESPACE_CXFILTERDIALOG) using namespace Cxfilterdialog; #endif #pragma pack(pop) #pragma option pop #pragma delphiheader end. //-- end unit ---------------------------------------------------------------- #endif // CxfilterdialogHPP
[ "bas@roomerpms.com" ]
bas@roomerpms.com
0e41211ac097970afad5e5827fa344f55615c976
2cf838b54b556987cfc49f42935f8aa7563ea1f4
/aws-cpp-sdk-appintegrations/include/aws/appintegrations/model/UpdateEventIntegrationResult.h
1912c865ecdb2a803b75f9e34b3b6845b5df038a
[ "MIT", "Apache-2.0", "JSON" ]
permissive
QPC-database/aws-sdk-cpp
d11e9f0ff6958c64e793c87a49f1e034813dac32
9f83105f7e07fe04380232981ab073c247d6fc85
refs/heads/main
2023-06-14T17:41:04.817304
2021-07-09T20:28:20
2021-07-09T20:28:20
384,714,703
1
0
Apache-2.0
2021-07-10T14:16:41
2021-07-10T14:16:41
null
UTF-8
C++
false
false
852
h
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/appintegrations/AppIntegrationsService_EXPORTS.h> namespace Aws { template<typename RESULT_TYPE> class AmazonWebServiceResult; namespace Utils { namespace Json { class JsonValue; } // namespace Json } // namespace Utils namespace AppIntegrationsService { namespace Model { class AWS_APPINTEGRATIONSSERVICE_API UpdateEventIntegrationResult { public: UpdateEventIntegrationResult(); UpdateEventIntegrationResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result); UpdateEventIntegrationResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result); }; } // namespace Model } // namespace AppIntegrationsService } // namespace Aws
[ "aws-sdk-cpp-automation@github.com" ]
aws-sdk-cpp-automation@github.com
874bba617e04bf22228bbb25b640d0b8a719340b
d3bf068ac90138457dd23649736f95a8793c33ae
/AutoPFA/ModelDataFrame.cpp
e6158b523a2054a9bc3f3a64471f1ce4d5007bbe
[]
no_license
xxxmen/uesoft-AutoPFA
cab49bfaadf716de56fef8e9411c070a4b1585bc
f9169e203d3dc3f2fd77cde39c0bb9b4bdf350a6
refs/heads/master
2020-03-13T03:38:50.244880
2013-11-12T05:52:34
2013-11-12T05:52:34
130,947,910
1
2
null
null
null
null
UTF-8
C++
false
false
2,047
cpp
// ModelDataFrame.cpp : implementation file // #include "stdafx.h" #include "autopfa.h" #include "ModelDataFrame.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CModelDataFrame IMPLEMENT_DYNCREATE(CModelDataFrame, CMDIChildWnd) CModelDataFrame::CModelDataFrame() { } CModelDataFrame::~CModelDataFrame() { } BEGIN_MESSAGE_MAP(CModelDataFrame, CMDIChildWnd) //{{AFX_MSG_MAP(CModelDataFrame) ON_WM_CREATE() ON_WM_CLOSE() //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CModelDataFrame message handlers BOOL CModelDataFrame::PreCreateWindow(CREATESTRUCT& cs) { // TODO: Add your specialized code here and/or call the base class //cs.lpszClass=::AfxRegisterWndClass(CS_NOCLOSE); if( !CMDIChildWnd::PreCreateWindow(cs) ) return FALSE; cs.style = WS_CHILD | WS_VISIBLE | WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | FWS_ADDTOTITLE | WS_THICKFRAME | WS_MINIMIZEBOX| WS_MAXIMIZEBOX|WS_MINIMIZE; return TRUE; } BOOL CModelDataFrame::DestroyWindow() { // TODO: Add your specialized code here and/or call the base class return CMDIChildWnd::DestroyWindow(); } int CModelDataFrame::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CMDIChildWnd::OnCreate(lpCreateStruct) == -1) return -1; // TODO: Add your specialized creation code here if (!m_wndDlgBar.Create(this, IDD_DLGMODELDATA, CBRS_TOP|CBRS_TOOLTIPS|CBRS_FLYBY, IDD_DLGMODELDATA)) { TRACE0("Failed to create DlgBar\n"); return -1; // fail to create } CComboBox* pCbmBox = (CComboBox*)m_wndDlgBar.GetDlgItem(IDC_CMBSHOWTYPE); pCbmBox->SetCurSel(0); return 0; } int CModelDataFrame::GetCurSelShow() { CComboBox* pCbmBox = (CComboBox*)m_wndDlgBar.GetDlgItem(IDC_CMBSHOWTYPE); return pCbmBox->GetCurSel(); } void CModelDataFrame::OnClose() { // TODO: Add your message handler code here and/or call default this->ShowWindow(SW_MINIMIZE); return; }
[ "uesoft@163.com" ]
uesoft@163.com
59c3f4a1179ab8b37b6b71c28a41577c61a4eb92
058f6cf55de8b72a7cdd6e592d40243a91431bde
/src/driver_cpu.cpp
596744923351a5c45a5dc6526c125b7eb15aa82a
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
LLNL/FPChecker
85e8ebf1d321b3208acee7ddfda2d8878a238535
e665ef0f050316f6bc4dfc64c1f17355403e771b
refs/heads/master
2023-08-30T23:24:43.749418
2022-04-14T19:57:44
2022-04-14T19:57:44
177,033,795
24
6
Apache-2.0
2022-09-19T00:09:50
2019-03-21T22:34:14
Python
UTF-8
C++
false
false
2,579
cpp
#include "Utility.h" #include "Instrumentation_cpu.h" #include "CodeMatching.h" #include "Logging.h" //#include "CommonTypes.h" //#include "ProgressBar.h" #include "llvm/Pass.h" #include "llvm/IR/Module.h" #include "llvm/IR/Function.h" #include "llvm/IR/BasicBlock.h" #include "llvm/IR/Instruction.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/Constants.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/Casting.h" #include "llvm/Transforms/IPO/PassManagerBuilder.h" #include "llvm/CodeGen/RegAllocRegistry.h" #include "llvm/IR/LegacyPassManager.h" #include <string> #include <iostream> #include <fstream> #include <set> using namespace llvm; namespace CPUAnalysis { class CPUKernelAnalysis : public ModulePass { public: static char ID; CPUKernelAnalysis() : ModulePass(ID) {} virtual bool runOnModule(Module &M) { Module *m = &M; CPUFPInstrumentation *fpInstrumentation = new CPUFPInstrumentation(m); long int instrumented = 0; #ifdef FPC_DEBUG std::string out = "Running Module pass on: " + m->getName().str(); CUDAAnalysis::Logging::info(out.c_str()); #endif for (auto f = M.begin(), e = M.end(); f != e; ++f) { // Discard function declarations if (f->isDeclaration()) continue; Function *F = &(*f); if (CUDAAnalysis::CodeMatching::isUnwantedFunction(F)) continue; #ifdef FPC_DEBUG std::string fname = "Instrumenting function: " + F->getName().str(); CUDAAnalysis::Logging::info(fname.c_str()); #endif long int c = 0; fpInstrumentation->instrumentFunction(F, &c); instrumented += c; if (CUDAAnalysis::CodeMatching::isMainFunction(F)) { #ifdef FPC_DEBUG CUDAAnalysis::Logging::info("main() found"); #endif fpInstrumentation->instrumentMainFunction(F); } } std::string out_tmp = "Instrumented " + std::to_string(instrumented) + " @ " + m->getName().str(); CUDAAnalysis::Logging::info(out_tmp.c_str()); // This emulates a failure in the pass if (getenv("FPC_INJECT_FAULT") != NULL) exit(-1); delete fpInstrumentation; return false; } }; char CPUKernelAnalysis::ID = 0; static RegisterPass<CPUKernelAnalysis> X( "cpukernels", "CPUKernelAnalysis Pass", false, false); static void registerPass(const PassManagerBuilder &, legacy::PassManagerBase &PM) { PM.add(new CPUKernelAnalysis()); } static RegisterStandardPasses RegisterMyPass(PassManagerBuilder::EP_EnabledOnOptLevel0,registerPass); static RegisterStandardPasses RegisterMyPass2(PassManagerBuilder::EP_OptimizerLast,registerPass); }
[ "ilaguna@llnl.gov" ]
ilaguna@llnl.gov
bd4e3b9994710fc2c146c6cb4dbc7d805b60daef
4f8a4ce45d4ba89aaa674254a2ac126e12e79f73
/Project2/Property.cpp
e37d13470151850d7232fc6a13ab18cb62a43deb
[]
no_license
aohara19/Ohara-CSC17A
659d8291e439d133311afb81fc122e1fca10cab2
7942fb628b943c240b09f7c8ed406209825bfe83
refs/heads/master
2020-04-22T18:20:15.821636
2019-05-27T13:35:57
2019-05-27T13:35:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
881
cpp
#include "Property.h" Property Property::operator++(){ ++typeOwned; return *this; } int Property::calcRent(int a,int b){ int tempRent = returnRent(); int z = 1; if(b==1) z = 5; else if(b==2) z = 15; else if(b==3) z = 40; tempRent *=z; if(b==0) tempRent *=a; return tempRent; } bool Property::operator>(const Property &right){ bool status; if(getPrice()+houses*houseCost > right.getPrice()+right.houses*right.houseCost){ status = true; } else if (getPrice()+houses*houseCost < right.getPrice()+right.houses*right.houseCost) status = false; else{ if(returnRent()>right.returnRent()) status = true; else status = false; } return status; }
[ "allis@DESKTOP-SBFFDHV.attlocal.net" ]
allis@DESKTOP-SBFFDHV.attlocal.net
f2a2962499359d575a6c8c5e41e29cce69cbcb19
7ea70521df78361fc6307ed946501e794a97f165
/engine/network/Log.h
c664fe816957d5f08229715bca07c1e03a466c23
[]
no_license
lewisham/server
8d1051980c58662d2fefb479a8ecc74dcb68eefe
381e804932ff06338f932666d27153e1a45c4a38
refs/heads/master
2020-05-02T19:14:33.775910
2019-04-04T11:44:17
2019-04-04T11:44:17
178,153,579
0
0
null
null
null
null
UTF-8
C++
false
false
587
h
#pragma once namespace wls { void Trace(const char * msg, ...); void Error(const char* fileName, const char* funcName, int line, const char* msg, ...); void Error(const char* fileName, const char* funcName, int line, int code, const char* msg, ...); void Setup(); void Cleanup(); void EnableTrace(bool enable); } #define NET_TRACE(msg, ...) wls::Trace(msg, __VA_ARGS__); #define NET_ERROR_MSG(msg, ...) wls::Error(__FILE__, __FUNCTION__, __LINE__, msg, __VA_ARGS__); #define NET_ERROR_CODE(code, msg, ...) wls::Error(__FILE__, __FUNCTION__, __LINE__, code, msg, __VA_ARGS__);
[ "zhanggongjian@weile.com" ]
zhanggongjian@weile.com
a79ab0de897d4d0920d8a70381db97fefbdaa4a6
2d5d7b44b7f05f8d1d8e1f6fad0065ed89cead0c
/inMyRoom_vulkan/include/ECS/ConceptHelpers.h
c61cb2e159daf1a07aa338a0e69b5bff9e697b93
[]
no_license
thesmallcreeper/inMyRoom_vulkan
b84bafbadd32228210969e9b466e7f8c213c90ec
8b0d96b02ecffd2bed04730363d0e8a349d12530
refs/heads/master
2023-04-30T10:09:40.771134
2023-04-23T20:47:10
2023-04-23T20:47:10
158,889,074
20
1
null
null
null
null
UTF-8
C++
false
false
792
h
#pragma once #include <concepts> #include <chrono> #include "ECS/ComponentBaseWrappedClass.h" #include "ECS/CompEntityBaseWrappedClass.h" // CONCEPTS OF TYPES // template <class T> concept Component = std::is_base_of<ComponentBaseClass, T>::value; template <class T> concept CompEntity = std::is_base_of<CompEntityBaseClass, T>::value; template <class T> concept DeltaTime = std::is_same<std::chrono::duration<float>, T>::value; template <class T> concept EntitiesHandlerType = std::is_same<class EntitiesHandler, T>::value; template <class T> concept TrivialUpdateParameter = Component<typename std::remove_pointer<T>::type> || CompEntity<typename std::remove_reference<T>::type> || DeltaTime<T> || EntitiesHandlerType<typename std::remove_pointer<T>::type>;
[ "nikostpt@hotmail.com" ]
nikostpt@hotmail.com
0cb27ad42180aa1a750d413b9a80c54886a3fb1b
6b1596c95fbddca79d84a3554c198ede99675ec2
/cpp_concepts/expressions.cpp
6b5f7fffb85d6391b56ce8bb5ed1b7b6f304663f
[]
no_license
sandeepjana/zenballmaster
f513fef761cc347a8c2d881a094efb205d912ae9
1c41b93ec9b585fa67fed755bf172dd7beff2b84
refs/heads/master
2020-03-09T06:19:44.199591
2018-08-30T19:41:08
2018-08-30T19:41:08
128,561,421
0
0
null
null
null
null
UTF-8
C++
false
false
2,543
cpp
#if 0 #include <iostream> #include <string> #include <functional> #include <algorithm> #include <vector> using namespace std; struct EXP { void left() { cout << "left"; } void right() { cout << "right"; } int a; int b; }; typedef std::function<void (const std::string&)> fxn_string_t; class CSayHello { public: CSayHello(fxn_string_t before, fxn_string_t after) { m_before = before; m_after = after; } void say_hello(const string& username) { m_before("Welcome "); cout << username << " "; m_after("to the lambdas!"); } private: fxn_string_t m_before; fxn_string_t m_after; }; struct SPrinter { bool caseIntact; void print_fxn(const string& s) { if(caseIntact) { cout << s; } else { string us(s); transform(s.begin(), s.end(), us.begin(), toupper); cout << us; } } void print_fxn_v2(const string& s, bool quote) { if(quote) cout << "\"" << s << "\""; else cout << s; } }; void error_check() {} int main() { vector<int> v(10); generate(v.begin(), v.end(), [](){ return rand()%99; }); } #if 0 int main(int argc, char** argv) { EXP e = {10, 20}; //pointer to members are useful when you have multiple objects // and you want to access one of their member functions/variables int EXP::* pma = &EXP::a; //declares and defines! void (EXP::* pmr)() = &EXP::right; auto pml = &EXP::left; //pmd is a pointer to a member of EXP that is type int. //how to remember? //For normal pointers, it is: // int * pa = &a; //So replace * and & with EXP::* and &EXP:: cout << e.*pma << endl; (e.*pml)(); //<- unfortunately, parenths are required around e.*pml cout << endl; (e.*pmr)(); cout << endl; SPrinter a, b; a.caseIntact = false; b.caseIntact = true; //CSayHello(&(a.print_fxn), &(a.print_fxn)); Wont work :P CSayHello guest([&a](const string& s){ a.print_fxn(s); }, [&b](const string& s){ b.print_fxn(s); }); guest.say_hello("zen ball master"); cout << endl; //changed my mind b.caseIntact = false; guest.say_hello("zen ball master"); cout << endl; //Note: The lambda type should match the fxn_string_t //but no need for the internal actual functions calls to match it. //Lamda expression just acts as a wrapper around functions. CSayHello guestV2([&a](const string& s){ a.print_fxn_v2(s, true); }, [&a](const string& s){ a.print_fxn_v2(s, true); }); guestV2.say_hello("zen ball master"); vector<int> v(10); generate(v.begin(), v.end(), [](){ error_check(); return rand()%99; }); return 0; } #endif #endif
[ "4102043+sandeepjana@users.noreply.github.com" ]
4102043+sandeepjana@users.noreply.github.com
ad487bee1f58228d412c97f432e1d752e8602cfb
ce43473e041f1eab581c191b4487795d3449977e
/codeforces/Laptops.cpp
f650502e61e1876ec48070ffd20b3bb5209b568c
[]
no_license
ismail-cse-15/Compitative-Programming
5d23d92a5e7a8bac11f79baf9920b6f2f9f2292f
fb37bcf4b4936850ff5044bbde9055c6829b11bb
refs/heads/main
2023-04-15T05:49:47.777427
2021-05-04T13:03:57
2021-05-04T13:03:57
364,000,563
0
0
null
null
null
null
UTF-8
C++
false
false
1,285
cpp
#include<bits/stdc++.h> using namespace std; bool prime[100010]; int c[510],row[510],b[510][510]; int main() { int n,m,a[510][510]; for(int i=2; i<=sqrt(100010); i++) { if(prime[i]==false) { for(int j=i*2; j<=100010; j+=i) { prime[j]=1; } } } prime[1]=1; cin>>n>>m; for(int i=1; i<=n; i++) { for(int j=1; j<=m; j++) { cin>>a[i][j]; int x; x=a[i][j]; if(prime[x]==true) { for(int k=x+1;; k++) { if(prime[k]==false) { b[i][j]=(k-x); break; } } } } } for(int i=1; i<=m; i++) { for(int j=1; j<=n; j++) c[i]+=b[j][i]; } for(int i=1; i<=n; i++) { for(int j=1; j<=m; j++) row[i]+=b[i][j]; } sort(c+1,c+(m+1)); sort(row+1,row+(n+1)); if(c[1]<row[1]) cout<<c[1]<<endl; else if(c[1]>row[1]) cout<<row[1]<<endl; else cout<<c[1]<<endl; return 0; }
[ "noreply@github.com" ]
noreply@github.com
3f927195dd03e16dbf08d4179c75b8429bfee52f
7396a56d1f6c61b81355fc6cb034491b97feb785
/algorithms/kernel/k_nearest_neighbors/kdtree_knn_classification_training_result_fpt.cpp
b1d1397f21a79a49918620181b5977c13fbd5f15
[ "Apache-2.0", "Intel" ]
permissive
francktcheng/daal
0ad1703be1e628a5e761ae41d2d9f8c0dde7c0bc
875ddcc8e055d1dd7e5ea51e7c1b39886f9c7b79
refs/heads/master
2018-10-01T06:08:39.904147
2017-09-20T22:37:02
2017-09-20T22:37:02
119,408,979
0
0
null
2018-01-29T16:29:51
2018-01-29T16:29:51
null
UTF-8
C++
false
false
2,704
cpp
/* file: kdtree_knn_classification_training_result_fpt.cpp */ /******************************************************************************* * Copyright 2014-2017 Intel Corporation * All Rights Reserved. * * If this software was obtained under the Intel Simplified Software License, * the following terms apply: * * The source code, information and material ("Material") contained herein is * owned by Intel Corporation or its suppliers or licensors, and title to such * Material remains with Intel Corporation or its suppliers or licensors. The * Material contains proprietary information of Intel or its suppliers and * licensors. The Material is protected by worldwide copyright laws and treaty * provisions. No part of the Material may be used, copied, reproduced, * modified, published, uploaded, posted, transmitted, distributed or disclosed * in any way without Intel's prior express written permission. No license under * any patent, copyright or other intellectual property rights in the Material * is granted to or conferred upon you, either expressly, by implication, * inducement, estoppel or otherwise. Any license under such intellectual * property rights must be express and approved by Intel in writing. * * Unless otherwise agreed by Intel in writing, you may not remove or alter this * notice or any other notice embedded in Materials by Intel or Intel's * suppliers or licensors in any way. * * * If this software was obtained under the Apache License, Version 2.0 (the * "License"), the following terms apply: * * 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. *******************************************************************************/ /* //++ // Implementation of the class defining the K-Nearest Neighbors (kNN) model //-- */ #include "kdtree_knn_classification_training_result.h" namespace daal { namespace algorithms { namespace kdtree_knn_classification { namespace training { template DAAL_EXPORT services::Status Result::allocate<DAAL_FPTYPE>(const daal::algorithms::Input * input, const Parameter * parameter, int method); }// namespace training }// namespace kdtree_knn_classification }// namespace algorithms }// namespace daal
[ "vasily.rubtsov@intel.com" ]
vasily.rubtsov@intel.com
9822b551583133ac0822946b47fa17b492f5e8a4
5d428b302b919c1a20353c784f8c1f79a3ce4204
/cartographer_interface.cpp
5d8213cd0b8f6eeffcfde465f0a7548ec1e8d08f
[ "MIT" ]
permissive
mgou123/cartographer_interface
c867292a1f93747e3babb7c08956c2a2ffe9ebbf
cc058b1fbfbdc8685b077c2a7a41f2940754a7d4
refs/heads/main
2023-05-27T21:59:01.999926
2021-06-11T08:04:34
2021-06-11T08:04:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,786
cpp
#include "cartographer_interface.h" #include <utility> /** * @brief 构造函数,设置传感器数据,并添加一条轨迹,加载当前地图 * @param map_path 需要加载的地图路径 * @param resolution 地图分辨率 * @param configuration_directory 配置参数目录 * @param configuration_basename 配置参数文件 */ cartographer_interface::cartographer_interface(const std::string& map_path, float resolution, const std::string& configuration_directory, const std::string& configuration_basename) { // 从配置文件中加载配置参数 std::tie(m_node_options, m_trajectory_options) = LoadOptions(configuration_directory,configuration_basename); // 调用 cartographer 接口,构造 MapBuilder 类 m_map_builder = cartographer::common::make_unique<cartographer::mapping::MapBuilder>(m_node_options.map_builder_options); // 加载现有的地图数据 //read_map(map_path); //@TODO need to change when change the sensors // 目前在本项目中使用一个2d雷达 + IMU + 轮速计 using SensorId = cartographer::mapping::TrajectoryBuilderInterface::SensorId; using SensorType = SensorId::SensorType; m_sensor_ids.insert(SensorId{SensorType::RANGE, "echoes"});// laser 2d m_sensor_ids.insert(SensorId{SensorType::IMU, "imu"});// IMU //m_sensor_ids.insert(SensorId{SensorType::ODOMETRY, "odometry"});// odometry // 调用接口构造一条轨迹,返回轨迹id // m_sensor_ids 传感器类型及id // trajectory_builder_options 轨迹的配置参数 // 最后一个参数为lambda表达式,为定位结果回调调用函数 m_trajectory_id = m_map_builder->AddTrajectoryBuilder(m_sensor_ids, m_trajectory_options.trajectory_builder_options, [this](const int id, const cartographer::common::Time time, const cartographer::transform::Rigid3d local_pose, cartographer::sensor::RangeData range_data_in_local, const std::unique_ptr<const ::cartographer::mapping::TrajectoryBuilderInterface::InsertionResult> res) { OnLocalSlamResult2(id, time, local_pose, range_data_in_local); }); // 获取轨迹轨迹生成类指针 m_trajectory_builder = m_map_builder->GetTrajectoryBuilder(m_trajectory_id); } /** * @brief 回调函数 * @param id 轨迹id * @param time 时间 * @param local_pose 局部地图上的位置 * @param range_data_in_local 局部地图到全局地图的转换关系 */ void cartographer_interface::OnLocalSlamResult2( const int id, const cartographer::common::Time time, const cartographer::transform::Rigid3d local_pose, cartographer::sensor::RangeData range_data_in_local) { cartographer::transform::Rigid3d local2global = m_map_builder->pose_graph()->GetLocalToGlobalTransform(m_trajectory_id); cartographer::transform::Rigid3d pose3d = local2global * local_pose; std::cout<<"pose: x"<<pose3d.translation().x()<<" y "<<pose3d.translation().y()<<" angle "<<pose3d.rotation().z()<<std::endl; return; } cartographer_interface::~cartographer_interface() { delete m_painted_slices; } /** * @brief read map from pbstream file * @param map_path * @return */ bool cartographer_interface::read_map(const std::string& map_path) { const std::string suffix = ".pbstream"; CHECK_EQ(map_path.substr( std::max<int>(map_path.size() - suffix.size(), 0)), suffix) << "The file containing the state to be loaded must be a " ".pbstream file."; cartographer::io::ProtoStreamReader stream(map_path); m_map_builder->LoadState(&stream,true); return true; } /** * @brief add one laser scan data with time && pos * @param sensor_id * @param time * @param pos * @param points */ void cartographer_interface::HandleLaserScanMessage(const std::string& sensor_id, const cartographer::common::Time time, const std::string& frame_id, const cartographer::sensor::TimedPointCloud& ranges) { Eigen::Vector3d trans(0.1007,0,0.0558); Eigen::Quaterniond rot(1,0,0,0); cartographer::transform::Rigid3d sensor_to_tracking(trans, rot); m_trajectory_builder->AddSensorData(sensor_id, cartographer::sensor::TimedPointCloudData{ time, sensor_to_tracking.translation().cast<float>(), cartographer::sensor::TransformTimedPointCloud(ranges,sensor_to_tracking.cast<float>())}); } /** * @brief * @param sensor_id * @param time * @param pose */ void cartographer_interface::HandleOdometryMessage(const std::string& sensor_id, cartographer::common::Time time, cartographer::transform::Rigid3d pose) { m_trajectory_builder->AddSensorData( sensor_id, cartographer::sensor::OdometryData{time, std::move(pose)}); } /** * @brief * @param sensor_id * @param data */ void cartographer_interface::HandleImuMessage( const std::string& sensor_id, std::unique_ptr<cartographer::sensor::ImuData> &data) { m_trajectory_builder->AddSensorData( sensor_id, *data); } /** * @brief 从配置文件中加载参数 * @param configuration_directory 配置文件目录 * @param configuration_basename 配置文件名称 * @return */ std::tuple<NodeOptions, TrajectoryOptions> LoadOptions( const std::string& configuration_directory, const std::string& configuration_basename) { auto file_resolver = cartographer::common::make_unique< cartographer::common::ConfigurationFileResolver>( std::vector<std::string>{configuration_directory}); const std::string code = file_resolver->GetFileContentOrDie(configuration_basename); cartographer::common::LuaParameterDictionary lua_parameter_dictionary( code, std::move(file_resolver)); return std::make_tuple(CreateNodeOptions(&lua_parameter_dictionary), CreateTrajectoryOptions(&lua_parameter_dictionary)); } /** * @brief 加载节点参数 * @param lua_parameter_dictionary * @return */ NodeOptions CreateNodeOptions( ::cartographer::common::LuaParameterDictionary* const lua_parameter_dictionary) { NodeOptions options; options.map_builder_options = ::cartographer::mapping::CreateMapBuilderOptions( lua_parameter_dictionary->GetDictionary("map_builder").get()); options.map_frame = lua_parameter_dictionary->GetString("map_frame"); options.lookup_transform_timeout_sec = lua_parameter_dictionary->GetDouble("lookup_transform_timeout_sec"); options.submap_publish_period_sec = lua_parameter_dictionary->GetDouble("submap_publish_period_sec"); options.pose_publish_period_sec = lua_parameter_dictionary->GetDouble("pose_publish_period_sec"); options.trajectory_publish_period_sec = lua_parameter_dictionary->GetDouble("trajectory_publish_period_sec"); return options; } /** * @brief 加载轨迹参数 * @param lua_parameter_dictionary * @return */ TrajectoryOptions CreateTrajectoryOptions( ::cartographer::common::LuaParameterDictionary* const lua_parameter_dictionary) { TrajectoryOptions options; options.trajectory_builder_options = ::cartographer::mapping::CreateTrajectoryBuilderOptions( lua_parameter_dictionary->GetDictionary("trajectory_builder").get()); options.tracking_frame = lua_parameter_dictionary->GetString("tracking_frame"); options.published_frame = lua_parameter_dictionary->GetString("published_frame"); options.odom_frame = lua_parameter_dictionary->GetString("odom_frame"); options.provide_odom_frame = lua_parameter_dictionary->GetBool("provide_odom_frame"); options.use_odometry = lua_parameter_dictionary->GetBool("use_odometry"); options.use_nav_sat = lua_parameter_dictionary->GetBool("use_nav_sat"); options.use_landmarks = lua_parameter_dictionary->GetBool("use_landmarks"); options.publish_frame_projected_to_2d = lua_parameter_dictionary->GetBool("publish_frame_projected_to_2d"); options.num_laser_scans = lua_parameter_dictionary->GetNonNegativeInt("num_laser_scans"); options.num_multi_echo_laser_scans = lua_parameter_dictionary->GetNonNegativeInt("num_multi_echo_laser_scans"); options.num_subdivisions_per_laser_scan = lua_parameter_dictionary->GetNonNegativeInt( "num_subdivisions_per_laser_scan"); options.num_point_clouds = lua_parameter_dictionary->GetNonNegativeInt("num_point_clouds"); options.rangefinder_sampling_ratio = lua_parameter_dictionary->GetDouble("rangefinder_sampling_ratio"); options.odometry_sampling_ratio = lua_parameter_dictionary->GetDouble("odometry_sampling_ratio"); options.fixed_frame_pose_sampling_ratio = lua_parameter_dictionary->GetDouble("fixed_frame_pose_sampling_ratio"); options.imu_sampling_ratio = lua_parameter_dictionary->GetDouble("imu_sampling_ratio"); options.landmarks_sampling_ratio = lua_parameter_dictionary->GetDouble("landmarks_sampling_ratio"); return options; } const char* GetBasename(const char* filepath) { const char* base = std::strrchr(filepath, '/'); return base ? (base + 1) : filepath; } // 都是默认使用的构造函数 ScopedLogSink::ScopedLogSink() : will_die_(false) { AddLogSink(this); } ScopedLogSink::~ScopedLogSink() { RemoveLogSink(this); } /** * @brief 重载该函数实现log日志或直接输出 * * */ void ScopedLogSink::send(const ::google::LogSeverity severity, const char* const filename, const char* const base_filename, const int line, const struct std::tm* const tm_time, const char* const message, const size_t message_len) { // 获取日志数据 const std::string message_string = ::google::LogSink::ToString( severity, GetBasename(filename), line, tm_time, message, message_len); // 根据不同消息等级进行处理 switch (severity) { // 普通输出 case ::google::GLOG_INFO: std::cout<<message_string<<std::endl; break; // 警告输出 case ::google::GLOG_WARNING: std::cout<<message_string<<std::endl; break; // 错误输出 case ::google::GLOG_ERROR: std::cerr<<message_string<<std::endl; break; // 致命错误输出 case ::google::GLOG_FATAL: std::cerr<<message_string<<std::endl; will_die_ = true; break; } } /** * @brief 线程等待函数 * */ void ScopedLogSink::WaitTillSent() { if (will_die_) { std::this_thread::sleep_for(std::chrono::milliseconds(1000)); } }
[ "hust_linyicheng@qq.com" ]
hust_linyicheng@qq.com
aae7886c64c33da86f7f19f5f9b0fcbabd79ac17
2d7b949e35fae895419183c71f776307722c51ec
/server/include/GameLoader.h
025b9e355673986ca785468ee54846facdd9f515
[]
no_license
nravesz/Wolfenstein3D
f964f0341eb655b55469f04f0d859dab31c73753
420d1fa9ec20119072b4a2b0e98fe648b5c4ff96
refs/heads/main
2023-03-19T17:52:08.305088
2021-03-09T21:28:38
2021-03-09T21:28:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
663
h
#ifndef GAMELOADER_H #define GAMELOADER_H #include <yaml-cpp/yaml.h> #include "server/Items/OpenableItem.h" #include "server/Items/Rocket.h" #include "Item.h" /*Clase que se encarga de cargar los datos del juego, incluyendo objetos*/ class GameLoader{ int uniqueId; YAML::Node sprites; YAML::Node idConfig; YAML::Node map; public: GameLoader(char* configPath); GameLoader(); Item* itemLoader(int& idItem); Item* weaponLoader(int& idItem); Item* weaponLoader(std::string& itemName); OpenableItem* setTexture(int& idItem); Item* itemLoader(std::string& idItem); Rocket* createRocket(); ~GameLoader(); }; #endif
[ "variosdemas@gmail.com" ]
variosdemas@gmail.com
bb1308def243d730c94f500d33ec44b40b29a9ed
1b3030394cb23b75f519551994faa910c7def8bf
/src/bootstrap/errors/exceptions.hpp
589763b7246d391ccc94c81fb2393cf30a890bff
[ "Apache-2.0" ]
permissive
wexaris/ivy
7873ef11a515007e5f050aed43e09407251646f6
9b752661c7db69296627307acc73978052c93eb4
refs/heads/master
2020-03-30T01:50:14.571655
2019-02-05T22:04:41
2019-02-05T22:04:41
150,598,046
3
0
null
null
null
null
UTF-8
C++
false
false
604
hpp
#pragma once #include <exception> class CompilerException : public std::exception { public: CompilerException() = default; virtual ~CompilerException() override = default; }; class ErrorException : public CompilerException { public: ErrorException() = default; virtual ~ErrorException() override = default; }; class FatalException : public CompilerException { public: FatalException() = default; virtual ~FatalException() override = default; }; class InternalException : public CompilerException { public: InternalException() = default; virtual ~InternalException() override = default; };
[ "wexaris@gmail.com" ]
wexaris@gmail.com
359eedb2bd036195cf95fd40bc96e3de76cfc39a
2232c179ab4aafbac2e53475447a5494b26aa3fb
/src/mesh/point_set/DofPointSetTriagEquidist.hpp
fddef08ef7c589c1dfea82b37e43574a321740ea
[]
no_license
martinv/pdekit
689986d252d13fb3ed0aa52a0f8f6edd8eef943c
37e127c81702f62f744c11cc2483869d8079f43e
refs/heads/master
2020-03-31T09:24:32.541648
2018-10-08T15:23:43
2018-10-08T15:23:43
152,095,058
1
0
null
null
null
null
UTF-8
C++
false
false
2,065
hpp
#ifndef PDEKIT_Mesh_Dof_Point_Set_Triag_Equidist_hpp #define PDEKIT_Mesh_Dof_Point_Set_Triag_Equidist_hpp #include "mesh/point_set/StdPointSetBase.hpp" #include "mesh/std_region/EquidistStdRegionTriag.hpp" namespace pdekit { namespace mesh { // ---------------------------------------------------------------------------- // Equidistant point set for lines // ---------------------------------------------------------------------------- class DofPointSetTriagEquidist : public StdPointSetBase { public: /// Default constructor DofPointSetTriagEquidist(const std::tuple<Uint> &p_order); /// Destructor ~DofPointSetTriagEquidist() override = default; static std::string type_name() { return "DofPointSetTriagEquidist"; } std::string name() const override { return "DofPointSetTriagEquidist"; } /// Order of polynomial which this quadrature integrates exactly Uint order() const override; /// Topological dimension of element for which this quadrature can be /// applied Uint dim() const override; /// Topological codimension of quadrature. Uint codim() const override; /// Return the number of local entities on which this quadrature /// has points defined Uint nb_local_entities() const override; /// Return the number of quadrature points Uint size(const Uint local_idx = 0) const override; /// Return a matrix containing the reference coordinates void reference_coords(math::DenseDMat<Real> &coords, const Uint local_idx = 0) const override; /// Compute weights void weights(math::DenseDVec<Real> &wgt, const Uint local_idx = 0) const override; /// Fill a vector which represents a permutation of points void permutation(const Uint local_id, const mesh::EntityRealignCode &permutation_code, std::vector<Uint> &permutation_vec) override; private: using std_reg_t = mesh::EquidistStdRegionTriag; const Uint m_poly_order; }; // ---------------------------------------------------------------------------- } // namespace mesh } // namespace pdekit #endif
[ "martin.vymazal@gmail.com" ]
martin.vymazal@gmail.com
d38363fe7343ca8bbd4090c09a1a264cc26e4983
81c74937fd4586b264b9ff3242be616292d06bdf
/trunk/src/c++/include/palbase/pair_filter.h
44ced31c030fe92dd070e36aa49051db5cd38ee1
[]
no_license
rahulkr007/sageCore
be877ff6bb2ee5825e5cc9b9d71e03ac32f4e29f
b1b19b95d80637b48fca789a09a8de16cdaad3ab
refs/heads/master
2021-06-01T12:41:41.374258
2016-09-02T19:14:02
2016-09-02T19:14:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,045
h
#ifndef PAIR_FILTER_H #define PAIR_FILTER_H //**************************************************************************** //* File: pair_filter.h * //* * //* Author: Kevin Jacobs & Yeunjoo Song * //* * //* History: Initial implementation kbj * //* Re-organization yjs May. 06 * //* * //* Notes: This header file defines pair_filter class. * //* * //* Copyright (c) 1999 R.C. Elston * //* All Rights Reserved * //**************************************************************************** #include "palbase/rel_pair.h" namespace SAGE { namespace PALBASE { // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // ~ Class: pair_filter ~ // ~ ~ // ~ Purpose: Defines the object to filter out the invalid relative pair. ~ // ~ ~ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ class pair_filter { public: pair_filter(); ~pair_filter(); bool filter_any() const; bool valid (const rel_pair& sp, bool sex_info = false, double cp = 0.0) const; bool valid_marker (const rel_pair& sp) const; bool valid_trait (const rel_pair& sp, double cp=0.0) const; bool valid_subset (const rel_pair& sp) const; bool valid_covariate(const rel_pair& sp) const; bool valid_sex_info (const rel_pair& sp) const; bool is_concordant_aff_pair (const rel_pair& sp, double cp) const; bool is_concordant_unaff_pair(const rel_pair& sp, double cp) const; bool is_discordant_pair (const rel_pair& sp, double cp) const; void add_marker(size_t m, double tolerance = std::numeric_limits<double>::infinity() ); void add_trait(size_t t, double min = -std::numeric_limits<double>::infinity(), double max = std::numeric_limits<double>::infinity()); void add_trait(size_t t, size_t a, double min = -std::numeric_limits<double>::infinity(), double max = std::numeric_limits<double>::infinity()); void add_trait(size_t t, const bool* a, double min = -std::numeric_limits<double>::infinity(), double max = std::numeric_limits<double>::infinity()); void add_subset(size_t t, double min = -std::numeric_limits<double>::infinity(), double max = std::numeric_limits<double>::infinity()); void add_subset(size_t t, size_t a, double min = -std::numeric_limits<double>::infinity(), double max = std::numeric_limits<double>::infinity()); void add_subset(size_t t, const bool* a, double min = -std::numeric_limits<double>::infinity(), double max = std::numeric_limits<double>::infinity()); void add_covariate(size_t t, double min = -std::numeric_limits<double>::infinity(), double max = std::numeric_limits<double>::infinity()); void add_pair_covariate(size_t t, double min = -std::numeric_limits<double>::infinity(), double max = std::numeric_limits<double>::infinity()); private: class filter_trait { public: filter_trait(); filter_trait(size_t t, double min = -std::numeric_limits<double>::infinity(), double max = std::numeric_limits<double>::infinity()); filter_trait(size_t t, size_t a, double min = -std::numeric_limits<double>::infinity(), double max = std::numeric_limits<double>::infinity()); filter_trait(size_t t, const bool* a, double min = -std::numeric_limits<double>::infinity(), double max = std::numeric_limits<double>::infinity()); void clear(); bool operator==(const filter_trait& m) const; bool operator<(const filter_trait& m) const; size_t trait; mutable double min; mutable double max; mutable bool affection[3]; }; class filter_marker { public: filter_marker(); filter_marker(size_t m, double tolerance = std::numeric_limits<double>::infinity()); void clear(); bool operator==(const filter_marker& m) const; bool operator<(const filter_marker& m) const; size_t marker; mutable double tolerance; }; typedef set<filter_marker> marker_set; typedef marker_set::iterator marker_iterator; typedef pair<marker_iterator, bool> marker_ibtype; typedef set<filter_trait> trait_set; typedef trait_set::iterator trait_iterator; typedef pair<trait_iterator, bool> trait_ibtype; marker_set my_markers; trait_set my_traits; trait_set my_subsets; trait_set my_covariates; trait_set my_pair_covariates; }; #include "pair_filter.ipp" } // end of namespace PALBASE } // end of namespace SAGE #endif
[ "opensagecwru@gmail.com" ]
opensagecwru@gmail.com
4dec5069ea043db4c461416cfa5984a494fd34fc
32fbef05ec5ac2de9f9df60bb49ec5d430830417
/cpp/iSparseMatrix.h
c04909271ebe6e193d2ea2c0531a628b0be128b0
[]
no_license
luoq/BS-thesis
2aa87cf5d81c0795a09e35af4e59f24bf15d5fa5
81129b411408ab4fdba21e0b2fad76f9d69f2ed3
refs/heads/master
2021-01-22T23:43:49.342629
2012-11-19T15:44:51
2012-11-19T15:44:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
14,527
h
/* iSparseMatrix.h --- * * Filename: iSparseMatrix.h * Description: my sparse matrix library * Author: Luo Qiang * Created: 03/17/2010 14:32:26 * Version: * Last-Updated: 10/17/2010 00:46:33 * By: Luo Qiang * Update #: 866 * Keywords: */ // Commentary: //use vector of sparse vector format to store //considering the much add and erase in my work //provide easy interface // Change log: // Code: #ifndef ISPARSEMATRIX_H #define ISPARSEMATRIX_H #include <vector> #include <string> #include <fstream> #include <algorithm> #include <iostream> #include "misc.h" #include "iFullMatrix.h" using namespace std; template<typename T> class element; template<typename T> bool operator<(const element<T> &,const element<T>&); template<typename T> bool operator==(const element<T> &,const element<T>&); template<typename T> class svec; template<typename T> ostream& operator<<(ostream&,const svec<T> &v); template<typename T> class smat; template<typename T> ostream& operator<<(ostream&,const smat<T> &m); template<typename T> ostream& operator<<(ostream&,const smat<T> &m); //eliminate minimal row template<typename T> T IDEM0(smat<T> &m,int node=0); //eliminate minimal row and column template<typename T> T IDEM(smat<T> &m,int node=0); //hybrd IDEM and RNW template<typename T> T H(smat<T> &m,int node=0); //for 3-regular only //eliminate row with <=2 elements //then eliminate row intersecting with maxium column template<typename T> T DEM(smat<T> &m,int node=1); //for 3-regular only //change some recursion to iteration template<typename T> T DEMiter(smat<T> &m,int node=1); //for 3-regular only //eliminate row with <=2 elements //then column <=1 elements //then eliminate row intersecting with maxium column template<typename T> T DEM2(smat<T> &m,int node=1); //for 3-regular only //eliminate row with <=2 elements //then column <=1 elements //then row with minimal elements template<typename T> T IDEM3(smat<T> &m,int node=1); //for 3-regular only //hybrid IDEM3 and RNW template<typename T> T H3(smat<T> &m,int node=1); template<typename T> void peelDEM(smat<T> &m,bool& end,T& ret); template<typename T> vector<int> selectElements(const smat<T>&,int& trytimes); template<typename T> void eliminate2(smat<T> &m,int r,int c1,int c2,T value1,T value2); template<typename T> void eliminate2T(smat<T> &m,int c,int r1,int r2,T value1,T value2); template<typename T> void eliminate1(smat<T> &m,int r,int c); template<typename T> class element { public: T value; int index; element(int index,T value) :value(value),index(index) {} element<T>&operator = (const element<T>& other) { value = other.value; index = other.index; return *this; } }; template<typename T> bool operator<(const element<T> &e1,const element<T> &e2) { return e1.index<e2.index; } template<typename T> bool operator==(const element<T> &e1,const element<T> &e2) { return e1.index==e2.index; } template <typename T> class svec { template <typename U> friend class smat; friend ostream& operator<<<> (ostream& Out,const svec<T>& v); friend ostream& operator<<<> (ostream& Out,const smat<T>& m); friend void eliminate2<>(smat<T> &m,int r,int c1,int c2,T value1,T value2); friend void eliminate2T<>(smat<T> &m,int c,int r1,int r2,T value1,T value2); friend T H<>(smat<T> &m,int node); friend T H3<>(smat<T> &m,int node); friend T IDEM<>(smat<T> &m,int node); friend T IDEM0<>(smat<T> &m,int node); friend T DEM<>(smat<T> &m,int node); friend T DEM2<>(smat<T> &m,int node); friend T IDEM3<>(smat<T> &m,int node); friend vector<int> selectElements<>(const smat<T>&,int& trytimes); friend void peelDEM<>(smat<T> &m,bool& end,T& ret); friend T DEMiter<>(smat<T> &m,int node); public: svec (){_size = 0;} svec(int size,int ennz); svec(int size) :_size(size) {} int size(){return _size;} int nnz(){return data.size();} T operator()(int i) const; //return 1 for add,-1 for erase,0 for change or nothing int set(int i,T value); //erase and return the value erased //return 0 for nothing to erase T erase(int i); void clear(); //return sum of all elements T sum(); protected: vector<element<T> > data; unsigned _size; }; template<typename T> svec<T>::svec(int size,int ennz) :_size(size) { data.reserve(ennz); } template<typename T> T svec<T>::operator()(int i) const { if(data.empty()) return 0; element<T> target(i,0); typename vector<element<T> >::const_iterator targetIterator =lower_bound(data.begin(),data.end(),target); if(targetIterator>=data.end()) return 0; if((*targetIterator).index==i) return (*targetIterator).value; return 0; } template<typename T> int svec<T>::set(int i,T value) { element<T> target(i,value); if(data.empty()) { if(value==0) return 0; data.push_back(target); return 1; } if(i>=_size) { if(target.value!=0) { _size=i+1; data.push_back(target); return 1; } return 0; } typename vector<element<T> >::iterator targetIterator = lower_bound(data.begin(),data.end(),target); if(targetIterator==data.end()) { if(value==0) return 0; data.push_back(target); return 1; } if((*targetIterator).index==i) { if(value==0) { data.erase(targetIterator); return -1; } else { (*targetIterator).value = value; return 0; } } if(value==0) return 0; else { data.insert(targetIterator,target); return 1; } } template<typename T> T svec<T>::erase(int i) { if(data.empty()) return 0; element<T> target(i,0); typename vector<element<T> >::iterator targetIterator = lower_bound(data.begin(),data.end(),target); if(targetIterator==data.end()) return 0; if((*targetIterator).index==i) { T temp=(*targetIterator).value; data.erase(targetIterator); return temp; } return 0; } template<typename T> ostream& operator<< (ostream& out,const svec<T>& v) { out<<"# size: "<<v._size<<endl; out<<"# nnz: "<<v.data.size()<<endl; for(typename vector<element<T> >::const_iterator i=v.data.begin();i != v.data.end();++i) out<<(*i).index<<'\t'<<(*i).value<<' '<<endl; return out; } template<typename T> void svec<T>::clear() { data.clear(); } template<typename T> T svec<T>::sum() { T sum = 0; for(int j=0;j<data.size();j++) sum += data[j].value; return sum; } template<typename T> class smat{ friend ostream& operator<<<> (ostream& out,const smat<T>& m); friend void eliminate2<>(smat<T> &m,int r,int c1,int c2,T value1,T value2); friend void eliminate2T<>(smat<T> &m,int c,int r1,int r2,T value1,T value2); friend T H<>(smat<T> &m,int node); friend T H3<>(smat<T> &m,int node); friend T IDEM<>(smat<T> &m,int node); friend T IDEM0<>(smat<T> &m,int node); friend T DEM<>(smat<T> &m,int node); friend T DEM2<>(smat<T> &m,int node); friend T IDEM3<>(smat<T> &m,int node); //generate a perfect match friend vector<int> selectElements<>(const smat<T>&,int& trytimes); friend void peelDEM<>(smat<T> &m,bool& end,T& ret); friend T DEMiter<>(smat<T> &m,int node); public: smat() { #ifndef nonnz _nnz = 0; #endif _cols=0; } smat(int rows,int cols) :_cols(cols),data(vector<svec<T> >(rows,svec<T>(cols))) { #ifndef nonnz _nnz=0; #endif #ifdef colnnzs _col_nnzs.assign(_cols,0); #endif } bool load(char* path); //initialize with size and allocate at least eMaxCols for each row smat(int rows,int cols,int eMaxCols); //get the element at r,c T operator()(unsigned r,unsigned c) const; //set element at (r,c) void set(int r,int c,T element); //earse element (r,c) and return its value T erase(int r,int c); void erase_row(unsigned r); void erase_col(unsigned c); void clear(); //convert to a full matrix fmat<T> full() const; //find element in a range,signal error info if fail void find(int r,int c,int start,int end,int& pos,int& info) { element<T> target(c,0); pos = lower_bound_find(data[r].data.begin()+start, data[r].data.begin()+end, target, info)-data[r].data.begin(); } element<T>& int_element(int r,int i) { return data[r].data[i]; } void int_erase(int r,int i) { //#ifdef colnnzs // _col_nnzs[int_element(r,i).index]--; //#endif data[r].data.erase(data[r].data.begin()+i); } void int_insert(int r,int i,element<T> e) { //#ifdef colnnzs // _col_nnzs[int_element(r,i).index]++; //#endif data[r].data.insert(data[r].data.begin()+i,e); } int rows() const {return data.size();} int cols() const {return _cols;} int nnz() const { #ifndef nonnz return _nnz; #else int nnz=0; for(int r=0;r<data.size();r++) nnz+=data[r].data.size(); return nnz; #endif } T row_sum(int r) const; T col_sum(int c) const; int row_nnz(int r) const; int col_nnz(int c) const; vector<int> col_nnzs() const; void print() const; protected: unsigned _cols; #ifndef nonnz unsigned _nnz; #endif #ifdef colnnzs vector<int> _col_nnzs; #endif vector<svec<T> > data; }; template<typename T> smat<T>::smat(int rows,int cols,int eMaxCols) :_cols(cols) { #ifndef nonnz _nnz=0; #endif data.reserve(rows); data.assign(rows,svec<T>(cols,eMaxCols)); #ifdef colnnzs _col_nnzs.assign(_cols,0); #endif } template <typename T> void smat<T>::set(int r,int c,T value) { #ifndef noautoenlarge //this following allows change of size,which is not useful in my experiment if(r>=data.size()) { if(value!=0) data.resize(r+1); else return; } if(c>=_cols) //this test maybe wrong other than int type { if(value!=0) _cols = c+1; else return; } #endif int temp=data[r].set(c,value); #ifndef nonnz _nnz+=temp; #endif #ifdef colnnzs _col_nnzs[c]+=temp; #endif } template<typename T> T smat<T>::operator()(unsigned r,unsigned c) const { //disabale check to speed up //if(r>=data.size()) // return 0; return (data[r])(c); } template<typename T> T smat<T>::erase(int r,int c) { //disable check for speed //if(r>=data.size()) // return 0; T ret = (data[r]).erase(c); #ifndef nonnz if(ret!=0) _nnz--; #endif #ifdef colnnzs if(ret!=0) _col_nnzs[c]--; #endif return ret; } template<typename T> void smat<T>::erase_row(unsigned r) { //disable check for speed //if(r>=data.size()) // return; #ifndef nonnz _nnz-=data[r].data.size(); #endif #ifdef colnnzs for(int i=0;i<data[r].data.size();i++) _col_nnzs[data[r].data[i].index]--; #endif data.erase(data.begin()+r); } template<typename T> void smat<T>::erase_col(unsigned c) { //disable check for speed //if(c>=_cols) // return; element<T> target(c,0); int pos,info; #ifndef nonnz int numErased=0; #endif for(unsigned r=0;r<data.size();r++) { pos = lower_bound_find(data[r].data.begin(),data[r].data.end(),target,info)-data[r].data.begin(); if(info==-1 || info==2) continue; for(unsigned col=pos;col<data[r].data.size();col++) data[r].data[col].index--; if(info==0) { #ifndef nonnz numErased++; #endif data[r].data.erase(data[r].data.begin()+pos); } } #ifndef nonnz _nnz-=numErased; #endif #ifdef colnnzs _col_nnzs.erase(_col_nnzs.begin()+c); #endif _cols--; } template<typename T> ostream & operator<<(ostream &out,const smat<T> &m) { out<<"# Created by iSpareMatrix"<<endl; out<<"# who am i"<<endl; out<<"# type: sparse matrix"<<endl; out<<"# nnz:"<<m.nnz()<<endl; out<<"# rows:"<<m.data.size()<<endl; out<<"# columns:"<<m._cols<<endl; for(int r=0;r<m.data.size();r++) for(int i=0;i<m.data[r].data.size();i++) out<<r<<'\t'<<(m.data[r].data)[i].index <<'\t'<<(m.data[r].data)[i].value<<endl; return out; } template<typename T> void smat<T>::clear() { #ifndef nonnz _nnz = 0; #endif #ifdef colnnzs _col_nnzs.assign(_cols,0); #endif for(int r=0;r<data.size();r++) data[r].clear(); } template<typename T> fmat<T> smat<T>::full() const { fmat<T> m(data.size(),_cols); for(int r=0;r<data.size();r++) for(int i=0;i<data[r].data.size();i++) m(r,data[r].data[i].index)=data[r].data[i].value; return m; } template<typename T> T smat<T>::row_sum(int r) const { return data[r].sum(); } template<typename T> T smat<T>::col_sum(int c) const { T sum = 0; for(int r=0;r<data.size();r++) sum += data[r](c); return sum; } template<typename T> int smat<T>::row_nnz(int r) const { return data[r].data.size(); } template<typename T> int smat<T>::col_nnz(int c) const { #ifdef colnnzs return _col_nnzs[c]; #else int nnz = 0; for(int r=0;r<data.size();r++) nnz+=int(data[r](c)!=0); return nnz; #endif } template<typename T> bool smat<T>::load(char* path) { ifstream In(path); if(!In) return false; //get head and parse string head; int minIndex = 0; getline(In,head); if(head.find("Octave ") != string::npos) minIndex=1; //get matrix size and nnz int nnz,rows,cols; In.ignore(1024,'\n'); In.ignore(1024,'\n'); In.ignore(1024,':'); In>>nnz; In.ignore(1024,':'); In>>rows; In.ignore(1024,':'); In>>cols; _cols = cols; data.assign(rows,svec<T>(cols,nnz/rows)); #ifdef colnnzs _col_nnzs.assign(cols,0); #endif int r,c; T value; while(In>>r>>c>>value) { r -= minIndex; c -= minIndex; //data[r].data.push_back(element<T>(c,value)); this->set(r,c,value); } In.close(); return true; } template<typename T> vector<int> smat<T>::col_nnzs() const { #ifdef colnnzs return _col_nnzs; #else //get column with minimal elements vector<int> helpIndex(data.size(),-1); vector<int> colSize(_cols,0); for(int r=0;r<helpIndex.size();r++) if(!data[r].data.empty()) helpIndex[r] = 0; for(int r=0;r<data.size();r++) { for(int c=0;c<_cols;c++) { if(helpIndex[r]==-1) break; if(c==data[r].data[helpIndex[r]].index) { colSize[c]++; if(helpIndex[r]==data[r].data.size()-1) helpIndex[r] = -1; else helpIndex[r]++; } } } return colSize; #endif } template <typename T> void smat<T>::print() const { //cout<<100*(double)_nnz/(_cols*_cols)<<" %\\n"; #ifdef plot #ifndef nonnz cout<<_nnz<<"\\n"; #endif for(int i=0;i<data.size();i++) { for(int j=0;j<_cols;j++) cout<<this->operator()(i,j)<<' '; cout<<"\\n"; } #else for(int i=0;i<data.size();i++) { for(int j=0;j<_cols;j++) cout<<this->operator()(i,j)<<' '; cout<<"\n"; } #endif } #endif /* _ISPARSEMATRIX_H_ */
[ "luoq08@gmail.com" ]
luoq08@gmail.com
61aba8ec5d0d87bf3c795c9ac001e8b4722fc989
4a598ca49e4be7c15609a94df9118bf2974a1318
/src/rpcserver.cpp
29986152ab49b50f9aeb5d98b17201ed67fcbad9
[ "MIT" ]
permissive
LordSoylent/SMNCoin
b41796e0dbb5484a7fa0821d2e273e198f8c9aff
01918f456f726a9240df4ccfffdd3626f9ddba4f
refs/heads/master
2020-03-28T19:23:47.897382
2018-06-05T00:17:59
2018-06-05T00:17:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
43,962
cpp
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The PIVX developers // Copyright (c) 2018 The Somnio developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "rpcserver.h" #include "base58.h" #include "init.h" #include "main.h" #include "ui_interface.h" #include "util.h" #ifdef ENABLE_WALLET #include "wallet.h" #endif #include "json/json_spirit_writer_template.h" #include <boost/algorithm/string.hpp> #include <boost/asio.hpp> #include <boost/asio/ssl.hpp> #include <boost/bind.hpp> #include <boost/filesystem.hpp> #include <boost/foreach.hpp> #include <boost/iostreams/concepts.hpp> #include <boost/iostreams/stream.hpp> #include <boost/shared_ptr.hpp> #include <boost/thread.hpp> using namespace boost; using namespace boost::asio; using namespace json_spirit; using namespace std; static std::string strRPCUserColonPass; static bool fRPCRunning = false; static bool fRPCInWarmup = true; static std::string rpcWarmupStatus("RPC server started"); static CCriticalSection cs_rpcWarmup; //! These are created by StartRPCThreads, destroyed in StopRPCThreads static asio::io_service* rpc_io_service = NULL; static map<string, boost::shared_ptr<deadline_timer> > deadlineTimers; static ssl::context* rpc_ssl_context = NULL; static boost::thread_group* rpc_worker_group = NULL; static boost::asio::io_service::work* rpc_dummy_work = NULL; static std::vector<CSubNet> rpc_allow_subnets; //!< List of subnets to allow RPC connections from static std::vector<boost::shared_ptr<ip::tcp::acceptor> > rpc_acceptors; void RPCTypeCheck(const Array& params, const list<Value_type>& typesExpected, bool fAllowNull) { unsigned int i = 0; BOOST_FOREACH (Value_type t, typesExpected) { if (params.size() <= i) break; const Value& v = params[i]; if (!((v.type() == t) || (fAllowNull && (v.type() == null_type)))) { string err = strprintf("Expected type %s, got %s", Value_type_name[t], Value_type_name[v.type()]); throw JSONRPCError(RPC_TYPE_ERROR, err); } i++; } } void RPCTypeCheck(const Object& o, const map<string, Value_type>& typesExpected, bool fAllowNull) { BOOST_FOREACH (const PAIRTYPE(string, Value_type) & t, typesExpected) { const Value& v = find_value(o, t.first); if (!fAllowNull && v.type() == null_type) throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing %s", t.first)); if (!((v.type() == t.second) || (fAllowNull && (v.type() == null_type)))) { string err = strprintf("Expected type %s for %s, got %s", Value_type_name[t.second], t.first, Value_type_name[v.type()]); throw JSONRPCError(RPC_TYPE_ERROR, err); } } } static inline int64_t roundint64(double d) { return (int64_t)(d > 0 ? d + 0.5 : d - 0.5); } CAmount AmountFromValue(const Value& value) { double dAmount = value.get_real(); if (dAmount <= 0.0 || dAmount > 21000000.0) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount"); CAmount nAmount = roundint64(dAmount * COIN); if (!MoneyRange(nAmount)) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount"); return nAmount; } Value ValueFromAmount(const CAmount& amount) { return (double)amount / (double)COIN; } uint256 ParseHashV(const Value& v, string strName) { string strHex; if (v.type() == str_type) strHex = v.get_str(); if (!IsHex(strHex)) // Note: IsHex("") is false throw JSONRPCError(RPC_INVALID_PARAMETER, strName + " must be hexadecimal string (not '" + strHex + "')"); uint256 result; result.SetHex(strHex); return result; } uint256 ParseHashO(const Object& o, string strKey) { return ParseHashV(find_value(o, strKey), strKey); } vector<unsigned char> ParseHexV(const Value& v, string strName) { string strHex; if (v.type() == str_type) strHex = v.get_str(); if (!IsHex(strHex)) throw JSONRPCError(RPC_INVALID_PARAMETER, strName + " must be hexadecimal string (not '" + strHex + "')"); return ParseHex(strHex); } vector<unsigned char> ParseHexO(const Object& o, string strKey) { return ParseHexV(find_value(o, strKey), strKey); } int ParseInt(const Object& o, string strKey) { const Value& v = find_value(o, strKey); if (v.type() != int_type) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, " + strKey + "is not an int"); return v.get_int(); } bool ParseBool(const Object& o, string strKey) { const Value& v = find_value(o, strKey); if (v.type() != bool_type) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, " + strKey + "is not a bool"); return v.get_bool(); } /** * Note: This interface may still be subject to change. */ string CRPCTable::help(string strCommand) const { string strRet; string category; set<rpcfn_type> setDone; vector<pair<string, const CRPCCommand*> > vCommands; for (map<string, const CRPCCommand*>::const_iterator mi = mapCommands.begin(); mi != mapCommands.end(); ++mi) vCommands.push_back(make_pair(mi->second->category + mi->first, mi->second)); sort(vCommands.begin(), vCommands.end()); BOOST_FOREACH (const PAIRTYPE(string, const CRPCCommand*) & command, vCommands) { const CRPCCommand* pcmd = command.second; string strMethod = pcmd->name; // We already filter duplicates, but these deprecated screw up the sort order if (strMethod.find("label") != string::npos) continue; if ((strCommand != "" || pcmd->category == "hidden") && strMethod != strCommand) continue; #ifdef ENABLE_WALLET if (pcmd->reqWallet && !pwalletMain) continue; #endif try { Array params; rpcfn_type pfn = pcmd->actor; if (setDone.insert(pfn).second) (*pfn)(params, true); } catch (std::exception& e) { // Help text is returned in an exception string strHelp = string(e.what()); if (strCommand == "") { if (strHelp.find('\n') != string::npos) strHelp = strHelp.substr(0, strHelp.find('\n')); if (category != pcmd->category) { if (!category.empty()) strRet += "\n"; category = pcmd->category; string firstLetter = category.substr(0, 1); boost::to_upper(firstLetter); strRet += "== " + firstLetter + category.substr(1) + " ==\n"; } } strRet += strHelp + "\n"; } } if (strRet == "") strRet = strprintf("help: unknown command: %s\n", strCommand); strRet = strRet.substr(0, strRet.size() - 1); return strRet; } Value help(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "help ( \"command\" )\n" "\nList all commands, or get help for a specified command.\n" "\nArguments:\n" "1. \"command\" (string, optional) The command to get help on\n" "\nResult:\n" "\"text\" (string) The help text\n"); string strCommand; if (params.size() > 0) strCommand = params[0].get_str(); return tableRPC.help(strCommand); } Value stop(const Array& params, bool fHelp) { // Accept the deprecated and ignored 'detach' boolean argument if (fHelp || params.size() > 1) throw runtime_error( "stop\n" "\nStop Somnio server."); // Shutdown will take long enough that the response should get back StartShutdown(); return "Somnio server stopping"; } /** * Call Table */ static const CRPCCommand vRPCCommands[] = { // category name actor (function) okSafeMode threadSafe reqWallet // --------------------- ------------------------ ----------------------- ---------- ---------- --------- /* Overall control/query calls */ {"control", "getinfo", &getinfo, true, false, false}, /* uses wallet if enabled */ {"control", "help", &help, true, true, false}, {"control", "stop", &stop, true, true, false}, /* P2P networking */ {"network", "getnetworkinfo", &getnetworkinfo, true, false, false}, {"network", "addnode", &addnode, true, true, false}, {"network", "getaddednodeinfo", &getaddednodeinfo, true, true, false}, {"network", "getconnectioncount", &getconnectioncount, true, false, false}, {"network", "getnettotals", &getnettotals, true, true, false}, {"network", "getpeerinfo", &getpeerinfo, true, false, false}, {"network", "ping", &ping, true, false, false}, /* Block chain and UTXO */ {"blockchain", "getblockchaininfo", &getblockchaininfo, true, false, false}, {"blockchain", "getbestblockhash", &getbestblockhash, true, false, false}, {"blockchain", "getblockcount", &getblockcount, true, false, false}, {"blockchain", "getblock", &getblock, true, false, false}, {"blockchain", "getblockhash", &getblockhash, true, false, false}, {"blockchain", "getblockheader", &getblockheader, false, false, false}, {"blockchain", "getchaintips", &getchaintips, true, false, false}, {"blockchain", "getdifficulty", &getdifficulty, true, false, false}, {"blockchain", "getmempoolinfo", &getmempoolinfo, true, true, false}, {"blockchain", "getrawmempool", &getrawmempool, true, false, false}, {"blockchain", "gettxout", &gettxout, true, false, false}, {"blockchain", "gettxoutsetinfo", &gettxoutsetinfo, true, false, false}, {"blockchain", "verifychain", &verifychain, true, false, false}, {"blockchain", "invalidateblock", &invalidateblock, true, true, false}, {"blockchain", "reconsiderblock", &reconsiderblock, true, true, false}, /* Mining */ {"mining", "getblocktemplate", &getblocktemplate, true, false, false}, {"mining", "getmininginfo", &getmininginfo, true, false, false}, {"mining", "getnetworkhashps", &getnetworkhashps, true, false, false}, {"mining", "prioritisetransaction", &prioritisetransaction, true, false, false}, {"mining", "submitblock", &submitblock, true, true, false}, {"mining", "reservebalance", &reservebalance, true, true, false}, #ifdef ENABLE_WALLET /* Coin generation */ {"generating", "getgenerate", &getgenerate, true, false, false}, {"generating", "gethashespersec", &gethashespersec, true, false, false}, {"generating", "setgenerate", &setgenerate, true, true, false}, #endif /* Raw transactions */ {"rawtransactions", "createrawtransaction", &createrawtransaction, true, false, false}, {"rawtransactions", "decoderawtransaction", &decoderawtransaction, true, false, false}, {"rawtransactions", "decodescript", &decodescript, true, false, false}, {"rawtransactions", "getrawtransaction", &getrawtransaction, true, false, false}, {"rawtransactions", "sendrawtransaction", &sendrawtransaction, false, false, false}, {"rawtransactions", "signrawtransaction", &signrawtransaction, false, false, false}, /* uses wallet if enabled */ /* Utility functions */ {"util", "createmultisig", &createmultisig, true, true, false}, {"util", "validateaddress", &validateaddress, true, false, false}, /* uses wallet if enabled */ {"util", "verifymessage", &verifymessage, true, false, false}, {"util", "estimatefee", &estimatefee, true, true, false}, {"util", "estimatepriority", &estimatepriority, true, true, false}, {"util", "makekeypair", &makekeypair, true, true, false }, /* Not shown in help */ {"hidden", "invalidateblock", &invalidateblock, true, true, false}, {"hidden", "reconsiderblock", &reconsiderblock, true, true, false}, {"hidden", "setmocktime", &setmocktime, true, false, false}, /* Somnio features */ {"somnio", "masternode", &masternode, true, true, false}, {"somnio", "listmasternodes", &listmasternodes, true, true, false}, {"somnio", "getmasternodecount", &getmasternodecount, true, true, false}, {"somnio", "masternodeconnect", &masternodeconnect, true, true, false}, {"somnio", "masternodecurrent", &masternodecurrent, true, true, false}, {"somnio", "masternodedebug", &masternodedebug, true, true, false}, {"somnio", "startmasternode", &startmasternode, true, true, false}, {"somnio", "createmasternodekey", &createmasternodekey, true, true, false}, {"somnio", "getmasternodeoutputs", &getmasternodeoutputs, true, true, false}, {"somnio", "listmasternodeconf", &listmasternodeconf, true, true, false}, {"somnio", "getmasternodestatus", &getmasternodestatus, true, true, false}, {"somnio", "getmasternodewinners", &getmasternodewinners, true, true, false}, {"somnio", "getmasternodescores", &getmasternodescores, true, true, false}, {"somnio", "mnbudget", &mnbudget, true, true, false}, {"somnio", "preparebudget", &preparebudget, true, true, false}, {"somnio", "submitbudget", &submitbudget, true, true, false}, {"somnio", "mnbudgetvote", &mnbudgetvote, true, true, false}, {"somnio", "getbudgetvotes", &getbudgetvotes, true, true, false}, {"somnio", "getnextsuperblock", &getnextsuperblock, true, true, false}, {"somnio", "getbudgetprojection", &getbudgetprojection, true, true, false}, {"somnio", "getbudgetinfo", &getbudgetinfo, true, true, false}, {"somnio", "mnbudgetrawvote", &mnbudgetrawvote, true, true, false}, {"somnio", "mnfinalbudget", &mnfinalbudget, true, true, false}, {"somnio", "checkbudgets", &checkbudgets, true, true, false}, {"somnio", "mnsync", &mnsync, true, true, false}, {"somnio", "spork", &spork, true, true, false}, {"somnio", "getpoolinfo", &getpoolinfo, true, true, false}, #ifdef ENABLE_WALLET {"somnio", "obfuscation", &obfuscation, false, false, true}, /* not threadSafe because of SendMoney */ /* Wallet */ {"wallet", "addmultisigaddress", &addmultisigaddress, true, false, true}, {"wallet", "autocombinerewards", &autocombinerewards, false, false, true}, {"wallet", "backupwallet", &backupwallet, true, false, true}, {"wallet", "dumpprivkey", &dumpprivkey, true, false, true}, {"wallet", "dumpwallet", &dumpwallet, true, false, true}, {"wallet", "bip38encrypt", &bip38encrypt, true, false, true}, {"wallet", "bip38decrypt", &bip38decrypt, true, false, true}, {"wallet", "encryptwallet", &encryptwallet, true, false, true}, {"wallet", "getaccountaddress", &getaccountaddress, true, false, true}, {"wallet", "getaccount", &getaccount, true, false, true}, {"wallet", "getaddressesbyaccount", &getaddressesbyaccount, true, false, true}, {"wallet", "getbalance", &getbalance, false, false, true}, {"wallet", "getnewaddress", &getnewaddress, true, false, true}, {"wallet", "getrawchangeaddress", &getrawchangeaddress, true, false, true}, {"wallet", "getreceivedbyaccount", &getreceivedbyaccount, false, false, true}, {"wallet", "getreceivedbyaddress", &getreceivedbyaddress, false, false, true}, {"wallet", "getstakingstatus", &getstakingstatus, false, false, true}, {"wallet", "getstakesplitthreshold", &getstakesplitthreshold, false, false, true}, {"wallet", "gettransaction", &gettransaction, false, false, true}, {"wallet", "getunconfirmedbalance", &getunconfirmedbalance, false, false, true}, {"wallet", "getwalletinfo", &getwalletinfo, false, false, true}, {"wallet", "importprivkey", &importprivkey, true, false, true}, {"wallet", "importwallet", &importwallet, true, false, true}, {"wallet", "importaddress", &importaddress, true, false, true}, {"wallet", "keypoolrefill", &keypoolrefill, true, false, true}, {"wallet", "listaccounts", &listaccounts, false, false, true}, {"wallet", "listaddressgroupings", &listaddressgroupings, false, false, true}, {"wallet", "listlockunspent", &listlockunspent, false, false, true}, {"wallet", "listreceivedbyaccount", &listreceivedbyaccount, false, false, true}, {"wallet", "listreceivedbyaddress", &listreceivedbyaddress, false, false, true}, {"wallet", "listsinceblock", &listsinceblock, false, false, true}, {"wallet", "listtransactions", &listtransactions, false, false, true}, {"wallet", "listunspent", &listunspent, false, false, true}, {"wallet", "lockunspent", &lockunspent, true, false, true}, {"wallet", "move", &movecmd, false, false, true}, {"wallet", "multisend", &multisend, false, false, true}, {"wallet", "sendfrom", &sendfrom, false, false, true}, {"wallet", "sendmany", &sendmany, false, false, true}, {"wallet", "sendtoaddress", &sendtoaddress, false, false, true}, {"wallet", "sendtoaddressix", &sendtoaddressix, false, false, true}, {"wallet", "setaccount", &setaccount, true, false, true}, {"wallet", "setstakesplitthreshold", &setstakesplitthreshold, false, false, true}, {"wallet", "settxfee", &settxfee, true, false, true}, {"wallet", "signmessage", &signmessage, true, false, true}, {"wallet", "walletlock", &walletlock, true, false, true}, {"wallet", "walletpassphrasechange", &walletpassphrasechange, true, false, true}, {"wallet", "walletpassphrase", &walletpassphrase, true, false, true}, {"zerocoin", "getzerocoinbalance", &getzerocoinbalance, false, false, true}, {"zerocoin", "listmintedzerocoins", &listmintedzerocoins, false, false, true}, {"zerocoin", "listspentzerocoins", &listspentzerocoins, false, false, true}, {"zerocoin", "listzerocoinamounts", &listzerocoinamounts, false, false, true}, {"zerocoin", "mintzerocoin", &mintzerocoin, false, false, true}, {"zerocoin", "spendzerocoin", &spendzerocoin, false, false, true}, {"zerocoin", "resetmintzerocoin", &resetmintzerocoin, false, false, true}, {"zerocoin", "resetspentzerocoin", &resetspentzerocoin, false, false, true}, {"zerocoin", "getarchivedzerocoin", &getarchivedzerocoin, false, false, true}, {"zerocoin", "importzerocoins", &importzerocoins, false, false, true}, {"zerocoin", "exportzerocoins", &exportzerocoins, false, false, true}, {"zerocoin", "reconsiderzerocoins", &reconsiderzerocoins, false, false, true} #endif // ENABLE_WALLET }; CRPCTable::CRPCTable() { unsigned int vcidx; for (vcidx = 0; vcidx < (sizeof(vRPCCommands) / sizeof(vRPCCommands[0])); vcidx++) { const CRPCCommand* pcmd; pcmd = &vRPCCommands[vcidx]; mapCommands[pcmd->name] = pcmd; } } const CRPCCommand* CRPCTable::operator[](string name) const { map<string, const CRPCCommand*>::const_iterator it = mapCommands.find(name); if (it == mapCommands.end()) return NULL; return (*it).second; } bool HTTPAuthorized(map<string, string>& mapHeaders) { string strAuth = mapHeaders["authorization"]; if (strAuth.substr(0, 6) != "Basic ") return false; string strUserPass64 = strAuth.substr(6); boost::trim(strUserPass64); string strUserPass = DecodeBase64(strUserPass64); return TimingResistantEqual(strUserPass, strRPCUserColonPass); } void ErrorReply(std::ostream& stream, const Object& objError, const Value& id) { // Send error reply from json-rpc error object int nStatus = HTTP_INTERNAL_SERVER_ERROR; int code = find_value(objError, "code").get_int(); if (code == RPC_INVALID_REQUEST) nStatus = HTTP_BAD_REQUEST; else if (code == RPC_METHOD_NOT_FOUND) nStatus = HTTP_NOT_FOUND; string strReply = JSONRPCReply(Value::null, objError, id); stream << HTTPReply(nStatus, strReply, false) << std::flush; } CNetAddr BoostAsioToCNetAddr(boost::asio::ip::address address) { CNetAddr netaddr; // Make sure that IPv4-compatible and IPv4-mapped IPv6 addresses are treated as IPv4 addresses if (address.is_v6() && (address.to_v6().is_v4_compatible() || address.to_v6().is_v4_mapped())) address = address.to_v6().to_v4(); if (address.is_v4()) { boost::asio::ip::address_v4::bytes_type bytes = address.to_v4().to_bytes(); netaddr.SetRaw(NET_IPV4, &bytes[0]); } else { boost::asio::ip::address_v6::bytes_type bytes = address.to_v6().to_bytes(); netaddr.SetRaw(NET_IPV6, &bytes[0]); } return netaddr; } bool ClientAllowed(const boost::asio::ip::address& address) { CNetAddr netaddr = BoostAsioToCNetAddr(address); BOOST_FOREACH (const CSubNet& subnet, rpc_allow_subnets) if (subnet.Match(netaddr)) return true; return false; } template <typename Protocol> class AcceptedConnectionImpl : public AcceptedConnection { public: AcceptedConnectionImpl( asio::io_service& io_service, ssl::context& context, bool fUseSSL) : sslStream(io_service, context), _d(sslStream, fUseSSL), _stream(_d) { } virtual std::iostream& stream() { return _stream; } virtual std::string peer_address_to_string() const { return peer.address().to_string(); } virtual void close() { _stream.close(); } typename Protocol::endpoint peer; asio::ssl::stream<typename Protocol::socket> sslStream; private: SSLIOStreamDevice<Protocol> _d; iostreams::stream<SSLIOStreamDevice<Protocol> > _stream; }; void ServiceConnection(AcceptedConnection* conn); //! Forward declaration required for RPCListen template <typename Protocol, typename SocketAcceptorService> static void RPCAcceptHandler(boost::shared_ptr<basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor, ssl::context& context, bool fUseSSL, boost::shared_ptr<AcceptedConnection> conn, const boost::system::error_code& error); /** * Sets up I/O resources to accept and handle a new connection. */ template <typename Protocol, typename SocketAcceptorService> static void RPCListen(boost::shared_ptr<basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor, ssl::context& context, const bool fUseSSL) { // Accept connection boost::shared_ptr<AcceptedConnectionImpl<Protocol> > conn(new AcceptedConnectionImpl<Protocol>(acceptor->get_io_service(), context, fUseSSL)); acceptor->async_accept( conn->sslStream.lowest_layer(), conn->peer, boost::bind(&RPCAcceptHandler<Protocol, SocketAcceptorService>, acceptor, boost::ref(context), fUseSSL, conn, _1)); } /** * Accept and handle incoming connection. */ template <typename Protocol, typename SocketAcceptorService> static void RPCAcceptHandler(boost::shared_ptr<basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor, ssl::context& context, const bool fUseSSL, boost::shared_ptr<AcceptedConnection> conn, const boost::system::error_code& error) { // Immediately start accepting new connections, except when we're cancelled or our socket is closed. if (error != asio::error::operation_aborted && acceptor->is_open()) RPCListen(acceptor, context, fUseSSL); AcceptedConnectionImpl<ip::tcp>* tcp_conn = dynamic_cast<AcceptedConnectionImpl<ip::tcp>*>(conn.get()); if (error) { // TODO: Actually handle errors LogPrintf("%s: Error: %s\n", __func__, error.message()); } // Restrict callers by IP. It is important to // do this before starting client thread, to filter out // certain DoS and misbehaving clients. else if (tcp_conn && !ClientAllowed(tcp_conn->peer.address())) { // Only send a 403 if we're not using SSL to prevent a DoS during the SSL handshake. if (!fUseSSL) conn->stream() << HTTPError(HTTP_FORBIDDEN, false) << std::flush; conn->close(); } else { ServiceConnection(conn.get()); conn->close(); } } static ip::tcp::endpoint ParseEndpoint(const std::string& strEndpoint, int defaultPort) { std::string addr; int port = defaultPort; SplitHostPort(strEndpoint, port, addr); return ip::tcp::endpoint(asio::ip::address::from_string(addr), port); } void StartRPCThreads() { rpc_allow_subnets.clear(); rpc_allow_subnets.push_back(CSubNet("127.0.0.0/8")); // always allow IPv4 local subnet rpc_allow_subnets.push_back(CSubNet("::1")); // always allow IPv6 localhost if (mapMultiArgs.count("-rpcallowip")) { const vector<string>& vAllow = mapMultiArgs["-rpcallowip"]; BOOST_FOREACH (string strAllow, vAllow) { CSubNet subnet(strAllow); if (!subnet.IsValid()) { uiInterface.ThreadSafeMessageBox( strprintf("Invalid -rpcallowip subnet specification: %s. Valid are a single IP (e.g. 1.2.3.4), a network/netmask (e.g. 1.2.3.4/255.255.255.0) or a network/CIDR (e.g. 1.2.3.4/24).", strAllow), "", CClientUIInterface::MSG_ERROR); StartShutdown(); return; } rpc_allow_subnets.push_back(subnet); } } std::string strAllowed; BOOST_FOREACH (const CSubNet& subnet, rpc_allow_subnets) strAllowed += subnet.ToString() + " "; LogPrint("rpc", "Allowing RPC connections from: %s\n", strAllowed); strRPCUserColonPass = mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]; if (((mapArgs["-rpcpassword"] == "") || (mapArgs["-rpcuser"] == mapArgs["-rpcpassword"])) && Params().RequireRPCPassword()) { unsigned char rand_pwd[32]; GetRandBytes(rand_pwd, 32); uiInterface.ThreadSafeMessageBox(strprintf( _("To use somniod, or the -server option to somnio-qt, you must set an rpcpassword in the configuration file:\n" "%s\n" "It is recommended you use the following random password:\n" "rpcuser=somniorpc\n" "rpcpassword=%s\n" "(you do not need to remember this password)\n" "The username and password MUST NOT be the same.\n" "If the file does not exist, create it with owner-readable-only file permissions.\n" "It is also recommended to set alertnotify so you are notified of problems;\n" "for example: alertnotify=echo %%s | mail -s \"Somnio Alert\" admin@foo.com\n"), GetConfigFile().string(), EncodeBase58(&rand_pwd[0], &rand_pwd[0] + 32)), "", CClientUIInterface::MSG_ERROR | CClientUIInterface::SECURE); StartShutdown(); return; } assert(rpc_io_service == NULL); rpc_io_service = new asio::io_service(); rpc_ssl_context = new ssl::context(*rpc_io_service, ssl::context::sslv23); const bool fUseSSL = GetBoolArg("-rpcssl", false); if (fUseSSL) { rpc_ssl_context->set_options(ssl::context::no_sslv2 | ssl::context::no_sslv3); filesystem::path pathCertFile(GetArg("-rpcsslcertificatechainfile", "server.cert")); if (!pathCertFile.is_complete()) pathCertFile = filesystem::path(GetDataDir()) / pathCertFile; if (filesystem::exists(pathCertFile)) rpc_ssl_context->use_certificate_chain_file(pathCertFile.string()); else LogPrintf("ThreadRPCServer ERROR: missing server certificate file %s\n", pathCertFile.string()); filesystem::path pathPKFile(GetArg("-rpcsslprivatekeyfile", "server.pem")); if (!pathPKFile.is_complete()) pathPKFile = filesystem::path(GetDataDir()) / pathPKFile; if (filesystem::exists(pathPKFile)) rpc_ssl_context->use_private_key_file(pathPKFile.string(), ssl::context::pem); else LogPrintf("ThreadRPCServer ERROR: missing server private key file %s\n", pathPKFile.string()); string strCiphers = GetArg("-rpcsslciphers", "TLSv1.2+HIGH:TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!3DES:@STRENGTH"); SSL_CTX_set_cipher_list(rpc_ssl_context->impl(), strCiphers.c_str()); } std::vector<ip::tcp::endpoint> vEndpoints; bool bBindAny = false; int defaultPort = GetArg("-rpcport", BaseParams().RPCPort()); if (!mapArgs.count("-rpcallowip")) // Default to loopback if not allowing external IPs { vEndpoints.push_back(ip::tcp::endpoint(asio::ip::address_v6::loopback(), defaultPort)); vEndpoints.push_back(ip::tcp::endpoint(asio::ip::address_v4::loopback(), defaultPort)); if (mapArgs.count("-rpcbind")) { LogPrintf("WARNING: option -rpcbind was ignored because -rpcallowip was not specified, refusing to allow everyone to connect\n"); } } else if (mapArgs.count("-rpcbind")) // Specific bind address { BOOST_FOREACH (const std::string& addr, mapMultiArgs["-rpcbind"]) { try { vEndpoints.push_back(ParseEndpoint(addr, defaultPort)); } catch (const boost::system::system_error&) { uiInterface.ThreadSafeMessageBox( strprintf(_("Could not parse -rpcbind value %s as network address"), addr), "", CClientUIInterface::MSG_ERROR); StartShutdown(); return; } } } else { // No specific bind address specified, bind to any vEndpoints.push_back(ip::tcp::endpoint(asio::ip::address_v6::any(), defaultPort)); vEndpoints.push_back(ip::tcp::endpoint(asio::ip::address_v4::any(), defaultPort)); // Prefer making the socket dual IPv6/IPv4 instead of binding // to both addresses seperately. bBindAny = true; } bool fListening = false; std::string strerr; std::string straddress; BOOST_FOREACH (const ip::tcp::endpoint& endpoint, vEndpoints) { try { asio::ip::address bindAddress = endpoint.address(); straddress = bindAddress.to_string(); LogPrintf("Binding RPC on address %s port %i (IPv4+IPv6 bind any: %i)\n", straddress, endpoint.port(), bBindAny); boost::system::error_code v6_only_error; boost::shared_ptr<ip::tcp::acceptor> acceptor(new ip::tcp::acceptor(*rpc_io_service)); acceptor->open(endpoint.protocol()); acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true)); // Try making the socket dual IPv6/IPv4 when listening on the IPv6 "any" address acceptor->set_option(boost::asio::ip::v6_only( !bBindAny || bindAddress != asio::ip::address_v6::any()), v6_only_error); acceptor->bind(endpoint); acceptor->listen(socket_base::max_connections); RPCListen(acceptor, *rpc_ssl_context, fUseSSL); rpc_acceptors.push_back(acceptor); fListening = true; rpc_acceptors.push_back(acceptor); // If dual IPv6/IPv4 bind successful, skip binding to IPv4 separately if (bBindAny && bindAddress == asio::ip::address_v6::any() && !v6_only_error) break; } catch (boost::system::system_error& e) { LogPrintf("ERROR: Binding RPC on address %s port %i failed: %s\n", straddress, endpoint.port(), e.what()); strerr = strprintf(_("An error occurred while setting up the RPC address %s port %u for listening: %s"), straddress, endpoint.port(), e.what()); } } if (!fListening) { uiInterface.ThreadSafeMessageBox(strerr, "", CClientUIInterface::MSG_ERROR); StartShutdown(); return; } rpc_worker_group = new boost::thread_group(); for (int i = 0; i < GetArg("-rpcthreads", 4); i++) rpc_worker_group->create_thread(boost::bind(&asio::io_service::run, rpc_io_service)); fRPCRunning = true; } void StartDummyRPCThread() { if (rpc_io_service == NULL) { rpc_io_service = new asio::io_service(); /* Create dummy "work" to keep the thread from exiting when no timeouts active, * see http://www.boost.org/doc/libs/1_51_0/doc/html/boost_asio/reference/io_service.html#boost_asio.reference.io_service.stopping_the_io_service_from_running_out_of_work */ rpc_dummy_work = new asio::io_service::work(*rpc_io_service); rpc_worker_group = new boost::thread_group(); rpc_worker_group->create_thread(boost::bind(&asio::io_service::run, rpc_io_service)); fRPCRunning = true; } } void StopRPCThreads() { if (rpc_io_service == NULL) return; // Set this to false first, so that longpolling loops will exit when woken up fRPCRunning = false; // First, cancel all timers and acceptors // This is not done automatically by ->stop(), and in some cases the destructor of // asio::io_service can hang if this is skipped. boost::system::error_code ec; BOOST_FOREACH (const boost::shared_ptr<ip::tcp::acceptor>& acceptor, rpc_acceptors) { acceptor->cancel(ec); if (ec) LogPrintf("%s: Warning: %s when cancelling acceptor", __func__, ec.message()); } rpc_acceptors.clear(); BOOST_FOREACH (const PAIRTYPE(std::string, boost::shared_ptr<deadline_timer>) & timer, deadlineTimers) { timer.second->cancel(ec); if (ec) LogPrintf("%s: Warning: %s when cancelling timer", __func__, ec.message()); } deadlineTimers.clear(); rpc_io_service->stop(); cvBlockChange.notify_all(); if (rpc_worker_group != NULL) rpc_worker_group->join_all(); delete rpc_dummy_work; rpc_dummy_work = NULL; delete rpc_worker_group; rpc_worker_group = NULL; delete rpc_ssl_context; rpc_ssl_context = NULL; delete rpc_io_service; rpc_io_service = NULL; } bool IsRPCRunning() { return fRPCRunning; } void SetRPCWarmupStatus(const std::string& newStatus) { LOCK(cs_rpcWarmup); rpcWarmupStatus = newStatus; } void SetRPCWarmupFinished() { LOCK(cs_rpcWarmup); assert(fRPCInWarmup); fRPCInWarmup = false; } bool RPCIsInWarmup(std::string* outStatus) { LOCK(cs_rpcWarmup); if (outStatus) *outStatus = rpcWarmupStatus; return fRPCInWarmup; } void RPCRunHandler(const boost::system::error_code& err, boost::function<void(void)> func) { if (!err) func(); } void RPCRunLater(const std::string& name, boost::function<void(void)> func, int64_t nSeconds) { assert(rpc_io_service != NULL); if (deadlineTimers.count(name) == 0) { deadlineTimers.insert(make_pair(name, boost::shared_ptr<deadline_timer>(new deadline_timer(*rpc_io_service)))); } deadlineTimers[name]->expires_from_now(posix_time::seconds(nSeconds)); deadlineTimers[name]->async_wait(boost::bind(RPCRunHandler, _1, func)); } class JSONRequest { public: Value id; string strMethod; Array params; JSONRequest() { id = Value::null; } void parse(const Value& valRequest); }; void JSONRequest::parse(const Value& valRequest) { // Parse request if (valRequest.type() != obj_type) throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object"); const Object& request = valRequest.get_obj(); // Parse id now so errors from here on will have the id id = find_value(request, "id"); // Parse method Value valMethod = find_value(request, "method"); if (valMethod.type() == null_type) throw JSONRPCError(RPC_INVALID_REQUEST, "Missing method"); if (valMethod.type() != str_type) throw JSONRPCError(RPC_INVALID_REQUEST, "Method must be a string"); strMethod = valMethod.get_str(); if (strMethod != "getblocktemplate") LogPrint("rpc", "ThreadRPCServer method=%s\n", SanitizeString(strMethod)); // Parse params Value valParams = find_value(request, "params"); if (valParams.type() == array_type) params = valParams.get_array(); else if (valParams.type() == null_type) params = Array(); else throw JSONRPCError(RPC_INVALID_REQUEST, "Params must be an array"); } static Object JSONRPCExecOne(const Value& req) { Object rpc_result; JSONRequest jreq; try { jreq.parse(req); Value result = tableRPC.execute(jreq.strMethod, jreq.params); rpc_result = JSONRPCReplyObj(result, Value::null, jreq.id); } catch (Object& objError) { rpc_result = JSONRPCReplyObj(Value::null, objError, jreq.id); } catch (std::exception& e) { rpc_result = JSONRPCReplyObj(Value::null, JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id); } return rpc_result; } static string JSONRPCExecBatch(const Array& vReq) { Array ret; for (unsigned int reqIdx = 0; reqIdx < vReq.size(); reqIdx++) ret.push_back(JSONRPCExecOne(vReq[reqIdx])); return write_string(Value(ret), false) + "\n"; } static bool HTTPReq_JSONRPC(AcceptedConnection* conn, string& strRequest, map<string, string>& mapHeaders, bool fRun) { // Check authorization if (mapHeaders.count("authorization") == 0) { conn->stream() << HTTPError(HTTP_UNAUTHORIZED, false) << std::flush; return false; } if (!HTTPAuthorized(mapHeaders)) { LogPrintf("ThreadRPCServer incorrect password attempt from %s\n", conn->peer_address_to_string()); /* Deter brute-forcing If this results in a DoS the user really shouldn't have their RPC port exposed. */ MilliSleep(250); conn->stream() << HTTPError(HTTP_UNAUTHORIZED, false) << std::flush; return false; } JSONRequest jreq; try { // Parse request Value valRequest; if (!read_string(strRequest, valRequest)) throw JSONRPCError(RPC_PARSE_ERROR, "Parse error"); // Return immediately if in warmup { LOCK(cs_rpcWarmup); if (fRPCInWarmup) throw JSONRPCError(RPC_IN_WARMUP, rpcWarmupStatus); } string strReply; // singleton request if (valRequest.type() == obj_type) { jreq.parse(valRequest); Value result = tableRPC.execute(jreq.strMethod, jreq.params); // Send reply strReply = JSONRPCReply(result, Value::null, jreq.id); // array of requests } else if (valRequest.type() == array_type) strReply = JSONRPCExecBatch(valRequest.get_array()); else throw JSONRPCError(RPC_PARSE_ERROR, "Top-level object parse error"); conn->stream() << HTTPReplyHeader(HTTP_OK, fRun, strReply.size()) << strReply << std::flush; } catch (Object& objError) { ErrorReply(conn->stream(), objError, jreq.id); return false; } catch (std::exception& e) { ErrorReply(conn->stream(), JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id); return false; } return true; } void ServiceConnection(AcceptedConnection* conn) { bool fRun = true; while (fRun && !ShutdownRequested()) { int nProto = 0; map<string, string> mapHeaders; string strRequest, strMethod, strURI; // Read HTTP request line if (!ReadHTTPRequestLine(conn->stream(), nProto, strMethod, strURI)) break; // Read HTTP message headers and body ReadHTTPMessage(conn->stream(), mapHeaders, strRequest, nProto, MAX_SIZE); // HTTP Keep-Alive is false; close connection immediately if ((mapHeaders["connection"] == "close") || (!GetBoolArg("-rpckeepalive", true))) fRun = false; // Process via JSON-RPC API if (strURI == "/") { if (!HTTPReq_JSONRPC(conn, strRequest, mapHeaders, fRun)) break; // Process via HTTP REST API } else if (strURI.substr(0, 6) == "/rest/" && GetBoolArg("-rest", false)) { if (!HTTPReq_REST(conn, strURI, mapHeaders, fRun)) break; } else { conn->stream() << HTTPError(HTTP_NOT_FOUND, false) << std::flush; break; } } } json_spirit::Value CRPCTable::execute(const std::string& strMethod, const json_spirit::Array& params) const { // Find method const CRPCCommand* pcmd = tableRPC[strMethod]; if (!pcmd) throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found"); #ifdef ENABLE_WALLET if (pcmd->reqWallet && !pwalletMain) throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found (disabled)"); #endif // Observe safe mode string strWarning = GetWarnings("rpc"); if (strWarning != "" && !GetBoolArg("-disablesafemode", false) && !pcmd->okSafeMode) throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, string("Safe mode: ") + strWarning); try { // Execute Value result; { if (pcmd->threadSafe) result = pcmd->actor(params, false); #ifdef ENABLE_WALLET else if (!pwalletMain) { LOCK(cs_main); result = pcmd->actor(params, false); } else { while (true) { TRY_LOCK(cs_main, lockMain); if (!lockMain) { MilliSleep(50); continue; } while (true) { TRY_LOCK(pwalletMain->cs_wallet, lockWallet); if (!lockMain) { MilliSleep(50); continue; } result = pcmd->actor(params, false); break; } break; } } #else // ENABLE_WALLET else { LOCK(cs_main); result = pcmd->actor(params, false); } #endif // !ENABLE_WALLET } return result; } catch (std::exception& e) { throw JSONRPCError(RPC_MISC_ERROR, e.what()); } } std::vector<std::string> CRPCTable::listCommands() const { std::vector<std::string> commandList; typedef std::map<std::string, const CRPCCommand*> commandMap; std::transform( mapCommands.begin(), mapCommands.end(), std::back_inserter(commandList), boost::bind(&commandMap::value_type::first,_1) ); return commandList; } std::string HelpExampleCli(string methodname, string args) { return "> somnio-cli " + methodname + " " + args + "\n"; } std::string HelpExampleRpc(string methodname, string args) { return "> curl --user myusername --data-binary '{\"jsonrpc\": \"1.0\", \"id\":\"curltest\", " "\"method\": \"" + methodname + "\", \"params\": [" + args + "] }' -H 'content-type: text/plain;' http://127.0.0.1:6081/\n"; } const CRPCTable tableRPC;
[ "root@vultr.guest" ]
root@vultr.guest
6d6addcfefd4319d9b6dfb04caed4f73dc8dadb0
e8edd19dc6df3977af1d6a42bb02fe0b72a960fc
/lab_03_domen/src/builder.cpp
e0b82b792aaff1470951e2415f61d5068948a1b6
[]
no_license
Sunshine-ki/BMSTU4_OOP
8ed159a5236d81378648a385cfb28f84d4272be7
d93a2f4693db54196823551b76acaf950a0a6329
refs/heads/master
2022-11-10T22:33:24.533465
2020-07-04T10:52:44
2020-07-04T10:52:44
244,690,781
2
0
null
null
null
null
UTF-8
C++
false
false
961
cpp
#include "builder.h" bool FigureBuilder::create() { std::shared_ptr<Figure> figure(new Figure()); if (!figure) return false; _figure = figure; return true; } bool FigureBuilder::fillPoints(std::vector<Point> &points) { if (!points.size()) return false; for (size_t i = 0; i < points.size(); i++) _figure->addPoint(points[i]); return true; } bool FigureBuilder::fillLinks(std::vector<Link> &links) { if (!links.size()) return false; for (size_t i = 0; i < links.size(); i++) { if (links[i].getLast() < 0 or links[i].getFirst() < 0) return false; _figure->addLink(links[i]); } return true; } std::shared_ptr<Figure> FigureBuilder::returnResult() { return _figure; } std::shared_ptr<Figure> Director::createFigure(std::vector<Point> &points, std::vector<Link> &links) { if (_builder->create() && _builder->fillPoints(points) && _builder->fillLinks(links)) return _builder->returnResult(); return std::shared_ptr<Figure>(); }
[ "sukocheva.alis@mail.ru" ]
sukocheva.alis@mail.ru
e925537c4cf4022dfd8d964eaef116b6456e4f75
3a7d683e2d3e80706d916a2f50be149bd24cda1b
/include/omniORB4/IIOP.h
c9c0bcd63a9fbbe790b8ee09a4d87c05728f2bb4
[]
no_license
rpavlik/vrjuggler-windows-binaries
de44ccab20e0476dd2b1b0a19710362031bdcfd1
d171aec37b3ec47d3598c9761b29d054755d7817
HEAD
2016-09-05T23:29:05.449999
2014-09-23T19:13:30
2014-09-23T20:07:12
1,789,116
0
0
null
null
null
null
UTF-8
C++
false
false
4,662
h
// -*- Mode: C++; -*- // Package : omniORB // IIOP.h Created on: 8/2/96 // Author : Sai Lai Lo (sll) // // Copyright (C) 1996-1999 AT&T Laboratories Cambridge // // This file is part of the omniORB library // // The omniORB library is free software; you can redistribute it and/or // modify it under the terms of the GNU Library General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library 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 // Library General Public License for more details. // // You should have received a copy of the GNU Library General Public // License along with this library; if not, write to the Free // Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA // 02111-1307, USA // // // Description: // C++ mapping of the OMG IIOP module // Reference: CORBA V2.0 12.8.2 // // /* $Log: IIOP.h,v $ Revision 1.4.2.1 2003/03/23 21:04:20 dgrisby Start of omniORB 4.1.x development branch. Revision 1.2.2.7 2001/07/31 16:06:15 sll Added marshalling operators for IIOP::Address. Revision 1.2.2.6 2001/05/09 16:59:08 sll Added unmarshalObjectKey() to allow quick extraction of the object key. Revision 1.2.2.5 2001/04/18 17:52:46 sll Rationalise marshalling and unmarshalling routines. Revision 1.2.2.4 2000/11/15 17:01:59 sll Default ProfileBody ctor set components max to 2. Revision 1.2.2.3 2000/10/04 16:50:06 sll Updated header comment. Revision 1.2.2.2 2000/09/27 17:06:43 sll New helper functions to decode an IOR. Revision 1.2.2.1 2000/07/17 10:35:34 sll Merged from omni3_develop the diff between omni3_0_0_pre3 and omni3_0_0. Revision 1.3 2000/07/13 15:26:05 dpg1 Merge from omni3_develop for 3.0 release. Revision 1.1.2.4 2000/05/25 08:45:54 dpg1 Forgot _core_attr onn IIOP::DEFAULT_CORBALOC_PORT Revision 1.1.2.3 2000/05/24 17:10:57 dpg1 Rename IIOP::DEFAULT_PORT IIOP::DEFAULT_CORBALOC_PORT Revision 1.1.2.2 2000/04/27 10:35:49 dpg1 Interoperable Naming Service Added IIOP default port constant. Revision 1.1.2.1 1999/09/24 09:51:40 djr Moved from omniORB2 + some new files. Revision 1.10 1999/06/18 21:13:24 sll Updted to copyright notice. Revision 1.9 1999/06/18 20:35:53 sll Replaced _LC_attr with _core_attr Revision 1.8 1999/01/07 18:20:05 djr Replaced _OMNIORB_NTDLL_IMPORT with _LC_attr. Revision 1.7 1998/04/07 19:57:16 sll Replace _OMNIORB2_NTDLL_ specification on class IIOP with _OMNIORB_NTDLL_IMPORT on static member constants. Revision 1.6 1997/12/09 20:39:38 sll Removed profileToEncapStream and EncapStreamToProfile. Revision 1.5 1997/08/21 22:21:19 sll ProfileBody now has a dtor to deallocate the storage for the host field. * Revision 1.4 1997/05/06 16:06:55 sll * Public release. * */ #ifndef __OMNIORB_IIOP_H__ #define __OMNIORB_IIOP_H__ class IIOP { public: typedef GIOP::Version Version; struct Address { _CORBA_String_member host; _CORBA_UShort port; void operator>>=(cdrStream&) const; void operator<<=(cdrStream&); }; struct ProfileBody { Version version; Address address; _CORBA_Unbounded_Sequence_Octet object_key; IOP::MultipleComponentProfile components; ProfileBody() : components(2) {} }; typedef _CORBA_Unbounded_Sequence<ProfileBody> ProfileBodyList; static _core_attr const _CORBA_UShort DEFAULT_CORBALOC_PORT; static void encodeProfile(const ProfileBody&,IOP::TaggedProfile&); static void encodeMultiComponentProfile(const IOP::MultipleComponentProfile&, IOP::TaggedProfile&); static void unmarshalProfile(const IOP::TaggedProfile&, ProfileBody&); static void unmarshalMultiComponentProfile(const IOP::TaggedProfile&, IOP::MultipleComponentProfile&); static void unmarshalObjectKey(const IOP::TaggedProfile& p, _CORBA_Unbounded_Sequence_Octet& key); // The input profile must be TAG_INTERNET_IOP // Extract the object key into <key>. The octet buffer inside <key> is // still own by <p>. So p must not be deallocated before key is. }; #endif // __OMNIORB_IIOP_H__
[ "rpavlik@iastate.edu" ]
rpavlik@iastate.edu
b7f5e19429a18796936ef20c7c6603e98d4b40ce
477c8309420eb102b8073ce067d8df0afc5a79b1
/Utilities/VisItBridge/databases/Enzo/avtEnzoFileFormat.h
a17b5ce272d30f8d68deb64a322059124eb32eef
[ "LicenseRef-scancode-paraview-1.2" ]
permissive
aashish24/paraview-climate-3.11.1
e0058124e9492b7adfcb70fa2a8c96419297fbe6
c8ea429f56c10059dfa4450238b8f5bac3208d3a
refs/heads/uvcdat-master
2021-07-03T11:16:20.129505
2013-05-10T13:14:30
2013-05-10T13:14:30
4,238,077
1
0
NOASSERTION
2020-10-12T21:28:23
2012-05-06T02:32:44
C++
UTF-8
C++
false
false
6,229
h
/***************************************************************************** * * Copyright (c) 2000 - 2010, Lawrence Livermore National Security, LLC * Produced at the Lawrence Livermore National Laboratory * LLNL-CODE-400124 * All rights reserved. * * This file is part of VisIt. For details, see https://visit.llnl.gov/. The * full copyright notice is contained in the file COPYRIGHT located at the root * of the VisIt distribution or at http://www.llnl.gov/visit/copyright.html. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the disclaimer below. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the disclaimer (as noted below) in the * documentation and/or other materials provided with the distribution. * - Neither the name of the LLNS/LLNL nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL LAWRENCE LIVERMORE NATIONAL SECURITY, * LLC, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. * *****************************************************************************/ // ************************************************************************* // // avtEnzoFileFormat.h // // ************************************************************************* // #ifndef AVT_Enzo_FILE_FORMAT_H #define AVT_Enzo_FILE_FORMAT_H #include <avtSTMDFileFormat.h> #include <vector> // **************************************************************************** // Class: avtEnzoFileFormat // // Purpose: // Reads in Enzo files as a plugin to VisIt. // // Programmer: Jeremy Meredith // Creation: December 3, 2004 // // Modifications: // Jeremy Meredith, Fri Feb 11 18:15:49 PST 2005 // Added HDF5 support to the existing HDF4 support. // // Jeremy Meredith, Fri Jul 15 15:27:49 PDT 2005 // Added fixes for multi-timestep Enzo runs. // // Jeremy Meredith, Wed Aug 3 10:21:56 PDT 2005 // Added support for 2D Enzo files. // // Jeremy Meredith, Thu Aug 11 14:35:39 PDT 2005 // Added new routine to unify global extents. // // Jeremy Meredith, Mon Apr 6 14:36:58 EDT 2009 // Added support for particle and grid file names. // This is for support for the new "Packed AMR" format. // // **************************************************************************** class avtEnzoFileFormat : public avtSTMDFileFormat { public: avtEnzoFileFormat(const char *); virtual ~avtEnzoFileFormat(); virtual bool HasInvariantMetaData(void) const { return false; }; virtual bool HasInvariantSIL(void) const { return false; }; virtual int GetCycle(void); virtual const char *GetType(void) { return "Enzo"; }; virtual void FreeUpResources(void); virtual vtkDataSet *GetMesh(int, const char *); virtual vtkDataArray *GetVar(int, const char *); virtual vtkDataArray *GetVectorVar(int, const char *); virtual void *GetAuxiliaryData(const char *var, int, const char *type, void *args, DestructorFunction &); void ActivateTimestep(void); virtual int GetCycleFromFilename(const char *f) const; protected: enum FileType { ENZO_FT_UNKNOWN, ENZO_FT_HDF4, ENZO_FT_HDF5 }; FileType fileType; // DATA MEMBERS struct Grid { int ID; std::vector<int> childrenID; int parentID; int level; int dimension; int numberOfParticles; double minSpatialExtents[3]; double maxSpatialExtents[3]; int zdims[3]; int ndims[3]; int minLogicalExtentsInParent[3]; int maxLogicalExtentsInParent[3]; int minLogicalExtentsGlobally[3]; int maxLogicalExtentsGlobally[3]; double refinementRatio[3]; std::string gridFileName; std::string particleFileName; public: void PrintRecursive(std::vector<Grid> &grids, int level = 0); void Print(); void DetermineExtentsInParent(std::vector<Grid> &grids); void DetermineExtentsGlobally(int numLevels,std::vector<Grid> &grids); }; std::string fname_dir; std::string fname_base; std::string fnameB; std::string fnameH; int dimension; std::vector<Grid> grids; int numGrids; int numLevels; int curCycle; double curTime; std::vector<std::string> varNames; std::vector<std::string> particleVarNames; std::vector<std::string> tracerparticleVarNames; virtual void PopulateDatabaseMetaData(avtDatabaseMetaData *); void ReadAllMetaData(); void ReadHierachyFile(); void ReadParameterFile(); void UnifyGlobalExtents(); void DetermineVariablesFromGridFile(); void BuildDomainNesting(); }; #endif
[ "aashish.chaudhary@kitware.com" ]
aashish.chaudhary@kitware.com
71ffd77883824ed893c7b37bca29494c863263d6
92e979498ec13e4ef1f9ff140e12865b5082c1dd
/SDK/GeneralFunctions_parameters.h
5e1a70b9425a66bad0b82f89d6e77845a80ef651
[]
no_license
ALEHACKsp/BlazingSails-SDK
ac1d98ff67983b9d8e9c527815f17233d045d44d
900cbb934dc85f7325f1fc8845b90def2298dc2d
refs/heads/master
2022-04-08T21:55:32.767942
2020-03-11T11:37:42
2020-03-11T11:37:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
27,695
h
#pragma once #include "../SDK.h" // Name: BlazingSails, Version: 1.481.81 #ifdef _MSC_VER #pragma pack(push, 0x8) #endif namespace SDK { //--------------------------------------------------------------------------- // Parameters //--------------------------------------------------------------------------- // Function GeneralFunctions.GeneralFunctions_C.CheckIfTeamIsDefeated struct UGeneralFunctions_C_CheckIfTeamIsDefeated_Params { int Team; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) class UObject* __WorldContext; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) bool Defeated; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) }; // Function GeneralFunctions.GeneralFunctions_C.GetMostCommonElementInActorArray struct UGeneralFunctions_C_GetMostCommonElementInActorArray_Params { TArray<class AActor*> Array; // (BlueprintVisible, BlueprintReadOnly, Parm, OutParm, ZeroConstructor, ReferenceParm) class UObject* __WorldContext; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) int Index; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) int AmountOfTimes; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) class AActor* Actor; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) }; // Function GeneralFunctions.GeneralFunctions_C.GetScar struct UGeneralFunctions_C_GetScar_Params { int Scar; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) class UObject* __WorldContext; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) class UTexture2D* RGB; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) class UTexture2D* Alpha; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) }; // Function GeneralFunctions.GeneralFunctions_C.OwnAllCullingVolumes struct UGeneralFunctions_C_OwnAllCullingVolumes_Params { class UObject* __WorldContext; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) }; // Function GeneralFunctions.GeneralFunctions_C.GetLookAtWindDirection struct UGeneralFunctions_C_GetLookAtWindDirection_Params { class UObject* __WorldContext; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) struct FText WindDirection; // (Parm, OutParm) TEnumAsByte<E_WindDirections> DirectionEnum; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) }; // Function GeneralFunctions.GeneralFunctions_C.AddScore struct UGeneralFunctions_C_AddScore_Params { class APlayerState* PlayerState; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) int ScoreAmount; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) TEnumAsByte<E_ScoreType> ScoreType; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) bool FromServer_; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) class ABP_Controller_C* Controller; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) class UObject* __WorldContext; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) }; // Function GeneralFunctions.GeneralFunctions_C.CheckIfChildActorsAreReady struct UGeneralFunctions_C_CheckIfChildActorsAreReady_Params { TArray<class UObject*> ChildActors; // (BlueprintVisible, BlueprintReadOnly, Parm, OutParm, ZeroConstructor, ReferenceParm) class UObject* __WorldContext; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) bool Ready; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) }; // Function GeneralFunctions.GeneralFunctions_C.CheckIfCrewHasRoom struct UGeneralFunctions_C_CheckIfCrewHasRoom_Params { int TeamID; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) bool FromClient; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) class UObject* __WorldContext; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) bool HasRoom; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) int AvailableSlots; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) int FilledSlots; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) }; // Function GeneralFunctions.GeneralFunctions_C.CreateDistortionWave struct UGeneralFunctions_C_CreateDistortionWave_Params { struct FVector Location; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) float WaveSpeed; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) float WaveMaxRadius; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) bool AttachToActorComponent; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) class USceneComponent* AttachComponent; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData) class UObject* __WorldContext; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) }; // Function GeneralFunctions.GeneralFunctions_C.SetKeyBind struct UGeneralFunctions_C_SetKeyBind_Params { TEnumAsByte<E_Actions> Action; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) struct FKey Key; // (BlueprintVisible, BlueprintReadOnly, Parm) TEnumAsByte<E_KeybindCategories> Category; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) class UObject* __WorldContext; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) bool Succesful_; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) TEnumAsByte<E_Actions> ConflictingAction; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) }; // Function GeneralFunctions.GeneralFunctions_C.GetKeyBind struct UGeneralFunctions_C_GetKeyBind_Params { TEnumAsByte<E_Actions> Action; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) class UObject* __WorldContext; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) struct FKey Key; // (Parm, OutParm) }; // Function GeneralFunctions.GeneralFunctions_C.PostTopScreenMessage struct UGeneralFunctions_C_PostTopScreenMessage_Params { class UClass* Widget; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) class UObject* __WorldContext; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) }; // Function GeneralFunctions.GeneralFunctions_C.GetWaterHeight struct UGeneralFunctions_C_GetWaterHeight_Params { struct FVector Location; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) class UObject* __WorldContext; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) float WaterHeight; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) }; // Function GeneralFunctions.GeneralFunctions_C.GetClothingInfo struct UGeneralFunctions_C_GetClothingInfo_Params { int ClothingItemIndex; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) class UObject* __WorldContext; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) class UStaticMesh* StaticMesh; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) class USkeletalMesh* SkeletalMesh; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) class UTexture2D* Texture; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) struct FString ClothingItemName; // (Parm, OutParm, ZeroConstructor) int Price; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) class UTexture2D* Icon; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) TEnumAsByte<E_ClothingCategories> Category; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) }; // Function GeneralFunctions.GeneralFunctions_C.GetDatatableAmount struct UGeneralFunctions_C_GetDatatableAmount_Params { class UDataTable* DataTable; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) class UObject* __WorldContext; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) int Amount; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) }; // Function GeneralFunctions.GeneralFunctions_C.GetFaceInfo struct UGeneralFunctions_C_GetFaceInfo_Params { int FaceIndex; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) class UObject* __WorldContext; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) class UTexture2D* FaceTexture; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) struct FString FaceName; // (Parm, OutParm, ZeroConstructor) }; // Function GeneralFunctions.GeneralFunctions_C.GetUpgradeInfo struct UGeneralFunctions_C_GetUpgradeInfo_Params { int Upgrade; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) class UObject* __WorldContext; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) class UClass* UpgradeBlueprint; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) }; // Function GeneralFunctions.GeneralFunctions_C.SortItems struct UGeneralFunctions_C_SortItems_Params { TArray<struct FST_InventoryArray> ItemArray; // (BlueprintVisible, BlueprintReadOnly, Parm, OutParm, ZeroConstructor, ReferenceParm) class UObject* __WorldContext; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) TArray<struct FST_InventoryArray> SortedArray; // (Parm, OutParm, ZeroConstructor) }; // Function GeneralFunctions.GeneralFunctions_C.GetItemCategoryAndColor struct UGeneralFunctions_C_GetItemCategoryAndColor_Params { TEnumAsByte<E_Items> Item; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) class UObject* __WorldContext; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) TEnumAsByte<E_ItemCategories> Category; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) struct FLinearColor ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData) }; // Function GeneralFunctions.GeneralFunctions_C.CheckIfInventoryHasItem struct UGeneralFunctions_C_CheckIfInventoryHasItem_Params { TEnumAsByte<E_Items> Item; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) class UInventory_C* InventoryRef; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData) class UObject* __WorldContext; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) bool HasItem; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) int Amount; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) }; // Function GeneralFunctions.GeneralFunctions_C.GetItemInfo struct UGeneralFunctions_C_GetItemInfo_Params { TEnumAsByte<E_Items> Item; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) class UObject* __WorldContext; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) class UTexture2D* Icon; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) int Weight; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) class UClass* ItemObject; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) bool throwable; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) TEnumAsByte<E_ItemCategories> Category; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) }; // Function GeneralFunctions.GeneralFunctions_C.FindCrew struct UGeneralFunctions_C_FindCrew_Params { int TeamID; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) class UObject* __WorldContext; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) int TeamFirstName; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) int TeamSecondaryNameRow; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) int TeamSecondaryNameIndex; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) int FlagColorRow; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) class ABP_Controller_C* LeaderControllerRed; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) struct FText ShipName; // (Parm, OutParm) }; // Function GeneralFunctions.GeneralFunctions_C.GetCrewInfo struct UGeneralFunctions_C_GetCrewInfo_Params { int FirstNameRow; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) int SecondaryNameRow; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) int SecondaryNameIndex; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) int ColorSetRow; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) class UObject* __WorldContext; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) struct FString FirstName; // (Parm, OutParm, ZeroConstructor) struct FString SecondaryName; // (Parm, OutParm, ZeroConstructor) struct FLinearColor BaseColor; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) struct FLinearColor AccentColor; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) class UTexture2D* emblem; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) struct FText FullName; // (Parm, OutParm) }; // Function GeneralFunctions.GeneralFunctions_C.GenerateCrew struct UGeneralFunctions_C_GenerateCrew_Params { class UObject* __WorldContext; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) int FirstCrewName; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) int SecondaryCrewName; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) int SecondaryCrewNameIndex; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) int Colorset; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) }; // Function GeneralFunctions.GeneralFunctions_C.CheckIfEnoughRoom struct UGeneralFunctions_C_CheckIfEnoughRoom_Params { class ABP_Character_C* Character; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) TEnumAsByte<E_Items> Item; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) int Amount; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) class UObject* __WorldContext; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) bool EnoughRoom; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) }; // Function GeneralFunctions.GeneralFunctions_C.GetWeaponInfo struct UGeneralFunctions_C_GetWeaponInfo_Params { int ItemID; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) class UObject* __WorldContext; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) class UClass* WeaponClass; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) class UTexture2D* Icon; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) struct FText Weapon_Name; // (Parm, OutParm) TEnumAsByte<E_Items> AmmoType; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) struct FVector FPSOffset; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) float AimZoomMultiplier; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) class UAnimMontage* ReloadAnimation; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) bool HideCharacter; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) TEnumAsByte<E_Tiers> Tier; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) struct FText Description; // (Parm, OutParm) int ClipSize; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) struct FRotator FPSOffsetRot; // (Parm, OutParm, ZeroConstructor, IsPlainOldData) }; // Function GeneralFunctions.GeneralFunctions_C.LeaveUIMode struct UGeneralFunctions_C_LeaveUIMode_Params { class UObject* __WorldContext; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) }; // Function GeneralFunctions.GeneralFunctions_C.EnterUIMode struct UGeneralFunctions_C_EnterUIMode_Params { bool EnableMouseCursor; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) bool DontDisableGameInput; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) bool CenterMouseCursor; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) class UObject* __WorldContext; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "zp2kshield@gmail.com" ]
zp2kshield@gmail.com
a648e56786f2844ec91522e693f5c2e8a8c0db54
879fb3581f03b5c17dd90c68b45751712fbcd671
/lib/spear/splitter.cc
64977417506eb8f1c534df2afb7d81d6f7475a41
[]
no_license
ivilab/kjb
9f970e1ce16188f72f0edb34394e474ca83a9f2b
238be8bc3c9018d4365741e56310067a52b715f9
refs/heads/master
2020-06-14T07:33:17.166805
2019-07-30T16:47:29
2019-07-30T16:47:29
194,946,614
1
0
null
null
null
null
UTF-8
C++
false
false
54,126
cc
#line 3 "<stdout>" #define YY_INT_ALIGNED short int /* A lexical scanner generated by flex */ #define yy_create_buffer splitter_create_buffer #define yy_delete_buffer splitter_delete_buffer #define yy_flex_debug splitter_flex_debug #define yy_init_buffer splitter_init_buffer #define yy_flush_buffer splitter_flush_buffer #define yy_load_buffer_state splitter_load_buffer_state #define yy_switch_to_buffer splitter_switch_to_buffer #define yyin splitterin #define yyleng splitterleng #define yylex splitterlex #define yylineno splitterlineno #define yyout splitterout #define yyrestart splitterrestart #define yytext splittertext #define yywrap splitterwrap #define yyalloc splitteralloc #define yyrealloc splitterrealloc #define yyfree splitterfree #define FLEX_SCANNER #define YY_FLEX_MAJOR_VERSION 2 #define YY_FLEX_MINOR_VERSION 5 #define YY_FLEX_SUBMINOR_VERSION 35 #if YY_FLEX_SUBMINOR_VERSION > 0 #define FLEX_BETA #endif /* First, we deal with platform-specific or compiler-specific issues. */ /* begin standard C headers. */ #include <stdio.h> #include <string.h> #include <errno.h> #include <stdlib.h> /* end standard C headers. */ /* flex integer type definitions */ #ifndef FLEXINT_H #define FLEXINT_H /* C99 systems have <inttypes.h>. Non-C99 systems may or may not. */ #if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 says to define __STDC_LIMIT_MACROS before including stdint.h, * if you want the limit (max/min) macros for int types. */ #ifndef __STDC_LIMIT_MACROS #define __STDC_LIMIT_MACROS 1 #endif #include <inttypes.h> typedef int8_t flex_int8_t; typedef uint8_t flex_uint8_t; typedef int16_t flex_int16_t; typedef uint16_t flex_uint16_t; typedef int32_t flex_int32_t; typedef uint32_t flex_uint32_t; #else typedef signed char flex_int8_t; typedef short int flex_int16_t; typedef int flex_int32_t; typedef unsigned char flex_uint8_t; typedef unsigned short int flex_uint16_t; typedef unsigned int flex_uint32_t; /* Limits of integral types. */ #ifndef INT8_MIN #define INT8_MIN (-128) #endif #ifndef INT16_MIN #define INT16_MIN (-32767-1) #endif #ifndef INT32_MIN #define INT32_MIN (-2147483647-1) #endif #ifndef INT8_MAX #define INT8_MAX (127) #endif #ifndef INT16_MAX #define INT16_MAX (32767) #endif #ifndef INT32_MAX #define INT32_MAX (2147483647) #endif #ifndef UINT8_MAX #define UINT8_MAX (255U) #endif #ifndef UINT16_MAX #define UINT16_MAX (65535U) #endif #ifndef UINT32_MAX #define UINT32_MAX (4294967295U) #endif #endif /* ! C99 */ #endif /* ! FLEXINT_H */ #ifdef __cplusplus /* The "const" storage-class-modifier is valid. */ #define YY_USE_CONST #else /* ! __cplusplus */ /* C99 requires __STDC__ to be defined as 1. */ #if defined (__STDC__) #define YY_USE_CONST #endif /* defined (__STDC__) */ #endif /* ! __cplusplus */ #ifdef YY_USE_CONST #define yyconst const #else #define yyconst #endif /* Returned upon end-of-file. */ #define YY_NULL 0 /* Promotes a possibly negative, possibly signed char to an unsigned * integer for use as an array index. If the signed char is negative, * we want to instead treat it as an 8-bit unsigned char, hence the * double cast. */ #define YY_SC_TO_UI(c) ((unsigned int) (unsigned char) c) /* Enter a start condition. This macro really ought to take a parameter, * but we do it the disgusting crufty way forced on us by the ()-less * definition of BEGIN. */ #define BEGIN (yy_start) = 1 + 2 * /* Translate the current start state into a value that can be later handed * to BEGIN to return to the state. The YYSTATE alias is for lex * compatibility. */ #define YY_START (((yy_start) - 1) / 2) #define YYSTATE YY_START /* Action number for EOF rule of a given start state. */ #define YY_STATE_EOF(state) (YY_END_OF_BUFFER + state + 1) /* Special action meaning "start processing a new file". */ #define YY_NEW_FILE splitterrestart(splitterin ) #define YY_END_OF_BUFFER_CHAR 0 /* Size of default input buffer. */ #ifndef YY_BUF_SIZE #ifdef __ia64__ /* On IA-64, the buffer size is 16k, not 8k. * Moreover, YY_BUF_SIZE is 2*YY_READ_BUF_SIZE in the general case. * Ditto for the __ia64__ case accordingly. */ #define YY_BUF_SIZE 32768 #else #define YY_BUF_SIZE 16384 #endif /* __ia64__ */ #endif /* The state buf must be large enough to hold one state per character in the main buffer. */ #define YY_STATE_BUF_SIZE ((YY_BUF_SIZE + 2) * sizeof(yy_state_type)) #ifndef YY_TYPEDEF_YY_BUFFER_STATE #define YY_TYPEDEF_YY_BUFFER_STATE typedef struct yy_buffer_state *YY_BUFFER_STATE; #endif extern int splitterleng; extern FILE *splitterin, *splitterout; #define EOB_ACT_CONTINUE_SCAN 0 #define EOB_ACT_END_OF_FILE 1 #define EOB_ACT_LAST_MATCH 2 #define YY_LESS_LINENO(n) /* Return all but the first "n" matched characters back to the input stream. */ #define yyless(n) \ do \ { \ /* Undo effects of setting up splittertext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ *yy_cp = (yy_hold_char); \ YY_RESTORE_YY_MORE_OFFSET \ (yy_c_buf_p) = yy_cp = yy_bp + yyless_macro_arg - YY_MORE_ADJ; \ YY_DO_BEFORE_ACTION; /* set up splittertext again */ \ } \ while ( 0 ) #define unput(c) yyunput( c, (yytext_ptr) ) #ifndef YY_TYPEDEF_YY_SIZE_T #define YY_TYPEDEF_YY_SIZE_T typedef size_t yy_size_t; #endif #ifndef YY_STRUCT_YY_BUFFER_STATE #define YY_STRUCT_YY_BUFFER_STATE struct yy_buffer_state { FILE *yy_input_file; char *yy_ch_buf; /* input buffer */ char *yy_buf_pos; /* current position in input buffer */ /* Size of input buffer in bytes, not including room for EOB * characters. */ yy_size_t yy_buf_size; /* Number of characters read into yy_ch_buf, not including EOB * characters. */ int yy_n_chars; /* Whether we "own" the buffer - i.e., we know we created it, * and can realloc() it to grow it, and should free() it to * delete it. */ int yy_is_our_buffer; /* Whether this is an "interactive" input source; if so, and * if we're using stdio for input, then we want to use getc() * instead of fread(), to make sure we stop fetching input after * each newline. */ int yy_is_interactive; /* Whether we're considered to be at the beginning of a line. * If so, '^' rules will be active on the next match, otherwise * not. */ int yy_at_bol; int yy_bs_lineno; /**< The line count. */ int yy_bs_column; /**< The column count. */ /* Whether to try to fill the input buffer when we reach the * end of it. */ int yy_fill_buffer; int yy_buffer_status; #define YY_BUFFER_NEW 0 #define YY_BUFFER_NORMAL 1 /* When an EOF's been seen but there's still some text to process * then we mark the buffer as YY_EOF_PENDING, to indicate that we * shouldn't try reading from the input source any more. We might * still have a bunch of tokens to match, though, because of * possible backing-up. * * When we actually see the EOF, we change the status to "new" * (via splitterrestart()), so that the user can continue scanning by * just pointing splitterin at a new input file. */ #define YY_BUFFER_EOF_PENDING 2 }; #endif /* !YY_STRUCT_YY_BUFFER_STATE */ /* Stack of input buffers. */ static size_t yy_buffer_stack_top = 0; /**< index of top of stack. */ static size_t yy_buffer_stack_max = 0; /**< capacity of stack. */ static YY_BUFFER_STATE * yy_buffer_stack = 0; /**< Stack as an array. */ /* We provide macros for accessing buffer states in case in the * future we want to put the buffer states in a more general * "scanner state". * * Returns the top of the stack, or NULL. */ #define YY_CURRENT_BUFFER ( (yy_buffer_stack) \ ? (yy_buffer_stack)[(yy_buffer_stack_top)] \ : NULL) /* Same as previous macro, but useful when we know that the buffer stack is not * NULL or when we need an lvalue. For internal use only. */ #define YY_CURRENT_BUFFER_LVALUE (yy_buffer_stack)[(yy_buffer_stack_top)] /* yy_hold_char holds the character lost when splittertext is formed. */ static char yy_hold_char; static int yy_n_chars; /* number of characters read into yy_ch_buf */ int splitterleng; /* Points to current character in buffer. */ static char *yy_c_buf_p = (char *) 0; static int yy_init = 0; /* whether we need to initialize */ static int yy_start = 0; /* start state number */ /* Flag which is used to allow splitterwrap()'s to do buffer switches * instead of setting up a fresh splitterin. A bit of a hack ... */ static int yy_did_buffer_switch_on_eof; void splitterrestart (FILE *input_file ); void splitter_switch_to_buffer (YY_BUFFER_STATE new_buffer ); YY_BUFFER_STATE splitter_create_buffer (FILE *file,int size ); void splitter_delete_buffer (YY_BUFFER_STATE b ); void splitter_flush_buffer (YY_BUFFER_STATE b ); void splitterpush_buffer_state (YY_BUFFER_STATE new_buffer ); void splitterpop_buffer_state (void ); static void splitterensure_buffer_stack (void ); static void splitter_load_buffer_state (void ); static void splitter_init_buffer (YY_BUFFER_STATE b,FILE *file ); #define YY_FLUSH_BUFFER splitter_flush_buffer(YY_CURRENT_BUFFER ) YY_BUFFER_STATE splitter_scan_buffer (char *base,yy_size_t size ); YY_BUFFER_STATE splitter_scan_string (yyconst char *yy_str ); YY_BUFFER_STATE splitter_scan_bytes (yyconst char *bytes,int len ); void *splitteralloc (yy_size_t ); void *splitterrealloc (void *,yy_size_t ); void splitterfree (void * ); #define yy_new_buffer splitter_create_buffer #define yy_set_interactive(is_interactive) \ { \ if ( ! YY_CURRENT_BUFFER ){ \ splitterensure_buffer_stack (); \ YY_CURRENT_BUFFER_LVALUE = \ splitter_create_buffer(splitterin,YY_BUF_SIZE ); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_is_interactive = is_interactive; \ } #define yy_set_bol(at_bol) \ { \ if ( ! YY_CURRENT_BUFFER ){\ splitterensure_buffer_stack (); \ YY_CURRENT_BUFFER_LVALUE = \ splitter_create_buffer(splitterin,YY_BUF_SIZE ); \ } \ YY_CURRENT_BUFFER_LVALUE->yy_at_bol = at_bol; \ } #define YY_AT_BOL() (YY_CURRENT_BUFFER_LVALUE->yy_at_bol) /* Begin user sect3 */ #define splitterwrap(n) 1 #define YY_SKIP_YYWRAP typedef unsigned char YY_CHAR; FILE *splitterin = (FILE *) 0, *splitterout = (FILE *) 0; typedef int yy_state_type; extern int splitterlineno; int splitterlineno = 1; extern char *splittertext; #define yytext_ptr splittertext static yy_state_type yy_get_previous_state (void ); static yy_state_type yy_try_NUL_trans (yy_state_type current_state ); static int yy_get_next_buffer (void ); static void yy_fatal_error (yyconst char msg[] ); /* Done after the current pattern has been matched and before the * corresponding action - sets up splittertext. */ #define YY_DO_BEFORE_ACTION \ (yytext_ptr) = yy_bp; \ splitterleng = (size_t) (yy_cp - yy_bp); \ (yy_hold_char) = *yy_cp; \ *yy_cp = '\0'; \ (yy_c_buf_p) = yy_cp; #define YY_NUM_RULES 12 #define YY_END_OF_BUFFER 13 /* This struct is not used in this scanner, but its presence is necessary. */ struct yy_trans_info { flex_int32_t yy_verify; flex_int32_t yy_nxt; }; static yyconst flex_int16_t yy_accept[83] = { 0, 0, 0, 13, 11, 1, 1, 11, 11, 11, 11, 11, 3, 11, 3, 11, 1, 0, 6, 3, 3, 2, 6, 0, 0, 0, 6, 2, 0, 0, 0, 0, 3, 0, 3, 0, 0, 3, 3, 10, 0, 3, 0, 2, 0, 0, 0, 0, 3, 3, 3, 0, 0, 0, 3, 5, 8, 0, 0, 0, 3, 0, 3, 2, 0, 0, 0, 0, 3, 0, 3, 3, 3, 0, 7, 7, 3, 0, 0, 0, 0, 9, 0 } ; static yyconst flex_int32_t yy_ec[256] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 4, 5, 1, 1, 1, 6, 7, 8, 9, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 13, 14, 1, 15, 1, 1, 16, 17, 18, 19, 20, 20, 20, 20, 20, 20, 20, 21, 20, 20, 22, 20, 20, 23, 24, 25, 20, 20, 20, 20, 20, 20, 1, 1, 1, 1, 26, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } ; static yyconst flex_int32_t yy_meta[29] = { 0, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 3, 1, 1, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1, 1, 3 } ; static yyconst flex_int16_t yy_base[87] = { 0, 0, 0, 188, 189, 27, 29, 0, 28, 176, 32, 25, 51, 0, 75, 159, 35, 172, 189, 34, 0, 95, 176, 161, 24, 159, 172, 169, 168, 167, 102, 166, 107, 165, 39, 160, 163, 112, 0, 189, 162, 54, 161, 120, 153, 153, 152, 151, 80, 114, 122, 156, 154, 151, 0, 70, 189, 146, 128, 109, 0, 104, 125, 131, 87, 101, 100, 80, 133, 67, 136, 139, 0, 32, 189, 189, 142, 38, 29, 24, 33, 189, 189, 30, 153, 158, 161 } ; static yyconst flex_int16_t yy_def[87] = { 0, 82, 1, 82, 82, 82, 82, 83, 84, 82, 82, 82, 82, 85, 82, 82, 82, 83, 82, 12, 14, 82, 82, 82, 82, 82, 82, 82, 86, 82, 86, 86, 12, 82, 30, 85, 30, 30, 14, 82, 86, 32, 82, 82, 82, 82, 82, 82, 30, 32, 32, 82, 30, 86, 32, 82, 82, 82, 30, 86, 37, 86, 32, 82, 82, 82, 82, 82, 32, 86, 32, 32, 37, 82, 82, 82, 32, 82, 82, 82, 82, 82, 0, 82, 82, 82, 82 } ; static yyconst flex_int16_t yy_nxt[218] = { 0, 4, 5, 6, 7, 8, 9, 4, 10, 11, 4, 12, 4, 4, 13, 4, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 4, 15, 14, 16, 16, 16, 16, 18, 26, 17, 27, 16, 16, 19, 22, 81, 45, 21, 40, 41, 82, 46, 36, 80, 37, 23, 79, 24, 78, 25, 28, 77, 29, 28, 30, 31, 32, 33, 61, 62, 82, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 28, 76, 34, 28, 55, 33, 28, 36, 28, 37, 29, 75, 30, 40, 38, 38, 38, 38, 38, 38, 38, 38, 38, 38, 28, 42, 38, 42, 42, 43, 28, 74, 74, 28, 73, 28, 49, 51, 68, 52, 53, 54, 57, 60, 58, 59, 60, 61, 68, 82, 42, 28, 42, 42, 43, 69, 70, 82, 61, 62, 82, 42, 60, 42, 42, 63, 61, 68, 82, 69, 70, 82, 61, 68, 82, 61, 76, 82, 20, 20, 72, 20, 35, 35, 35, 70, 35, 34, 68, 34, 71, 67, 66, 65, 64, 63, 49, 37, 56, 55, 50, 48, 37, 27, 26, 47, 44, 22, 39, 18, 21, 82, 3, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82 } ; static yyconst flex_int16_t yy_chk[218] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 5, 6, 6, 8, 11, 83, 11, 16, 16, 8, 10, 80, 24, 10, 19, 19, 19, 24, 34, 79, 34, 10, 78, 10, 77, 10, 12, 73, 12, 12, 12, 12, 12, 12, 41, 41, 41, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 69, 12, 14, 55, 55, 14, 14, 14, 14, 48, 67, 48, 48, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 21, 14, 21, 21, 21, 30, 66, 65, 30, 64, 30, 30, 32, 61, 32, 32, 32, 37, 59, 37, 37, 37, 49, 49, 49, 43, 30, 43, 43, 43, 50, 50, 50, 62, 62, 62, 63, 58, 63, 63, 63, 68, 68, 68, 70, 70, 70, 71, 71, 71, 76, 76, 76, 84, 84, 57, 84, 85, 85, 85, 53, 85, 86, 52, 86, 51, 47, 46, 45, 44, 42, 40, 36, 35, 33, 31, 29, 28, 27, 26, 25, 23, 22, 17, 15, 9, 3, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82 } ; static yy_state_type yy_last_accepting_state; static char *yy_last_accepting_cpos; extern int splitter_flex_debug; int splitter_flex_debug = 0; /* The intent behind this definition is that it'll catch * any uses of REJECT which flex missed. */ #define REJECT reject_used_but_not_detected #define yymore() yymore_used_but_not_detected #define YY_MORE_ADJ 0 #define YY_RESTORE_YY_MORE_OFFSET char *splittertext; #line 1 "splitter.l" /** * Basic tokenizer, without multiword support */ #line 7 "splitter.l" #include <iostream> #include <vector> #include <string> /** Start of the input buffer */ static char * bufferBegin; /** End of the input buffer */ static char * bufferEnd; /** Output token vector */ static std::vector<std::string> * tokens; /** Transfers from input buffer into the lex buffer */ static int splitterTransfer(char * buffer, int size); /** Finds if this string ends with an apostrophe construction, e.g. 've */ static int hasApostropheBlock(const std::string & s); static std::string toLower(const std::string & s); #undef YY_INPUT #define YY_INPUT(buffer, count, size) (count = splitterTransfer(buffer, size)) #line 580 "<stdout>" #define INITIAL 0 #ifndef YY_NO_UNISTD_H /* Special case for "unistd.h", since it is non-ANSI. We include it way * down here because we want the user's section 1 to have been scanned first. * The user has a chance to override it with an option. */ #include <unistd.h> #endif #ifndef YY_EXTRA_TYPE #define YY_EXTRA_TYPE void * #endif static int yy_init_globals (void ); /* Accessor methods to globals. These are made visible to non-reentrant scanners for convenience. */ int splitterlex_destroy (void ); int splitterget_debug (void ); void splitterset_debug (int debug_flag ); YY_EXTRA_TYPE splitterget_extra (void ); void splitterset_extra (YY_EXTRA_TYPE user_defined ); FILE *splitterget_in (void ); void splitterset_in (FILE * in_str ); FILE *splitterget_out (void ); void splitterset_out (FILE * out_str ); int splitterget_leng (void ); char *splitterget_text (void ); int splitterget_lineno (void ); void splitterset_lineno (int line_number ); /* Macros after this point can all be overridden by user definitions in * section 1. */ #ifndef YY_SKIP_YYWRAP #ifdef __cplusplus extern "C" int splitterwrap (void ); #else extern int splitterwrap (void ); #endif #endif static void yyunput (int c,char *buf_ptr ); #ifndef yytext_ptr static void yy_flex_strncpy (char *,yyconst char *,int ); #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (yyconst char * ); #endif #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput (void ); #else static int input (void ); #endif #endif /* Amount of stuff to slurp up with each read. */ #ifndef YY_READ_BUF_SIZE #ifdef __ia64__ /* On IA-64, the buffer size is 16k, not 8k */ #define YY_READ_BUF_SIZE 16384 #else #define YY_READ_BUF_SIZE 8192 #endif /* __ia64__ */ #endif /* Copy whatever the last rule matched to the standard output. */ #ifndef ECHO /* This used to be an fputs(), but since the string might contain NUL's, * we now use fwrite(). */ #define ECHO do { if (fwrite( splittertext, splitterleng, 1, splitterout )) {} } while (0) #endif /* Gets input and stuffs it into "buf". number of characters read, or YY_NULL, * is returned in "result". */ #ifndef YY_INPUT #define YY_INPUT(buf,result,max_size) \ if ( YY_CURRENT_BUFFER_LVALUE->yy_is_interactive ) \ { \ int c = '*'; \ size_t n; \ for ( n = 0; n < max_size && \ (c = getc( splitterin )) != EOF && c != '\n'; ++n ) \ buf[n] = (char) c; \ if ( c == '\n' ) \ buf[n++] = (char) c; \ if ( c == EOF && ferror( splitterin ) ) \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ result = n; \ } \ else \ { \ errno=0; \ while ( (result = fread(buf, 1, max_size, splitterin))==0 && ferror(splitterin)) \ { \ if( errno != EINTR) \ { \ YY_FATAL_ERROR( "input in flex scanner failed" ); \ break; \ } \ errno=0; \ clearerr(splitterin); \ } \ }\ \ #endif /* No semi-colon after return; correct usage is to write "yyterminate();" - * we don't want an extra ';' after the "return" because that will cause * some compilers to complain about unreachable statements. */ #ifndef yyterminate #define yyterminate() return YY_NULL #endif /* Number of entries by which start-condition stack grows. */ #ifndef YY_START_STACK_INCR #define YY_START_STACK_INCR 25 #endif /* Report a fatal error. */ #ifndef YY_FATAL_ERROR #define YY_FATAL_ERROR(msg) yy_fatal_error( msg ) #endif /* end tables serialization structures and prototypes */ /* Default declaration of generated scanner - a define so the user can * easily add parameters. */ #ifndef YY_DECL #define YY_DECL_IS_OURS 1 extern int splitterlex (void); #define YY_DECL int splitterlex (void) #endif /* !YY_DECL */ /* Code executed at the beginning of each rule, after splittertext and splitterleng * have been set up. */ #ifndef YY_USER_ACTION #define YY_USER_ACTION #endif /* Code executed at the end of each rule. */ #ifndef YY_BREAK #define YY_BREAK break; #endif #define YY_RULE_SETUP \ YY_USER_ACTION /** The main scanner function which does all the work. */ YY_DECL { register yy_state_type yy_current_state; register char *yy_cp, *yy_bp; register int yy_act; #line 56 "splitter.l" #line 770 "<stdout>" if ( !(yy_init) ) { (yy_init) = 1; #ifdef YY_USER_INIT YY_USER_INIT; #endif if ( ! (yy_start) ) (yy_start) = 1; /* first start state */ if ( ! splitterin ) splitterin = stdin; if ( ! splitterout ) splitterout = stdout; if ( ! YY_CURRENT_BUFFER ) { splitterensure_buffer_stack (); YY_CURRENT_BUFFER_LVALUE = splitter_create_buffer(splitterin,YY_BUF_SIZE ); } splitter_load_buffer_state( ); } while ( 1 ) /* loops until end-of-file is reached */ { yy_cp = (yy_c_buf_p); /* Support of splittertext. */ *yy_cp = (yy_hold_char); /* yy_bp points to the position in yy_ch_buf of the start of * the current run. */ yy_bp = yy_cp; yy_current_state = (yy_start); yy_match: do { register YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)]; if ( yy_accept[yy_current_state] ) { (yy_last_accepting_state) = yy_current_state; (yy_last_accepting_cpos) = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 83 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; ++yy_cp; } while ( yy_base[yy_current_state] != 189 ); yy_find_action: yy_act = yy_accept[yy_current_state]; if ( yy_act == 0 ) { /* have to back up */ yy_cp = (yy_last_accepting_cpos); yy_current_state = (yy_last_accepting_state); yy_act = yy_accept[yy_current_state]; } YY_DO_BEFORE_ACTION; do_action: /* This label is used only to access EOF actions. */ switch ( yy_act ) { /* beginning of action switch */ case 0: /* must back up */ /* undo the effects of YY_DO_BEFORE_ACTION */ *yy_cp = (yy_hold_char); yy_cp = (yy_last_accepting_cpos); yy_current_state = (yy_last_accepting_state); goto yy_find_action; case 1: /* rule 1 can match eol */ YY_RULE_SETUP #line 58 "splitter.l" { } YY_BREAK case 2: YY_RULE_SETUP #line 61 "splitter.l" { // this recognizes special numbers that // start with a dot (decimals) or with a sign (signed) tokens->push_back(splittertext); return 1; } YY_BREAK case 3: YY_RULE_SETUP #line 68 "splitter.l" { // // The word includes alphas, regular numbers (not num, // see above), alphanums, and acronyms // IMPORTANT NOTE: the grammar does not separate inner // dashes and dots! Hence the detection of abbreviations // simply has to verify the dot following the word. // // split apostrophes followed by letters, e.g. 's, 'm, 're, 've, n't std::string buffer = splittertext; int block = -1; if(buffer.size() > 3 && toLower(buffer.substr(buffer.size() - 3, 3)) == "n't"){ tokens->push_back(buffer.substr(0, buffer.size() - 3)); tokens->push_back(buffer.substr(buffer.size() - 3, 3)); } else if((block = hasApostropheBlock(buffer)) > 0){ tokens->push_back(buffer.substr(0, block)); tokens->push_back(buffer.substr(block, buffer.size() - block)); } else{ tokens->push_back(splittertext); } return 1; } YY_BREAK case 4: YY_RULE_SETUP #line 94 "splitter.l" { tokens->push_back(splittertext); return 1; } YY_BREAK case 5: YY_RULE_SETUP #line 99 "splitter.l" { tokens->push_back(splittertext); return 1; } YY_BREAK case 6: YY_RULE_SETUP #line 104 "splitter.l" { tokens->push_back(splittertext); return 1; } YY_BREAK case 7: YY_RULE_SETUP #line 109 "splitter.l" { tokens->push_back(splittertext); return 1; } YY_BREAK case 8: /* rule 8 can match eol */ YY_RULE_SETUP #line 114 "splitter.l" { tokens->push_back(splittertext); return 1; } YY_BREAK case 9: YY_RULE_SETUP #line 119 "splitter.l" { tokens->push_back(splittertext); return 1; } YY_BREAK case 10: YY_RULE_SETUP #line 124 "splitter.l" { tokens->push_back(splittertext); return 1; } YY_BREAK case 11: YY_RULE_SETUP #line 129 "splitter.l" { tokens->push_back(splittertext); return 1; } YY_BREAK case 12: YY_RULE_SETUP #line 134 "splitter.l" ECHO; YY_BREAK #line 969 "<stdout>" case YY_STATE_EOF(INITIAL): yyterminate(); case YY_END_OF_BUFFER: { /* Amount of text matched not including the EOB char. */ int yy_amount_of_matched_text = (int) (yy_cp - (yytext_ptr)) - 1; /* Undo the effects of YY_DO_BEFORE_ACTION. */ *yy_cp = (yy_hold_char); YY_RESTORE_YY_MORE_OFFSET if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW ) { /* We're scanning a new file or input source. It's * possible that this happened because the user * just pointed splitterin at a new source and called * splitterlex(). If so, then we have to assure * consistency between YY_CURRENT_BUFFER and our * globals. Here is the right place to do so, because * this is the first action (other than possibly a * back-up) that will match for the new input source. */ (yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; YY_CURRENT_BUFFER_LVALUE->yy_input_file = splitterin; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL; } /* Note that here we test for yy_c_buf_p "<=" to the position * of the first EOB in the buffer, since yy_c_buf_p will * already have been incremented past the NUL character * (since all states make transitions on EOB to the * end-of-buffer state). Contrast this with the test * in input(). */ if ( (yy_c_buf_p) <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] ) { /* This was really a NUL. */ yy_state_type yy_next_state; (yy_c_buf_p) = (yytext_ptr) + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( ); /* Okay, we're now positioned to make the NUL * transition. We couldn't have * yy_get_previous_state() go ahead and do it * for us because it doesn't know how to deal * with the possibility of jamming (and we don't * want to build jamming into it because then it * will run more slowly). */ yy_next_state = yy_try_NUL_trans( yy_current_state ); yy_bp = (yytext_ptr) + YY_MORE_ADJ; if ( yy_next_state ) { /* Consume the NUL. */ yy_cp = ++(yy_c_buf_p); yy_current_state = yy_next_state; goto yy_match; } else { yy_cp = (yy_c_buf_p); goto yy_find_action; } } else switch ( yy_get_next_buffer( ) ) { case EOB_ACT_END_OF_FILE: { (yy_did_buffer_switch_on_eof) = 0; if ( splitterwrap( ) ) { /* Note: because we've taken care in * yy_get_next_buffer() to have set up * splittertext, we can now set up * yy_c_buf_p so that if some total * hoser (like flex itself) wants to * call the scanner after we return the * YY_NULL, it'll still work - another * YY_NULL will get returned. */ (yy_c_buf_p) = (yytext_ptr) + YY_MORE_ADJ; yy_act = YY_STATE_EOF(YY_START); goto do_action; } else { if ( ! (yy_did_buffer_switch_on_eof) ) YY_NEW_FILE; } break; } case EOB_ACT_CONTINUE_SCAN: (yy_c_buf_p) = (yytext_ptr) + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( ); yy_cp = (yy_c_buf_p); yy_bp = (yytext_ptr) + YY_MORE_ADJ; goto yy_match; case EOB_ACT_LAST_MATCH: (yy_c_buf_p) = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)]; yy_current_state = yy_get_previous_state( ); yy_cp = (yy_c_buf_p); yy_bp = (yytext_ptr) + YY_MORE_ADJ; goto yy_find_action; } break; } default: YY_FATAL_ERROR( "fatal flex scanner internal error--no action found" ); } /* end of action switch */ } /* end of scanning one token */ } /* end of splitterlex */ /* yy_get_next_buffer - try to read in a new buffer * * Returns a code representing an action: * EOB_ACT_LAST_MATCH - * EOB_ACT_CONTINUE_SCAN - continue scanning from current position * EOB_ACT_END_OF_FILE - end of file */ static int yy_get_next_buffer (void) { register char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf; register char *source = (yytext_ptr); register int number_to_move, i; int ret_val; if ( (yy_c_buf_p) > &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] ) YY_FATAL_ERROR( "fatal flex scanner internal error--end of buffer missed" ); if ( YY_CURRENT_BUFFER_LVALUE->yy_fill_buffer == 0 ) { /* Don't try to fill the buffer, so this is an EOF. */ if ( (yy_c_buf_p) - (yytext_ptr) - YY_MORE_ADJ == 1 ) { /* We matched a single character, the EOB, so * treat this as a final EOF. */ return EOB_ACT_END_OF_FILE; } else { /* We matched some text prior to the EOB, first * process it. */ return EOB_ACT_LAST_MATCH; } } /* Try to read more data. */ /* First move last chars to start of buffer. */ number_to_move = (int) ((yy_c_buf_p) - (yytext_ptr)) - 1; for ( i = 0; i < number_to_move; ++i ) *(dest++) = *(source++); if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_EOF_PENDING ) /* don't do the read, it's not guaranteed to return an EOF, * just force an EOF */ YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars) = 0; else { int num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; while ( num_to_read <= 0 ) { /* Not enough room in the buffer - grow it. */ /* just a shorter name for the current buffer */ YY_BUFFER_STATE b = YY_CURRENT_BUFFER; int yy_c_buf_p_offset = (int) ((yy_c_buf_p) - b->yy_ch_buf); if ( b->yy_is_our_buffer ) { int new_size = b->yy_buf_size * 2; if ( new_size <= 0 ) b->yy_buf_size += b->yy_buf_size / 8; else b->yy_buf_size *= 2; b->yy_ch_buf = (char *) /* Include room in for 2 EOB chars. */ splitterrealloc((void *) b->yy_ch_buf,b->yy_buf_size + 2 ); } else /* Can't grow it, we don't own it. */ b->yy_ch_buf = 0; if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "fatal error - scanner input buffer overflow" ); (yy_c_buf_p) = &b->yy_ch_buf[yy_c_buf_p_offset]; num_to_read = YY_CURRENT_BUFFER_LVALUE->yy_buf_size - number_to_move - 1; } if ( num_to_read > YY_READ_BUF_SIZE ) num_to_read = YY_READ_BUF_SIZE; /* Read in more data. */ YY_INPUT( (&YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]), (yy_n_chars), (size_t) num_to_read ); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars); } if ( (yy_n_chars) == 0 ) { if ( number_to_move == YY_MORE_ADJ ) { ret_val = EOB_ACT_END_OF_FILE; splitterrestart(splitterin ); } else { ret_val = EOB_ACT_LAST_MATCH; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_EOF_PENDING; } } else ret_val = EOB_ACT_CONTINUE_SCAN; if ((yy_size_t) ((yy_n_chars) + number_to_move) > YY_CURRENT_BUFFER_LVALUE->yy_buf_size) { /* Extend the array by 50%, plus the number we really need. */ yy_size_t new_size = (yy_n_chars) + number_to_move + ((yy_n_chars) >> 1); YY_CURRENT_BUFFER_LVALUE->yy_ch_buf = (char *) splitterrealloc((void *) YY_CURRENT_BUFFER_LVALUE->yy_ch_buf,new_size ); if ( ! YY_CURRENT_BUFFER_LVALUE->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in yy_get_next_buffer()" ); } (yy_n_chars) += number_to_move; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] = YY_END_OF_BUFFER_CHAR; YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars) + 1] = YY_END_OF_BUFFER_CHAR; (yytext_ptr) = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[0]; return ret_val; } /* yy_get_previous_state - get the state just before the EOB char was reached */ static yy_state_type yy_get_previous_state (void) { register yy_state_type yy_current_state; register char *yy_cp; yy_current_state = (yy_start); for ( yy_cp = (yytext_ptr) + YY_MORE_ADJ; yy_cp < (yy_c_buf_p); ++yy_cp ) { register YY_CHAR yy_c = (*yy_cp ? yy_ec[YY_SC_TO_UI(*yy_cp)] : 1); if ( yy_accept[yy_current_state] ) { (yy_last_accepting_state) = yy_current_state; (yy_last_accepting_cpos) = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 83 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; } return yy_current_state; } /* yy_try_NUL_trans - try to make a transition on the NUL character * * synopsis * next_state = yy_try_NUL_trans( current_state ); */ static yy_state_type yy_try_NUL_trans (yy_state_type yy_current_state ) { register int yy_is_jam; register char *yy_cp = (yy_c_buf_p); register YY_CHAR yy_c = 1; if ( yy_accept[yy_current_state] ) { (yy_last_accepting_state) = yy_current_state; (yy_last_accepting_cpos) = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 83 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; yy_is_jam = (yy_current_state == 82); return yy_is_jam ? 0 : yy_current_state; } static void yyunput (int c, register char * yy_bp ) { register char *yy_cp; yy_cp = (yy_c_buf_p); /* undo effects of setting up splittertext */ *yy_cp = (yy_hold_char); if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 ) { /* need to shift things up to make room */ /* +2 for EOB chars. */ register int number_to_move = (yy_n_chars) + 2; register char *dest = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[ YY_CURRENT_BUFFER_LVALUE->yy_buf_size + 2]; register char *source = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[number_to_move]; while ( source > YY_CURRENT_BUFFER_LVALUE->yy_ch_buf ) *--dest = *--source; yy_cp += (int) (dest - source); yy_bp += (int) (dest - source); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_buf_size; if ( yy_cp < YY_CURRENT_BUFFER_LVALUE->yy_ch_buf + 2 ) YY_FATAL_ERROR( "flex scanner push-back overflow" ); } *--yy_cp = (char) c; (yytext_ptr) = yy_bp; (yy_hold_char) = *yy_cp; (yy_c_buf_p) = yy_cp; } #ifndef YY_NO_INPUT #ifdef __cplusplus static int yyinput (void) #else static int input (void) #endif { int c; *(yy_c_buf_p) = (yy_hold_char); if ( *(yy_c_buf_p) == YY_END_OF_BUFFER_CHAR ) { /* yy_c_buf_p now points to the character we want to return. * If this occurs *before* the EOB characters, then it's a * valid NUL; if not, then we've hit the end of the buffer. */ if ( (yy_c_buf_p) < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)] ) /* This was really a NUL. */ *(yy_c_buf_p) = '\0'; else { /* need more input */ int offset = (yy_c_buf_p) - (yytext_ptr); ++(yy_c_buf_p); switch ( yy_get_next_buffer( ) ) { case EOB_ACT_LAST_MATCH: /* This happens because yy_g_n_b() * sees that we've accumulated a * token and flags that we need to * try matching the token before * proceeding. But for input(), * there's no matching to consider. * So convert the EOB_ACT_LAST_MATCH * to EOB_ACT_END_OF_FILE. */ /* Reset buffer status. */ splitterrestart(splitterin ); /*FALLTHROUGH*/ case EOB_ACT_END_OF_FILE: { if ( splitterwrap( ) ) return EOF; if ( ! (yy_did_buffer_switch_on_eof) ) YY_NEW_FILE; #ifdef __cplusplus return yyinput(); #else return input(); #endif } case EOB_ACT_CONTINUE_SCAN: (yy_c_buf_p) = (yytext_ptr) + offset; break; } } } c = *(unsigned char *) (yy_c_buf_p); /* cast for 8-bit char's */ *(yy_c_buf_p) = '\0'; /* preserve splittertext */ (yy_hold_char) = *++(yy_c_buf_p); return c; } #endif /* ifndef YY_NO_INPUT */ /** Immediately switch to a different input stream. * @param input_file A readable stream. * * @note This function does not reset the start condition to @c INITIAL . */ void splitterrestart (FILE * input_file ) { if ( ! YY_CURRENT_BUFFER ){ splitterensure_buffer_stack (); YY_CURRENT_BUFFER_LVALUE = splitter_create_buffer(splitterin,YY_BUF_SIZE ); } splitter_init_buffer(YY_CURRENT_BUFFER,input_file ); splitter_load_buffer_state( ); } /** Switch to a different input buffer. * @param new_buffer The new input buffer. * */ void splitter_switch_to_buffer (YY_BUFFER_STATE new_buffer ) { /* TODO. We should be able to replace this entire function body * with * splitterpop_buffer_state(); * splitterpush_buffer_state(new_buffer); */ splitterensure_buffer_stack (); if ( YY_CURRENT_BUFFER == new_buffer ) return; if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *(yy_c_buf_p) = (yy_hold_char); YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars); } YY_CURRENT_BUFFER_LVALUE = new_buffer; splitter_load_buffer_state( ); /* We don't actually know whether we did this switch during * EOF (splitterwrap()) processing, but the only time this flag * is looked at is after splitterwrap() is called, so it's safe * to go ahead and always set it. */ (yy_did_buffer_switch_on_eof) = 1; } static void splitter_load_buffer_state (void) { (yy_n_chars) = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; (yytext_ptr) = (yy_c_buf_p) = YY_CURRENT_BUFFER_LVALUE->yy_buf_pos; splitterin = YY_CURRENT_BUFFER_LVALUE->yy_input_file; (yy_hold_char) = *(yy_c_buf_p); } /** Allocate and initialize an input buffer state. * @param file A readable stream. * @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE. * * @return the allocated buffer state. */ YY_BUFFER_STATE splitter_create_buffer (FILE * file, int size ) { YY_BUFFER_STATE b; b = (YY_BUFFER_STATE) splitteralloc(sizeof( struct yy_buffer_state ) ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in splitter_create_buffer()" ); b->yy_buf_size = size; /* yy_ch_buf has to be 2 characters longer than the size given because * we need to put in 2 end-of-buffer characters. */ b->yy_ch_buf = (char *) splitteralloc(b->yy_buf_size + 2 ); if ( ! b->yy_ch_buf ) YY_FATAL_ERROR( "out of dynamic memory in splitter_create_buffer()" ); b->yy_is_our_buffer = 1; splitter_init_buffer(b,file ); return b; } /** Destroy the buffer. * @param b a buffer created with splitter_create_buffer() * */ void splitter_delete_buffer (YY_BUFFER_STATE b ) { if ( ! b ) return; if ( b == YY_CURRENT_BUFFER ) /* Not sure if we should pop here. */ YY_CURRENT_BUFFER_LVALUE = (YY_BUFFER_STATE) 0; if ( b->yy_is_our_buffer ) splitterfree((void *) b->yy_ch_buf ); splitterfree((void *) b ); } #ifndef __cplusplus extern int isatty (int ); #endif /* __cplusplus */ /* Initializes or reinitializes a buffer. * This function is sometimes called more than once on the same buffer, * such as during a splitterrestart() or at EOF. */ static void splitter_init_buffer (YY_BUFFER_STATE b, FILE * file ) { int oerrno = errno; splitter_flush_buffer(b ); b->yy_input_file = file; b->yy_fill_buffer = 1; /* If b is the current buffer, then splitter_init_buffer was _probably_ * called from splitterrestart() or through yy_get_next_buffer. * In that case, we don't want to reset the lineno or column. */ if (b != YY_CURRENT_BUFFER){ b->yy_bs_lineno = 1; b->yy_bs_column = 0; } b->yy_is_interactive = file ? (isatty( fileno(file) ) > 0) : 0; errno = oerrno; } /** Discard all buffered characters. On the next scan, YY_INPUT will be called. * @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER. * */ void splitter_flush_buffer (YY_BUFFER_STATE b ) { if ( ! b ) return; b->yy_n_chars = 0; /* We always need two end-of-buffer characters. The first causes * a transition to the end-of-buffer state. The second causes * a jam in that state. */ b->yy_ch_buf[0] = YY_END_OF_BUFFER_CHAR; b->yy_ch_buf[1] = YY_END_OF_BUFFER_CHAR; b->yy_buf_pos = &b->yy_ch_buf[0]; b->yy_at_bol = 1; b->yy_buffer_status = YY_BUFFER_NEW; if ( b == YY_CURRENT_BUFFER ) splitter_load_buffer_state( ); } /** Pushes the new state onto the stack. The new state becomes * the current state. This function will allocate the stack * if necessary. * @param new_buffer The new state. * */ void splitterpush_buffer_state (YY_BUFFER_STATE new_buffer ) { if (new_buffer == NULL) return; splitterensure_buffer_stack(); /* This block is copied from splitter_switch_to_buffer. */ if ( YY_CURRENT_BUFFER ) { /* Flush out information for old buffer. */ *(yy_c_buf_p) = (yy_hold_char); YY_CURRENT_BUFFER_LVALUE->yy_buf_pos = (yy_c_buf_p); YY_CURRENT_BUFFER_LVALUE->yy_n_chars = (yy_n_chars); } /* Only push if top exists. Otherwise, replace top. */ if (YY_CURRENT_BUFFER) (yy_buffer_stack_top)++; YY_CURRENT_BUFFER_LVALUE = new_buffer; /* copied from splitter_switch_to_buffer. */ splitter_load_buffer_state( ); (yy_did_buffer_switch_on_eof) = 1; } /** Removes and deletes the top of the stack, if present. * The next element becomes the new top. * */ void splitterpop_buffer_state (void) { if (!YY_CURRENT_BUFFER) return; splitter_delete_buffer(YY_CURRENT_BUFFER ); YY_CURRENT_BUFFER_LVALUE = NULL; if ((yy_buffer_stack_top) > 0) --(yy_buffer_stack_top); if (YY_CURRENT_BUFFER) { splitter_load_buffer_state( ); (yy_did_buffer_switch_on_eof) = 1; } } /* Allocates the stack if it does not exist. * Guarantees space for at least one push. */ static void splitterensure_buffer_stack (void) { int num_to_alloc; if (!(yy_buffer_stack)) { /* First allocation is just for 2 elements, since we don't know if this * scanner will even need a stack. We use 2 instead of 1 to avoid an * immediate realloc on the next call. */ num_to_alloc = 1; (yy_buffer_stack) = (struct yy_buffer_state**)splitteralloc (num_to_alloc * sizeof(struct yy_buffer_state*) ); if ( ! (yy_buffer_stack) ) YY_FATAL_ERROR( "out of dynamic memory in splitterensure_buffer_stack()" ); memset((yy_buffer_stack), 0, num_to_alloc * sizeof(struct yy_buffer_state*)); (yy_buffer_stack_max) = num_to_alloc; (yy_buffer_stack_top) = 0; return; } if ((yy_buffer_stack_top) >= ((yy_buffer_stack_max)) - 1){ /* Increase the buffer to prepare for a possible push. */ int grow_size = 8 /* arbitrary grow size */; num_to_alloc = (yy_buffer_stack_max) + grow_size; (yy_buffer_stack) = (struct yy_buffer_state**)splitterrealloc ((yy_buffer_stack), num_to_alloc * sizeof(struct yy_buffer_state*) ); if ( ! (yy_buffer_stack) ) YY_FATAL_ERROR( "out of dynamic memory in splitterensure_buffer_stack()" ); /* zero only the new slots.*/ memset((yy_buffer_stack) + (yy_buffer_stack_max), 0, grow_size * sizeof(struct yy_buffer_state*)); (yy_buffer_stack_max) = num_to_alloc; } } /** Setup the input buffer state to scan directly from a user-specified character buffer. * @param base the character buffer * @param size the size in bytes of the character buffer * * @return the newly allocated buffer state object. */ YY_BUFFER_STATE splitter_scan_buffer (char * base, yy_size_t size ) { YY_BUFFER_STATE b; if ( size < 2 || base[size-2] != YY_END_OF_BUFFER_CHAR || base[size-1] != YY_END_OF_BUFFER_CHAR ) /* They forgot to leave room for the EOB's. */ return 0; b = (YY_BUFFER_STATE) splitteralloc(sizeof( struct yy_buffer_state ) ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in splitter_scan_buffer()" ); b->yy_buf_size = size - 2; /* "- 2" to take care of EOB's */ b->yy_buf_pos = b->yy_ch_buf = base; b->yy_is_our_buffer = 0; b->yy_input_file = 0; b->yy_n_chars = b->yy_buf_size; b->yy_is_interactive = 0; b->yy_at_bol = 1; b->yy_fill_buffer = 0; b->yy_buffer_status = YY_BUFFER_NEW; splitter_switch_to_buffer(b ); return b; } /** Setup the input buffer state to scan a string. The next call to splitterlex() will * scan from a @e copy of @a str. * @param yystr a NUL-terminated string to scan * * @return the newly allocated buffer state object. * @note If you want to scan bytes that may contain NUL values, then use * splitter_scan_bytes() instead. */ YY_BUFFER_STATE splitter_scan_string (yyconst char * yystr ) { return splitter_scan_bytes(yystr,strlen(yystr) ); } /** Setup the input buffer state to scan the given bytes. The next call to splitterlex() will * scan from a @e copy of @a bytes. * @param yybytes the byte buffer to scan * @param _yybytes_len the number of bytes in the buffer pointed to by @a bytes. * * @return the newly allocated buffer state object. */ YY_BUFFER_STATE splitter_scan_bytes (yyconst char * yybytes, int _yybytes_len ) { YY_BUFFER_STATE b; char *buf; yy_size_t n; int i; /* Get memory for full buffer, including space for trailing EOB's. */ n = _yybytes_len + 2; buf = (char *) splitteralloc(n ); if ( ! buf ) YY_FATAL_ERROR( "out of dynamic memory in splitter_scan_bytes()" ); for ( i = 0; i < _yybytes_len; ++i ) buf[i] = yybytes[i]; buf[_yybytes_len] = buf[_yybytes_len+1] = YY_END_OF_BUFFER_CHAR; b = splitter_scan_buffer(buf,n ); if ( ! b ) YY_FATAL_ERROR( "bad buffer in splitter_scan_bytes()" ); /* It's okay to grow etc. this buffer, and we should throw it * away when we're done. */ b->yy_is_our_buffer = 1; return b; } #ifndef YY_EXIT_FAILURE #define YY_EXIT_FAILURE 2 #endif static void yy_fatal_error (yyconst char* msg ) { (void) fprintf( stderr, "%s\n", msg ); exit( YY_EXIT_FAILURE ); } /* Redefine yyless() so it works in section 3 code. */ #undef yyless #define yyless(n) \ do \ { \ /* Undo effects of setting up splittertext. */ \ int yyless_macro_arg = (n); \ YY_LESS_LINENO(yyless_macro_arg);\ splittertext[splitterleng] = (yy_hold_char); \ (yy_c_buf_p) = splittertext + yyless_macro_arg; \ (yy_hold_char) = *(yy_c_buf_p); \ *(yy_c_buf_p) = '\0'; \ splitterleng = yyless_macro_arg; \ } \ while ( 0 ) /* Accessor methods (get/set functions) to struct members. */ /** Get the current line number. * */ int splitterget_lineno (void) { return splitterlineno; } /** Get the input stream. * */ FILE *splitterget_in (void) { return splitterin; } /** Get the output stream. * */ FILE *splitterget_out (void) { return splitterout; } /** Get the length of the current token. * */ int splitterget_leng (void) { return splitterleng; } /** Get the current token. * */ char *splitterget_text (void) { return splittertext; } /** Set the current line number. * @param line_number * */ void splitterset_lineno (int line_number ) { splitterlineno = line_number; } /** Set the input stream. This does not discard the current * input buffer. * @param in_str A readable stream. * * @see splitter_switch_to_buffer */ void splitterset_in (FILE * in_str ) { splitterin = in_str ; } void splitterset_out (FILE * out_str ) { splitterout = out_str ; } int splitterget_debug (void) { return splitter_flex_debug; } void splitterset_debug (int bdebug ) { splitter_flex_debug = bdebug ; } static int yy_init_globals (void) { /* Initialization is the same as for the non-reentrant scanner. * This function is called from splitterlex_destroy(), so don't allocate here. */ (yy_buffer_stack) = 0; (yy_buffer_stack_top) = 0; (yy_buffer_stack_max) = 0; (yy_c_buf_p) = (char *) 0; (yy_init) = 0; (yy_start) = 0; /* Defined in main.c */ #ifdef YY_STDINIT splitterin = stdin; splitterout = stdout; #else splitterin = (FILE *) 0; splitterout = (FILE *) 0; #endif /* For future reference: Set errno on error, since we are called by * splitterlex_init() */ return 0; } /* splitterlex_destroy is for both reentrant and non-reentrant scanners. */ int splitterlex_destroy (void) { /* Pop the buffer stack, destroying each element. */ while(YY_CURRENT_BUFFER){ splitter_delete_buffer(YY_CURRENT_BUFFER ); YY_CURRENT_BUFFER_LVALUE = NULL; splitterpop_buffer_state(); } /* Destroy the stack itself. */ splitterfree((yy_buffer_stack) ); (yy_buffer_stack) = NULL; /* Reset the globals. This is important in a non-reentrant scanner so the next time * splitterlex() is called, initialization will occur. */ yy_init_globals( ); return 0; } /* * Internal utility routines. */ #ifndef yytext_ptr static void yy_flex_strncpy (char* s1, yyconst char * s2, int n ) { register int i; for ( i = 0; i < n; ++i ) s1[i] = s2[i]; } #endif #ifdef YY_NEED_STRLEN static int yy_flex_strlen (yyconst char * s ) { register int n; for ( n = 0; s[n]; ++n ) ; return n; } #endif void *splitteralloc (yy_size_t size ) { return (void *) malloc( size ); } void *splitterrealloc (void * ptr, yy_size_t size ) { /* The cast to (char *) in the following accommodates both * implementations that use char* generic pointers, and those * that use void* generic pointers. It works with the latter * because both ANSI C and C++ allow castless assignment from * any pointer type to void*, and deal with argument conversions * as though doing an assignment. */ return (void *) realloc( (char *) ptr, size ); } void splitterfree (void * ptr ) { free( (char *) ptr ); /* see splitterrealloc() for (char *) cast */ } #define YYTABLES_NAME "yytables" #line 134 "splitter.l" static std::string toLower(const std::string & s) { std::string out = s; for(unsigned int i = 0; i < out.size(); i ++){ out[i] = tolower(out[i]); } return out; } /** does it end with "'string"? */ static int hasApostropheBlock(const std::string & s) { for(int i = s.size() - 1; i > 0; i --){ if(s[i] == '\'' && i < (int) s.size() - 1){ return i; } if(! isalpha(s[i])){ return -1; } } return -1; } static int splitterTransfer(char * buffer, int size) { int howMuch = bufferEnd - bufferBegin; if(size < howMuch){ howMuch = size; } /* The actual transfer */ if(howMuch > 0){ memcpy(buffer, bufferBegin, howMuch); bufferBegin += howMuch; } return howMuch; } void unitSplit(const char * inputBuffer, unsigned int inputSize, std::vector<std::string> & output) { bufferBegin = (char *) inputBuffer; bufferEnd = bufferBegin + inputSize; tokens = & output; while(splitterlex()); }
[ "52473452+ivilab-sync@users.noreply.github.com" ]
52473452+ivilab-sync@users.noreply.github.com
1c1f96d1dce5a1500ba1e89bd11db7bad5f3fb40
04ac4f25086abb864d61772e29c6aab67bd0b0b6
/term2/seminar16_error_handling/classroom_tasks/code04_errors/vector_at.cpp
577ec332b29e0946476b03d78b1a8a5c86cf8d11
[]
no_license
v-biryukov/cs_mipt_faki
9adb3e1ca470ab647e2555af6fa095cad0db12ca
075fe8bc104921ab36350e71636fd59aaf669fe9
refs/heads/master
2023-06-22T04:18:50.220177
2023-06-15T09:58:48
2023-06-15T09:58:48
42,241,044
5
2
null
null
null
null
UTF-8
C++
false
false
112
cpp
#include <iostream> #include <vector> int main() { std::vector v {10, 20, 30}; std::cout << v.at(5); }
[ "biryukov.vova@gmail.com" ]
biryukov.vova@gmail.com
e698aed83a471b768fa9b1fc568b8111dac3b586
53e07ca444de3697b78c62a6a9e13c66ad581feb
/task_7_bounce.cpp
c5604ed5892123b44b2cbd56b3eccb1589f1607c
[]
no_license
uhioma-0/git
bc191eec21bddc962f10de8ca1d2edd6eaa27ab4
83e60aa40fc368b2332f4f42f2f1e57082f8da36
refs/heads/master
2023-01-09T16:06:35.026512
2020-11-15T20:36:59
2020-11-15T20:36:59
313,111,619
0
0
null
null
null
null
UTF-8
C++
false
false
380
cpp
#include <iostream> using namespace std; void descending_ascending(int n) { if (n < 0) cout << "Error! Input cannot be negative."; for (int i = n; i >= 0; i--) { cout << i; } for (int i = 1; i <=n; i++) { cout << i; } } /*int main() { string message1 = "please inter positive number"; cout << message1 << endl; int n; cin >> n; descending_ascending(n); } */
[ "husen.husni@gmail.com" ]
husen.husni@gmail.com
88396e3ca098b2b2eb56a92f8c4c9a1aaa036fb4
c77a0f1524e24dff8737f49be71d0ee66ee4dbf3
/MidpointMethod.cpp
68cdd1853856e54cba11be993fe530cc728f8659
[]
no_license
zellxu/galileo
82aa73a0d0556fb7d31c289a611bed3c2efb5fff
b0014c2abf95de874fe77b4d6a641d48d8da8738
refs/heads/master
2021-01-23T10:44:41.266424
2015-02-12T20:18:34
2015-02-12T20:47:25
30,721,588
0
0
null
null
null
null
UTF-8
C++
false
false
739
cpp
#include "MidpointMethod.h" void MidpointMethod::integrate(SystemInterface* system, double timestep){ Eigen::VectorXd initState = system->getState(); system->setState(initState + timestep/2 * system->derivEval()); system->setState(initState + timestep * system->derivEval()); } Eigen::VectorXd MidpointMethod::integrate(Eigen::VectorXd state, Eigen::VectorXd derivEval, double timestep) { Eigen::VectorXd halfstep = state + timestep/2.0 * derivEval; //Manually evaluating because I won't do this on MyWorldClass. :( Eigen::VectorXd fHalfStep = Eigen::VectorXd::Zero(halfstep.size()); fHalfStep.segment<3>(0) = halfstep.segment<3>(3); fHalfStep.segment<3>(3) = derivEval.segment<3>(3); return (state + timestep * fHalfStep); }
[ "zellxu@gmail.com" ]
zellxu@gmail.com
c5151b948688de5c33c9c81b7beeed92509520ed
fad45426c65e559203b98641703928fe5aee38ce
/util.cpp
4f870f651faf25bb4fa5af1a391a2edd9d8a5e99
[]
no_license
jeffminton/lib
e08b5ffa18072028683113de78eb091fd301e0c1
55f4014097896752ee0556cf618a961631e335cf
refs/heads/master
2021-01-24T06:29:59.460943
2011-04-25T03:37:25
2011-04-25T03:37:25
1,303,678
1
0
null
null
null
null
UTF-8
C++
false
false
845
cpp
/** Programmer: Jeffrey Minton File: util.cpp Description: A file containing various utilities */ #include "util.h" //match bool Util::match(string str, string pattern) { regex regPattern = regex(pattern); return regex_match(str, regPattern); } //getMatch string Util::getMatch(string str, string pattern, int grp) { regex regPattern = regex(pattern); smatch regOut; if(regex_match(str, regOut, regPattern) == false) { return ""; } return regOut[grp]; } //split vector<string> Util::split(string str, string pattern) { vector<string> out; regex splitReg = regex(pattern); const sregex_token_iterator end; for(sregex_token_iterator i(str.begin(), str.end(), splitReg); i != end; ++i) { out.push_back(*i); } return out; } //strip void Util::strip(string &str) { str = getMatch(str, STRIPLINE, 1); return; }
[ "jeffrey.minton@gmail.com" ]
jeffrey.minton@gmail.com
ddd472c682f5a8c2dc99cc15b6c1612f9147c9cc
478233633e5fd5772f63328702356e428f317172
/video-slider-controls.cpp
098d5c70270bd55f9cc3e1b2e9b2306c2de84201
[]
no_license
BilboBlockins/opencv-examples
84f7624ec76055653973a4f484239aa53c7e20f7
c6155650fbdf474ac1e00ee3e73db6771e9d516e
refs/heads/master
2022-11-27T07:10:26.416630
2020-08-06T20:49:10
2020-08-06T20:49:10
285,668,393
0
0
null
null
null
null
UTF-8
C++
false
false
1,993
cpp
#include <iostream> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> //Program for reading video from the default camera. using namespace std; using namespace cv; void locator(int event, int x, int y, int flags, void* userdata) { if (event == EVENT_LBUTTONDOWN) { cout << "Left click has been made, Position: (" << x << ", " << y << ")" << endl; } else if (event == EVENT_RBUTTONDOWN) { cout << "Right click has been made, position: (" << x << ", " << y << ")" << endl; } else if (event == EVENT_MBUTTONDOWN) { cout << "Middle click has been made, position: (" << x << ", " << y << ")" << endl; } else if (event == EVENT_MOUSEMOVE) { cout << "Current mouse position: (" << x << ", " << y << ")" << endl; } } int main(int argc, char*argv[]) { VideoCapture video(0); //capturing video from webcam - use (1),(2), for cameras in different usb ports. namedWindow("VideoPlayer", CV_WINDOW_AUTOSIZE);//declaring the window namedWindow("Slider", CV_WINDOW_KEEPRATIO); /*declaring window to show image*/ int light = 50; /*starting value of the track-bar*/ createTrackbar("Brightness", "Slider", &light, 100); /*creating a trackbar*/ int contrast = 50; /*starting value of the track-bar*/ createTrackbar("Contrast", "Slider", &contrast, 100); /*creating a trackbar*/ while (true) { Mat image; //delcaring a Matrix named image video.read(image); //reading frames from camera and loading them in image Matrix int Brightness = light - 50; //interaction with trackbar double Contrast = contrast / 50.0; //interaction with trackbar setMouseCallback("VideoPlayer", locator, NULL); //Mouse callback function on define window image.convertTo(image, -1, Contrast, Brightness); //implement the effect of chnage of trackbar imshow("VideoPlayer", image); //showing the image in window named VideoPlayer waitKey(20); //wait for 20 milliseconds } return 0; }
[ "abretthiebert@gmail.com" ]
abretthiebert@gmail.com
87bfb09506751ba51a806a76f12d51214abbfaea
c2d361ceba435b49db81994fecee8038bd786c6a
/Main.cpp
75001e95da54217af563feefd629eb2fe44bc3da
[]
no_license
NumbFish-Luo/UsbDev_Test
59c9fda34c4955f0d30d0cdcb2e4c687d7b2cb9d
dc37d5193fd317cdcd97e079eda0c87e2414cb86
refs/heads/master
2020-08-27T07:22:50.996058
2019-10-24T11:31:54
2019-10-24T11:31:54
217,283,349
2
0
null
null
null
null
UTF-8
C++
false
false
51
cpp
#include "UsbDev.h" int main() { return 0; }
[ "numbfish@yeah.net" ]
numbfish@yeah.net
08061d9bed65cf9504c291b8b2e06474015ca0cf
2ac1419480f7177ce7cbce2ea51734ac2f14d810
/Algorithm_problems/C/문법 및 실습예제/함수/19_포인터SWAP(call by address).cpp
d9705c57b73213e1551b3099ac856f7e3f6f8912
[]
no_license
swarthyPig/Algorithm-training-and-SQL-query
d0e854c8118dfa0565848f0a98facaa68034fb99
562888ee5a6386f4ae52d60d3012de66931159cc
refs/heads/master
2020-07-07T16:05:04.045583
2020-03-03T09:38:53
2020-03-03T09:38:53
203,399,615
0
0
null
null
null
null
UHC
C++
false
false
797
cpp
#include "stdafx.h" #include <time.h> #include <stdlib.h> #include <Windows.h> #pragma warning(disable:4996) #define _CRT_SECURE_NO_WARNINGS // ctrl + d 자동 복붙 // ctrl + k + d 코드 정렬 // alt + 방향키위아래 : 이동 // 전체주석 : ctrl + k + c <---> ctrl + k + u // 18번 과의 비교, 포인터를 사용하여 메모리를 공유하고나서는 값이 교환 된다 call by address // 포인터를 이용한 SWAP void func19(int *a, int *b) { if (a == NULL || b == NULL) { //방어적인 프로그램, 포인터는 적어줘야된다. return; } int t; t = *a; *a = *b; *b = t; } void main() { srand((unsigned)time(NULL)); int n8 = 10, n9 = 20; printf("%d %d\n", n8, n9); func19(&n8, &n9); printf("%d %d\n", n8, n9); }
[ "noreply@github.com" ]
noreply@github.com
1cf259d9b3e0effedf0893f60dc73e1d0690dd19
717cfbb815d7232f69b7836e6b8a19ab1c8214ec
/sstd_tools/build_install/boost_filesystem/static_boost/type_traits/add_rvalue_reference.hpp
48a4d6839c4e418affc56f0ec0de6582bd11fefd
[]
no_license
ngzHappy/QtQmlBook
b1014fb862aa6b78522e06ec59b94b13951edd56
296fabfd4dc47b884631598c05a2f123e1e5a3b5
refs/heads/master
2020-04-09T04:34:41.261770
2019-02-26T13:13:15
2019-02-26T13:13:15
160,028,971
4
0
null
null
null
null
UTF-8
C++
false
false
2,418
hpp
// add_rvalue_reference.hpp ---------------------------------------------------------// // Copyright 2010 Vicente J. Botet Escriba // Distributed under the Boost Software License, Version 1.0. // See http://www.boost.org/LICENSE_1_0.txt #ifndef BOOST_TYPE_TRAITS_EXT_ADD_RVALUE_REFERENCE__HPP #define BOOST_TYPE_TRAITS_EXT_ADD_RVALUE_REFERENCE__HPP #include <static_boost/config.hpp> //----------------------------------------------------------------------------// #include <static_boost/type_traits/is_void.hpp> #include <static_boost/type_traits/is_reference.hpp> //----------------------------------------------------------------------------// // // // C++03 implementation of // // 20.9.7.2 Reference modifications [meta.trans.ref] // // Written by Vicente J. Botet Escriba // // // // If T names an object or function type then the member typedef type // shall name T&&; otherwise, type shall name T. [ Note: This rule reflects // the semantics of reference collapsing. For example, when a type T names // a type T1&, the type add_rvalue_reference<T>::type is not an rvalue // reference. -end note ] //----------------------------------------------------------------------------// namespace boost { namespace type_traits_detail { template <typename T, bool b> struct add_rvalue_reference_helper { typedef T type; }; #if !defined(BOOST_NO_CXX11_RVALUE_REFERENCES) template <typename T> struct add_rvalue_reference_helper<T, true> { typedef T&& type; }; #endif template <typename T> struct add_rvalue_reference_imp { typedef typename boost::type_traits_detail::add_rvalue_reference_helper <T, (is_void<T>::value == false && is_reference<T>::value == false) >::type type; }; } template <class T> struct add_rvalue_reference { typedef typename boost::type_traits_detail::add_rvalue_reference_imp<T>::type type; }; #if !defined(BOOST_NO_CXX11_TEMPLATE_ALIASES) template <class T> using add_rvalue_reference_t = typename add_rvalue_reference<T>::type; #endif } // namespace boost #endif // BOOST_TYPE_TRAITS_EXT_ADD_RVALUE_REFERENCE__HPP
[ "zhaixueqiang@hotmail.com" ]
zhaixueqiang@hotmail.com
f949d73a322c85abf6f7e349162e9df5512ff816
c1f078681e4ad1a6a34c3bf2a32388f7e66c8364
/@library/sources/XLSharedStrings.cpp
fdd64a82ab26af44e6674e3c80d41dd2934817e8
[ "BSD-3-Clause", "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
yang123vc/OpenXLSX
bda224b969ece60b138cc709c9a4f83805ac7edf
523582eae210a85af37f8a4bb82bc118f05913f6
refs/heads/master
2020-04-12T13:09:59.949665
2018-08-08T13:30:42
2018-08-08T13:30:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,126
cpp
// // Created by Troldal on 01/09/16. // #include "../headers/XLSharedStrings.h" #include "../headers/XLDocument.h" using namespace std; using namespace OpenXLSX; /** * @details Constructs a new XLSharedStrings object. Only one (common) object is allowed per XLDocument instance. * A filepath to the underlying XML file must be provided. */ XLSharedStrings::XLSharedStrings(XLDocument &parent, const std::string &filePath) : XLAbstractXMLFile(parent, filePath), XLSpreadsheetElement(parent), m_sharedStringNodes(), m_emptyString("") { ParseXMLData(); } /** * @details Saves the XML file (if modified) and destroys the object. */ XLSharedStrings::~XLSharedStrings() { //CommitXMLData(); } /** * @details Overrides the method in XLAbstractXMLFile. Clears the internal datastructure and fills it with the strings * in the XML file. * @todo Consider making the return value void. */ bool XLSharedStrings::ParseXMLData() { // Clear the datastructure m_sharedStringNodes.clear(); // Find the first node and iterate through the XML file, storing all string nodes in the internal datastructure for (auto &node : XmlDocument()->first_child().children()) m_sharedStringNodes.push_back(node.first_child()); return true; } /** * @details Look up a shared string by index and return a pointer to the corresponding node in the underlying XML file. * If the index is larger than the number of shared strings a nullptr will be returned. * The resulting string is returned as pointer-to-const, as the client is not supposed to modify the shared strings * directly. */ const XMLNode XLSharedStrings::GetStringNode(unsigned long index) const { if (index > m_sharedStringNodes.size() - 1) throw std::range_error("Node does not exist"); else return m_sharedStringNodes.at(index); } /** * @details Look up a shared string node by string and return a pointer to the corresponding node in the underlying XML file. * If the index is larger than the number of shared strings a nullptr will be returned. * The resulting string is returned as pointer-to-const, as the client is not supposed to modify the shared strings * directly. */ const XMLNode XLSharedStrings::GetStringNode(string_view str) const { for (const auto &s : m_sharedStringNodes) { if (string_view(s.text().get()) == str) return s; } throw std::range_error("Node does not exist"); } /** * @details Look up a string index by the string content. If the string does not exist, the returned index is -1. */ long XLSharedStrings::GetStringIndex(string_view str) const { long result = -1; long counter = 0; for (const auto &s : m_sharedStringNodes) { if (string_view(s.text().get()) == str) { result = counter; break; } counter++; } return result; } /** * @details */ bool XLSharedStrings::StringExists(string_view str) const { if (GetStringIndex(str) < 0) return false; else return true; } /** * @details */ bool XLSharedStrings::StringExists(unsigned long index) const { if (index > m_sharedStringNodes.size() - 1) throw false; else return true; } /** * @details Append a string by creating a new node in the XML file and adding the string to it. The index to the * shared string is returned */ long XLSharedStrings::AppendString(string_view str) { // Create the required nodes auto node = XmlDocument()->append_child("si"); auto value = node.append_child("t"); value.text().set(string(str).c_str()); // Add the node pointer to the internal datastructure. m_sharedStringNodes.push_back(value); SetModified(); // Return the Index of the new string. return m_sharedStringNodes.size() - 1; } /** * @details Clear the string at the given index. This will affect the entire spreadsheet; everywhere the shared string * is used, it will be erased. */ void XLSharedStrings::ClearString(int index) { m_sharedStringNodes.at(index).set_value(""); SetModified(); }
[ "kenneth.balslev@gmail.com" ]
kenneth.balslev@gmail.com
3b59ebdfaf7807b44c29ac29f51438b2c8cd9270
d43e1ec775f194c2dd6d45007c50ed999571bd5d
/Codeforces/353D2/B/b.cpp
c13871c7e8021d685285642256780aa2b121561e
[]
no_license
marcoskwkm/code
842fd498ec625b25f361b435f0bca843b8d81967
636866a7ee28f9f24da62c5dcf93dc1bce7a496e
refs/heads/master
2022-10-28T16:40:50.710771
2022-09-24T20:10:59
2022-09-24T20:10:59
57,255,944
3
0
null
null
null
null
UTF-8
C++
false
false
630
cpp
#include <bits/stdc++.h> using namespace std; #define debug(args...) fprintf(stderr,args) typedef long long lint; typedef pair<int,int> pii; typedef pair<lint,lint> pll; const int INF = 0x3f3f3f3f; const lint LINF = 0x3f3f3f3f3f3f3f3fll; int main() { int n, a, b, c, d; scanf("%d%d%d%d%d", &n, &a, &b, &c, &d); lint ans = 0; for (int i = 1; i <= n; i++) { int s = i + a + b; if (s - a - c < 1 || s - a - c > n) continue; if (s - c - d < 1 || s - c - d > n) continue; if (s - b - d < 1 || s - b - d > n) continue; ans += n; } cout << ans << endl; return 0; }
[ "marcoskwkm@gmail.com" ]
marcoskwkm@gmail.com
668d802b2c292f0b93bbb404f3d9b21a77e2cdbd
bd2c611c53160a5a0c39dd2dcf55100083afae4c
/Frogger/Frog.h
69e57a3f1d63342ad5e2a70b6247ef81836b2c79
[]
no_license
darienmiller88/Frogger
ac469804dca296916ecde8b2b34acc71acbc5aea
6333df266103421320d9f8628b38b0212882a476
refs/heads/master
2020-10-02T06:06:59.676417
2020-05-02T16:22:31
2020-05-02T16:22:31
227,718,245
0
0
null
null
null
null
UTF-8
C++
false
false
727
h
#pragma once #include "Entity.h" class Frog : public Entity{ public: Frog(const sf::Vector2f &bodySize, const sf::Vector2f &initialPosition, const sf::Color &color); void moveEntity(const sf::Vector2f &windowSize, const sf::Event &e) override; int getRemainingLives() const; //set the position of the point from where the frog will respawn when it dies or reaches the top of the screen. void setRespawnPoint(const sf::Vector2f &respawn); //change the position of the frog to that of the respawn point. void setFrogToRespawn(); void decreaseLives(); bool attachTo(const Entity &entityToAttachTo, const sf::Vector2u &windowSize); private: int lives; sf::Vector2f respawnPoint; };
[ "noreply@github.com" ]
noreply@github.com