blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
247
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
4
111
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
58
visit_date
timestamp[ns]date
2015-07-25 18:16:41
2023-09-06 10:45:08
revision_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
committer_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
github_id
int64
3.89k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
25 values
gha_event_created_at
timestamp[ns]date
2012-06-07 00:51:45
2023-09-14 21:58:52
gha_created_at
timestamp[ns]date
2008-03-27 23:40:48
2023-08-24 19:49:39
gha_language
stringclasses
159 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
10.5M
extension
stringclasses
111 values
filename
stringlengths
1
195
text
stringlengths
7
10.5M
ed26c68b071eee0e4977e59757a266035d768e0a
62e82246e7dd5e4148f9b10f4c0823124d044615
/Draggable.h
7d2299dcff6bcd9953432e1187364e648fe88a86
[]
no_license
ben-humphries/LD46
444abed5cbd7f2737c9c8989f1be96148ef47300
048281d95e0beb5fed59ddef7b009784a708a3d4
refs/heads/master
2022-04-18T16:43:38.237606
2020-04-20T01:14:40
2020-04-20T01:14:40
257,138,146
0
1
null
null
null
null
UTF-8
C++
false
false
108
h
Draggable.h
#pragma once class Draggable { public: static bool firefighterPickedUp; bool thisFirefighterPickedUp; };
81c8bf4467e62bfcfbeadee9d030727b2cfc1e1d
bd2f2c2b238053f8d722fe286ce0f16db8128b8a
/static/static_func.cc
82f9b06840616525ea29ee2921bfa17c607bbec9
[]
no_license
syuhung/linuxCommand
5c85e264ab04133ab35bec3f1296172ab41512cc
e7b5a99505e2430d72032dd2e65e45c1b871481c
refs/heads/master
2020-12-11T04:50:38.913778
2020-08-14T11:00:50
2020-08-14T11:00:50
233,780,878
0
0
null
null
null
null
UTF-8
C++
false
false
238
cc
static_func.cc
#include <iostream> #include <string> using namespace std; void demo() { static int count = 0; cout << "count is: " << count << endl; count++; } int main(int argc, char *argv[]) { for (int i = 0; i < 5; ++i) demo(); return 0; }
33914fa4aada93048be21e1c32315ce443b73435
717ee27800a23102fefce10b72f6e65017bd3c03
/lab1/ProjectTry/ProjectTry/Source.cpp
46bb7be6c86c340c6289a8c396477824db9c746c
[]
no_license
ZakharPustovgarov/SP2018
8982a13f3527562fe8f51a6c566355459bd6e685
1dbb036cc4e41e541302de6a00728f417d31ab93
refs/heads/master
2020-03-28T17:38:24.800448
2019-01-14T16:48:30
2019-01-14T16:48:30
148,804,992
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
14,096
cpp
Source.cpp
#define _CRT_SECURE_NO_WARNINGS #include <stdlib.h> #include <windows.h> #include <cstdio> #include <stdio.h> #include <iostream> #include <cstdlib> #include <conio.h> #include <process.h> #include <string> #include <sstream> #include <Winbase.h.> #include <shellapi.h> #include <fstream> const char *srcpath = "C:\\ServerProgVault\\"; const char *metapath = "C:\\ServerProgMetas\\"; const char *pipename = "\\\\.\\pipe\\New_pipe"; using namespace std; struct Metadata { char dnum[100]; char aname[100]; char dfname[200]; }; DWORD WINAPI InstanceThread(LPVOID lpvParam) // This routine is a thread processing function to read from and reply to a client // via the open pipe connection passed from the main loop. Note this allows // the main loop to continue executing, potentially creating more threads of // of this procedure to run concurrently, depending on the number of incoming // client connections. { DWORD cbWritten = 0; DWORD cbRead = 0; BOOL fSuccess = FALSE; HANDLE hPipe = NULL; WIN32_FIND_DATA fdat; HANDLE hdata; Metadata mdata; *mdata.aname = { 0 }; *mdata.dfname = { 0 }; *mdata.dnum = { 0 }; CreateDirectoryA(srcpath, NULL); CreateDirectoryA(metapath, NULL); setlocale(LC_ALL, "Russian"); char user; int usr; char str1[1000] = { 0 }; char str2[1000] = { 0 }; char buff[1000] = { 0 }; char buff1[1000] = { 0 }; char fext[10] = { 0 }; char * buffer = 0; long size = 0; ofstream fout; ifstream fin; bool ch = true; // Do some extra error checking since the app will keep running even if this // thread fails. if (lpvParam == NULL) { printf("\nERROR - Pipe Server Failure:\n"); printf(" InstanceThread got an unexpected NULL value in lpvParam.\n"); printf(" InstanceThread exitting.\n"); return -1; } // Print verbose messages. In production code, this should be for debugging only. printf("InstanceThread created, receiving and processing messages.\n"); // The thread's parameter is a handle to a pipe object instance. hPipe = (HANDLE)lpvParam; // Loop until done reading ///////////////-w -i 5 -a "C:\ServerProgVault\asdfasdf.txt" notepad.exe do { fSuccess = ReadFile(hPipe, &user, 512, &cbRead, NULL); if (!fSuccess) { cout << "0. InstanceThread ReadFile failed, GLE=" << GetLastError() << "\n"; break; } else { cout << "0. ReadDone!\n"; } try { usr = atoi(&user); switch (usr) { case 1: ch = true; fSuccess = ReadFile(hPipe, str2, 1000, &cbRead, NULL); if (!fSuccess) { cout << "1-1.InstanceThread ReadFile failed, GLE=" << GetLastError() << "\n"; break; } else { cout << "1-1. ReadDone!\n"; } fSuccess = ReadFile(hPipe, fext, 10, &cbRead, NULL); if (!fSuccess) { cout << "1-extension.InstanceThread ReadFile failed, GLE=" << GetLastError() << "\n"; break; } else { cout << "1-extension. ReadDone!\n"; } strcat(buff1, srcpath); strcat(buff1, "*.*"); strcat(buff, str2); strcat(buff, fext); hdata = FindFirstFileA(buff1, &fdat); if (hdata != INVALID_HANDLE_VALUE) { while (FindNextFile(hdata, &fdat) != 0) { cout << "\n" << fdat.cFileName << " ? " << buff << "\n"; if (strcmp(fdat.cFileName, buff) == 0) { cout << "Equal..\n"; ch = false; break; } else { cout << "Not equal!\n"; } } } FindClose(hdata); *buff1 = { 0 }; *buff = { 0 }; WriteFile(hPipe, &ch, 1, &cbWritten, NULL); if (ch == false) { cout << "Bad things happens\n"; *str2 = { 0 }; *fext = { 0 }; size = 0; break; } strcat(buff, srcpath); strcat(buff, str2); strcat(buff, fext); fSuccess = ReadFile(hPipe, &size, 4, &cbRead, NULL); if (!fSuccess) { cout << "1-2. InstanceThread ReadFile failed, GLE=" << GetLastError() << "\n"; break; } else { cout << "1-2. ReadDone!\n"; } cout << size << "\n"; buffer = (char*)malloc(sizeof(char) * size); // выделить память для хранения содержимого файла if (buffer == NULL) { fputs("Ошибка памяти", stderr); exit(2); } fSuccess = ReadFile(hPipe, buffer, (sizeof(char) * size), &cbRead, NULL); if (!fSuccess) { cout << "1-3. InstanceThread ReadFile failed, GLE=" << GetLastError() << "\n"; break; } else { cout << "1-3. ReadDone!\n"; } fSuccess = ReadFile(hPipe, &mdata, sizeof(mdata), &cbRead, NULL); if (!fSuccess) { cout << "1-4. InstanceThread ReadFile failed, GLE=" << GetLastError() << "\n"; break; } else { cout << "1-4. ReadDone!\n"; } fout.open(buff, ios_base::out | ios_base::binary); if (fout.is_open() != 1) cout << "Error: file isn't open\n"; fout.write(buffer, size); fout.close(); strcat(buff1, metapath); strcat(buff1, "_"); strcat(buff1, str2); strcat(buff1, fext); strcat(buff1, ".txt"); strcat(mdata.aname, "\n"); strcat(mdata.dfname, "\n"); strcat(mdata.dnum, "\n"); fout.open(buff1, ios_base::out ); if (fout.is_open() != 1) cout << "Error: file isn't open"; fout << mdata.dnum; fout << mdata.aname; fout << mdata.dfname; fout.close(); *buff = { 0 }; *buff1 = { 0 }; *str2 = { 0 }; *fext = { 0 }; size = 0; *mdata.aname = { 0 }; *mdata.dfname = { 0 }; *mdata.dnum = { 0 }; break; case 2: ch = true; fSuccess = ReadFile(hPipe, str2, 1000, &cbRead, NULL); if (!fSuccess) { cout << "1-1.InstanceThread ReadFile failed, GLE=" << GetLastError() << "\n"; break; } else { cout << "1-1. ReadDone!\n"; } fSuccess = ReadFile(hPipe, fext, 10, &cbRead, NULL); if (!fSuccess) { cout << "1-extension.InstanceThread ReadFile failed, GLE=" << GetLastError() << "\n"; break; } else { cout << "1-extension. ReadDone!\n"; } strcat(buff1, srcpath); strcat(buff1, "*.*"); strcat(buff, str2); strcat(buff, fext); hdata = FindFirstFileA(buff1, &fdat); if (hdata != INVALID_HANDLE_VALUE) { while (FindNextFile(hdata, &fdat) != 0) { cout << "\n" << fdat.cFileName << " ? " << buff << "\n"; if (strcmp(fdat.cFileName, buff) == 0) { cout << "Equal..\n"; ch = false; break; } else { cout << "Not equal!\n"; } } } FindClose(hdata); *buff1 = { 0 }; *buff = { 0 }; WriteFile(hPipe, &ch, 1, &cbWritten, NULL); if (ch == true) { cout << "Bad things happens\n"; *str2 = { 0 }; *fext = { 0 }; size = 0; break; } strcat(buff, srcpath); strcat(buff, str2); strcat(buff, fext); fSuccess = ReadFile(hPipe, &size, 4, &cbRead, NULL); if (!fSuccess) { cout << "1-2. InstanceThread ReadFile failed, GLE=" << GetLastError() << "\n"; break; } else { cout << "1-2. ReadDone!\n"; } cout << size << "\n"; buffer = (char*)malloc(sizeof(char) * size); // выделить память для хранения содержимого файла if (buffer == NULL) { fputs("Ошибка памяти", stderr); exit(2); } fSuccess = ReadFile(hPipe, buffer, (sizeof(char) * size), &cbRead, NULL); if (!fSuccess) { cout << "1-3. InstanceThread ReadFile failed, GLE=" << GetLastError() << "\n"; break; } else { cout << "1-3. ReadDone!\n"; } fout.open(buff, ios_base::out | ios_base::binary); if (fout.is_open() != 1) cout << "Error: file isn't open\n"; fout.write(buffer, size); fout.close(); *buff = { 0 }; *buff1 = { 0 }; *str2 = { 0 }; *fext = { 0 }; size = 0; ch = true; break; case 3: ch = true; fSuccess = ReadFile(hPipe, str2, 1000, &cbRead, NULL); if (!fSuccess) { cout << "1-1.InstanceThread ReadFile failed, GLE=" << GetLastError() << "\n"; break; } else { cout << "1-1. ReadDone!\n"; } strcat(buff1, srcpath); strcat(buff1, "*.*"); hdata = FindFirstFileA(buff1, &fdat); if (hdata != INVALID_HANDLE_VALUE) { while (FindNextFile(hdata, &fdat) != 0) { cout << "\n" << fdat.cFileName << " ? " << str2 << "\n"; if (strcmp(fdat.cFileName, str2) == 0) { cout << "Equal..\n"; ch = false; break; } else { cout << "Not equal!\n"; } } } FindClose(hdata); *buff1 = { 0 }; WriteFile(hPipe, &ch, 1, &cbWritten, NULL); if (ch == true) { cout << "Bad things happens\n"; *str2 = { 0 }; *fext = { 0 }; size = 0; break; } fSuccess = ReadFile(hPipe, &mdata, sizeof(mdata), &cbRead, NULL); if (!fSuccess) { cout << "1-4. InstanceThread ReadFile failed, GLE=" << GetLastError() << "\n"; break; } else { cout << "1-4. ReadDone!\n"; } strcat(buff1, metapath); strcat(buff1, "_"); strcat(buff1, str2); strcat(buff1, ".txt"); strcat(mdata.aname, "\n"); strcat(mdata.dfname, "\n"); strcat(mdata.dnum, "\n"); fout.open(buff1, ios_base::out); if (fout.is_open() != 1) cout << "Error: file isn't open"; fout << mdata.dnum; fout << mdata.aname; fout << mdata.dfname; fout.close(); *buff1 = { 0 }; *str2 = { 0 }; *mdata.aname = { 0 }; *mdata.dfname = { 0 }; *mdata.dnum = { 0 }; ch = true; break; case 4: ch = true; fSuccess = ReadFile(hPipe, str2, 1000, &cbRead, NULL); if (!fSuccess) { cout << "1-1.InstanceThread ReadFile failed, GLE=" << GetLastError() << "\n"; break; } else { cout << "1-1. ReadDone!\n"; } strcat(buff1, srcpath); strcat(buff1, "*.*"); hdata = FindFirstFileA(buff1, &fdat); if (hdata != INVALID_HANDLE_VALUE) { while (FindNextFile(hdata, &fdat) != 0) { cout << "\n" << fdat.cFileName << " ? " << str2 << "\n"; if (strcmp(fdat.cFileName, str2) == 0) { cout << "Equal..\n"; ch = false; break; } else { cout << "Not equal!\n"; } } } FindClose(hdata); *buff1 = { 0 }; WriteFile(hPipe, &ch, 1, &cbWritten, NULL); if (ch == true) { cout << "Bad things happens\n"; *str2 = { 0 }; *fext = { 0 }; size = 0; break; } // определяем размер файла strcat(buff1, srcpath); strcat(buff1, str2); fin.open(buff1, ios_base::binary | ios_base::ate); if (fin.is_open() != 1) cout << "Error: file isn't open"; size = fin.tellg(); fin.close(); buffer = (char*)malloc(sizeof(char) * size); if (buffer == NULL) { fputs("Ошибка памяти", stderr); exit(2); } fin.open(buff1, ios_base::binary | ios_base::in); if (fin.is_open() != 1) cout << "Error: file isn't open"; fin.read(buffer, size); fin.close(); //содержимое файла теперь находится в буфере cout << size << "\n"; fSuccess = WriteFile(hPipe, &size, 4, &cbWritten, NULL); if (!fSuccess) { cout << "InstanceThread WriteFile failed, GLE=" << GetLastError() << "\n"; break; } fSuccess = WriteFile(hPipe, buffer, (sizeof(char) * size), &cbWritten, NULL); if (!fSuccess) { cout << "InstanceThread WriteFile failed, GLE=" << GetLastError() << "\n"; break; } *str1 = { 0 }; *str2 = { 0 }; *fext = { 0 }; *buffer = { 0 }; *buff1 = { 0 }; size = 0; ch = true; break; case 5: strcat(buff1, srcpath); strcat(buff1, "*.*"); hdata = FindFirstFileA(buff1, &fdat); cout << buff1 << "\n"; cout << fdat.cFileName << "\n"; if (hdata != INVALID_HANDLE_VALUE) { while (FindNextFile(hdata, &fdat) != 0) { cout << fdat.cFileName << "\n"; fSuccess = WriteFile(hPipe, &fdat.cFileName, 1000, &cbWritten, NULL); if (!fSuccess) { cout << "5-1. InstanceThread WriteFile failed, GLE=" << GetLastError() << "\n"; break; } cout << "5-1. Write done!\n"; } } FindClose(hdata); fSuccess = WriteFile(hPipe, "End of list\n", 1000, &cbWritten, NULL); if (!fSuccess) { cout << "5-2. InstanceThread WriteFile failed, GLE=" << GetLastError() << "\n"; break; } *buff1 = { 0 }; break; } } catch (char er) { cout << "Ошибка:" << er << "\n"; } } while (usr != 0); // Flush the pipe to allow the client to read the pipe's contents // before disconnecting. Then disconnect the pipe, and close the // handle to this pipe instance. FlushFileBuffers(hPipe); DisconnectNamedPipe(hPipe); CloseHandle(hPipe); printf("InstanceThread exitting.\n"); return 1; } int main(int argc, char *argv[]) { DWORD dwThreadId = 0; for (;;) { HANDLE pipe = CreateNamedPipeA(pipename, PIPE_ACCESS_DUPLEX, PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT, PIPE_UNLIMITED_INSTANCES, 512, 512, 5000, NULL); if (pipe == INVALID_HANDLE_VALUE) { printf(TEXT("CreateNamedPipe failed, GLE=%d.\n"), GetLastError()); return -1; } printf("Wait client\n"); if (ConnectNamedPipe(pipe, NULL)) { printf("Client connected\n"); HANDLE thread; thread = CreateThread( NULL, // no security attribute 0, // default stack size InstanceThread, // thread proc (LPVOID)pipe, // thread parameter 0, // not suspended &dwThreadId); // returns thread ID if (thread == NULL) { printf(TEXT("CreateThread failed, GLE=%d.\n"), GetLastError()); return -1; } else CloseHandle(thread); } else // The client could not connect, so close the pipe. CloseHandle(pipe); } return 0; }
088ea57a984bc17afbd6a1bb1c1fc80ad9870cae
41730ec8bf12f48e1b13bfbabb3b73b003571160
/AULA - 6/OperacoesDeConjuntos/OperacoesDeConjuntos/Controle.cpp
ab6433ed7850df8c6dab975b92a9e394e4e0f429
[]
no_license
evertonferreirasrs/Exercicios-em-CPP
1b1a819f553bb604e9ae13612330d3be64f0aaf7
2441cdb7f37e542ffef168efd2336c449effb7b8
refs/heads/master
2021-06-30T17:47:15.731437
2017-09-20T23:34:39
2017-09-20T23:34:39
104,277,904
0
0
null
null
null
null
UTF-8
C++
false
false
1,011
cpp
Controle.cpp
#include "Controle.h" Controle::Controle() { } Controle::~Controle() { } void Controle::controlarExecucao(void) { InterfaceUsuario iu; ManipulacaoDeConjuntos mdc; int CjA1[5] = { 0, 0, 0, 0, 0 }, CjA2[5] = { 0, 0, 0, 0, 0 }; int CjSolucaoA[10] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; do{ iu.mostrarMenu1(); //nesta linha vem a entrada de dados do teclado iu.getCjsInt(CjA1, CjA2); mdc.setCjA(CjA1, CjA2); switch (iu.getOpcao1()){ case 1: iu.mostrarMenu2(); switch (iu.getOpcao2()) { case 1://esta contido mdc.calcularIntersecaoA(); break; case 2://Uniao mdc.calcularUniaoA(); break; case 3://intersecao mdc.calcularIntersecaoA(); break; case 4://pertence mdc.calcularIntersecaoA(); break; case 5://Subtracao A mdc.calcularSubtracaoA(); break; } mdc.getSolucaoA(CjSolucaoA); iu.mostrarCjSolucao(CjSolucaoA); break; case 2: iu.mostrarMenu2(); break; } } while (iu.getOpcao1() != 0); }
7ad4df472d5b2c156ef6c1108cedda74362f82bb
cb7da5de0c4e94249eb71d427122f1d95446d99e
/ch16/ex16_4/main.cpp
cd0ec3803989525f9f8ca58c4c62e6147847f07e
[]
no_license
loveleon/My-Cpp-Primer
a9533077552066d87f69848bfdff6514ae9d030d
521d884d14f4fd6b3686efc471b6605bc3ce8a17
refs/heads/master
2021-01-15T16:41:42.278812
2018-10-22T06:01:48
2018-10-22T06:01:48
99,716,392
2
1
null
2017-08-09T17:36:27
2017-08-08T16:58:57
C++
UTF-8
C++
false
false
604
cpp
main.cpp
#include "find.h" #include <vector> #include <list> #include <string> #include <iostream> using std::vector; using std::list; using std::string; using std::cout;using std::endl; int main(){ vector<int> vec = {1,2,3,4,5,6}; list<string> lst = {"str","cxh","hello","world","ni"}; auto itVec = ex16::find(vec.begin(),vec.end(),4); cout << std::boolalpha << (itVec != vec.end()) << " value: " <<*itVec << endl; string str("cxh"); auto is_itLst_found = (lst.cend() != ex16::find(lst.cbegin(),lst.cend(),"cxh")); cout << std::boolalpha << is_itLst_found << endl; return 0; }
272eb9139f7ffaa53554d4344f2d86c605383261
4689a9333948eb4f6ac5977820d98d5ea5cf03bd
/src/elliptic/amgSolver/parAlmond/level.hpp
fc72160759719b8d8580dfa60195fd0f8ae2fa22
[ "BSD-3-Clause" ]
permissive
spatel81/nekRS
95315d455687c781f268a290353079a9c5aadb3a
8ee9c381f86f5f70867d942616e585ee726a8ca1
refs/heads/master
2023-05-24T03:31:00.650283
2022-05-13T09:31:06
2022-05-13T09:31:06
280,201,246
0
0
NOASSERTION
2020-07-16T16:18:55
2020-07-16T16:18:54
null
UTF-8
C++
false
false
2,805
hpp
level.hpp
/* The MIT License (MIT) Copyright (c) 2017 Tim Warburton, Noel Chalmers, Jesse Chan, Ali Karakus, Rajesh Gandham 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 PARALMOND_LEVEL_HPP #define PARALMOND_LEVEL_HPP namespace parAlmond { class multigridLevel { public: dlong Nrows, Ncols; dfloat *x=NULL; dfloat *rhs=NULL; dfloat *res=NULL; occa::memory o_x, o_rhs, o_res; //extra storage for kcycle dfloat *ck=NULL; dfloat *vk=NULL; dfloat *wk=NULL; occa::memory o_ck, o_vk, o_wk; //switch for weighted inner products bool weighted; dfloat *weight=NULL; occa::memory o_weight; KrylovType ktype; SmoothType stype; MPI_Comm comm; multigridLevel(dlong N, dlong M, KrylovType Ktype, MPI_Comm comm); ~multigridLevel(); virtual void Ax(dfloat *x, dfloat *Ax)=0; virtual void Ax(occa::memory o_x, occa::memory o_Ax)=0; virtual void smooth(dfloat *rhs, dfloat *x, bool x_is_zero)=0; virtual void smooth(occa::memory o_rhs, occa::memory o_x, bool x_is_zero)=0; virtual void residual(dfloat *rhs, dfloat *x, dfloat *res)=0; virtual void residual(occa::memory o_rhs, occa::memory o_x, occa::memory o_res)=0; virtual void coarsen(dfloat *x, dfloat *Cx)=0; virtual void coarsen(occa::memory o_x, occa::memory o_Cx)=0; virtual void prolongate(dfloat *x, dfloat *Px)=0; virtual void prolongate(occa::memory o_x, occa::memory o_Px)=0; virtual void Report()=0; void kcycleOp1(dfloat *alpha1, dfloat *rho1, dfloat *norm_rhs, dfloat *norm_rhstilde); void kcycleOp2(const dfloat alpha1, const dfloat rho1); void device_kcycleOp1(dfloat *alpha1, dfloat *rho1, dfloat *norm_rhs, dfloat *norm_rhstilde); void device_kcycleOp2(const dfloat alpha1, const dfloat rho1); }; } #endif
9303d626f20805590d8ff5b86385536fe85ac8ad
5926ff763a5055c535462b5a3479946ce77aa0a9
/Answersheet/314ExtendToPalindromes.cpp
3d868ad4689829c921f7e7d75cd2445af838ddab
[]
no_license
wuzijian4/CS3391_Answer
765886b237415ae1c6abe22ea0ee83ac50f4c649
8ccb57501e00ed7e55da21f4fb6dc2083eb47069
refs/heads/master
2022-08-03T08:47:03.012167
2020-05-28T05:50:04
2020-05-28T05:50:04
267,270,885
0
0
null
null
null
null
GB18030
C++
false
false
988
cpp
314ExtendToPalindromes.cpp
#include <iostream> #include <string> #include <algorithm> #include <memory.h> using namespace std; string in; string out; int nextPos[100005]; void getNext() { //构建next list 当出现不匹配的情况时, 指针的走向 memset(nextPos, 0, sizeof(nextPos)); nextPos[0] = -1; int i = 0; int j = -1; while (i < out.length() - 1) { if (j == -1 || out[i] == out[j]) { i++; j++; nextPos[i] = out[i] == out[j] ? nextPos[j] : j; } else j = nextPos[j]; } } int kmp() { int i = 0; int j = 0; while ((i < (int)in.length()) && (j < (int)out.length())) { if (j == -1 || in[i] == out[j]) { i++; j++; } else { j = nextPos[j]; } } return j; } int main() { while (getline(cin, in)) { out.assign(in.begin(), in.end()); reverse(out.begin(), out.end()); getNext(); int j = kmp(); string right = out.substr(j, out.length()); in += right; cout << in << endl; } return 0; }
2719b71fd671f458d6374f4897541b2b7e1e137a
e8717f54486d13ea334945386714b825ab125de4
/CF/1303B.cpp
a5a2fa62e202c054a301ae89b6ee56b488d9ac96
[]
no_license
prajwal1721/Competitve-Programming
a6a6de9c8a6c8e9fd3bf382166a53aa49d562551
39e5049e16044830396d6ff504f739e71dbec3bb
refs/heads/master
2023-02-10T05:26:24.143539
2020-12-21T03:45:59
2020-12-21T03:45:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
252
cpp
1303B.cpp
#include<iostream> #include<cmath> using namespace std; typedef long long ll; int main() { ll q;cin>>q; while (q--) { ll len,g,b ;cin>>len>>g>>b; cout<<(len+1)/2+max(len-(len+1)/2,(len-1)/(2*g)*b)<<"\n"; } }
59673c8bbdc6ce2bb862e821d388776e24c693fe
eb01414ffd9bbdf8e3a7bea134d767b434c5eb01
/3b/3b/main.cpp
ed626ee8c6343753287d87098b6027bc21d2fa4e
[]
no_license
schoonod/165-Intro-to-CS
71b0b3a9f7fef94dece6bc0f1a0e08a7eac6e59a
d93f373ca82c02524e08253c78e5e7f37f081e6c
refs/heads/master
2021-01-21T13:21:20.920680
2016-05-29T21:01:13
2016-05-29T21:01:13
50,952,609
0
0
null
null
null
null
UTF-8
C++
false
false
402
cpp
main.cpp
// #include <cmath> #include <iostream> #include "LineSegment.hpp" int main() { Point p1 (5.0, 10.0); Point p2 (3.0, 11.0); Point p3; std::cout << p3.getXCoord() << std::endl; LineSegment line1(p1,p2); std::cout << p1.distanceTo(p2) << std::endl; std::cout << line1.length() << std::endl; std::cout << line1.slope() << std::endl; return 0; }
cad12c0887fe8859ede5ccec2c36a26b2201e17f
2fec4da6a88b3a4cfcbe48f18b640d91668e9cfe
/hiSpeed/HiSpeed/OpenFeint/api/internal/Systems/AuroraLib/Kernel/IO/OFDictionaryWriter.h
dbfaa490ef23aac49fe3ae9210ce9e8ee3673f45
[]
no_license
pmark/Seanote
ff3efffe3ddfcff18ecd2e911c7b96df4834c577
acfbe49ffbeddd6c7635f2793307e492fd75b166
refs/heads/master
2020-05-21T01:02:38.306056
2009-09-21T02:06:52
2009-09-21T02:06:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,009
h
OFDictionaryWriter.h
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// /// Copyright (c) 2009 Aurora Feint Inc. /// /// This library is free software; you can redistribute it and/or /// modify it under the terms of the GNU Lesser General Public /// License as published by the Free Software Foundation; either /// /// version 3 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 /// Lesser General Public License for more details. /// /// /// You should have received a copy of the GNU Lesser General Public /// License along with this library; if not, write to the Free Software /// /// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA /// //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma once #include "OFOutputSerializer.h" #include <cstdio> class OFDictionaryWriter : public OFOutputSerializer { OFDeclareRTTI; public: OFDictionaryWriter(); ~OFDictionaryWriter(); bool supportsKeys() const; NSDictionary* getDictionary() const; private: void nviIo(OFISerializerKey* keyName, bool& value); void nviIo(OFISerializerKey* keyName, int& value); void nviIo(OFISerializerKey* keyName, unsigned int& value); void nviIo(OFISerializerKey* keyName, int64_t& value); void nviIo(OFISerializerKey* keyName, float& value); void nviIo(OFISerializerKey* keyName, double& value); void nviIo(OFISerializerKey* keyName, std::string& value); void nviIo(OFISerializerKey* keyName, OFRetainedPtr<NSString>& value); const OFRTTI* beginDecodeType(); void endDecodeType(); void beginEncodeType(const OFRTTI* typeToEncode); void endEncodeType(); OFRetainedPtr<NSMutableDictionary> mDictionary; };
16b4f6960344132334a0e7e6459cbd2f63edc85f
7a5e76e7b629a085c1c8fbda46896d5dcc5f7993
/CrossApp/platform/android/CAScanQRcode.cpp
0a30ce0c929597ed76de3b0de602366d6d262d80
[ "MIT" ]
permissive
AojiaoZero/CrossApp
12d2f5a11c9feddc2bb0d94db28b5c835c6e730f
1f5375e061bf69841eb19728598f5ae3f508d620
refs/heads/master
2021-11-04T23:30:43.750169
2021-05-15T03:19:17
2021-05-15T03:19:17
22,117,240
0
0
null
null
null
null
UTF-8
C++
false
false
1,364
cpp
CAScanQRcode.cpp
// // CAScanQRcode.cpp // CrossApp // // Created by mac on 2021/3/12. // Copyright © 2021 cocos2d-x. All rights reserved. // #include "platform/CAScanQRcode.h" #include "basics/CAApplication.h" #include "platform/android/jni/JniHelper.h" #include <jni.h> static std::function<void(const std::string&)> s_ResultScanning_callback = nullptr; extern "C" { // 扫描二维码结果 void Java_org_CrossApp_lib_CameraView_resultScanning(JNIEnv *env, jobject thiz, jstring value) { const char* str = env->GetStringUTFChars(value, NULL); if (s_ResultScanning_callback) s_ResultScanning_callback(str); s_ResultScanning_callback = nullptr; env->ReleaseStringUTFChars(value, str); } // 摄像头关闭 void Java_org_CrossApp_lib_CameraView_cameraClosed(JNIEnv *env, jobject thiz) { CrossApp::CAApplication::getApplication()->resume(); } } NS_CC_BEGIN void CAScanQRcode::showScanQRcode(const std::function<void(const std::string&)>& callback) { JniMethodInfo info; bool ret = JniHelper::getStaticMethodInfo(info, "org/CrossApp/lib/CrossAppActivity", "showQRCodeView", "()V"); if (ret) { info.env->CallStaticVoidMethod(info.classID, info.methodID); s_ResultScanning_callback = callback; } CrossApp::CAApplication::getApplication()->pause(); } NS_CC_END
97da4d374251100a1b907d35f9bb580cc6470fe7
503510d6e899af409e75b4ae1f3fb6c964f11448
/src/AnimationEditor/DataObjects/AAnimation.h
e7e049586348aba39abd3ba39b095a5ad4a9f77b
[ "MIT" ]
permissive
karelz/WarPlusPlus
5d0002066f705f9ae1952ed03a26d0e94f73cbdf
9750f0d63bcddd91f253cc9618da3f8b1dda6c9c
refs/heads/master
2020-06-05T05:31:41.208218
2019-09-16T14:00:26
2019-09-16T14:00:26
192,327,562
4
4
MIT
2019-09-16T14:00:27
2019-06-17T10:44:55
C++
UTF-8
C++
false
false
5,489
h
AAnimation.h
/*********************************************************** * * Project: Strategy game * Part: Animation editor - Data objects * Author: Vit Karas * * Description: Animation object class * ***********************************************************/ #ifndef _ANIMATIONEDITOR_AANIMATION_H_ #define _ANIMATIONEDITOR_AANIMATION_H_ #include "Structures.h" #include "AFrame.h" class CAAnimation : public CObject { // RTCI for our objects DECLARE_DYNAMIC ( CAAnimation ); public: // Construction // Constructor CAAnimation (); // Destructor virtual ~CAAnimation (); // Debug functions #ifdef _DEBUG // Asserts validity of the object's data virtual void AssertValid () const; // Dumps object's data virtual void Dump ( CDumpContext & dc ) const; #endif // Creation // Creates empty animation void Create (); // Creates the frame from given archive file void Create ( CArchiveFile cFile ); // Deletes the frame virtual void Delete (); // Operations // Saves the animation to given file void Save ( CArchiveFile cFile ); // Inserts new frame from given file // This will insert the frame before specified index // If the index is behind the end of animation, the frame will be inserted to the end CAFrame * InsertFrame ( CArchiveFile cFile, DWORD dwBeforeIndex ); // Removes and deletes the frame on specified index from the animation void DeleteFrame ( DWORD dwIndex ); // Set frame X offset void SetFrameXOffset ( DWORD dwIndex, int nXOffset ) { ASSERT_VALID ( this ); ASSERT ( dwIndex < m_dwFrameCount ); FindFrame ( dwIndex )->SetXOffset ( nXOffset ); SetModified (); } // Set frame Y offset void SetFrameYOffset ( DWORD dwIndex, int nYOffset ) { ASSERT_VALID ( this ); ASSERT ( dwIndex < m_dwFrameCount ); FindFrame ( dwIndex )->SetYOffset ( nYOffset ); SetModified (); } // Set frame delay void SetFrameDelay ( DWORD dwIndex, DWORD dwDelay ) { ASSERT_VALID ( this ); ASSERT ( dwIndex < m_dwFrameCount ); FindFrame ( dwIndex )->SetFrameDelay ( dwDelay ); SetModified (); } // Crop the frame void CropFrame ( DWORD dwIndex, BYTE nAlphaTolerance ) { ASSERT_VALID ( this ); ASSERT ( dwIndex < m_dwFrameCount ); FindFrame ( dwIndex )->Crop ( nAlphaTolerance ); } // Moves given frame before the previous frame void MoveFrameLeft ( DWORD dwIndex ); // Moves given frame after the next frame void MoveFrameRight ( DWORD dwIndex ); // Get/Set functions // Returns number of frames in the animation DWORD GetFrameCount () const { ASSERT_VALID ( this ); return m_dwFrameCount; } // Returns default frame delay for the animation // 0 - statci image DWORD GetDefaultFrameDelay () const { ASSERT_VALID ( this ); return m_dwDefaultFrameDelay; } // Sets default frame delay for the animation // 0 - static image void SetDefaultFrameDelay ( DWORD dwDefaultFrameDelay ) { ASSERT_VALID ( this ); m_dwDefaultFrameDelay = dwDefaultFrameDelay; SetModified (); } // Returns the loop flag bool GetLoop () const { ASSERT_VALID ( this ); return m_bLoop; } // Sets the loop flag void SetLoop ( bool bLoop ) { ASSERT_VALID ( this ); m_bLoop = bLoop; SetModified (); } // Returns destination color DWORD GetDestinationColor () const { ASSERT_VALID ( this ); return m_dwDestinationColor; } // Sets new destination color void SetDestinationColor ( DWORD dwDestinationColor ); // Returns pointer to the coloring structure // You should call ReleaseColoring when you end working with it SColoring * GetColoring () { ASSERT_VALID ( this ); return &m_sColoring; } // This recomputes whole animation with new coloring void ReleaseColoring (); // Returns true if the object was modified from the last save bool GetModified () const { ASSERT_VALID ( this ); return m_bModified; } // Sets the modification flag void SetModified ( bool bModified = true ) { ASSERT_VALID ( this ); m_bModified = bModified; } // Returns X graphical offset of the whole animation int GetXOffset () const { ASSERT_VALID ( this ); return m_nXOffset; } // Sets new X graphical offset of the whole animation void SetXOffset ( int nXOffset ) { ASSERT_VALID ( this ); m_nXOffset = nXOffset; SetModified (); } // Returns Y graphical offset of the whole animation int GetYOffset () const { ASSERT_VALID ( this ); return m_nYOffset; } // Sets new Y graphical offset of the whole animation void SetYOffset ( int nYOffset ) { ASSERT_VALID ( this ); m_nYOffset = nYOffset; SetModified (); } // Returns frame for given index const CAFrame * GetFrame ( DWORD dwIndex ) const { ASSERT_VALID ( this ); return FindFrame ( dwIndex ); } // Returns true if someting is modified (animation or any frame) bool IsModified () const; private: // Data members // Number of frames in the animation DWORD m_dwFrameCount; // Default frame delay DWORD m_dwDefaultFrameDelay; // true if the animation is about to loop bool m_bLoop; // List of frames in the animation CAFrame * m_pFrames; // Modification flag bool m_bModified; // The X graphical offset of the whole animation int m_nXOffset; // The Y graphical offset of the whole animation int m_nYOffset; // Coloring structure for the animation SColoring m_sColoring; // Destination color for the animation DWORD m_dwDestinationColor; // Helper functions // Finds frame by index CAFrame * FindFrame ( DWORD dwIndex ) const; }; #endif // _ANIMATIONEDITOR_AANIMATION_H_
305d3250fa5d229e22074359ececdefa8ea97fb5
e1cb4d1965347068786c8d96f1c0dde81bc007e8
/src/orbital/ui/tab_gpu.h
f46fdf6bdc59f9a5ed428e217ea4099378c1c30f
[ "MIT" ]
permissive
Lagaffe91/orbital
44f199f148e60ae88c7e7f251e694d8b919f2fd8
b00aedbdadee73a659e39d4e8cd7ce17b433204e
refs/heads/master
2023-01-08T11:11:58.744909
2023-01-03T14:58:23
2023-01-03T14:58:23
259,028,233
0
0
MIT
2020-04-26T12:45:07
2020-04-26T12:45:07
null
UTF-8
C++
false
false
808
h
tab_gpu.h
/** * UI tab for GPU debugging. * * Copyright 2017-2021. Orbital project. * Released under MIT license. Read LICENSE for more details. * * Authors: * - Alexandro Sanchez Bach <alexandro@phi.nz> */ #pragma once #include "tab.h" #define IMGUI_IMPL_API #include <imgui.h> #include "imgui/widgets/imgui_memory_editor.h" // Forward declarations class PS4Machine; class LiverpoolGCDevice; class TabGPU : public Tab { public: friend PS4Machine; TabGPU(); // Interface void set_font_code(ImFont* font_code) { this->font_code = font_code; } void render(PS4Machine& ps4); private: ImFont* font_code; // Helpers void render_dce(const LiverpoolGCDevice& c); void render_gfx(const LiverpoolGCDevice& c); void render_sam(const LiverpoolGCDevice& c); };
542e65ff2d2e6661bf3f1d2a638ba14bfb23827e
8bfdc2752cb192dae470058df5d1a562086903cd
/outputhandler/pause.cc
6019284bbea9c1a46a77dd9239740666daf1ad25
[]
no_license
YoggYG/belt_balancer
997f74344038a8740058c007f9f6d1adbfb5777b
a63e92c87757b73eba5982ecca4912accb1090c5
refs/heads/master
2021-10-27T16:07:11.866961
2018-04-20T13:48:09
2018-04-20T13:48:09
111,812,278
0
0
null
null
null
null
UTF-8
C++
false
false
115
cc
pause.cc
#include "outputhandler.ih" void OutputHandler::pause() { this_thread::sleep_for(seconds(s_dist(s_engine))); }
5e479d1c703e7ff51509ffe4e48209808059cfeb
764e0c624bdee10f22b0420483c6c7555a7ca4a5
/VAT/cmeans/Unicode/UnicodeUtil.h
d81702b5376b43a57608b8a761b10d348428801c
[]
no_license
gzumpan/fuzzy-cmeans
729dc2c7b7c4a9db4d0f07d43fbb2f48b888a21c
a767170eadd1983bf94204c396844dfbce403c12
refs/heads/master
2016-09-06T09:16:47.526597
2014-08-03T03:10:03
2014-08-03T03:10:03
42,700,077
1
0
null
null
null
null
UTF-8
C++
false
false
1,145
h
UnicodeUtil.h
// UnicodeUtil.h: interface for the UnicodeUtil class. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_UNICODEUTIL_H__CA2FBAB3_B3DF_42EE_A791_CA63E9279089__INCLUDED_) #define AFX_UNICODEUTIL_H__CA2FBAB3_B3DF_42EE_A791_CA63E9279089__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "ConvertUTF.h" #include <string> class UnicodeUtil { public: UnicodeUtil(); virtual ~UnicodeUtil(); /** * Convert from UTF8 string to wide string (UTF16, UTF32) * * @author: Ninh * @param: const std::string utf8string * @param: std::wstring &resultstring * @return: BOOL */ static BOOL Utf8ToWstring(const std::string utf8string, std::wstring &resultstring); /** * Convert from wide string (UTF16, UTF32)to UTF8 string * * @author: Ninh * @param: const std::wstring widestring * @param: std::string &resultstring * @return: BOOL */ static BOOL WstringToUtf8(const std::wstring widestring, std::string &resultstring); }; #endif // !defined(AFX_UNICODEUTIL_H__CA2FBAB3_B3DF_42EE_A791_CA63E9279089__INCLUDED_)
8b8b56b3e9dc24778f8ba8c856ca80537a4b991e
13f65d615b7b8a451f02b5fc629a0f1899c954e1
/tlg.cpp
c2ad69ec9c9817ff679962c36c1548f671c19392
[]
no_license
yodebu/Algo-codes
c9b288761c03a407915bdff0674d8ddc5f9a4391
f1bbf5001cb54c5d3f0b6da0f8b61fb99f92c5c0
refs/heads/master
2020-12-25T22:36:34.216427
2014-11-14T14:17:46
2014-11-14T14:17:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
553
cpp
tlg.cpp
#include<iostream> #include<cmath> using namespace std; main() { int n; cin>>n; int lead=0; int winner=0; int a0=0,b0=0; int diff=0; int a,b; while(n--) { cin>>a>>b; a=a+a0; b=b+b0; diff=a-b; diff=abs(diff); if(diff>lead) { lead=diff; winner=a>b; } /* if(a>b) { if((a-b)>=lead) { lead=a-b; winner=1; } } else { if((b-a)>=lead) { lead=b-a; winner=2; } }*/ a0=a; b0=b; } cout<<(winner?1:2)<<" "<<lead<<endl; return 0; }
9c650c46f1e9061a53764475777aac2651ab1165
12b534a8a6de29b56d21afd20148e49021b8c6ef
/src/MenuHandler.cpp
37eb4d71e59b0e96fccf93bd84b82e845bb7cb69
[ "MIT" ]
permissive
gromchek/lavarun
2610fa04dccea52c21be761897b37b6ffdcd4254
3d4e7924244d8b0e1a96dfc2be90df3bf308469e
refs/heads/master
2020-07-16T03:26:18.841942
2020-02-09T23:57:44
2020-02-09T23:57:44
205,708,607
0
0
null
null
null
null
UTF-8
C++
false
false
2,954
cpp
MenuHandler.cpp
#include "MenuHandler.h" #include "MenuScreen.h" #include "UserInput.h" #include "Misc.h" #include <cassert> void MenuHandler::Draw( sf::RenderTarget &render ) { if( !IsActive() ) { return; } screens[current]->Draw( render ); } MenuHandler_Menu::MenuHandler_Menu() : MenuHandler() { screens.reserve( int( MenuScreenWidget::COUNT ) ); screens.push_back( std::make_shared<MenuScreen_MainMenu>( *this ) ); screens.push_back( std::make_shared<MenuScreen_NewGame>( *this ) ); screens.push_back( std::make_shared<MenuScreen_Highscore>( *this ) ); } void MenuHandler_Menu::Update() { if( current != next ) { // assert( next > int( MenuScreenWidget::INVALID ) || next < int( MenuScreenWidget::COUNT ) ); if( inRange( MenuScreenWidget::INVALID, MenuScreenWidget::COUNT, current ) ) { screens[current]->HideScreen(); } current = next; if( inRange( MenuScreenWidget::INVALID, MenuScreenWidget::COUNT, current ) ) { screens[current]->ShowScreen(); } } if( current == int( MenuScreenWidget::INVALID ) ) { return; } WidgetEvent evType = WidgetEvent::NONE; if( userInput.GetKeyState( sf::Keyboard::Down ) ) { evType = WidgetEvent::SCROLL_DOWN; } if( userInput.GetKeyState( sf::Keyboard::Up ) ) { evType = WidgetEvent::SCROLL_UP; } if( userInput.GetKeyState( sf::Keyboard::Escape ) ) { evType = WidgetEvent::GO_BACK; } if( userInput.GetKeyState( sf::Keyboard::Return ) ) { evType = WidgetEvent::PRESS; } screens[current]->Update(); screens[current]->HandleEvent( evType ); } void MenuHandler_Menu::Show( bool show ) { active = show; if( show ) { current = int( MenuScreenWidget::INVALID ); next = int( MenuScreenWidget::MAIN ); } else { current = int( MenuScreenWidget::INVALID ); next = int( MenuScreenWidget::INVALID ); } } MenuHandler_HUD::MenuHandler_HUD() : MenuHandler() { screens.reserve( int( HUDScreenWidget::COUNT ) ); hudScreen = std::make_shared<MenuScreen_HUD>( *this ); screens.push_back( hudScreen ); } void MenuHandler_HUD::Update() { if( current != next ) { // assert( next > int( HUDScreenWidget::INVALID ) || next < int( HUDScreenWidget::COUNT ) ); if( inRange( HUDScreenWidget::INVALID, HUDScreenWidget::COUNT, current ) ) { screens[current]->HideScreen(); } current = next; if( inRange( HUDScreenWidget::INVALID, HUDScreenWidget::COUNT, current ) ) { screens[current]->ShowScreen(); } } if( current == int( HUDScreenWidget::INVALID ) ) { return; } WidgetEvent evType = WidgetEvent::NONE; screens[current]->Update(); screens[current]->HandleEvent( evType ); } void MenuHandler_HUD::Show( bool show ) { active = show; if( show ) { current = int( HUDScreenWidget::INVALID ); next = int( HUDScreenWidget::MAIN ); } else { current = int( HUDScreenWidget::INVALID ); next = int( HUDScreenWidget::INVALID ); } }
deb15f70355687d98797af0d83359eaeb6f4fd7b
3cff2b750e5293a05f15c2120c09e14cb2632726
/prismer/include/common.h
e5550e12ba59298b19126d789c13c3d18010a4f3
[]
no_license
jwbuurlage/Prismer
7d9a20aa12b6979f39d7adb51f10c94426ab59ae
b68b1d4c6d876c0133fab08a245a54df9270edd5
refs/heads/master
2021-01-13T04:46:41.693215
2017-01-14T19:44:28
2017-01-14T19:44:28
78,962,957
1
0
null
null
null
null
UTF-8
C++
false
false
212
h
common.h
#include <random> namespace GRandom { int genrand() { std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<> dis(1, 1000000); return dis(gen); } } // namespace GRandom
4dcc9bd60dc011e1ff34f3c1436050db7b09d639
c20c4812ac0164c8ec2434e1126c1fdb1a2cc09e
/Source/Source/KG3DEngine/KG3DEngine/KG3DRepresentObjectSoundBall.h
61820851833b16ef3d6e85a463a9b601252389e7
[ "MIT" ]
permissive
uvbs/FullSource
f8673b02e10c8c749b9b88bf18018a69158e8cb9
07601c5f18d243fb478735b7bdcb8955598b9a90
refs/heads/master
2020-03-24T03:11:13.148940
2018-07-25T18:30:25
2018-07-25T18:30:25
142,408,505
2
2
null
2018-07-26T07:58:12
2018-07-26T07:58:12
null
GB18030
C++
false
false
3,311
h
KG3DRepresentObjectSoundBall.h
#pragma once #include "kg3drepresentobject.h" struct IKG3DSoundShell; class KG3DSceneOutDoorSpaceMgr; class KG3DSoundBallDataTable : public IKG3DSoundBallTable { public: void UnInit(); void Release(UINT uID); HRESULT LoadSoundBallData(SoundBallData** ppData, UINT &uHashID, LPCTSTR strFileName); HRESULT FindSoundBallData(SoundBallData** ppData, UINT uHashID); virtual HRESULT LoadFromFile(LPCTSTR strFileName, SoundBallData *pData); virtual HRESULT SaveToFile(LPCTSTR strFileName, SoundBallData *pData); virtual void Refresh(LPCSTR strFileName); private: const static int s_nVersion = 1; map<UINT, SoundBallData*>m_mapSoundBallData; // Inherited via IKG3DSoundBallTable virtual HRESULT LoadFromFile(LPCTSTR strFileName, SoundDataBase * pData) override; virtual HRESULT SaveToFile(LPCTSTR strFileName, SoundDataBase * pData) override; }; struct SoundBallConfigInfo { float m_f3DSoundMinDistance; float m_fSoundBallCheckRange; float m_fMaxListenRange; float m_fBoundingBoxSize; bool m_bRenderSoundBallRange; D3DXCOLOR m_crSoundBallColor; D3DXCOLOR m_crSoundBallRangeColor; SoundBallConfigInfo(); }; class KG3DRepresentObjectSoundBall : public KG3DRepresentObject, public IEKG3DRepresentObjectSoundBall { public: virtual ULONG STDMETHODCALLTYPE AddRef(); virtual ULONG STDMETHODCALLTYPE Release(); SoundBallData* m_lpSoundBallData; string m_szSoundBallDataFileName; UINT m_uFileHash; int m_nCurrentSound;//当前播放的声音序号,相对于m_lpSoundBallData DWORD m_dwSoundID;//当前播放的声音句柄 DWORD m_dwLastCheckTime;//上一次检测是否播放的时间 BOOL m_bHalt;//组织多线程更新soundball BOOL m_bRenderRange; HRESULT LoadFromSoundBallDataFile(LPCTSTR pFileName); virtual HRESULT GetName(LPTSTR pName, size_t BufferSize); virtual HRESULT SaveToInformationBuffer(KG3DMemoryFile* pFile); virtual HRESULT LoadFromInformationBuffer(const KG3DMemoryFile* pFile,DWORD dwOption); virtual HRESULT ComputeDynamicBBox(); virtual HRESULT ComputeBBox(); virtual HRESULT RenderSelectMark(DWORD dwColor /* = 0xFFFF0000 */); BOOL IsRayIntersect(D3DXVECTOR3&Inter,D3DXVECTOR3 Origin,D3DXVECTOR3 Direction); virtual HRESULT OnSelect(); virtual HRESULT OnUnSelect(); virtual HRESULT FrameMove(const D3DXMATRIX& matView); virtual HRESULT Render(DWORD dwOption); void Render(); virtual HRESULT Copy(KG3DRepresentObject* pSrcObject); virtual HRESULT Load(LPCTSTR lpFileName, DWORD_PTR wParam, DWORD_PTR lParam); virtual HRESULT GetAnotherIEInterface(DWORD dwType, VOID** ppAnotherInterface); virtual HRESULT UnInit(); KG3DRepresentObjectSoundBall(void); virtual ~KG3DRepresentObjectSoundBall(void); HRESULT SetTranslation(const D3DXVECTOR3* pTrans); HRESULT SetScaling(const D3DXVECTOR3* pScale); private: float m_fVolume; BOOL m_bPlayFailed; HRESULT StopSound(); public: //编辑器使用的 virtual void Stop(); virtual void Start(); }; class KG3DSoundBallRender { public: KG3DSoundBallRender(); ~KG3DSoundBallRender(); void Render(); void PushBack(KG3DRepresentObjectSoundBall *pSoundBall); private: std::vector<KG3DRepresentObjectSoundBall*> m_SoundBalls; }; extern KG3DSoundBallDataTable g_cSoundBallTable; extern KG3DSoundBallRender g_cSoundBallRender; extern SoundBallConfigInfo g_SoundBallConfig;
5adee00c757dc8964f080bfec703ee3409d5c9f0
df3f9446252192675faca8a2ce4eca8c3d82897a
/Snake/SnakeHead.cpp
a02eadc7ed0ae6039f5455009431bc03ac22be3c
[]
no_license
NisheethP/Snake
cfab776d7b9de547ba946800fef6016e44272027
61b99b5cf6aabbac160822a2f7d63e5f2f0e26dc
refs/heads/master
2016-09-09T19:14:47.906728
2014-11-19T16:38:31
2014-11-19T16:38:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
171
cpp
SnakeHead.cpp
#include "SnakeHead.h" SnakeHead::SnakeHead() { pegColour = Colour::Red; pegShape = Constants::Head; pegType = PegType::SnakeHeadPeg; } SnakeHead::~SnakeHead() { }
b328a4719f3139a3db30df244f1b2642a94bc1aa
2cb681e118e3f1e4b2b141372ae1c6914599b835
/codeforces/699_A.cpp
91bd2d63876c1bc75062c147355f7601145b294b
[]
no_license
jatinarora2702/Competitive-Coding
1ad978a91122c920c839483e46812b5fb70a246e
a77f5d4f1737ca4e408ccf706128ba90ed664286
refs/heads/master
2021-01-11T20:11:34.791960
2020-12-31T00:21:06
2020-12-31T00:21:06
79,060,813
0
0
null
null
null
null
UTF-8
C++
false
false
531
cpp
699_A.cpp
#include <bits/stdc++.h> using namespace std; const int INF = 1e9 + 7; #define N 200005 int a[N]; int main() { int n, i, x, y, f; string s; scanf("%d", &n); cin >> s; for(i = 0 ; i < n ; i++) { scanf("%d", &a[i]); } i = 0; f = INF; while(i < n) { while(i < n && s[i] == 'L') i++; if(i == n) break; x = a[i]; i++; while(i < n && s[i] == 'R') { x = a[i]; i++; } if(i == n) break; y = a[i]; f = min(f, (y-x)/2); } if(f == INF) printf("-1\n"); else printf("%d\n", f); return 0; }
8b22d82c3b5a61ed557fc962cf36c704de5e1e2b
a35b30a7c345a988e15d376a4ff5c389a6e8b23a
/boost/range/algorithm/mismatch.hpp
7a1c696dba6355726d8a8be25fd96d802193c862
[]
no_license
huahang/thirdparty
55d4cc1c8a34eff1805ba90fcbe6b99eb59a7f0b
07a5d64111a55dda631b7e8d34878ca5e5de05ab
refs/heads/master
2021-01-15T14:29:26.968553
2014-02-06T07:35:22
2014-02-06T07:35:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
70
hpp
mismatch.hpp
#include "thirdparty/boost_1_55_0/boost/range/algorithm/mismatch.hpp"
9e2ed07a9e3fb36c88a17e5bc2a82ec29f37b666
e094cc953e5e24e475fbca428f7722bf6bd8cd08
/project/project/examples/ExampleMS/include/ExampleMS/ExampleMSViewer.hpp
ce74f7893b40ae7d1e240bb6e94cbf31c98f7636
[]
no_license
potaopereira/mechanical_sys_simulator_2d
4e4ff50be47ccc95e084a258c7469293c9edf496
bb530fcf9d51e06de7d076be0c275193e2f86415
refs/heads/master
2023-07-26T23:53:47.109525
2021-09-14T19:12:55
2021-09-14T19:12:55
406,483,063
0
0
null
null
null
null
UTF-8
C++
false
false
411
hpp
ExampleMSViewer.hpp
#pragma once // ExampleMSSolver #include "ExampleMS/ExampleMSSolver.hpp" // IMS2DImpl #include <msinterface/interface.hpp> // MSView<N> #include <msviewer/viewerimpl.hpp> typedef MSView<1> MSVIEW1; class ExampleMSViewer: public ExampleMSSolver, // this is the solver public MSVIEW1, // this is the viewer public IMS2D // link viewer with solver { public: ExampleMSViewer(); virtual void reset(); };
37de10d92e2d78130f60e45cf4820728bd50bc5f
2ef4c0132aed0a198449e3b832282ff8c262c19f
/src_matlab_interface/GenericContainerMatlabInterface.cc
b43fa7e473377e535a808b1a908de9e9b8095f9e
[ "BSD-2-Clause" ]
permissive
ebertolazzi/GenericContainer
c11362fbbbc74fb88712d3c933f0b91cfb94590d
20149037a504096739e8476e297522212f1dba6a
refs/heads/master
2023-08-23T01:14:30.071914
2022-09-19T07:55:34
2022-09-19T07:55:34
12,334,594
2
3
BSD-2-Clause
2021-10-15T11:11:26
2013-08-23T23:10:18
C++
UTF-8
C++
false
false
22,756
cc
GenericContainerMatlabInterface.cc
/****************************************************************************\ Copyright (c) Enrico Bertolazzi 2014 See file license.txt \****************************************************************************/ #include "GenericContainer/GenericContainerMatlabInterface.hh" #include <iostream> #include <cstdint> #ifndef DOXYGEN_SHOULD_SKIP_THIS using namespace std; #endif namespace GC_namespace { // =========================================================================== void mexPrint( GenericContainer const & gc ) { std::ostringstream ss; gc.print(ss); mexPrintf("%s\n", ss.str().c_str()); } // =========================================================================== static void mx_to_vec_bool( mxArray const * mx, GenericContainer & gc ) { if ( mxGetNumberOfElements(mx) == 1 ) { gc = mxIsLogicalScalarTrue(mx); } else { mxLogical const * pr = mxGetLogicals(mx); mwSize total_num_of_elements = mxGetNumberOfElements(mx); vector_type & vec = gc.set_vector( total_num_of_elements ); for ( mwSize idx = 0; idx < total_num_of_elements; ++idx ) vec[idx] = *pr++; } } template <typename T> static void mx_to_vec_int( mxArray const * mx, GenericContainer & gc ) { mwSize const * dims = mxGetDimensions(mx); T * pr = static_cast<T*>(mxGetData(mx)); if ( mxGetNumberOfElements(mx) == 1 ) { gc.set_int( int_type(*pr) ); } else { mwSize number_of_dimensions = mxGetNumberOfDimensions(mx); switch ( number_of_dimensions ) { case 1: { mwSize total_num_of_elements = mxGetNumberOfElements(mx); vec_int_type & vec = gc.set_vec_int( total_num_of_elements ); for ( mwSize idx = 0; idx < total_num_of_elements; ++idx ) vec[idx] = int_type(*pr++); } break; case 2: if ( dims[0] == 1 ) { mwSize total_num_of_elements = mxGetNumberOfElements(mx); vec_int_type & vec = gc.set_vec_int( total_num_of_elements ); for ( mwSize idx = 0; idx < total_num_of_elements; ++idx ) vec[idx] = int_type(*pr++); } else { mat_int_type & mat = gc.set_mat_int( dims[0], dims[1] ); for ( mwSize j = 0; j < dims[1]; ++j ) for ( mwSize i = 0; i < dims[0]; ++i ) mat(i,j) = int_type(*pr++); } break; default: mexPrintf("number_of_dimensions = %d\n", number_of_dimensions ); break; } } } template <typename T> static void mx_to_vec_long( mxArray const * mx, GenericContainer & gc ) { mwSize const * dims = mxGetDimensions(mx); T * pr = static_cast<T*>(mxGetData(mx)); if ( mxGetNumberOfElements(mx) == 1 ) { gc.set_long( long_type(*pr) ); } else { mwSize number_of_dimensions = mxGetNumberOfDimensions(mx); switch ( number_of_dimensions ) { case 1: { mwSize total_num_of_elements = mxGetNumberOfElements(mx); vec_long_type & vec = gc.set_vec_long( total_num_of_elements ); for ( mwSize idx = 0; idx < total_num_of_elements; ++idx ) vec[idx] = long_type(*pr++); } break; case 2: if ( dims[0] == 1 ) { mwSize total_num_of_elements = mxGetNumberOfElements(mx); vec_long_type & vec = gc.set_vec_long( total_num_of_elements ); for ( mwSize idx = 0; idx < total_num_of_elements; ++idx ) vec[idx] = long_type(*pr++); } else { mat_long_type & mat = gc.set_mat_long( dims[0], dims[1] ); for ( mwSize j = 0; j < dims[1]; ++j ) for ( mwSize i = 0; i < dims[0]; ++i ) mat(i,j) = long_type(*pr++); } break; default: mexPrintf("number_of_dimensions = %d\n", number_of_dimensions ); break; } } } // =========================================================================== template <typename T> static void mx_to_vec_real( mxArray const * mx, GenericContainer & gc ) { mwSize const * dims = mxGetDimensions(mx); T * pr = static_cast<T*>(mxGetData(mx)); if ( mxGetNumberOfElements(mx) == 1 ) { gc = real_type(*pr); } else { mwSize number_of_dimensions = mxGetNumberOfDimensions(mx); switch ( number_of_dimensions ) { case 1: { mwSize total_num_of_elements = mxGetNumberOfElements(mx); vec_real_type & vec = gc.set_vec_real( total_num_of_elements ); for ( mwSize idx = 0; idx < total_num_of_elements; ++idx ) vec[idx] = real_type(*pr++); } break; case 2: if ( dims[0] == 1 ) { mwSize total_num_of_elements = mxGetNumberOfElements(mx); vec_real_type & vec = gc.set_vec_real( total_num_of_elements ); for ( mwSize idx = 0; idx < total_num_of_elements; ++idx ) vec[idx] = real_type(*pr++); } else { mat_real_type & mat = gc.set_mat_real( dims[0], dims[1] ); mwSize total_num_of_elements = mxGetNumberOfElements(mx); for ( mwSize idx = 0; idx < total_num_of_elements; ++idx ) mat[idx] = real_type(*pr++); } break; default: mexPrintf("number_of_dimensions = %d\n", number_of_dimensions ); break; } } } // =========================================================================== template <typename T> static void mx_to_vec_complex( mxArray const * mx, GenericContainer & gc ) { mwSize const * dims = mxGetDimensions(mx); T * pr = static_cast<T*>(mxGetData(mx)); T * pi = static_cast<T*>(mxGetImagData(mx)); if ( mxGetNumberOfElements(mx) == 1 ) { gc = complex_type(*pr,*pi); } else { mwSize number_of_dimensions = mxGetNumberOfDimensions(mx); switch ( number_of_dimensions ) { case 1: { mwSize total_num_of_elements = mxGetNumberOfElements(mx); vec_complex_type & vec = gc.set_vec_complex( total_num_of_elements ); for ( mwSize idx = 0; idx < total_num_of_elements; ++idx ) vec[idx] = complex_type(*pr++,*pi++); } break; case 2: if ( dims[0] == 1 ) { mwSize total_num_of_elements = mxGetNumberOfElements(mx); vec_complex_type & vec = gc.set_vec_complex( total_num_of_elements ); for ( mwSize idx = 0; idx < total_num_of_elements; ++idx ) vec[idx] = complex_type(*pr++,*pi++); } else { mat_complex_type & mat = gc.set_mat_complex( dims[0], dims[1] ); mwSize total_num_of_elements = mxGetNumberOfElements(mx); for ( mwSize idx = 0; idx < total_num_of_elements; ++idx ) mat[idx] = complex_type(*pr++,*pi++); } break; default: mexPrintf("number_of_dimensions = %d\n", number_of_dimensions ); break; } } } // =========================================================================== static void mx_to_vector( mxArray const * mx, GenericContainer & gc ) { unsigned ne = mxGetNumberOfElements(mx); gc.set_vector(ne); for ( unsigned idx = 0; idx < ne; ++idx ) { GenericContainer & gc1 = gc[idx]; mxArray const * cell = mxGetCell(mx, idx); mxArray_to_GenericContainer( cell, gc1 ); } } // =========================================================================== static void mx_to_map( mxArray const * mx, GenericContainer & gc ) { gc.set_map(); unsigned numFields = mxGetNumberOfFields(mx); for ( unsigned ifield = 0; ifield < numFields; ++ifield ) { char const * field_name = mxGetFieldNameByNumber(mx,ifield); GenericContainer & gc1 = gc[field_name]; unsigned nr = mxGetM(mx); unsigned nc = mxGetN(mx); if ( nc == 1 && nr == 1 ) { mxArray const * mxField = mxGetFieldByNumber(mx,0,ifield); mxArray_to_GenericContainer( mxField, gc1 ); } else { gc1.set_vector(nr*nc); for ( unsigned i = 0; i < nr*nc; ++i ) { mxArray const * mxField = mxGetFieldByNumber(mx,i,ifield); mxArray_to_GenericContainer( mxField, gc1[i] ); } } } } // =========================================================================== void mxSparse_to_GenericContainer( mxArray const * mx, GenericContainer & gc ) { mwIndex const * irs = mxGetIr(mx); mwIndex const * jcs = mxGetJc(mx); size_t nc = mxGetN(mx); mwIndex nnz = jcs[nc]; vec_int_type & jc = gc["jc"].set_vec_int( nc+1 ); vec_int_type & ir = gc["ir"].set_vec_int( nnz ); for ( unsigned i = 0; i <= nc; ++i ) jc[i] = jcs[i]; for ( unsigned i = 0; i < nnz; ++i ) ir[i] = irs[i]; double * sr = mxGetPr(mx); if ( mxIsComplex( mx ) ) { double * si = mxGetPi(mx); vec_complex_type & val = gc["values"].set_vec_complex( nnz ); for ( unsigned i = 0; i < nnz; ++i ) val[i] = complex_type(sr[i],si[i]); } else { vec_real_type & val = gc["values"].set_vec_real( nnz ); for ( unsigned i = 0; i < nnz; ++i ) val[i] = sr[i]; } } // =========================================================================== void mxArray_to_GenericContainer( mxArray const * mx, GenericContainer & gc ) { gc.clear(); if ( mx == nullptr ) return; mxClassID category = mxGetClassID(mx); //mexPrintf("\n\n\n%s\n\n\n",mxGetClassName(mx)); if ( category == mxCELL_CLASS ) { mx_to_vector(mx,gc); } else if ( category == mxSTRUCT_CLASS ) { mx_to_map(mx,gc); } else if ( category == mxCHAR_CLASS ) { gc = mxArrayToString(mx); } else if ( mxIsSparse(mx) ) { mxSparse_to_GenericContainer( mx, gc ); } else if ( mxIsClass(mx,"string") ) { // https://it.mathworks.com/matlabcentral/answers/330929-how-to-access-matlab-string-data-in-mex-c // Matlab's String class is encapsulated, // use Matlab call to convert it to char array mxArray * string_class[1]; mxArray * char_array[1]; string_class[0] = const_cast<mxArray*>(mx); mexCallMATLAB(1, char_array, 1, string_class, "char"); // Parse the char array to create an std::string int buflen = mxGetN(char_array[0])*sizeof(mxChar)+1; char* buf = new char[buflen]; mxGetString(char_array[0],buf,buflen); gc = buf; delete [] buf; } else { if ( mxIsComplex(mx) ) { switch (category) { case mxLOGICAL_CLASS: mx_to_vec_bool(mx,gc); break; case mxINT8_CLASS: mx_to_vec_complex<int8_t>(mx,gc); break; case mxUINT8_CLASS: mx_to_vec_complex<uint8_t>(mx,gc); break; case mxINT16_CLASS: mx_to_vec_complex<int16_t>(mx,gc); break; case mxUINT16_CLASS: mx_to_vec_complex<uint16_t>(mx,gc); break; case mxINT32_CLASS: mx_to_vec_complex<int32_t>(mx,gc); break; case mxUINT32_CLASS: mx_to_vec_complex<uint32_t>(mx,gc); break; case mxINT64_CLASS: mx_to_vec_complex<int64_t>(mx,gc); break; case mxUINT64_CLASS: mx_to_vec_complex<uint64_t>(mx,gc); break; case mxSINGLE_CLASS: mx_to_vec_complex<float>(mx,gc); break; case mxDOUBLE_CLASS: mx_to_vec_complex<double>(mx,gc); break; default: mexPrintf("Complex Class ID = %d not converted!\n", category ); break; } } else { switch (category) { case mxLOGICAL_CLASS: mx_to_vec_bool(mx,gc); break; case mxINT8_CLASS: mx_to_vec_int<int8_t>(mx,gc); break; case mxUINT8_CLASS: mx_to_vec_int<uint8_t>(mx,gc); break; case mxINT16_CLASS: mx_to_vec_int<int16_t>(mx,gc); break; case mxUINT16_CLASS: mx_to_vec_int<uint16_t>(mx,gc); break; case mxINT32_CLASS: mx_to_vec_int<int32_t>(mx,gc); break; case mxUINT32_CLASS: mx_to_vec_int<uint32_t>(mx,gc); break; case mxINT64_CLASS: mx_to_vec_long<int64_t>(mx,gc); break; case mxUINT64_CLASS: mx_to_vec_long<uint64_t>(mx,gc); break; case mxSINGLE_CLASS: mx_to_vec_real<float>(mx,gc); break; case mxDOUBLE_CLASS: mx_to_vec_real<double>(mx,gc); break; default: mexPrintf("Class ID = %d not converted!\n", category ); break; } } } } // =========================================================================== void to_mxArray( bool const & val_in, mxArray * & mx ) { mxLogical val = val_in ? 1 : 0; mx = mxCreateLogicalScalar(val); } void to_mxArray( int_type const & val, mxArray * & mx ) { mwSize dims[2] = {1,1}; mx = mxCreateNumericArray(2,dims,mxINT64_CLASS,mxREAL); *(mwSize *)mxGetData(mx) = mwSize(val); } void to_mxArray( long_type const & val, mxArray * & mx ) { mwSize dims[2] = {1,1}; mx = mxCreateNumericArray(2,dims,mxINT64_CLASS,mxREAL); *(int64_t*)mxGetData(mx) = int64_t(val); } void to_mxArray( real_type const & val, mxArray * & mx ) { mx = mxCreateDoubleScalar(val); } void to_mxArray( complex_type const & val, mxArray * & mx ) { mwSize dims[2] = {1,1}; mx = mxCreateNumericArray(2,dims,mxDOUBLE_CLASS,mxCOMPLEX); *mxGetPr(mx) = val.real(); *mxGetPi(mx) = val.imag(); } void to_mxArray( string_type const & val, mxArray * & mx ) { mx = mxCreateString( val.c_str() ); } void to_mxArray( vec_bool_type const & val, mxArray * & mx ) { mwSize dims[2] = { mwSize(val.size()), 1 }; mx = mxCreateNumericArray(2,dims,mxLOGICAL_CLASS,mxREAL); mxLogical * ptr = (mxLogical*)mxGetData(mx); for ( mwSize i = 0; i < dims[0]; ++i ) ptr[i] = val[i]; } void to_mxArray( vec_int_type const & val, mxArray * & mx ) { cout << "in to_mxArray( vec_int_type\n"; mwSize dims[2] = { mwSize(val.size()), 1 }; mx = mxCreateNumericArray(2,dims,mxINT32_CLASS,mxREAL); int32_t * ptr = (int32_t*)mxGetData(mx); for ( mwSize i = 0; i < dims[0]; ++i ) ptr[i] = int32_t(val[i]); } void to_mxArray( vec_long_type const & val, mxArray * & mx ) { mwSize dims[2] = { mwSize(val.size()), 1 }; mx = mxCreateNumericArray(2,dims,mxINT64_CLASS,mxREAL); int64_t * ptr = (int64_t*)mxGetData(mx); for ( mwSize i = 0; i < dims[0]; ++i ) ptr[i] = int64_t(val[i]); } void to_mxArray( vec_real_type const & val, mxArray * & mx ) { mwSize dims[2] = { mwSize(val.size()), 1 }; mx = mxCreateNumericArray(2,dims,mxDOUBLE_CLASS,mxREAL); double * ptr = mxGetPr(mx); for ( mwSize i = 0; i < dims[0]; ++i ) ptr[i] = val[i]; } void to_mxArray( vec_complex_type const & val, mxArray * & mx ) { mwSize dims[2] = { mwSize(val.size()), 1 }; mx = mxCreateNumericArray(2,dims,mxDOUBLE_CLASS,mxCOMPLEX); double * ptr = mxGetPr(mx); double * pti = mxGetPi(mx); for ( mwSize i = 0; i < dims[0]; ++i ) { ptr[i] = val[i].real(); pti[i] = val[i].imag(); } } void to_mxArray( vec_string_type const & val, mxArray * & mx ) { mwSize dims[2] = { mwSize(val.size()), 1 }; mx = mxCreateCellMatrix(dims[0], dims[1]); for( mwSize i = 0; i < dims[0]; ++i ) mxSetCell(mx,i,mxCreateString( val[i].c_str()) ); } void to_mxArray( mat_int_type const & val, mxArray * & mx ) { mwSize dims[2] = { mwSize(val.numRows()), mwSize(val.numCols()) }; mx = mxCreateNumericArray(2,dims,mxINT32_CLASS,mxREAL); int32_t * ptr = static_cast<int32_t*>(mxGetData(mx)); mwSize k = 0; for ( mwSize j = 0; j < dims[1]; ++j ) for ( mwSize i = 0; i < dims[0]; ++i ) ptr[k++] = val(i,j); } void to_mxArray( mat_long_type const & val, mxArray * & mx ) { mwSize dims[2] = { mwSize(val.numRows()), mwSize(val.numCols()) }; mx = mxCreateNumericArray(2,dims,mxINT64_CLASS,mxREAL); int64_t * ptr = static_cast<int64_t*>(mxGetData(mx)); mwSize k = 0; for ( mwSize j = 0; j < dims[1]; ++j ) for ( mwSize i = 0; i < dims[0]; ++i ) ptr[k++] = val(i,j); } void to_mxArray( mat_real_type const & val, mxArray * & mx ) { mwSize dims[2] = { mwSize(val.numRows()), mwSize(val.numCols()) }; mx = mxCreateNumericArray(2,dims,mxDOUBLE_CLASS,mxREAL); double * ptr = mxGetPr(mx); mwSize k = 0; for ( mwSize j = 0; j < dims[1]; ++j ) for ( mwSize i = 0; i < dims[0]; ++i ) ptr[k++] = val(i,j); } void to_mxArray( mat_complex_type const & val, mxArray * & mx ) { mwSize dims[2] = { mwSize(val.numRows()), mwSize(val.numCols()) }; mx = mxCreateNumericArray(2,dims,mxDOUBLE_CLASS,mxCOMPLEX); double * ptr = mxGetPr(mx); double * pti = mxGetPi(mx); mwSize k = 0; for ( mwSize j = 0; j < dims[1]; ++j ) { for ( mwSize i = 0; i < dims[0]; ++i ) { ptr[k] = val(i,j).real(); pti[k] = val(i,j).imag(); ++k; } } } // =========================================================================== void GenericContainer_to_mxArray( GenericContainer const & gc, mxArray * & mx ) { static char const where[] = "in GenericContainer_to_mxArray: "; mwSize dims[2] = {1,1}; switch ( gc.get_type() ) { case GC_NOTYPE: case GC_POINTER: case GC_VEC_POINTER: mx = mxCreateDoubleMatrix(0,0,mxREAL); break; case GC_BOOL: { mxLogical val = gc.get_bool() ? 1 : 0; mx = mxCreateLogicalScalar(val); } break; case GC_INTEGER: mx = mxCreateNumericArray(2,dims,mxINT64_CLASS,mxREAL); *(mwSize *)mxGetData(mx) = gc.get_int(); break; case GC_LONG: mx = mxCreateNumericArray(2,dims,mxINT64_CLASS,mxREAL); *(mwSize *)mxGetData(mx) = gc.get_long(); break; case GC_REAL: mx = mxCreateDoubleScalar(gc.get_real()); break; case GC_COMPLEX: { mx = mxCreateNumericArray(2,dims,mxDOUBLE_CLASS,mxCOMPLEX); real_type re, im; gc.get_complex_number(re,im); *mxGetPr(mx) = re; *mxGetPi(mx) = im; } break; case GC_STRING: mx = mxCreateString( gc.get_string().c_str() ); break; case GC_VEC_BOOL: { dims[1] = gc.get_num_elements(); mx = mxCreateNumericArray(2,dims,mxLOGICAL_CLASS,mxREAL); mxLogical * ptr = (mxLogical*)mxGetData(mx); for ( mwSize i = 0; i < dims[1]; ++i ) ptr[i] = gc.get_bool_at(i,where); } break; case GC_VEC_INTEGER: { dims[1] = gc.get_num_elements(); mx = mxCreateNumericArray(2,dims,mxINT64_CLASS,mxREAL); mwSize * ptr = (mwSize*)mxGetData(mx); for ( mwSize i = 0; i < dims[1]; ++i ) ptr[i] = gc.get_int_at(i,where); } break; case GC_VEC_LONG: { dims[1] = gc.get_num_elements(); mx = mxCreateNumericArray(2,dims,mxINT64_CLASS,mxREAL); mwSize * ptr = (mwSize*)mxGetData(mx); for ( mwSize i = 0; i < dims[1]; ++i ) ptr[i] = gc.get_long_at(i,where); } break; case GC_VEC_REAL: { dims[1] = gc.get_num_elements(); mx = mxCreateNumericArray(2,dims,mxDOUBLE_CLASS,mxREAL); double * ptr = mxGetPr(mx); for ( mwSize i = 0; i < dims[1]; ++i ) ptr[i] = gc.get_real_at(i,where); } break; case GC_VEC_COMPLEX: { dims[1] = gc.get_num_elements(); mx = mxCreateNumericArray(2,dims,mxDOUBLE_CLASS,mxCOMPLEX); double * ptr = mxGetPr(mx); double * pti = mxGetPi(mx); for ( mwSize i = 0; i < dims[1]; ++i ) gc.get_complex_number_at(i,ptr[i],pti[i]); } break; case GC_VEC_STRING: { dims[1] = gc.get_num_elements(); mx = mxCreateCellMatrix(dims[0], dims[1]); for( mwSize i = 0; i < dims[1]; ++i ) mxSetCell(mx,i,mxCreateString( gc.get_string_at(i,where).c_str())); } break; case GC_MAT_INTEGER: { dims[0] = gc.get_numRows(); dims[1] = gc.get_numCols(); mx = mxCreateNumericArray(2,dims,mxINT32_CLASS,mxREAL); int_type * ptr = static_cast<int_type *>(mxGetData(mx)); mwSize k = 0; for ( mwSize j = 0; j < dims[1]; ++j ) for ( mwSize i = 0; i < dims[0]; ++i ) ptr[k++] = gc.get_int_at(i,j,where); } break; case GC_MAT_LONG: { dims[0] = gc.get_numRows(); dims[1] = gc.get_numCols(); mx = mxCreateNumericArray(2,dims,mxINT64_CLASS,mxREAL); long_type * ptr = static_cast<long_type *>(mxGetData(mx)); mwSize k = 0; for ( mwSize j = 0; j < dims[1]; ++j ) for ( mwSize i = 0; i < dims[0]; ++i ) ptr[k++] = gc.get_long_at(i,j,where); } break; case GC_MAT_REAL: { dims[0] = gc.get_numRows(); dims[1] = gc.get_numCols(); mx = mxCreateNumericArray(2,dims,mxDOUBLE_CLASS,mxREAL); double * ptr = mxGetPr(mx); mwSize k = 0; for ( mwSize j = 0; j < dims[1]; ++j ) for ( mwSize i = 0; i < dims[0]; ++i ) ptr[k++] = gc.get_real_at(i,j,where); } break; case GC_MAT_COMPLEX: { dims[0] = gc.get_numRows(); dims[1] = gc.get_numCols(); mx = mxCreateNumericArray(2,dims,mxDOUBLE_CLASS,mxCOMPLEX); double * ptr = mxGetPr(mx); double * pti = mxGetPi(mx); mwSize k = 0; for ( mwSize j = 0; j < dims[1]; ++j ) { for ( mwSize i = 0; i < dims[0]; ++i ) { complex_type val = gc.get_complex_at(i,j,where); ptr[k] = val.real(); pti[k] = val.imag(); ++k; } } } break; case GC_VECTOR: { dims[1] = gc.get_num_elements(); mx = mxCreateCellMatrix(dims[0], dims[1]); for( mwSize i = 0; i < dims[1]; ++i ) { mxArray * mxi = nullptr; GenericContainer_to_mxArray( gc[i], mxi ); if ( mxi != nullptr ) mxSetCell( mx, i, mxi ); } } break; case GC_MAP: { map_type const & mappa = gc.get_map(); std::vector<char const *> fieldnames; int nfield = mappa.size(); fieldnames.reserve(nfield); for ( map_type::const_iterator im = mappa.begin(); im != mappa.end(); ++im ) fieldnames.push_back(im->first.c_str()); mx = mxCreateStructMatrix(1,1,nfield,&fieldnames.front()); int ifield = 0; for ( map_type::const_iterator im = mappa.begin(); im != mappa.end(); ++im, ++ifield ) { mxArray * mxi = nullptr; GenericContainer_to_mxArray( im->second, mxi ); if ( mxi != nullptr ) mxSetFieldByNumber( mx, 0, ifield, mxi ); } } break; } } }
386a30d94d7a2c52320ced6cb1aefab6744af895
b8d1007362afcd7dbe85ff82745217388c435150
/cf/1194-b.cpp
f996856c5762ed1194899356415502ad14361b8b
[ "MIT" ]
permissive
PIPIKAI/ACM
5ef5bcd0193ed49e48806cca64875c1abaa00c42
b8e4416a29c0619946c9b73b0fe5699b6e96e782
refs/heads/master
2021-07-19T02:29:04.010478
2020-08-03T01:36:58
2020-08-03T01:36:58
200,979,733
0
0
null
null
null
null
UTF-8
C++
false
false
847
cpp
1194-b.cpp
#include<bits/stdc++.h> using namespace std; typedef long long ll; #define inf 1e9+7 #define ffr(i,a,b) for(int i=a;i<b;i++) #define mem(a,b) memset( a,b,sizeof a) #define Max(x,y) y>x?x=y:x=x int n,m; int a[500005],b[500005]; int main() { std::ios::sync_with_stdio(false); int q; cin>>q; while(q--){ int ans=inf; cin>>n>>m; vector<string>s(n); for(int i=0;i<n;i++){ cin>>s[i]; } vector<int>a(n); vector<int>b(m); for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ s[i][j]=='.'?a[i]++,b[j]++:0; } } for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ ans=min(a[i]+b[j]- (s[i][j]=='.'),ans); } } cout<<ans<<endl; } return 0; }
fe48e03fbc35793702adc2ee9448c455acfca518
2692e11c292fea05510830af9712b91a03428ac9
/toonz/sources/toonz/castviewer.cpp
ec71d72a5a61d0c330ba5d0fbc5cb408b1077730
[ "BSD-3-Clause" ]
permissive
manongjohn/OTX
92b72589fbcf26867f18997862e8cdb8ef5a1af6
a80fe827b7a6316480974d712f9175d970729f04
refs/heads/master
2021-06-15T09:33:57.878785
2021-05-13T16:01:59
2021-05-13T16:01:59
188,602,761
20
9
NOASSERTION
2019-08-05T01:06:23
2019-05-25T19:02:45
C++
UTF-8
C++
false
false
30,574
cpp
castviewer.cpp
#include "castviewer.h" // Tnz6 includes #include "castselection.h" #include "tapp.h" #include "menubarcommandids.h" #include "floatingpanelcommand.h" #include "iocommand.h" #include "filmstripcommand.h" #include "flipbook.h" // TnzLib includes #include "toonz/tscenehandle.h" #include "toonz/txsheethandle.h" #include "toonz/txshlevelhandle.h" #include "toonz/levelset.h" #include "toonz/toonzscene.h" #include "toonz/txshsimplelevel.h" #include "toonz/txshleveltypes.h" // TnzQt includes #include "toonzqt/dvdialog.h" #include "toonzqt/gutil.h" #include "toonzqt/trepetitionguard.h" #include "toonzqt/icongenerator.h" #include "toonzqt/infoviewer.h" #include "historytypes.h" // TnzCore includes #include "tundo.h" #include "tfiletype.h" #include "tsystem.h" // Qt includes #include <QDrag> #include <QDragEnterEvent> #include <QDragMoveEvent> #include <QDropEvent> #include <QDragLeaveEvent> #include <QHeaderView> #include <QPainter> #include <QBoxLayout> #include <QLabel> #include <QByteArray> #include <QDesktopServices> #include <QUrl> #include <QMenu> #include <QDir> const char *AudioFolderName = "Audio"; using namespace DVGui; namespace { // Se il widget del cast viewer viene spostato in toonzqt (e quindi fatto // dipendere dallo sceneHandle) // questo undo puo' essere spostato in un nuovo file levelsetcommand in // toonzlib. class MoveLevelToFolderUndo final : public TUndo { TLevelSet *m_levelSet; std::wstring m_levelName; TFilePath m_oldFolder; TFilePath m_newFolder; public: MoveLevelToFolderUndo(TLevelSet *levelSet, std::wstring levelName, TFilePath newFolder) : m_levelSet(levelSet), m_levelName(levelName), m_newFolder(newFolder) { TXshLevel *level = m_levelSet->getLevel(m_levelName); m_oldFolder = m_levelSet->getFolder(level); } void undo() const override { TXshLevel *level = m_levelSet->getLevel(m_levelName); m_levelSet->moveLevelToFolder(m_oldFolder, level); TApp::instance()->getCurrentScene()->notifyCastChange(); } void redo() const override { TXshLevel *level = m_levelSet->getLevel(m_levelName); m_levelSet->moveLevelToFolder(m_newFolder, level); TApp::instance()->getCurrentScene()->notifyCastChange(); } int getSize() const override { return sizeof(*this); } QString getHistoryString() override { return QObject::tr("Move Level to Cast Folder"); } }; } //============================================================================= // // CastTreeViewer // //----------------------------------------------------------------------------- CastTreeViewer::CastTreeViewer(QWidget *parent) : QTreeWidget(parent), m_dropTargetItem(0) { setObjectName("OnePixelMarginFrame"); // setObjectName("BrowserTreeView"); // setStyleSheet("#BrowserTreeView {border: 0px; margin: 1px; // qproperty-autoFillBackground: true;}"); header()->close(); setIconSize(QSize(16, 16)); setUniformRowHeights(true); // m_treeViewer->setColumnCount(1); setAcceptDrops(true); connect(this, SIGNAL(itemChanged(QTreeWidgetItem *, int)), this, SLOT(onItemChanged(QTreeWidgetItem *, int))); connect(this, SIGNAL(currentItemChanged(QTreeWidgetItem *, QTreeWidgetItem *)), this, SLOT(onFolderChanged(QTreeWidgetItem *, QTreeWidgetItem *))); connect(TApp::instance()->getCurrentScene(), SIGNAL(sceneSwitched()), this, SLOT(rebuildCastTree())); connect(TApp::instance()->getCurrentScene(), SIGNAL(castFolderAdded(const TFilePath &)), this, SLOT(onCastFolderAdded(const TFilePath &))); connect(TApp::instance()->getCurrentScene(), SIGNAL(nameSceneChanged()), this, SLOT(onSceneNameChanged())); // Connect all possible changes that can alter the // bottom horizontal scrollbar to resize contents... connect(this, SIGNAL(expanded(const QModelIndex &)), this, SLOT(resizeToConts())); connect(this, SIGNAL(collapsed(const QModelIndex &)), this, SLOT(resizeToConts())); connect(this->model(), SIGNAL(layoutChanged()), this, SLOT(resizeToConts())); rebuildCastTree(); } //----------------------------------------------------------------------------- //! Resizes viewport to contents void CastTreeViewer::resizeToConts(void) { resizeColumnToContents(0); } //----------------------------------------------------------------------------- void CastTreeViewer::resizeEvent(QResizeEvent *event) { resizeColumnToContents(0); QTreeView::resizeEvent(event); } //----------------------------------------------------------------------------- TLevelSet *CastTreeViewer::getLevelSet() { return TApp::instance()->getCurrentScene()->getScene()->getLevelSet(); } //----------------------------------------------------------------------------- void CastTreeViewer::enableCommands() { enableCommand(this, MI_Clear, &CastTreeViewer::deleteFolder); } //----------------------------------------------------------------------------- void CastTreeViewer::onFolderChanged(QTreeWidgetItem *current, QTreeWidgetItem *previous) { // rende la selezione corrente; serve per intercettare il comando MI_Clear makeCurrent(); } //----------------------------------------------------------------------------- void CastTreeViewer::populateFolder(QTreeWidgetItem *folder) { TFilePath folderPath( folder->data(1, Qt::DisplayRole).toString().toStdWString()); std::vector<TFilePath> folders; getLevelSet()->listFolders(folders, folderPath); int i; for (i = 0; i < (int)folders.size(); i++) { TFilePath fp = folders[i]; QString fpQstr = QString::fromStdWString(fp.getWideString()); QString name = QString::fromStdWString(fp.withoutParentDir().getWideString()); QTreeWidgetItem *child = new QTreeWidgetItem((QTreeWidgetItem *)0, QStringList(name) << fpQstr); if (name != AudioFolderName) child->setFlags(child->flags() | Qt::ItemIsEditable); folder->addChild(child); populateFolder(child); } } //----------------------------------------------------------------------------- void CastTreeViewer::onSceneNameChanged() { QTreeWidgetItem *root = topLevelItem(0); if (!root) return; ToonzScene *scene = TApp::instance()->getCurrentScene()->getScene(); QString rootName = QString("Root"); if (scene) { std::wstring name = (scene->isUntitled()) ? L"Untitled" : scene->getSceneName(); rootName = rootName.fromStdWString(name); } root->setText(0, rootName); } //----------------------------------------------------------------------------- void CastTreeViewer::onCastFolderAdded(const TFilePath &path) { QTreeWidgetItem *root = topLevelItem(0)->child(0); assert(root->data(1, Qt::DisplayRole).toString() == toQString(getLevelSet()->getDefaultFolder())); QString childName = QString::fromStdWString(path.getWideName()); QString childPathQstr = QString::fromStdWString(path.getWideString()); QTreeWidgetItem *childItem = new QTreeWidgetItem(root, QStringList(childName) << childPathQstr); childItem->setFlags(childItem->flags() | Qt::ItemIsEditable); root->addChild(childItem); setCurrentItem(childItem); } //----------------------------------------------------------------------------- void CastTreeViewer::rebuildCastTree() { clear(); ToonzScene *scene = TApp::instance()->getCurrentScene()->getScene(); QString rootName = QString("Root"); if (scene) { std::wstring name = (scene->isUntitled()) ? L"Untitled" : scene->getSceneName(); rootName = rootName.fromStdWString(name); } QTreeWidgetItem *root = new QTreeWidgetItem((QTreeWidgetItem *)0, QStringList(rootName)); static QIcon clapboard = createQIcon("clapboard"); root->setIcon(0, clapboard); insertTopLevelItem(0, root); populateFolder(root); } //----------------------------------------------------------------------------- QSize CastTreeViewer::sizeHint() const { return QSize(100, 100); } //----------------------------------------------------------------------------- void CastTreeViewer::paintEvent(QPaintEvent *event) { QTreeWidget::paintEvent(event); QPainter p(viewport()); if (m_dropTargetItem) { p.setPen(QColor(50, 105, 200)); p.drawRect(visualItemRect(m_dropTargetItem).adjusted(0, 0, -1, 0)); } } //----------------------------------------------------------------------------- void CastTreeViewer::dragEnterEvent(QDragEnterEvent *e) { m_dropFilePath = TFilePath(); if (acceptResourceOrFolderDrop(e->mimeData()->urls())) { if (e->mimeData()->urls().size() != 1) return; TFilePath path(e->mimeData()->urls()[0].toLocalFile().toStdWString()); if (path.getType() == "tnz") m_dropFilePath = path; else return; } if (!e->mimeData()->hasFormat("application/vnd.toonz.levels") && m_dropFilePath == TFilePath()) return; m_dropTargetItem = itemAt(e->pos()); if (m_dropTargetItem && m_dropTargetItem->data(0, Qt::DisplayRole).toString() == AudioFolderName) m_dropTargetItem = 0; e->acceptProposedAction(); viewport()->update(); } //----------------------------------------------------------------------------- void CastTreeViewer::dragMoveEvent(QDragMoveEvent *event) { if (!event->mimeData()->hasFormat("application/vnd.toonz.levels") || m_dropFilePath != TFilePath()) return; m_dropTargetItem = itemAt(event->pos()); ToonzScene *scene = TApp::instance()->getCurrentScene()->getScene(); QString rootName = QString("Root"); if (scene) { std::wstring name = (scene->isUntitled()) ? L"Untitled" : scene->getSceneName(); rootName = rootName.fromStdWString(name); } if ((m_dropTargetItem && m_dropTargetItem->data(0, Qt::DisplayRole).toString() == AudioFolderName) || (m_dropFilePath != TFilePath() && m_dropTargetItem->data(0, Qt::DisplayRole).toString() == rootName)) m_dropTargetItem = 0; if (!m_dropTargetItem) event->ignore(); else event->acceptProposedAction(); viewport()->update(); } //----------------------------------------------------------------------------- void CastTreeViewer::dropEvent(QDropEvent *event) { m_dropTargetItem = 0; if (m_dropFilePath != TFilePath()) { IoCmd::loadScene(m_dropFilePath); m_dropFilePath = TFilePath(); m_dropTargetItem = 0; update(); return; } if (!event->mimeData()->hasFormat("application/vnd.toonz.levels")) return; m_dropTargetItem = itemAt(event->pos()); if (!m_dropTargetItem) return; TFilePath folderPath( m_dropTargetItem->data(1, Qt::DisplayRole).toString().toStdWString()); m_dropTargetItem = 0; update(); if (folderPath.getName() == AudioFolderName) { event->ignore(); return; } event->acceptProposedAction(); TLevelSet *levelSet = getLevelSet(); const CastItems *castItems = dynamic_cast<const CastItems *>(event->mimeData()); assert(castItems); if (!castItems) return; int i; TUndoManager::manager()->beginBlock(); for (i = 0; i < castItems->getItemCount(); i++) { CastItem *item = castItems->getItem(i); if (LevelCastItem *li = dynamic_cast<LevelCastItem *>(item)) { TXshLevel *level = li->getLevel(); std::wstring levelName = level->getName(); MoveLevelToFolderUndo *undo = new MoveLevelToFolderUndo(levelSet, levelName, folderPath); levelSet->moveLevelToFolder(folderPath, level); TUndoManager::manager()->add(undo); } else if (SoundCastItem *si = dynamic_cast<SoundCastItem *>(item)) { } } TUndoManager::manager()->endBlock(); emit itemMovedToFolder(); } //----------------------------------------------------------------------------- void CastTreeViewer::dragLeaveEvent(QDragLeaveEvent *event) { m_dropTargetItem = 0; m_dropFilePath = TFilePath(); update(); } //----------------------------------------------------------------------------- void CastTreeViewer::onItemChanged(QTreeWidgetItem *item, int column) { if (column != 0) return; if (item->isSelected()) { TFilePath oldPath(item->data(1, Qt::DisplayRole).toString().toStdWString()); TFilePath newPath = getLevelSet()->renameFolder(oldPath, item->text(0).toStdWString()); item->setText(1, QString::fromStdWString(newPath.getWideString())); } } //----------------------------------------------------------------------------- TFilePath CastTreeViewer::getCurrentFolder() const { if (!currentItem()) return TFilePath(); QVariant data = currentItem()->data(1, Qt::DisplayRole); if (data == QVariant()) return TFilePath(); return TFilePath(data.toString().toStdWString()); } //----------------------------------------------------------------------------- void CastTreeViewer::folderUp() { QTreeWidgetItem *item = currentItem(); if (item && item->parent() != (QTreeWidgetItem *)0) setCurrentItem(item->parent()); } //----------------------------------------------------------------------------- void CastTreeViewer::newFolder() { QTreeWidgetItem *parentItem = currentItem(); if (parentItem == (QTreeWidgetItem *)0) return; QString parentName = parentItem->data(0, Qt::DisplayRole).toString(); if (parentName == AudioFolderName) return; TFilePath parentPath = TFilePath(parentItem->data(1, Qt::DisplayRole).toString().toStdWString()); QString childName("New Folder"); TFilePath childPath = parentPath + childName.toStdWString(); QString childPathQstr = QString::fromStdWString(childPath.getWideString()); QTreeWidgetItem *childItem = new QTreeWidgetItem(parentItem, QStringList(childName) << childPathQstr); childItem->setFlags(childItem->flags() | Qt::ItemIsEditable); parentItem->addChild(childItem); setCurrentItem(childItem); editItem(childItem); TLevelSet *levelSet = TApp::instance()->getCurrentScene()->getScene()->getLevelSet(); levelSet->createFolder(parentPath, childName.toStdWString()); TApp::instance()->getCurrentScene()->setDirtyFlag(true); } //----------------------------------------------------------------------------- void CastTreeViewer::deleteFolder() { QTreeWidgetItem *item = currentItem(); if (!item || !item->parent()) return; QString itemName = item->data(0, Qt::DisplayRole).toString(); if (itemName == AudioFolderName) return; int ret = DVGui::MsgBox(tr("Delete folder ") + item->text(0) + "?", tr("Yes"), tr("No"), 1); if (ret == 2 || ret == 0) return; QTreeWidgetItem *parentItem = item->parent(); TFilePath childPath(item->data(1, Qt::DisplayRole).toString().toStdWString()); TLevelSet *levelSet = TApp::instance()->getCurrentScene()->getScene()->getLevelSet(); levelSet->removeFolder(childPath); TApp::instance()->getCurrentScene()->setDirtyFlag(true); parentItem->removeChild(item); setCurrentItem(parentItem); } //============================================================================= // // CastBrowser // //----------------------------------------------------------------------------- #if QT_VERSION >= 0x050500 CastBrowser::CastBrowser(QWidget *parent, Qt::WindowFlags flags) #else CastBrowser::CastBrowser(QWidget *parent, Qt::WFlags flags) #endif : QSplitter(parent) , m_treeViewer(0) , m_folderName(0) , m_itemViewer(0) , m_castItems(new CastItems()) { // style sheet setObjectName("CastBrowser"); setFrameStyle(QFrame::StyledPanel); m_treeViewer = new CastTreeViewer(this); m_treeViewer->resize(300, m_treeViewer->size().height()); QFrame *box = new QFrame(this); box->setFrameStyle(QFrame::StyledPanel); QVBoxLayout *boxLayout = new QVBoxLayout(box); boxLayout->setMargin(0); boxLayout->setSpacing(0); m_folderName = new QLabel("", box); m_folderName->setObjectName("CastBrowserFolderName"); m_folderName->setFrameStyle(QFrame::Box); m_itemViewer = new DvItemViewer(box, false, true, DvItemViewer::Cast); DvItemViewerPanel *viewerPanel = m_itemViewer->getPanel(); viewerPanel->setMissingTextColor(QColor(200, 0, 0)); CastSelection *castSelection = new CastSelection(); castSelection->setBrowser(this); viewerPanel->setSelection(castSelection); viewerPanel->addColumn(DvItemListModel::FrameCount, 50); m_itemViewer->setModel(this); DvItemViewerTitleBar *titleBar = new DvItemViewerTitleBar(m_itemViewer, box); // titleBar->hide(); DvItemViewerButtonBar *buttonBar = new DvItemViewerButtonBar(m_itemViewer, box); boxLayout->addWidget(m_folderName); boxLayout->addWidget(titleBar); boxLayout->addWidget(m_itemViewer); boxLayout->addWidget(buttonBar); boxLayout->setAlignment(buttonBar, Qt::AlignBottom); box->setLayout(boxLayout); addWidget(m_treeViewer); addWidget(box); setStretchFactor(1, 2); TSceneHandle *sceneHandle = TApp::instance()->getCurrentScene(); connect(sceneHandle, SIGNAL(sceneSwitched()), this, SLOT(refresh())); connect(sceneHandle, SIGNAL(castChanged()), this, SLOT(refresh())); TXsheetHandle *xhseetHandle = TApp::instance()->getCurrentXsheet(); connect(xhseetHandle, SIGNAL(xsheetChanged()), m_itemViewer, SLOT(update())); connect(buttonBar, SIGNAL(folderUp()), m_treeViewer, SLOT(folderUp())); connect(buttonBar, SIGNAL(newFolder()), m_treeViewer, SLOT(newFolder())); connect(m_treeViewer, SIGNAL(currentItemChanged(QTreeWidgetItem *, QTreeWidgetItem *)), this, SLOT(folderChanged(QTreeWidgetItem *, QTreeWidgetItem *))); connect(m_treeViewer, SIGNAL(itemMovedToFolder()), this, SLOT(refresh())); } //----------------------------------------------------------------------------- CastBrowser::~CastBrowser() {} //----------------------------------------------------------------------------- void CastBrowser::sortByDataModel(DataType dataType, bool isDiscendent) { if (dataType != getCurrentOrderType()) { // Sort by another dataType int i; for (i = 1; i < m_castItems->getItemCount(); i++) { int index = i; while (index > 0 && compareData(dataType, index - 1, index) > 0) { m_castItems->swapItem(index - 1, index); index = index - 1; } } setIsDiscendentOrder(true); setOrderType(dataType); } // Sort by order (invert current) if (isDiscendentOrder() != isDiscendent) { setIsDiscendentOrder(isDiscendent); std::vector<CastItem *> items; for (int i = 0; i < m_castItems->getItemCount(); i++) items.push_back(m_castItems->getItem(i)->clone()); m_castItems->clear(); for (int i = items.size() - 1; i >= 0; i--) m_castItems->addItem(items[i]); } m_itemViewer->getPanel()->update(); } //----------------------------------------------------------------------------- void CastBrowser::folderChanged(QTreeWidgetItem *current, QTreeWidgetItem *previous) { refresh(); } //----------------------------------------------------------------------------- void CastBrowser::refresh() { if (isHidden()) return; refreshData(); m_itemViewer->refresh(); } //----------------------------------------------------------------------------- /* void CastBrowser::getLevels(std::vector<TXshLevel*> &levels) const { TLevelSet *levelSet = CastTreeViewer::getLevelSet(); TFilePath folder = m_treeViewer->getCurrentFolder(); if(folder != TFilePath()) levelSet->listLevels(levels, folder); else levelSet->listLevels(levels); } */ //----------------------------------------------------------------------------- void CastBrowser::refreshData() { m_castItems->clear(); TLevelSet *levelSet = CastTreeViewer::getLevelSet(); TFilePath folder = m_treeViewer->getCurrentFolder(); m_folderName->setText(toQString(folder)); std::vector<TXshLevel *> levels; if (folder != TFilePath()) levelSet->listLevels(levels, folder); else levelSet->listLevels(levels); int i; for (i = 0; i < (int)levels.size(); i++) { if (levels[i]->getSimpleLevel()) m_castItems->addItem(new LevelCastItem( levels[i], m_itemViewer->getPanel()->getIconSize())); else if (levels[i]->getPaletteLevel()) m_castItems->addItem( new PaletteCastItem(levels[i]->getPaletteLevel(), m_itemViewer->getPanel()->getIconSize())); else if (levels[i]->getSoundLevel()) m_castItems->addItem(new SoundCastItem( levels[i]->getSoundLevel(), m_itemViewer->getPanel()->getIconSize())); } } //----------------------------------------------------------------------------- int CastBrowser::getItemCount() const { return m_castItems->getItemCount(); } //----------------------------------------------------------------------------- QVariant CastBrowser::getItemData(int index, DataType dataType, bool isSelected) { if (index < 0 || index >= getItemCount()) return QVariant(); CastItem *item = m_castItems->getItem(index); if (dataType == Name) return item->getName(); else if (dataType == Thumbnail) return item->getPixmap(isSelected); else if (dataType == ToolTip) return item->getToolTip(); else if (dataType == FrameCount) return item->getFrameCount(); else if (dataType == VersionControlStatus) { if (!item->exists()) return VC_Missing; else return 0; // No version control status displayed } else return QVariant(); } //----------------------------------------------------------------------------- /* TXshSimpleLevel *CastBrowser::getSelectedSimpleLevel() const { const std::set<int> &indices = m_itemViewer->getSelectedIndices(); if(indices.empty()) return 0; int index = *indices.begin(); std::vector<TXshLevel*> levels; getLevels(levels); if(index<0 || index>=(int)levels.size()) return 0; TXshLevel*level = levels[index]; if(!level) return 0; else return level->getSimpleLevel(); } */ //----------------------------------------------------------------------------- void CastBrowser::startDragDrop() { TRepetitionGuard guard; if (!guard.hasLock()) return; const std::set<int> &indices = m_itemViewer->getSelectedIndices(); if (indices.empty()) return; QDrag *drag = new QDrag(this); QVariant v = getItemData(*indices.begin(), Thumbnail); if (v != QVariant()) { QPixmap dropThumbnail = v.value<QPixmap>(); if (!dropThumbnail.isNull()) drag->setPixmap(dropThumbnail); } drag->setMimeData(m_castItems->getSelectedItems(indices)); Qt::DropAction dropAction = drag->exec(Qt::CopyAction | Qt::MoveAction); } //----------------------------------------------------------------------------- bool CastBrowser::acceptDrop(const QMimeData *data) const { return acceptResourceOrFolderDrop(data->urls()); } //----------------------------------------------------------------------------- bool CastBrowser::drop(const QMimeData *data) { if (!acceptDrop(data)) return false; if (data->hasUrls()) { IoCmd::LoadResourceArguments args; for (const QUrl &url : data->urls()) { TFilePath fp(url.toLocalFile().toStdWString()); args.resourceDatas.push_back(fp); } args.castFolder = m_treeViewer->getCurrentFolder(); IoCmd::loadResources(args); } refresh(); return true; } //----------------------------------------------------------------------------- QMenu *CastBrowser::getContextMenu(QWidget *parent, int index) { const std::set<int> &indices = m_itemViewer->getSelectedIndices(); if (indices.empty()) { QMenu *menu = new QMenu(parent); menu->addAction(CommandManager::instance()->getAction(MI_RemoveUnused)); return menu; } // controllo cosa c'e' nella selezione. // => audioSelected, vectorLevelSelected, paletteSelected std::set<int>::const_iterator it; bool audioSelected = false; bool paletteSelected = false; bool vectorLevelSelected = false; bool meshLevelSelected = false; bool otherFileSelected = false; int levelSelectedCount = 0; for (it = indices.begin(); it != indices.end(); ++it) { int index = *it; if (index < 0 || index >= m_castItems->getItemCount()) continue; // non dovrebbe mai succedere TXshSimpleLevel *sl = m_castItems->getItem(index)->getSimpleLevel(); if (!sl) { if (m_castItems->getItem(index)->getPaletteLevel()) paletteSelected = true; else audioSelected = true; continue; } levelSelectedCount++; if (sl->getType() == PLI_XSHLEVEL) vectorLevelSelected = true; else if (sl->getType() == MESH_XSHLEVEL) meshLevelSelected = true; else otherFileSelected = true; } QMenu *menu = new QMenu(parent); CommandManager *cm = CommandManager::instance(); menu->addAction(cm->getAction(MI_LevelSettings)); menu->addAction(cm->getAction(MI_ExposeResource)); menu->addAction(cm->getAction(MI_ShowFolderContents)); if (!audioSelected && !paletteSelected && !meshLevelSelected) menu->addAction(cm->getAction(MI_ViewFile)); menu->addAction(cm->getAction(MI_FileInfo)); // MI_EditLevel solo se e' stato selezionato un singolo diverso da livelli // palette a livelli audio if (indices.size() == 1 && !audioSelected && !paletteSelected) menu->addAction(cm->getAction(MI_EditLevel)); if (!paletteSelected) menu->addAction(cm->getAction(MI_SaveLevel)); menu->addSeparator(); // MI_ConvertToVectors se sono stati selezionati solo livelli non vettoriali if (!audioSelected && !paletteSelected && !vectorLevelSelected) menu->addAction(cm->getAction(MI_ConvertToVectors)); menu->addSeparator(); menu->addAction(cm->getAction(MI_RemoveLevel)); menu->addAction(cm->getAction(MI_RemoveUnused)); return menu; } //----------------------------------------------------------------------------- void CastBrowser::expose() { std::set<int> selectedIndices = m_itemViewer->getPanel()->getSelectedIndices(); TUndoManager::manager()->beginBlock(); for (int index : selectedIndices) { CastItem *item = m_castItems->getItem(index); TXshSimpleLevel *sl = item->getSimpleLevel(); TXshPaletteLevel *pl = item->getPaletteLevel(); TXshSoundLevel *soundl = item->getSoundLevel(); if (sl) FilmstripCmd::moveToScene(sl); else if (pl) FilmstripCmd::moveToScene(pl); else if (soundl) FilmstripCmd::moveToScene(soundl); } TUndoManager::manager()->endBlock(); } //----------------------------------------------------------------------------- void CastBrowser::edit() { CastSelection *castSelection = dynamic_cast<CastSelection *>(TSelection::getCurrent()); if (!castSelection) return; std::vector<TXshLevel *> levels; castSelection->getSelectedLevels(levels); if ((int)levels.size() == 1) { TXshLevel *l = levels[0]; if (l) { TXshSimpleLevel *sl = l->getSimpleLevel(); if (sl) { TApp::instance()->getCurrentLevel()->setLevel(sl); return; } } error(tr("It is not possible to edit the selected file.")); } else error(tr("It is not possible to edit more than one file at once.")); } //----------------------------------------------------------------------------- void CastBrowser::showFolderContents() { int i = 0; CastSelection *castSelection = dynamic_cast<CastSelection *>(TSelection::getCurrent()); if (!castSelection) return; std::vector<TXshLevel *> levels; castSelection->getSelectedLevels(levels); ToonzScene *scene = TApp::instance()->getCurrentScene()->getScene(); TFilePath folderPath, filePath; for (i = 0; i < levels.size(); i++) { folderPath = levels[i]->getPath().getParentDir(); filePath = levels[i]->getPath(); folderPath = scene->decodeFilePath(folderPath); filePath = scene->decodeFilePath(filePath); if (!TSystem::doesExistFileOrLevel(filePath)) { error( tr("It is not possible to show the folder containing the selected " "file, as the file has not been saved yet.")); } else { if (TSystem::isUNC(folderPath)) QDesktopServices::openUrl( QUrl(QString::fromStdWString(folderPath.getWideString()))); else QDesktopServices::openUrl(QUrl::fromLocalFile( QString::fromStdWString(folderPath.getWideString()))); } } } //----------------------------------------------------------------------------- void CastBrowser::viewFile() { CastSelection *castSelection = dynamic_cast<CastSelection *>(TSelection::getCurrent()); if (!castSelection) return; std::vector<TXshLevel *> levels; castSelection->getSelectedLevels(levels); ToonzScene *scene = TApp::instance()->getCurrentScene()->getScene(); TFilePath filePath; if (levels.empty()) return; int i = 0; for (i = 0; i < levels.size(); i++) { filePath = levels[i]->getPath(); filePath = scene->decodeFilePath(filePath); if (!TSystem::doesExistFileOrLevel(filePath)) { error( tr("It is not possible to view the selected file, as the file has " "not been saved yet.")); } else { if (!TFileType::isViewable(TFileType::getInfo(filePath))) return; if (Preferences::instance()->isDefaultViewerEnabled() && (filePath.getType() == "mov" || filePath.getType() == "avi" || filePath.getType() == "3gp")) QDesktopServices::openUrl(QUrl("file:///" + toQString(filePath))); else ::viewFile(filePath); } } } //----------------------------------------------------------------------------- void CastBrowser::viewFileInfo() { CastSelection *castSelection = dynamic_cast<CastSelection *>(TSelection::getCurrent()); if (!castSelection) return; std::vector<TXshLevel *> levels; castSelection->getSelectedLevels(levels); ToonzScene *scene = TApp::instance()->getCurrentScene()->getScene(); int i = 0; if (levels.empty()) { return; } else { for (i = 0; i < levels.size(); i++) { TFilePath filePath; filePath = levels[i]->getPath(); filePath = scene->decodeFilePath(filePath); if (!TSystem::doesExistFileOrLevel(filePath)) { error( tr("It is not possible to show the info of the selected file, as " "the file has not been saved yet.")); } else { InfoViewer *infoViewer = 0; infoViewer = new InfoViewer(this); infoViewer->setItem(0, 0, filePath); } } } } //============================================================================= OpenFloatingPanel openCastPane(MI_OpenFileBrowser2, "SceneCast", QObject::tr("Scene Cast"));
c7059fc796feabcd3797eaae6c14f735086932cb
44e95837245e37af690c2a41089face0812f1aa5
/iothingies/spark/temphumid-push/temphumid-push.ino
a9544e8e2ae2c0ee8ed72b1821d018e77c8d44fd
[]
no_license
Nexus7/hardware
ab4a59ab27752a40c731f0d7b8dbbfe55c18ba0b
df39e62ada730b2277339111302ce2d4c6213ef3
refs/heads/master
2016-08-12T15:58:00.743091
2015-10-19T07:57:28
2015-10-19T07:57:28
44,516,941
0
0
null
null
null
null
UTF-8
C++
false
false
3,628
ino
temphumid-push.ino
// Device: Particle Core or Photon // Sensor: Thermocouple needs to be attached via Adafruit MAX31855 // Function: Testing out the push functionality from device to iothingies using http request // Tested: Not Tested #include "HttpClient/HttpClient.h" #include "Adafruit_MAX31855/Adafruit_MAX31855.h" #include "application.h" #include <math.h> #define DO 3 #define CS 4 #define CLK 5 Adafruit_MAX31855 thermocouple(CLK, CS, DO); #define TEMP_UNIT "C" // Rick Home IP #define METEOR_SERVER_IP "192.168.1.9" #define METEOR_SERVER_PORT 3000 // Hard code this device ID for now #define DEVICEID "67tCTgueyGXBAEg7p" HttpClient http; // Headers currently need to be set at init, useful for API keys etc. http_header_t headers[] = { { "Content-Type", "application/json" }, { NULL, NULL } // NOTE: Always terminate headers will NULL }; http_request_t request; http_response_t response; double tempC = 0; double humid = 0; unsigned int nextTime = 0; // Next time to contact the server void setup() { Serial.begin(9600); Particle.function("readTemps", readTemp); Particle.variable("temp", &tempC, DOUBLE); Particle.variable("humidity", &humid, DOUBLE); request.hostname = METEOR_SERVER_IP; request.port = METEOR_SERVER_PORT; } void loop() { if (nextTime > millis()) { return; } readTemp("Spark"); sendDataToCloud(); nextTime = millis() + 5000; } double readTemp(String input) { double internalTemp; double c; if (humid == 0) { humid = random(20,40); } else if (humid < 20) { humid = humid + random(0,5); } else if (humid > 40) { humid = humid + random(-5,0); } else { humid = humid + random (-1,1); } for (int i = 1; i <= 10; i++) { Serial.print("Internal Temp = "); c = thermocouple.readInternal(); Serial.println(thermocouple.readInternal()); internalTemp = c; double c = thermocouple.readCelsius(); if (isnan(c) and isnan(internalTemp)) { Serial.println("Something wrong with thermocouple!"); return 0; } else if (isnan(internalTemp)) { Serial.print("C = "); Serial.println(c); tempC = c; return c; } else { Serial.print("C = "); Serial.println(internalTemp); tempC = internalTemp; return internalTemp; } } Serial.println("Somebody trying to read temperature..."); Serial.print("temperature to be sent is "); Serial.println(tempC); return tempC; } void sendDataToCloud() { request.path = "/api/device/" + DEVICEID + "/data"; request.body = "{\"readings\": [{\"name\": \"humidity\", \"value\":" + String(humid) + "},{\"name\": \"temp\", \"value\": " + String(tempC) +"}]}"; Serial.println("REQUEST===================>"); Serial.println(request.body); Serial.println("=========================>"); http.post(request, response, headers); Serial.println("RESPONSE==================>"); Serial.println(response.body); Serial.println("=========================>"); } String twoChar(String input) { if (input.length() < 2) { return String("0" + input); } else { return String(input); } } String getCurrentTimeString() { String timeString = twoChar(String(Time.year())) + "-" + twoChar(String(Time.month())) + "-" + twoChar(String(Time.day())) + "T" + twoChar(String(Time.hour())) + ":" + twoChar(String(Time.minute())) + ":" + twoChar(String(Time.second())) + ".700Z"; return timeString; }
d6818fb1cc98294376b52a3d11890880d2f3ce9e
aab2d401b545f5bef00f931abcd39aef58e3a955
/heuristics.cpp
10be0da41c11f92055dad93df3fc1786f245949e
[]
no_license
DejanPopovic1/Rook
22c223b8db576ff67a17b90f6d71e6f1a91e5615
a6e701ae090a94962b0d1d3a3d9ba35aad2b4d44
refs/heads/master
2023-04-08T08:02:51.230079
2021-04-06T12:16:35
2021-04-06T12:16:35
331,443,245
0
0
null
null
null
null
UTF-8
C++
false
false
880
cpp
heuristics.cpp
#include "heuristics.hpp" #include "state.hpp" int evaluateWhiteMaterial(T_boardState *c){ return PAWN_VALUE*(__builtin_popcountll(c->wPawn)) + BISHOP_VALUE*(__builtin_popcountll(c->wBishop)) + KNIGHT_VALUE*(__builtin_popcountll(c->wKnight)) + ROOK_VALUE*(__builtin_popcountll(c->wRook)) + QUEEN_VALUE*(__builtin_popcountll(c->wQueen)) + KING_VALUE*(__builtin_popcountll(c->wKing)); } int evaluateBlackMaterial(T_boardState *c){ return PAWN_VALUE*(__builtin_popcountll(c->bPawn)) + BISHOP_VALUE*(__builtin_popcountll(c->bBishop)) + KNIGHT_VALUE*(__builtin_popcountll(c->bKnight)) + ROOK_VALUE*(__builtin_popcountll(c->bRook)) + QUEEN_VALUE*(__builtin_popcountll(c->bQueen)) + KING_VALUE*(__builtin_popcountll(c->bKing)); } int evaluateBoard(T_boardState *c){ return evaluateWhiteMaterial(c) - evaluateBlackMaterial(c); }
bf28f3783666ef8a12e6194b7d7c0d9cd3dd9282
0f54b1448e6b0374f8ddc5ab9e8fb09fd9592580
/Component.h
eddeab6769d35b4e9d66ce87579246446b42ea2f
[]
no_license
thomasqian/RHUD
3d1803f7386cfb2e8372c79a746e273e5f8c0c22
e02de0706004d315808329810c3d999bbaad4f8f
refs/heads/master
2021-06-06T22:20:15.209594
2016-09-17T00:18:18
2016-09-17T00:18:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,455
h
Component.h
#ifndef _COMPONENT_H_ #define _COMPONENT_H_ #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <vector> #include <string> using namespace cv; class Component { protected: const static int MIN_HEIGHT = 75; const static int MIN_WIDTH = 100; constexpr static float RESIZE_PERCENT = 0.05f; Mat gui; Point p1, p2; Size size; Scalar foreground; Scalar background; double opacity; bool locked; std::string data; void overlay(Mat& bg, const Mat& fg, Point p); public: Component(Point p1, Point p2, std::string data, Scalar fg, Scalar bg, double o=0.5, bool l=false); Component(Point p1, Size s, std::string data, Scalar fg, Scalar bg, double o=0.5, bool l=false); Component(); ~Component(); void draw(Mat& frame); bool containsPoint(int x, int y); bool inResizeZone(int x, int y); void setFrame(std::string file); Point getPoint(); void setPoint(Point p); void setPoint(double x, double y); void movePoint(double dx, double dy); Point getBottomRightPoint(); Size getSize(); void setSize(Size s); void setSize(double width, double height); void changeSize(double dw, double dh); void setOpacity(double o); void changeOpacity(double c); void lock(); void unlock(); void toggleLock(); void setForeground(Scalar c); void setBackground(Scalar c); }; #endif
ad1cef15dcbe4d24188ece0da5214e6bbdd361eb
16f8548d278a8954ba0eb19a0f68252f9cb0cdc4
/Cpp/90_subset_with_dup.cpp
ce546b87adf7c8c6fc0e959202ca6d02ad78fe7d
[]
no_license
Bolvvv/leetcode
8d7214a20acb4a5aabf5cf185c55eb268c19c820
f26dcdbecc8bfa9c9c39e946a7d6981179d2008a
refs/heads/master
2021-07-18T07:48:24.147887
2021-07-17T12:44:28
2021-07-17T12:44:28
156,241,163
0
0
null
null
null
null
UTF-8
C++
false
false
1,512
cpp
90_subset_with_dup.cpp
// // Created by bolvvv on 2021/7/17. // #include <vector> using namespace std; class Solution { public: //思路错误 // vector<vector<int>> subsetsWithDup(vector<int>& nums) { // vector<int> path; // vector<vector<int>> result; // result.push_back(path); // dfs(0, 0, path, nums, result); // return result; // } // void dfs(int tmp, int start, vector<int>& path, vector<int>& nums, vector<vector<int>>& result){ // if(tmp >= nums.size()){ // path.clear(); // start++; // if(start < nums.size()){ // dfs(start, start, path, nums, result); // } // else return; // } // path.push_back(nums[tmp]); // result.push_back(path); // dfs(tmp+1, start, path, nums, result); // } //官方实现 vector<int> t; vector<vector<int>> ans; void dfs(bool choosePre, int cur, vector<int>& nums){ if(cur == nums.size()){ ans.push_back(t); return; } dfs(false, cur + 1, nums); if(!choosePre && cur > 0 && nums[cur -1] == nums[cur]) return; t.push_back(nums[cur]); dfs(true, cur + 1, nums); t.pop_back(); } vector<vector<int>> subsetsWithDup(vector<int> &nums) { sort(nums.begin(), nums.end()); dfs(false, 0, nums); return ans; } }; int main(){ Solution solution; vector<int> nums = {1,2,2}; solution.subsetsWithDup(nums); }
ec1b13309a171b8d4429dfa9e59e65f9e6e771f3
7b257882453e1f5e21136c92f269b483b029bf2c
/Sources/Vehicles/Commands/VehicleCommandArm.h
41d93e43794a0f39286983d6c1a4b495e9557895
[]
no_license
Aliar1st/MAL-master
3c5eb36538a5cc7abde8b6e2e935bcec17858d15
7b9f68fe418fdda626c3ab9b1b4e8e672e0227a2
refs/heads/master
2023-04-07T16:18:26.055604
2021-04-06T12:51:26
2021-04-06T12:58:27
355,187,108
0
0
null
null
null
null
UTF-8
C++
false
false
288
h
VehicleCommandArm.h
#pragma once #include "VehicleCommand.h" /** * @brief Command to arm the MAVLink device */ class VehicleCommandArm : public VehicleCommand { protected: virtual Vehicle_Command_Execution_Result execute(Vehicle* vehicle) override; public: virtual const char* GetName() override; };
74c0e1efe41863e309ac33a20a53e3f601114ef6
3a949925bb3eee9373d391142025aaae3ac007a1
/StringStream.cpp
6adf5867b39e481df7267835b96ecca0b184a6c6
[]
no_license
miloudbelaabed/hackerrank
59b9b4959356c478a306ec61a3f4fb057136dbe7
316db6ab5e275cf5503b688df118805fdd027f8e
refs/heads/master
2023-02-11T00:24:15.869775
2020-12-31T09:30:07
2020-12-31T09:30:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,413
cpp
StringStream.cpp
#include <iostream> #include <vector> #include <sstream> #include <string> using namespace std; vector<int> parseInts2(string str) { vector<int>parser; string conca = ""; str=str+'e'; for (size_t i=0;i<str.length();i++) { if ((str[i]==',') || (i == str.size()-1)){ stringstream geek(conca); int x; geek >> x; parser.push_back(x); conca =""; }else { conca+=str[i]; } } } vector<int> parseInts(string str) { vector<char>p; vector<int>parser; for (size_t i=0;i<str.length();i++) { if (str[i]==','){ string conca = ""; for (auto i:p) { conca+=i; p.pop_back(); } stringstream geek(conca); int x; geek >> x; parser.push_back(x); }else{ if(i == str.size()-1){ p.push_back(str[i]); string conca = ""; for (auto i:p){ conca+=i; p.pop_back(); } stringstream geek(conca); int x; geek >> x; parser.push_back(x); }else p.push_back(str[i]); } } return parser; } int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); #ifndef ONLINE_JUDGE freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); #endif string str; cin >> str; vector<int> integers = parseInts(str); for(int i = 0; i < integers.size(); i++) { cout << integers[i] << "\n"; } return 0; }
5d9a80751d01742b53b498fd5100b3cd0dbe5177
714af7612c2adb201efe0f024dbf1a8dcfed38f8
/src/Track.cpp
fca9e52c22e6a2c0c159924ac317ee40581e8b0b
[]
no_license
Athos06/CyberVS
95f5a76550f7546a1f74e50719fe0e7d1ae043db
f4b3e6712488989fcd365d6e87f70e4e8230abdb
refs/heads/master
2020-03-17T03:12:36.643235
2018-05-13T10:08:05
2018-05-13T10:08:05
133,225,359
0
0
null
null
null
null
UTF-8
C++
false
false
5,031
cpp
Track.cpp
#include <OgreArchive.h> #include <OgreResourceGroupManager.h> #include <OgreLogManager.h> #include "Track.h" Track::Track (Ogre::ResourceManager * pManager, const Ogre::String & resource_name, Ogre::ResourceHandle handle, const Ogre::String & resource_group, bool manual_load, Ogre::ManualResourceLoader * pLoader): // Delegamos en el constructor de Ogre::Resource... Ogre::Resource (pManager, resource_name, handle, resource_group, manual_load, pLoader) { // Creación del tipo de recurso. createParamDictionary ("Track"); _pTrack = 0; _size = 0; m_Volume = 100; } Track::~Track () { // unload() delega en unloadImpl(). unload (); } void Track::loadImpl () // Carga del recurso. { Ogre::LogManager * pLogManager = Ogre::LogManager::getSingletonPtr (); // Ruta al archivo. Ogre::FileInfoListPtr info; info = Ogre::ResourceGroupManager::getSingleton ().findResourceFileInfo (mGroup, mName); for (Ogre::FileInfoList::const_iterator i = info->begin (); i != info->end (); ++i) _path = i->archive->getName () + "/" + i->filename; // Archivo no encontrado... if (_path == "") { pLogManager-> logMessage ("Track::loadImpl() Imposible cargar el recurso de sonido."); throw (Ogre:: Exception (Ogre::Exception::ERR_FILE_NOT_FOUND, "Archivo no encontrado", "Track::loadImpl()")); } // Cargar el recurso de sonido. if ((_pTrack = Mix_LoadMUS (_path.c_str ())) == NULL) { pLogManager-> logMessage ("Track::loadI() Imposible cargar el recurso de sonido."); throw (Ogre:: Exception (Ogre::Exception::ERR_FILE_NOT_FOUND, "Archivo no encontrado", "Track::loadI()")); } // Cálculo del tamaño del recurso de sonido. std::ifstream stream; char byteBuffer; stream.open (_path.c_str (), std::ios_base::binary); while (stream >> byteBuffer) _size++; stream.close (); } void Track::unloadImpl () { if (_pTrack) // Liberar el recurso de sonido. Mix_FreeMusic (_pTrack); } size_t Track::calculateSize () const { return _size; } void Track::play (int loop) { Ogre::LogManager * pLogManager = Ogre::LogManager::getSingletonPtr (); if (Mix_PausedMusic ()) // Estaba pausada? Mix_ResumeMusic (); // Reanudación. // Si no, se reproduce desde el principio. else { if (Mix_PlayMusic (_pTrack, loop) == -1) { pLogManager-> logMessage ("Track::play() Error al reproducir el recurso de sonido."); throw (Ogre:: Exception (Ogre::Exception::ERR_FILE_NOT_FOUND, "Imposible reproducir el recurso de sonido", "Track::play()")); } } } void Track::pause () { Mix_PauseMusic (); } void Track::stop () { Mix_HaltMusic (); } void Track::volume(int vol){ if(vol>100){ m_Volume=100; } else{ if(vol<0){ m_Volume=0; } else{ m_Volume = vol; } } Mix_VolumeMusic(m_Volume); } // Fachada de MixFadeInMusic() void Track::fadeIn (int ms, int loop) { Ogre::LogManager * pLogManager = Ogre::LogManager::getSingletonPtr (); if (Mix_FadeInMusic (_pTrack, ms, loop) == -1) { pLogManager-> logMessage ("Track::fadeIn() Error al aplicar efecto de sonido."); throw (Ogre:: Exception (Ogre::Exception::ERR_INTERNAL_ERROR, "Imposible aplicar suavizado de sonido", "Track::fadeIn()")); } } // Fachada de MixFadeOutMusic() void Track::fadeOut (int ms) { Ogre::LogManager * pLogManager = Ogre::LogManager::getSingletonPtr (); if (Mix_FadeOutMusic (ms) == -1) { pLogManager-> logMessage ("Track::fadeIn() Error al aplicar efecto de sonido."); throw (Ogre:: Exception (Ogre::Exception::ERR_INTERNAL_ERROR, "Imposible aplicar suavizado de sonido", "Track::fadeIn()")); } } bool Track::isPlaying () { if (Mix_PlayingMusic ()) return true; else return false; } TrackPtr::TrackPtr (const Ogre::ResourcePtr & resource): Ogre::SharedPtr < Track > () { // Comprobar la validez del recurso. if (resource.isNull ()) return; // Para garantizar la exclusión mutua... OGRE_LOCK_MUTEX (*resource.OGRE_AUTO_MUTEX_NAME) OGRE_COPY_AUTO_SHARED_MUTEX (resource.OGRE_AUTO_MUTEX_NAME) pRep = static_cast < Track * >(resource.getPointer ()); pUseCount = resource.useCountPointer (); useFreeMethod = resource.freeMethod (); // Incremento del contador de referencias. if (pUseCount) ++(*pUseCount); } TrackPtr & TrackPtr::operator= (const Ogre::ResourcePtr & resource) { if (pRep == static_cast < Track * >(resource.getPointer ())) return *this; release (); if (resource.isNull ()) return *this; OGRE_LOCK_MUTEX (*resource.OGRE_AUTO_MUTEX_NAME) OGRE_COPY_AUTO_SHARED_MUTEX (resource.OGRE_AUTO_MUTEX_NAME) pRep = static_cast < Track * >(resource.getPointer ()); pRep = static_cast < Track * >(resource.getPointer ()); pUseCount = resource.useCountPointer (); useFreeMethod = resource.freeMethod (); if (pUseCount) ++(*pUseCount); return *this; }
e826f3e2a08898d2109e1b0f361a6b428dc5db6d
a07d1ae886800fe3758203683d6067089322b78c
/src/backends/reference/workloads/RefPadWorkload.hpp
b1de53e9300be2758050fa1d6819da9a85220a87
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
oubotong/arm-secure-nn-1
7a896f15e20636493a485b5a8ea71081bb8af12a
a92eba03be9a4df62f21d2494869e74b44de3364
refs/heads/master
2023-03-17T17:22:54.972293
2020-04-14T14:36:58
2020-04-14T14:36:58
557,095,350
1
0
MIT
2022-10-25T04:11:50
2022-10-25T04:11:49
null
UTF-8
C++
false
false
947
hpp
RefPadWorkload.hpp
// // Copyright © 2017 Arm Ltd. All rights reserved. // SPDX-License-Identifier: MIT // #pragma once #include <backendsCommon/Workload.hpp> #include <backendsCommon/WorkloadData.hpp> #include <armnn/TypesUtils.hpp> namespace armnn { template <armnn::DataType DataType> class RefPadWorkload : public TypedWorkload<PadQueueDescriptor, DataType> { public: static const std::string& GetName() { static const std::string name = std::string("RefPad") + GetDataTypeName(DataType) + "Workload"; return name; } using TypedWorkload<PadQueueDescriptor, DataType>::m_Data; using TypedWorkload<PadQueueDescriptor, DataType>::TypedWorkload; void Execute() const override; }; using RefPadFloat32Workload = RefPadWorkload<DataType::Float32>; using RefPadQAsymm8Workload = RefPadWorkload<DataType::QuantisedAsymm8>; using RefPadQSymm16Workload = RefPadWorkload<DataType::QuantisedSymm16>; } //namespace armnn
645df899ea287c89124783ea9883dd54f110d610
de46440266fe632768a686d1b945c75955577a89
/d04/ex03/MateriaSource.hpp
e8bf3655514bf425b0623d6191dd04366eb2a70a
[]
no_license
dylanmpeck/CPP-Piscine
b9deab0f1055f1430c34b984ef7d3ae8dacbbd4d
b6822127588bd7ec4d3451b28a3838b4712ef50b
refs/heads/master
2020-06-11T15:00:17.746351
2019-06-29T02:35:49
2019-06-29T02:35:49
194,005,025
0
0
null
null
null
null
UTF-8
C++
false
false
1,357
hpp
MateriaSource.hpp
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* MateriaSource.hpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dpeck <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/05/04 12:29:57 by dpeck #+# #+# */ /* Updated: 2019/05/04 12:30:14 by dpeck ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef MATERIASOURCE_HPP #define MATERIASOURCE_HPP #include "IMateriaSource.hpp" class MateriaSource : public IMateriaSource { private: AMateria *_knownMateria[4]; int _materiaCount; public: MateriaSource(); ~MateriaSource(); MateriaSource(MateriaSource const &); MateriaSource const & operator=(MateriaSource const &); void learnMateria(AMateria * m); AMateria *createMateria(std::string const & type); }; #endif
fcfc0175e95b632eeabd06b5f174ac6a7c4b590c
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/squid/gumtree/squid_repos_function_3374_squid-3.3.14.cpp
846a255067f6453703f5d6c0ab89a73596efc077
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
563
cpp
squid_repos_function_3374_squid-3.3.14.cpp
void clientReplyContext::sendClientUpstreamResponse() { StoreIOBuffer tempresult; removeStoreReference(&old_sc, &old_entry); /* here the data to send is the data we just received */ tempBuffer.offset = 0; old_reqsize = 0; /* sendMoreData tracks the offset as well. * Force it back to zero */ reqofs = 0; assert(!EBIT_TEST(http->storeEntry()->flags, ENTRY_ABORTED)); /* TODO: provide sendMoreData with the ready parsed reply */ tempresult.length = reqsize; tempresult.data = tempbuf; sendMoreData(tempresult); }
1af10c65d89f0c3ea9a2265a5d0451450a929681
98f9f977a39843e5f7719062f43011ebfd169e42
/Libs/Core/ctkModelTester.h
d287132976355cbb41bebca1aeae58e56b2d5303
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
txdy077345/CTK
71cab2d77193d09340afe7a50e5dddc3ea66a06d
7cd253376139ea73f0450e1bad75bab41aa1b507
refs/heads/master
2023-05-27T19:20:21.825916
2023-04-29T16:35:03
2023-04-29T16:35:03
276,658,777
1
0
Apache-2.0
2020-07-02T13:50:30
2020-07-02T13:50:29
null
UTF-8
C++
false
false
6,374
h
ctkModelTester.h
/*========================================================================= Library: CTK Copyright (c) Kitware Inc. 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.txt Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =========================================================================*/ #ifndef __ctkModelTester_h #define __ctkModelTester_h /// Qt includes #include <QObject> #include <QModelIndex> #include <QPersistentModelIndex> #include <QList> /// CTK includes #include "ctkPimpl.h" #include "ctkCoreExport.h" class QAbstractItemModel; class ctkModelTesterPrivate; /// \ingroup Core /// ctkModelTester is a tool that tests any QAbstractItemModel /// Most of the signals fired by the model set (ctkModelTester::setModel()) /// are connected to the tester that check their consistency with the /// model contents. /// ctkModelTester is typically used when developing a new QAbstractItemModel /// or during unit tests. class CTK_CORE_EXPORT ctkModelTester: public QObject { Q_OBJECT Q_PROPERTY(bool nestedInserts READ nestedInserts WRITE setNestedInserts); Q_PROPERTY(bool testDataEnabled READ testDataEnabled WRITE setTestDataEnabled); Q_PROPERTY(bool throwOnError READ throwOnError WRITE setThrowOnError); Q_PROPERTY(bool verbose READ verbose WRITE setVerbose); public: /// /// Constructor /// No model is set by default. To be tested, a model must be set using /// setModel(...) explicit ctkModelTester(QObject *parent = 0); /// /// Constructor that set the model to test. /// A new model can later be set using setModel(...) /// by default, throwOnError is true, /// nestedInsert is false, /// testDataEnabled is true, /// verbose is true. ctkModelTester(QAbstractItemModel *model, QObject *parent = 0); /// /// Destructor virtual ~ctkModelTester(); /// /// Set the model to be tested, the model must remain valid during /// the life ctkModelTester. void setModel(QAbstractItemModel* model); QAbstractItemModel* model()const; /// /// Throw an exception when an error is found in the model. /// True by default void setThrowOnError(bool throwException); bool throwOnError()const; /// /// nestedInserts controls whether the model is allowed to make /// nested row/column insertions ( an insertion signal is fired when an /// insertion a previous insertion was not finished). A row insertion /// consists of 2 signals: rowsAboutToBeInserted and rowsInserted /// It also applies for row/column suppressions. void setNestedInserts(bool enable); bool nestedInserts()const; /// /// When TestData is enabled, it checks if the display role of a valid /// model index is valid too. /// You can disable the test if you are ok with temporary invalid display /// roles. void setTestDataEnabled(bool enable); bool testDataEnabled()const; /// When Verbose is enabled, message will be printed to standard or error output. void setVerbose(bool enable); bool verbose()const; /// /// Test the data consistency of a QModelIndex. /// Note: Only DisplayRole is checked. virtual void testData(const QModelIndex& index)const; /// /// Run all the tests on the model previously set in setModel(...) virtual void testModel()const; /// /// Run a collection of tests on a QModelIndex virtual void testModelIndex(const QModelIndex& index)const; /// /// Check the hierarchy consistency of a QModelIndex /// child/parent/siblings relationships virtual void testParent(const QModelIndex& parent)const; /// /// Test a persistent model index virtual void testPersistentModelIndex(const QPersistentModelIndex& index)const; protected Q_SLOTS: void onColumnsAboutToBeInserted(const QModelIndex & parent, int start, int end); void onColumnsAboutToBeRemoved(const QModelIndex & parent, int start, int end); void onColumnsInserted(const QModelIndex & parent, int start, int end); void onColumnsRemoved(const QModelIndex & parent, int start, int end); void onDataChanged(const QModelIndex & topLeft, const QModelIndex & bottomRight); void onHeaderDataChanged(Qt::Orientation orientation, int first, int last); void onLayoutAboutToBeChanged(); void onLayoutChanged(); void onModelAboutToBeReset(); void onModelReset(); void onRowsAboutToBeInserted(const QModelIndex &parent, int start, int end); void onRowsAboutToBeRemoved(const QModelIndex &parent, int start, int end); void onRowsInserted(const QModelIndex & parent, int start, int end); void onRowsRemoved(const QModelIndex & parent, int start, int end); protected: /// /// The logic of onColumnsAboutToBeInserted and onRowsAboutToBeInserted is /// gathered in onItemsAboutToBeInserted virtual void onItemsAboutToBeInserted(const QModelIndex& parent, Qt::Orientation, int start, int end); /// /// The logic of onColumnsAboutToBeRemoved and onRowsAboutToBeRemoved is /// gathered in onItemsAboutToBeRemoved virtual void onItemsAboutToBeRemoved(const QModelIndex& parent, Qt::Orientation, int start, int end); /// /// The logic of onColumnsInserted and onRowsInserted is gathered in /// onItemsInserted virtual void onItemsInserted(const QModelIndex& parent, Qt::Orientation, int start, int end); /// /// The logic of onColumnsRemoved and onRowsRemoved is gathered in /// onItemsRemoved virtual void onItemsRemoved(const QModelIndex& parent, Qt::Orientation, int start, int end); /// /// Create a list of persistent index of all the index's children QList<QPersistentModelIndex> persistentModelIndexes(const QModelIndex& index)const; /// /// Utility function that process the result of a test virtual void test(bool result, const QString& errorString)const; protected: QScopedPointer<ctkModelTesterPrivate> d_ptr; private: Q_DECLARE_PRIVATE(ctkModelTester); Q_DISABLE_COPY(ctkModelTester); }; #endif
945da079ee106ad8d8430cf333746f2962ec17f9
b5a547a5fcfa417bd1c73d241d59d7918ddde668
/Examples/DnsSpoofing/main.cpp
268231a57e31d8366ca24f9a5b5b75bf74d98fc6
[ "Unlicense" ]
permissive
seladb/PcapPlusPlus
ae994498a11139753d320594e3aad2db6a31ab18
0725fa175ab2a7cb78a6c48d3b4d113eb7221810
refs/heads/master
2023-08-05T07:51:20.501998
2023-08-04T01:51:24
2023-08-04T01:51:24
24,911,519
2,464
700
Unlicense
2023-09-14T09:24:09
2014-10-07T21:04:05
C++
UTF-8
C++
false
false
13,645
cpp
main.cpp
/** * DNS spoofing example application * ================================ * This application does simple DNS spoofing. It's provided with interface name or IP and starts capturing DNS requests on that * interface. Each DNS request that matches is edited and turned into a DNS response with a user-provided IP address as the resolved IP. * Then it's sent back on the network on the same interface */ #include <vector> #include <iostream> #include <algorithm> #include <sstream> #include <utility> #include <map> #if !defined(_WIN32) #include <errno.h> #endif #include "IpAddress.h" #include "RawPacket.h" #include "ProtocolType.h" #include "Packet.h" #include "EthLayer.h" #include "IPv4Layer.h" #include "IPv6Layer.h" #include "UdpLayer.h" #include "DnsLayer.h" #include "PcapFilter.h" #include "PcapLiveDevice.h" #include "PcapLiveDeviceList.h" #include "TablePrinter.h" #include "SystemUtils.h" #include "PcapPlusPlusVersion.h" #include <getopt.h> #define EXIT_WITH_ERROR(reason) do { \ printUsage(); \ std::cout << std::endl << "ERROR: " << reason << std::endl << std::endl; \ exit(1); \ } while(0) static struct option DnsSpoofingOptions[] = { {"interface", required_argument, nullptr, 'i'}, {"spoof-dns-server", required_argument, nullptr, 'd'}, {"client-ip", required_argument, nullptr, 'c'}, {"host-list", required_argument, nullptr, 'o'}, {"help", no_argument, nullptr, 'h'}, {"version", no_argument, nullptr, 'v'}, {"list", no_argument, nullptr, 'l'}, {nullptr, 0, nullptr, 0} }; /** * A struct that holds all counters that are collected during application runtime */ struct DnsSpoofStats { int numOfSpoofedDnsRequests; std::map<std::string, int> spoofedHosts; DnsSpoofStats() : numOfSpoofedDnsRequests(0) {} }; /** * A struct that holds all arguments passed to handleDnsRequest() */ struct DnsSpoofingArgs { pcpp::IPAddress dnsServer; std::vector<std::string> dnsHostsToSpoof; DnsSpoofStats stats; bool shouldStop; DnsSpoofingArgs() : shouldStop(false) {} }; /** * Print application usage */ void printUsage() { std::cout << std::endl << "Usage:" << std::endl << "------" << std::endl << pcpp::AppName::get() << " [-hvl] [-o host1,host2,...,host_n] [-c ip_address] -i interface -d ip_address" << std::endl << std::endl << "Options:" << std::endl << std::endl << " -h : Displays this help message and exits" << std::endl << " -v : Displays the current version and exists" << std::endl << " -l : Print the list of available interfaces" << std::endl << " -i interface : The interface name or interface IP address to use." << std::endl << " Use the -l switch to see all interfaces" << std::endl << " -d ip_address : The IP address of the spoofed DNS server. Supports both IPv4 and IPv6" << std::endl << " (all responses will be sent with this IP address)" << std::endl << " -c ip_address : Spoof only DNS requests coming from a specific IP address" << std::endl << " -o host1,host2,...,host_n : A comma-separated list of hosts to spoof. If list is not given," << std::endl << " all hosts will be spoofed. If an host contains '*' all sub-domains" << std::endl << " will be spoofed, for example: if '*.google.com' is given" << std::endl << " then 'mail.google.com', 'tools.google.com', etc. will be spoofed" << std::endl << std::endl; } /** * Print application version */ void printAppVersion() { std::cout << pcpp::AppName::get() << " " << pcpp::getPcapPlusPlusVersionFull() << std::endl << "Built: " << pcpp::getBuildDateTime() << std::endl << "Built from: " << pcpp::getGitInfo() << std::endl; exit(0); } /** * Go over all interfaces and output their names */ void listInterfaces() { const std::vector<pcpp::PcapLiveDevice*>& devList = pcpp::PcapLiveDeviceList::getInstance().getPcapLiveDevicesList(); std::cout << std::endl << "Network interfaces:" << std::endl; for (std::vector<pcpp::PcapLiveDevice*>::const_iterator iter = devList.begin(); iter != devList.end(); iter++) { std::cout << " -> Name: '" << (*iter)->getName() << "' IP address: " << (*iter)->getIPv4Address().toString() << std::endl; } exit(0); } /** * The method that is called each time a DNS request is received. This methods turns the DNS request into a DNS response with the * spoofed information and sends it back to the network */ void handleDnsRequest(pcpp::RawPacket* packet, pcpp::PcapLiveDevice* dev, void* cookie) { DnsSpoofingArgs* args = (DnsSpoofingArgs*)cookie; // create a parsed packet from the raw packet pcpp::Packet dnsRequest(packet); if (!dnsRequest.isPacketOfType(pcpp::DNS) || !dnsRequest.isPacketOfType(pcpp::IP) || !dnsRequest.isPacketOfType(pcpp::UDP) || !dnsRequest.isPacketOfType(pcpp::Ethernet)) return; // extract all packet layers pcpp::EthLayer* ethLayer = dnsRequest.getLayerOfType<pcpp::EthLayer>(); pcpp::IPLayer* ipLayer = dnsRequest.getLayerOfType<pcpp::IPLayer>(); pcpp::UdpLayer* udpLayer = dnsRequest.getLayerOfType<pcpp::UdpLayer>(); pcpp::DnsLayer* dnsLayer = dnsRequest.getLayerOfType<pcpp::DnsLayer>(); // skip DNS requests with more than 1 request or with 0 requests if (dnsLayer->getDnsHeader()->numberOfQuestions != pcpp::hostToNet16(1) || dnsLayer->getFirstQuery() == nullptr) return; // skip DNS requests which are not of class IN and type A (IPv4) or AAAA (IPv6) pcpp::DnsType dnsType = (args->dnsServer.isIPv4()? pcpp::DNS_TYPE_A : pcpp::DNS_TYPE_AAAA); pcpp::DnsQuery* dnsQuery = dnsLayer->getFirstQuery(); if (dnsQuery->getDnsType() != dnsType || dnsQuery->getDnsClass() != pcpp::DNS_CLASS_IN) return; // empty dnsHostsToSpoof means spoofing all hosts if (!args->dnsHostsToSpoof.empty()) { bool hostMatch = false; // go over all hosts in dnsHostsToSpoof list and see if current query matches one of them for (std::vector<std::string>::iterator iter = args->dnsHostsToSpoof.begin(); iter != args->dnsHostsToSpoof.end(); iter++) { if (dnsLayer->getQuery(*iter, false) != nullptr) { hostMatch = true; break; } } if (!hostMatch) return; } // create a response out of the request packet // reverse src and dst MAC addresses pcpp::MacAddress srcMac = ethLayer->getSourceMac(); ethLayer->setSourceMac(ethLayer->getDestMac()); ethLayer->setDestMac(srcMac); // reverse src and dst IP addresses pcpp::IPAddress srcIP = ipLayer->getSrcIPAddress(); pcpp::IPv4Layer* ip4Layer = dynamic_cast<pcpp::IPv4Layer*>(ipLayer); pcpp::IPv6Layer* ip6Layer = dynamic_cast<pcpp::IPv6Layer*>(ipLayer); if (ip4Layer != nullptr) { ip4Layer->setSrcIPv4Address(ip4Layer->getDstIPv4Address()); ip4Layer->setDstIPv4Address(srcIP.getIPv4()); ip4Layer->getIPv4Header()->ipId = 0; } else { ip6Layer->setSrcIPv6Address(ip6Layer->getDstIPv6Address()); ip6Layer->setDstIPv6Address(srcIP.getIPv6()); } // reverse src and dst UDP ports uint16_t srcPort = udpLayer->getUdpHeader()->portSrc; udpLayer->getUdpHeader()->portSrc = udpLayer->getUdpHeader()->portDst; udpLayer->getUdpHeader()->portDst = srcPort; // add DNS response dnsLayer->getDnsHeader()->queryOrResponse = 1; if (args->dnsServer.isIPv4()) { pcpp::IPv4DnsResourceData dnsServer(args->dnsServer.getIPv4()); if (!dnsLayer->addAnswer(dnsQuery->getName(), pcpp::DNS_TYPE_A, pcpp::DNS_CLASS_IN, 1, &dnsServer)) return; } else { pcpp::IPv6DnsResourceData dnsServer(args->dnsServer.getIPv6()); if (!dnsLayer->addAnswer(dnsQuery->getName(), pcpp::DNS_TYPE_AAAA, pcpp::DNS_CLASS_IN, 1, &dnsServer)) return; } dnsRequest.computeCalculateFields(); // send DNS response back to the network if (!dev->sendPacket(&dnsRequest)) return; args->stats.numOfSpoofedDnsRequests++; args->stats.spoofedHosts[dnsQuery->getName()]++; } /** * An auxiliary method for sorting the string count map. Used for printing the summary of spoofed hosts */ bool stringCountComparer(const std::pair<std::string, int>& first, const std::pair<std::string, int>& second) { if (first.second == second.second) { return first.first > second.first; } return first.second > second.second; } /** * A callback for application interrupted event (ctrl+c): print DNS spoofing summary */ void onApplicationInterrupted(void* cookie) { DnsSpoofingArgs* args = (DnsSpoofingArgs*)cookie; if (args->stats.spoofedHosts.size() == 0) { std::cout << std::endl << "Application closing. No hosts were spoofed." << std::endl; } else { std::cout << std::endl << "Summary of spoofed hosts:" << std::endl << "-------------------------" << std::endl << std::endl << "Total spoofed: " << args->stats.numOfSpoofedDnsRequests << std::endl << "Number of host spoofed: " << args->stats.spoofedHosts.size() << std::endl << std::endl; // create a table std::vector<std::string> columnNames; columnNames.push_back("Host"); columnNames.push_back("# of times spoofed"); std::vector<int> columnsWidths; columnsWidths.push_back(40); columnsWidths.push_back(18); pcpp::TablePrinter printer(columnNames, columnsWidths); // sort the spoofed hosts map so the most spoofed hosts will be first // since it's not possible to sort a std::map you must copy it to a std::vector and sort it then std::vector<std::pair<std::string, int> > map2vec(args->stats.spoofedHosts.begin(), args->stats.spoofedHosts.end()); std::sort(map2vec.begin(),map2vec.end(), &stringCountComparer); // go over all items (hosts + count) in the sorted vector and print them for(std::vector<std::pair<std::string, int> >::iterator iter = map2vec.begin(); iter != map2vec.end(); iter++) { std::stringstream values; values << iter->first << "|" << iter->second; printer.printRow(values.str(), '|'); } } args->shouldStop = true; } /** * Activate DNS spoofing: prepare the device and start capturing DNS requests */ void doDnsSpoofing(pcpp::PcapLiveDevice* dev, const pcpp::IPAddress& dnsServer, const pcpp::IPAddress& clientIP, const std::vector<std::string> &dnsHostsToSpoof) { // open device if (!dev->open()) EXIT_WITH_ERROR("Cannot open capture device"); // set a filter to capture only DNS requests and client IP if provided pcpp::PortFilter dnsPortFilter(53, pcpp::DST); if (!clientIP.isValid()) { if (!dev->setFilter(dnsPortFilter)) EXIT_WITH_ERROR("Cannot set DNS filter for device"); } else { pcpp::IPFilter clientIpFilter(clientIP.toString(), pcpp::SRC); std::vector<pcpp::GeneralFilter*> filterForAnd; filterForAnd.push_back(&dnsPortFilter); filterForAnd.push_back(&clientIpFilter); pcpp::AndFilter andFilter(filterForAnd); if (!dev->setFilter(andFilter)) EXIT_WITH_ERROR("Cannot set DNS and client IP filter for device"); } // make args for callback DnsSpoofingArgs args; args.dnsServer = dnsServer; args.dnsHostsToSpoof = dnsHostsToSpoof; // start capturing DNS requests if (!dev->startCapture(handleDnsRequest, &args)) EXIT_WITH_ERROR("Cannot start packet capture"); // register the on app close event to print summary stats on app termination pcpp::ApplicationEventHandler::getInstance().onApplicationInterrupted(onApplicationInterrupted, &args); // run an endless loop until ctrl+c is pressed while (!args.shouldStop) { std::cout << "Spoofed " << args.stats.numOfSpoofedDnsRequests << " DNS requests so far" << std::endl; pcpp::multiPlatformSleep(5); } } /** * main method of the application */ int main(int argc, char* argv[]) { pcpp::AppName::init(argc, argv); int optionIndex = 0; int opt = 0; std::string interfaceNameOrIP; pcpp::IPAddress dnsServer; pcpp::IPAddress clientIP; bool clientIpSet = false; std::vector<std::string> hostList; while((opt = getopt_long(argc, argv, "i:d:c:o:hvl", DnsSpoofingOptions, &optionIndex)) != -1) { switch (opt) { case 0: { break; } case 'h': { printUsage(); exit(0); } case 'v': { printAppVersion(); break; } case 'l': { listInterfaces(); exit(0); } case 'i': { interfaceNameOrIP = optarg; break; } case 'd': { dnsServer = pcpp::IPAddress(static_cast<char const *>(optarg)); break; } case 'c': { clientIP = pcpp::IPAddress(static_cast<char const *>(optarg)); clientIpSet = true; break; } case 'o': { std::string input = optarg; std::istringstream stream(input); std::string token; while(std::getline(stream, token, ',')) hostList.push_back(token); break; } default: { printUsage(); exit(1); } } } pcpp::PcapLiveDevice* dev = nullptr; // check if interface argument is IP or name and extract the device if (interfaceNameOrIP.empty()) { EXIT_WITH_ERROR("Interface name or IP weren't provided. Please use the -i switch or -h for help"); } dev = pcpp::PcapLiveDeviceList::getInstance().getPcapLiveDeviceByIpOrName(interfaceNameOrIP); if (dev == nullptr) EXIT_WITH_ERROR("Couldn't find interface by provided IP address or name"); // verify DNS server IP is a valid IPv4 address if (dnsServer == pcpp::IPv4Address::Zero || !dnsServer.isValid()) EXIT_WITH_ERROR("Spoof DNS server IP provided is empty or not a valid IPv4 address"); // verify client IP is valid if set if (clientIpSet && !clientIP.isValid()) EXIT_WITH_ERROR("Client IP to spoof is invalid"); doDnsSpoofing(dev, dnsServer, clientIP, hostList); }
e4ef2ad7bd4fecd0281ea45f91d0109a8ef09c94
078948d5552a36d0fb62c90fb613c189398d4e4d
/model/boundary_conditions/MidRectRect2DBoundaryCondWeight.hpp
3247174f5f61e6e9a7a7cadecde1ad5ea3fa9d71
[]
no_license
aschils/pdetect
4e9838192a3986ca5833beea0537c5aa6b8ff704
8138c6f964bd8b95fbefe903d4457d577846d4ae
refs/heads/master
2021-01-21T04:37:23.971467
2016-07-03T21:56:33
2016-07-03T21:56:33
45,048,636
0
0
null
null
null
null
UTF-8
C++
false
false
682
hpp
MidRectRect2DBoundaryCondWeight.hpp
/* * MidRectRect2DBoundaryCondWeight.hpp * * Created on: 3 févr. 2016 * Author: aschils */ #pragma once #include "MidRectRect2DBoundaryCond.hpp" #include "MidRectRect2DBoundaryValuesWeight.hpp" #include "../geometry_info/MidRectRectGeoInfo.hpp" template <unsigned dim> class MidRectRect2DBoundaryCondWeight: public MidRectRect2DBoundaryCond<dim> { public: MidRectRect2DBoundaryCondWeight(MidRectRectGeoInfo *geo_info, double potential){ this->set_class_var(geo_info->get_nbr_of_strips(), geo_info->get_half_inter_strip_dist(), geo_info->get_strip_length()); this->values = new MidRectRect2DBoundaryValuesWeight<dim>(geo_info, potential); } };
8cb5dfe13d1cf8b305ef10ca6da8527b728cdc69
632dcb4e37cadd87cb7ff8715b0048df5cd0d11b
/CompuCell3D/core/CompuCell3D/steppables/PDESolvers/candidate_code/FiPySolver.h
f9787b9573663b502d303294501c7abba3f518c3
[ "MIT" ]
permissive
CompuCell3D/CompuCell3D
df638e3bdc96f84b273978fb479842d071de4a83
65a65eaa693a6d2b3aab303f9b41e71819f4eed4
refs/heads/master
2023-08-26T05:22:52.183485
2023-08-19T17:13:19
2023-08-19T17:13:19
12,253,945
51
41
null
2023-08-27T16:36:14
2013-08-20T20:53:07
C++
UTF-8
C++
false
false
4,759
h
FiPySolver.h
#ifndef COMPUCELL3DFIPYSOLVER_H #define COMPUCELL3DFIPYSOLVER_H #include <CompuCell3D/Steppable.h> #include <CompuCell3D/Potts3D/Cell.h> #include "FiPyContiguous.h" #include "DiffSecrData.h" #include <CompuCell3D/Serializer.h> #include <string> #include <vector> #include <set> #include <map> #include <iostream> #include "PDESolversDLLSpecifier.h" namespace CompuCell3D { /** @author m */ //forward declarations class Potts3D; class Simulator; class Cell; class CellInventory; class Automaton; class BoxWatcher; class DiffusionData; class SecretionDataFiPy; class FiPySolverSerializer; class TestFiPySolver; // Testing FiPySolver class ParallelUtilsOpenMP; template<typename Y> class Field3D; template<typename Y> class Field3DImpl; template<typename Y> class WatchableField3D; class FiPySolver; class PDESOLVERS_EXPORT SecretionDataFiPy :public SecretionData { public: typedef void (FiPySolver::*secrSingleFieldFcnPtr_t)(unsigned int); std::vector <secrSingleFieldFcnPtr_t> secretionFcnPtrVec; }; class PDESOLVERS_EXPORT DiffusionSecretionFiPyFieldTupple{ public: DiffusionData diffData; SecretionDataFiPy secrData; DiffusionData * getDiffusionData(){ return &diffData; } SecretionDataFiPy * getSecretionData(){ return &secrData; } }; class PDESOLVERS_EXPORT FiPySolver :public FiPyContiguous<float> { friend class FiPySolverSerializer; // For Testing friend class TestFiPySolver; // In production version you need to enclose with #ifdef #endif public : typedef void (FiPySolver::*diffSecrFcnPtr_t)(void); typedef void (FiPySolver::*secrSingleFieldFcnPtr_t)(unsigned int); typedef float precision_t; typedef Array3DFiPy <precision_t> ConcentrationField_t; BoxWatcher *boxWatcherSteppable; protected: Potts3D *potts; Simulator *simPtr; ParallelUtilsOpenMP *pUtils; unsigned int currentStep; unsigned int maxDiffusionZ; float diffConst; float decayConst; float deltaX;///spacing float deltaT;///time interval float dt_dx2; ///ratio delta_t/delta_x^2 WatchableField3D<CellG *> *cellFieldG; Automaton *automaton; // std::vector<DiffusionData> diffDataVec; // std::vector<SecretionDataFiPy> secrDataVec; std::vector<bool> periodicBoundaryCheckVector; std::vector <BoundaryConditionSpecifier> bcSpecVec; std::vector<bool> bcSpecFlagVec; CellInventory *cellInventoryPtr; void (FiPySolver::*diffusePtr)(void);///ptr to member method - Forward Euler diffusion solver void (FiPySolver::*secretePtr)(void);///ptr to member method - Forward Euler diffusion solver void secrete(); void FindDoNotDiffusePixels(unsigned int idx); void secreteOnContact(); void secreteSingleField(unsigned int idx); void secreteOnContactSingleField(unsigned int idx); void secreteConstantConcentrationSingleField(unsigned int idx); void scrarch2Concentration(ConcentrationField_t *concentrationField, ConcentrationField_t *scratchField); void outputField(std::ostream &_out, ConcentrationField_t *_concentrationField); void readConcentrationField(std::string fileName, ConcentrationField_t *concentrationField); //void boundaryConditionInit(ConcentrationField_t *concentrationField); void boundaryConditionInit(int idx); bool isBoudaryRegion(int x, int y, int z, Dim3D dim); unsigned int numberOfFields; Dim3D fieldDim; Dim3D workFieldDim; float couplingTerm(Point3D &_pt, std::vector <CouplingData> &_couplDataVec, float _currentConcentration); void initializeConcentration(); bool serializeFlag; bool readFromFileFlag; unsigned int serializeFrequency; FiPySolverSerializer *serializerPtr; bool haveCouplingTerms; std::vector <DiffusionSecretionFiPyFieldTupple> diffSecrFieldTuppleVec; //vector<string> concentrationFieldNameVectorTmp; public: FiPySolver(); virtual ~ FiPySolver(); virtual void init(Simulator *_simulator, CC3DXMLElement *_xmlData = 0); virtual void extraInit(Simulator *simulator); // Begin Steppable interface virtual void start(); virtual void step(const unsigned int _currentStep); virtual void finish() {} // End Steppable interface //SteerableObject interface virtual void update(CC3DXMLElement *_xmlData, bool _fullInitFlag = false); virtual std::string steerableName(); virtual std::string toString(); }; class PDESOLVERS_EXPORT FiPySolverSerializer : public Serializer{ public: FiPySolverSerializer() : Serializer() { solverPtr = 0; serializedFileExtension = "dat"; currentStep = 0; } ~ FiPySolverSerializer() {} FiPySolver *solverPtr; virtual void serialize(); virtual void readFromFile(); void setCurrentStep(unsigned int _currentStep) { currentStep = _currentStep; } protected: unsigned int currentStep; }; }; #endif
b42e850df7476c2fa25f7c76be05946424760103
bbf92ba38f84dd7ae5c74177f0de919a20ffa99f
/Task3cPlusPlus/Queue2List.h
012ce5824fabdcc3fd32002f8777f5c65c6db47d
[]
no_license
SuperUser001/cPlusPlusOldTasks
f1cc92be998d8cab2ee6305ac23c77eceeb9e28c
ae802262dcb4b50a26f543797701174d146dc972
refs/heads/master
2021-05-09T16:00:48.560091
2018-01-26T21:37:15
2018-01-26T21:37:15
119,104,984
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
1,280
h
Queue2List.h
//Создайте новый класс Queue2 на основе к. List наследованием #ifndef Queue2List_h_ #define Queue2List_h_ #include "NewList6.h" class Queue2 : public IndexedList { Node *first = nullptr; Node *last = nullptr; std::size_t s = 0; public: Queue2() : first(nullptr), last(nullptr), s(0) { } ~Queue2() { } bool empty() const; std::size_t getSize() const; void Append(const LL); void Erase(); LL Front() const; LL Back() const; }; inline bool Queue2::empty() const { return first == nullptr; } inline std::size_t Queue2::getSize() const { return s; } void Queue2::Append(const LL x) { // Pushing into the queue Node *t = new Node(x); if (empty()) { first = last = t; first->prev = last->next = nullptr; } else { t->prev = last; last->next = t; last = t; } ++s; } void Queue2::Erase() { if (empty()) throw std::underflow_error("Underflow!"); auto t = first; first = first->next; delete t; t = nullptr; --s; } LL Queue2::Front() const { if (empty()) throw std::underflow_error("Underflow"); return first->data; } LL Queue2::Back() const { if (empty()) throw std::underflow_error("Underflow"); return last->data; } #endif
4d64ee72bd453312e2b1cd000300610096956983
e03da4e28acff14f62379fea06d33c5cc1636038
/table_of_symbols/SymbolTable.h
a4c4b8c0052bf695ea5c25e79dfbaab8ae612e83
[]
no_license
Vladislav27/hand-written-compiler
7292173a03a3813bae2fcf52c14cb6b97e2c8625
4da165dcc668567f1668d1a62e692606bd24ce18
refs/heads/master
2022-01-06T07:57:38.112897
2019-05-19T08:46:39
2019-05-19T08:46:39
149,116,251
0
0
null
null
null
null
UTF-8
C++
false
false
1,459
h
SymbolTable.h
#pragma once #include "Common.h" #include "ClassInfo.h" #include <abstr/StringInterner.h> #include <memory> #include <unordered_map> namespace NSymbolTable { class SymbolTable { std::unordered_map<const NTree::Symbol*, ClassInfo> classes; const NTree::Symbol* mainClass; NTree::Location mainClassLocation; std::shared_ptr<NTree::StringInterner> interner; public: SymbolTable() = delete; explicit SymbolTable(std::shared_ptr<NTree::StringInterner> interner) : mainClass(nullptr), interner(std::move(interner)) { } bool HasClass(const NTree::Symbol* id) const; const ClassInfo& GetClassInfo(const NTree::Symbol* id) const; const std::unordered_map<const NTree::Symbol*, ClassInfo>& GetClasses() const; void InsertClassInfo(const ClassInfo&); void SetMainClass(const NTree::Symbol*); void SetMainClassLocation(const NTree::Location&); const NTree::Symbol* GetMainClassId() const; const NTree::Location& GetMainClassLocation() const; std::shared_ptr<NTree::StringInterner> GetInterner() const; const VariableInfo* FindIdentifier(const ClassInfo *classInfo , const NTree::Symbol *id , const MethodInfo *methodInfo = nullptr) const; const MethodInfo* FindMethod(const NTree::Symbol *methodId , const NTree::Symbol *classId) const; }; }
fe1988682b0a6ffc7ac3f9727755b384ab3e6921
135886ef48a7f65a4823d376e308d0a720b1f86d
/src/occa/internal/lang/modes/metal.hpp
f1559a0a713260428da05c218bc94230a64646c5
[ "MIT" ]
permissive
libocca/occa
b912a379243f7f532694dcdd54c50697cf5c838d
ef5218f32ad2444434d84be01716f14243bc174f
refs/heads/main
2023-08-22T15:47:54.847685
2023-06-20T02:23:30
2023-06-20T02:23:30
38,410,417
372
104
MIT
2023-09-12T18:50:01
2015-07-02T04:03:29
C++
UTF-8
C++
false
false
1,175
hpp
metal.hpp
#ifndef OCCA_INTERNAL_LANG_MODES_METAL_HEADER #define OCCA_INTERNAL_LANG_MODES_METAL_HEADER #include <occa/internal/lang/modes/withLauncher.hpp> namespace occa { namespace lang { namespace okl { class metalParser : public withLauncher { public: qualifier_t kernel_q; qualifier_t device_q; qualifier_t threadgroup_q; qualifier_t constant_q; metalParser(const occa::json &settings_ = occa::json()); virtual void onClear() override; virtual void beforePreprocessing() override; virtual void beforeKernelSplit() override; virtual void afterKernelSplit() override; virtual std::string getOuterIterator(const int loopIndex) override; virtual std::string getInnerIterator(const int loopIndex) override; virtual std::string launchBoundsAttribute(const int innerDims[3]) override; void setSharedQualifiers(); void addBarriers(); void setupHeaders(); void setupKernels(); void migrateLocalDecls(functionDeclStatement &kernelSmnt); void setKernelQualifiers(function_t &function); }; } } } #endif
f5848a16e06c4cdf92183c66e7d483a6353d0658
92a9f837503a591161330d39d061ce290c996f0e
/LIB/SiNDYLib/EditMeshTable.h
fbf2e7dca06e598b39d8480b143ce63ca5f5d2c4
[]
no_license
AntLJ/TestUploadFolder
53a7dae537071d2b1e3bab55e925c8782f3daa0f
31f9837abbd6968fc3a0be7610560370c4431217
refs/heads/master
2020-12-15T21:56:47.756829
2020-01-23T07:33:23
2020-01-23T07:33:23
235,260,509
1
1
null
null
null
null
SHIFT_JIS
C++
false
false
4,018
h
EditMeshTable.h
/* * Copyright (C) INCREMENT P CORP. All Rights Reserved. * * THIS SOFTWARE IS PROVIDED BY INCREMENT P CORP., 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 HOLDER BE LIABLE FOR ANY * CLAIM, DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING * OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. */ /** * @file EditMeshTable.h * @brief <b>CEditMeshTableクラス定義ファイル</b>\n * @author 地図DB制作部開発グループ 古川貴宏 * $Id$ */ #ifndef _EDITMESHTABLE_H_ #define _EDITMESHTABLE_H_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "Table.h" #include "EditMesh.h" #include "Geometry.h" #include <list> namespace sindy { class CGeometry; namespace editmesh { /** * @class CEditMeshTable * @brief <b>編集可能メッシュ管理テーブルクラス(ルール用)</b>\n * このクラスは、REFERNCE.EDITMESHテーブルのラップクラスです。 */ #pragma warning(push) #pragma warning(disable: 4251) class SINDYLIB_API CEditMeshTable : public CTable { public: CEditMeshTable() : m_bCached(false) {} virtual ~CEditMeshTable() {} CEditMeshTable& operator=(ITable* lp) { AtlComPtrAssign((IUnknown**)&p, lp); return *this; } CEditMeshTable& operator=(const CEditMeshTable& lp ) { AtlComPtrAssign((IUnknown**)&p, (ITable*)lp ); return *this; } /** * @brief <b>編集可能なエリアかどうかをチェックする</b>\n * キャッシュされているものから検索を行います。 * @param lPurposeID [in] 作業目的ID * @param lLayerNameID [in] レイヤ名ID * @param lOperatorID [in] 作業者名ID * @param ipGeom [in] チェックエリア * @retval true 編集可能 * @retval false 編集不可 */ bool IsEditable( long lPurposeID, long lLayerNameID, long lOperatorID, IGeometry* ipGeom ) const; /** * @brief <b>テーブルを全てキャッシュする</b>\n * テーブルの内容を全てキャッシュします。 * bDetatchをtrueにすると、読み込んだレコード及び * テーブルのDBへの接続を切り離します。 * * @note 特定の作業目的だけキャッシュしたい場合はlPurposeIDに作業目的IDをセットします。 * デフォルトの状態では全作業目的をキャッシュします。 * * @param bDetatch [in,optional] キャッシュした後接続を切り離す(デフォルト:false) * @param lPurposeID [in,optional] 作業目的を限定してキャッシュを作成する(デフォルト:-1) */ long CreateTableCache( bool bDetatch = false, long lPurposeID = -1 ); /** * @brief <b>キャッシュをクリアする</b>\n */ void ClearTableCache(); /** * @brief <b>既にキャッシュされているかどうか</b>\n * @return キャッシュされていればtrue */ bool IsCached() const { return m_bCached; } /** * @brief <b>作業可能エリアを設定する</b>\n * @param ipGeom [in] セットするエリア * @note NULLをセットすると空になります */ void SetGlobalWorkArea( IGeometry* ipGeom ); /** * @brief <b>作業可能エリアを取得する</b>\n * @return 作業可能エリア */ const CGeometry& GetGlobalWorkArea() const; private: CGeometry m_cGlobalWorkArea; //!< 全てのレイヤ・作業目的に課せられる作業エリア(キャッシュ対象ではない、空なら制限なし) std::map<long, std::map<long, std::map<long, std::pair<CGeometry, std::list<CEditMesh> > > > > m_mapCache; //!< キャッシュ用リスト bool m_bCached; //!< 全レコードをキャッシュしたかどうかのフラグ }; #pragma warning(pop) } // editmesh } // sindy #endif // _EDITMESHTABLE_H_
cb1c884db02bf94c066cd5a8bf4dbdcf72351ace
40f73a14d163a8cc33dfde92f1109743d9ecdbe2
/stringpermutation_backtracking.cpp
d74a3744f6765edaed4ad96bc84b09650ed6f264
[]
no_license
pravirtual/Leetcode
dc83d09f6fc15f24e05e8fca7546e2f003f45c37
7f754f38e507b7f4aaeb267b05873437b1ca5bcf
refs/heads/master
2023-08-28T07:52:59.019305
2021-10-29T14:21:01
2021-10-29T14:21:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
736
cpp
stringpermutation_backtracking.cpp
public: vector<string>find_permutation(string S) { map <char,int> mp; // Code here there vector<string> ans; for(int i=0;i<S.length();i++) { mp[S[i]]++; } generatepermutation(mp,"",0,S.length(),S,ans); return ans; } void generatepermutation(map<char,int> mp,string asf,int indx,int n,string a,vector<string> &ans) { if(indx==n) { ans.push_back(asf); return; } for(auto it : mp) { if(mp[it.first]!=0) { mp[it.first]--; generatepermutation(mp,asf+(it.first),indx+1,n,a,ans); mp[it.first]++; } } }
bc2f031aae2b0a0c55828c01277d91ba2fb3760e
b070ad79985320cf5053c84d1f9d0821339285c9
/example/src/overview.cpp
31b39182d2a0a3c288646806a18bece053aa0ee6
[ "MIT" ]
permissive
brunocodutra/alloy
b8d4f1030f52ddbe34a9372e471c2ced95b38c3c
e05e30a40b1b04c09819b8b968829ba4f62dc221
refs/heads/master
2021-11-24T11:39:55.028214
2021-10-24T17:22:30
2021-10-24T17:43:05
75,228,347
16
1
MIT
2021-08-02T21:59:12
2016-11-30T21:23:18
C++
UTF-8
C++
false
false
2,583
cpp
overview.cpp
// NOTE: keep in sync with the README /// [overview] #include "alloy.hpp" #include <iostream> #include <string> #include <utility> int main() { // suppose you have some data auto data = alloy::capture("Hello", ' ', "World" , '!'); // and means to consume it auto print = [](auto&&... data) { // we'll simply print to the standard output in this example (std::cout << ... << std::forward<decltype(data)>(data)) << std::endl; }; // all you need is to connect the ends data >> print; // Hello World! // just as easily you can build data pipelines auto predicate = [](auto x) { return std::string{x} != "!"; }; data >> alloy::filter(predicate) >> print; // Hello World // with Alloy you can kiss `std::apply` goodbye alloy::unpack(std::make_tuple(3, '.', "14")) >> print; // 3.14 // you can even iterate through tuples in a regular for-loop auto tup = std::make_tuple(3, '.', "14"); for(std::size_t i = 0; i < std::tuple_size<decltype(tup)>{}; ++i) alloy::unpack(tup) >> alloy::at(i) >> alloy::prepend(i, ": ") >> print; // 0: 3 // 1: . // 2: 14 // `std::visit` is also a thing of the past using var = std::variant<int, char, std::string>; var i = 3; var c = '.'; var s = "14"; alloy::unpack(i, c, s) >> print; // 3.14 // while you are at it, why not mixing tuples and variants together? alloy::unpack(std::make_tuple("pi", '='), i, c, s) >> print; // pi=3.14 // tuples and variants are too mainstream? // not a problem, you can also provide your very own custom data sources auto produce = [](auto consume) { return consume("Hello", ' ', "World"); }; // the following are all equivalent and print Hello World alloy::source{produce} >> print; produce >> alloy::sink{print}; alloy::source{produce} >> alloy::sink{print}; // and your very own streams too auto process = [](auto const& sink) { return [&sink](auto hello, auto _, auto world) { return sink(hello, _, "brave", _, "new", _, world, '!'); }; }; produce >> alloy::stream{process} >> print; // Hello brave new World! // embrace (post) modern C++ auto wrap = [](auto const& sink) { return [&sink](auto word) { return sink('(', word, ')'); }; }; alloy::forward("post") >> alloy::stream{wrap} >> alloy::prepend("embrace", ' ') >> alloy::append(' ', "modern C++") >> print; } /// [overview]
9b21bcc9e737f3f36781ec148aa135ca49e08622
d775bac0e4e04f94963681a1896354cc549feccc
/Jump/EntityListCreator.cpp
7ef0d380a04df1ef46b9f0754b379c4ea921f19c
[]
no_license
kobraks/Jump
15086ec29c52d4cea5d7a93e4745c053d5772ada
7e1b9306614d082fae46302eecb6c9d8d0a02752
refs/heads/master
2021-01-01T05:16:11.935482
2017-11-16T12:33:31
2017-11-16T12:33:31
57,133,520
0
0
null
null
null
null
UTF-8
C++
false
false
1,086
cpp
EntityListCreator.cpp
#include "EntityListCreator.h" #include "EntityManager.h" #include "Entity.h" #include <string.h> jump::utilities::EntityListCreator::EntityListCreator(): list_(nullptr), count_(0) { } jump::utilities::EntityListCreator::~EntityListCreator() { clear(); } void jump::utilities::EntityListCreator::update() { if (count_ == entity::EntityManager::get_count()) return; clear(); list_ = new char*[entity::EntityManager::get_count()]; for (size_t i = 0; i < entity::EntityManager::get_count(); ++i) { auto entity_type = entity::EntityManager::get_entity(i)->get_type(); list_[i] = new char[entity_type.size() + 1]; strcpy_s(list_[i], entity_type.size() + 1, entity_type.c_str()); } count_ = entity::EntityManager::get_count(); } char** jump::utilities::EntityListCreator::get_list() const { return list_; } size_t jump::utilities::EntityListCreator::get_count() const { return count_; } void jump::utilities::EntityListCreator::clear() { for (size_t i = 0; i < count_; ++i) { delete[] list_[i]; list_[i] = nullptr; } delete[] list_; list_ = nullptr; }
97416495d5efbbbb478f751a9307f947a1f8519a
444c57414ed6aee2ff4eddffb677032e4f617647
/graph/0-1bfs.cpp
ed51e31cd15086e9328c214c669d7b4f8b6492d0
[]
no_license
DailyPS/Teamnote
67d02e3c2d70abd75010796c93eb05a87462c488
1fa9aeebc56afddc79298cb4d33b5a99d11c94b2
refs/heads/master
2023-08-02T00:02:56.037299
2021-10-06T12:22:06
2021-10-06T12:22:06
414,133,000
0
0
null
null
null
null
UTF-8
C++
false
false
572
cpp
0-1bfs.cpp
#define MAX 100005 deque<int> dq; vector<int> g[MAX]; bool visited[MAX] = { 0 }; void bfs(int start) { dq.push_back(start); visited[start] = true; while(!dq.empty()) { int dq_size = dq.size(); while(dq_size) { int item = dq.front(); dq.pop_front(); for (auto& w : g[item]) { if ((w == zero_value) && !visited[w]) { visited[w] = true; dq.push_front(w); } else { visited[w] = true; dq.push_back(w); } } dq_size--; } } }
0efc75617f344364c8417be6e80af6d270a2e621
c136c9813c77df614f1bca1c869a5bcdbfa01d0b
/build_expression/src/build_expression.cpp
af2789e057151a2e50fdd690ecf747cbebb47dde
[]
no_license
anuar-a/CPP-Yandex-belts
21076f8216b731fedb8533a388bd970b51efad61
e93ac12ec99c508fd03353d628c79c8dd16cc4a4
refs/heads/master
2023-03-26T22:40:30.225941
2021-03-28T16:36:02
2021-03-28T16:36:09
352,305,363
0
0
null
null
null
null
UTF-8
C++
false
false
424
cpp
build_expression.cpp
#include <iostream> #include <string> #include <deque> using namespace std; int main() { deque<string> d; string num; int n; cin >> num; cin >> n; d.push_front(num); for (int i = 0; i < n; ++i) { d.push_front("("); d.push_back(")"); string a; string op; cin >> op; cin >> a; d.push_back(" "); d.push_back(op); d.push_back(" "); d.push_back(a); } for (auto i : d) { cout << i; } return 0; }
10e67839e1d3b7203c54ce259967872082f9a7db
6fcdb181bc665c9e104d82bc99a9a3aeb766b2c8
/femMesh.h
609b965cb6107615bedff4e0f7e036bd2332a100
[]
no_license
benjones/fem2D
c0180e54cb63c9331967a1a3f0812518d59b08c1
77e9fbaa3a8f4912fa52b7747e655c8a2d1f9502
refs/heads/master
2020-12-25T17:34:21.059508
2016-08-17T19:07:06
2016-08-17T19:07:06
20,545,528
1
1
null
null
null
null
UTF-8
C++
false
false
1,637
h
femMesh.h
#pragma once #include <vector> #include "eigenTypedefs.h" #include "stiffnessMatrix.h" class PlaneObstacle; class FemNode { public: vec2 referencePos, worldPos, velocity; double mass; vec2 force; vec2 tensileForces, compressiveForces; mat2 tensileTensor, compressiveTensor; std::vector<size_t> triangles; }; class FemElement { public: unsigned nodes[3]; vec2 faceNormals[3]; mat2 beta; mat2 bMatrix; mat2 stiffnessMatrices[6]; //00, 01, 02, 11, 12, 22, symmetric, so only store these mat2 stress, elementRotation; double area; vec2 forceOffset[3]; }; struct MaterialParameters{ double density, lambda, mu, dampLambda, dampMu; double raleighAlpha, raleighBeta; double toughness; //C = alpha*massMatrix + beta*stiffnessMatrix }; class FemMesh { public: FemMesh() {} void initialize (const std::vector<double>& vertices, const std::vector<unsigned>& triangles, MaterialParameters _materialParameters); void integrate(double dt); void integrateBackwardsEuler(double dt); void collidePlanes(const std::vector<PlaneObstacle>& planes); void renderOpenGL(); void setForcesToGravity(); void computeDeformationGradient(bool isExplicit); void constrainNodes(); void doFracture(); std::vector<FemNode> nodes; std::vector<FemElement> elements; MaterialParameters materialParameters; StiffnessMatrix stiffnessMatrix; std::vector<double> rhsSolve, velocityGuess; std::vector<size_t> constrainedNodes; double dt; }; //compute y = Ax, with A = M*(1+dt*alpha) + K(dt^2 + dt*beta) void mult(const FemMesh& mesh, double* x, double* y);
2707701813ca917591ccd65daac05087680678a3
637dbfb2262b8f0b0d013c2abba4fd7fcd547730
/chapter 4/ex.21.cpp
b86c7125d8e1baabf209c5d23ff37a34e4522061
[]
no_license
lewislu77/Starting_with_Cpp_9thEd.
cee000f7e60e8090d0ec6592f06d940421d42794
968816322beb6790c3eb0e325cfd8b25a065b642
refs/heads/master
2020-08-27T20:13:16.055760
2020-03-15T21:11:59
2020-03-15T21:11:59
217,479,125
0
0
null
null
null
null
UTF-8
C++
false
false
2,291
cpp
ex.21.cpp
// // Created by Marcin Luberda on 08/12/2019. // #include <iostream> #include <iomanip> using namespace std; int main(){ int choice; double odo, time; cout << "\n\tWybierz ośrodek rozchodzenia sie dźwieku:\n\t1 - DWUTLENEK WĘGLA \n\t" "2 - POWIETRZE \n\t3 - HEL \n\t4 - WODÓR \n\n\t"; cin >> choice; switch (choice){ case 1: cout << "\n\tDWUTLENEK WĘGLA"; cout << "\n\tPodaj czas detekcji dźwieku (do 30 sek.): "; cin >> time; if (time > 0 && time <= 30) { odo = time * 258.0; cout << "\tOdległości od źródła dźwięku, to: " << setprecision(2) << fixed << odo << " m.\n"; } else cout << "\tPodany czas przekroczył dopuszczalny zakres."; break; case 2: cout << "\n\tPOWIETRZE"; cout << "\n\tPodaj czas detekcji dźwieku (do 30 sek.): "; cin >> time; if (time > 0 && time <= 30) { odo = time * 331.5; cout << "\tOdległości od źródła dźwięku, to: " << setprecision(2) << fixed << odo << " m.\n"; } else cout << "\tPodany czas przekroczył dopuszczalny zakres."; break; case 3: cout << "\n\tHEL"; cout << "\n\tPodaj czas detekcji dźwieku (do 30 sek.): "; cin >> time; if (time > 0 && time <= 30) { odo = time * 972.0; cout << "\tOdległości od źródła dźwięku, to: " << setprecision(2) << fixed << odo << " m.\n"; } else cout << "\tPodany czas przekroczył dopuszczalny zakres."; break; case 4: cout << "\n\tWODÓR"; cout << "\n\tPodaj czas detekcji dźwieku (do 30 sek.): "; cin >> time; if (time > 0 && time <= 30) { odo = time * 1270.0; cout << "\tOdległości od źródła dźwięku, to: " << setprecision(2) << fixed << odo << " m.\n"; } else cout << "\tPodany czas przekroczył dopuszczalny zakres."; break; default: cout << "\n\tWybrałeś błędną pozycję menu.\n"; } return 0; }
95e47fedc289d143dedd5c65e7c2a3e683aac899
69eef3551213bcf348cbcdedcaac91a8b436c0e5
/Project2/源.cpp
3a0c0f91bd762d55577c7f1d26c6a6cf101957b1
[]
no_license
1225993807/book-p83
1153889075f60f57bc3112ad6be5ae2329fe61e6
fd522557643008404bdd9bd2fa5bbb97ee70f274
refs/heads/master
2021-07-23T16:42:24.983261
2017-11-05T08:27:26
2017-11-05T08:27:26
109,563,069
0
0
null
null
null
null
UTF-8
C++
false
false
351
cpp
源.cpp
#include<stdio.h> int prime(int n); int main() { float i; double sum = 0; for (i = 2; i <= 100; i++) { if (prime(i) == 1) sum = sum +1.0/i; } printf("%f", sum); return 0; } int prime(int n) { int j; int flag = 1; for (j = 2; j < n; j++) { flag = 1; while (n%j == 0) { flag = 0; goto label_1; } } label_1:return flag; }
e07b4747764b287a89c584636c76af750ff57b55
a5da02227cbbc30effaf43d52bdca26223daf98e
/CCC/Stage1/09-Done/ccc09s1.cpp
48db31130b508af9a3e36bb6f944969ecfa28b5c
[ "MIT" ]
permissive
zzh8829/CompetitiveProgramming
853edabdfc728504abaa27333bd4900a7f97c8c9
36f36b10269b4648ca8be0b08c2c49e96abede25
refs/heads/master
2021-01-01T15:41:08.984386
2018-03-25T17:32:39
2018-03-25T17:32:39
35,587,680
1
0
null
null
null
null
UTF-8
C++
false
false
320
cpp
ccc09s1.cpp
#include <iostream> #include <cstdio> #include <cmath> using namespace std; int main() { int a,b,cnt=0; cin >> a >> b; for(int i=int(pow(a,1.0/3.0)+0.5);i<=pow(b,1.0/3.0)+1;i++) { int t=i*i*i ; if((int)sqrt(t)*(int)sqrt(t)==t) cnt++; } cout << cnt <<endl; system("pause"); return 0; }
86c1cc424d0e48286b981779dac7cc97098fefca
78ea8c04353863ef30b031e230b880be2b51f78c
/server/src/map.h
6e6c6ae4a40cf0cf7c522b0ce2e5ef7c87060d3b
[]
no_license
mbpolan/freerpg
91848a9fe8e0a6e618bbbf2e2cba7d1592399152
f2dd2a461fd814cfa58f9850bc860f37629874de
refs/heads/master
2020-03-26T17:52:19.760206
2012-06-02T05:40:06
2012-06-02T05:40:06
145,184,861
0
0
null
null
null
null
UTF-8
C++
false
false
2,087
h
map.h
/*************************************************************************** * Copyright (C) 2012 by FreeRPG Team * * http://freerpg.sf.net * * * * 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. * ***************************************************************************/ // map.h: declaration of the Map class. #ifndef MAP_H #define MAP_H #include <iostream> #include <map> #include <vector> class Tile; class Map { public: typedef std::pair<char, short> TileID; typedef std::vector<std::vector<TileID> > IDMap; public: ~Map(); IDMap getAreaAround(int x, int y) const; Tile* getTile(int x, int y) const; private: Map(int width, int height); void addTilesetTile(int ts, Tile *tile); void putTile(int x, int y, int ts, int id); int m_Width; int m_Height; std::map<int, std::map<int, Tile*> > m_Tilesets; std::vector<Tile*> m_Map; friend class MapLoaderXML; }; #endif
dcddfbf4001338d50da8955e8f34d4a0b4f9eed9
8857f5dddb04256a9a52ed2c9b713f519f4ed547
/chrome/services/speech/audio_source_fetcher_impl.h
288121d41553f487c2b212b8ed937a37a2048e4f
[ "BSD-3-Clause" ]
permissive
itzhp/chromium
77b96ca5c8032d98da8c6c7349f2c020cb24bad8
80a6c1e209340eca4caecbf846e059bcb4f14fad
refs/heads/master
2023-03-18T23:49:54.797015
2021-03-11T16:34:16
2021-03-11T16:34:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,177
h
audio_source_fetcher_impl.h
// Copyright 2021 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. #ifndef CHROME_SERVICES_SPEECH_AUDIO_SOURCE_FETCHER_IMPL_H_ #define CHROME_SERVICES_SPEECH_AUDIO_SOURCE_FETCHER_IMPL_H_ #include "base/memory/weak_ptr.h" #include "media/base/audio_capturer_source.h" #include "media/mojo/mojom/speech_recognition_service.mojom.h" #include "mojo/public/cpp/bindings/receiver.h" #include "mojo/public/cpp/bindings/remote.h" namespace speech { class SpeechRecognitionRecognizerImpl; // Class to get microphone audio data and send it to a // SpeechRecognitionRecognizerImpl for transcription. Runs in Browser process in // Chrome OS and Speech Recognition Service on Chrome or web speech fallback. // TODO(crbug.com/1173135): Override from // media::AudioCapturerSource::CaptureCallback to capture audio. class AudioSourceFetcherImpl : public media::mojom::AudioSourceFetcher { public: AudioSourceFetcherImpl( mojo::PendingRemote<media::mojom::AudioStreamFactory> stream_factory, std::unique_ptr<SpeechRecognitionRecognizerImpl> recognition_recognizer); ~AudioSourceFetcherImpl() override; AudioSourceFetcherImpl(const AudioSourceFetcherImpl&) = delete; AudioSourceFetcherImpl& operator=(const AudioSourceFetcherImpl&) = delete; static void Create( mojo::PendingReceiver<media::mojom::AudioSourceFetcher> receiver, mojo::PendingRemote<media::mojom::AudioStreamFactory> stream_factory, std::unique_ptr<SpeechRecognitionRecognizerImpl> recognition_recognizer); // media::mojom::AudioSourceFetcher: void Stop() override; private: // Audio capturerer source for microphone recording. scoped_refptr<media::AudioCapturerSource> audio_capturer_source_; // Owned SpeechRecognitionRecognizerImpl was constructed by the // SpeechRecognitionService as appropriate for the platform. std::unique_ptr<SpeechRecognitionRecognizerImpl> speech_recognition_recognizer_; base::WeakPtrFactory<AudioSourceFetcherImpl> weak_factory_{this}; }; } // namespace speech #endif // CHROME_SERVICES_SPEECH_AUDIO_SOURCE_FETCHER_IMPL_H_
3a149bc6bdeec12da93fbc9c022541254b00ee3e
9e1b63dae8d3991115fed84a8d5a87fc50463e71
/targets/DataStore/Table.cpp
8ec76baf2b91489c0d90ea22a68f51df22e5b659
[]
no_license
pkubik/tin
5bcef81b3ca8245ae0d3aceff4f094890fc5de29
9c50d9bcdb69b3115e0066670df433531193bb3e
refs/heads/master
2016-09-13T09:59:21.334138
2016-01-17T23:41:28
2016-01-17T23:41:28
57,905,740
0
0
null
null
null
null
UTF-8
C++
false
false
764
cpp
Table.cpp
#include "Table.hpp" namespace table { Table::Table(){ columnCount=0; rowCount=0; } /*returns how many rows is in table*/ int Table::tableSize(){ return rowCount; } /*returns how many columns has single row*/ int Table::rowSize(){ return columnCount; } /*returns names of colmns*/ vector<string> Table::getColumnsNames(){ return columnsNames; } /*returns row selected by argument*/ vector<string> Table::getRow(int i){ return queryResult[i]; } /*adds row to table*/ void Table::addRow(vector<std::string> &row){ ++rowCount; queryResult.push_back(row); } /*adds column name*/ void Table::addColumnName(std::string columName){ ++columnCount; columnsNames.push_back(columName); //columnsType.push_back(columnType); } }
0829282f4426f3a3fb861720213512778732a598
d6e3c5c5328ff7dc6a5c02da5452de94e6673017
/no_stl/heap_variant/heap_variant_common.h
fb3d00c34813d235806ec8304bf51808cec6340e
[]
no_license
mastrost/no_stl
7f41ec0f6df1e225c7bcec5528a85eafe4e32cce
b5302ce0a2312cf0ef0c48687808d2a42a019463
refs/heads/master
2023-06-23T22:24:01.644427
2021-07-14T13:09:33
2021-07-14T13:09:33
385,945,140
0
0
null
null
null
null
UTF-8
C++
false
false
172
h
heap_variant_common.h
#pragma once #include "cpp_tools/defines.h"//[mto] namespace mto::no_stl::heap_variant {//[mto.ns_begin] template<typename... _ts> struct heap_variant_t; }//[mto.ns_end]
c0ce56ea62fd5fa173aa84b97898106a63e00668
bf8edeb33273c5d4926d56b9f926d59f8f326e01
/main_BST.cc
1159cee7e63e6f0098dd908ad479c736eb04d151
[]
no_license
NaimaNess/Exam-c-
1e416001fd1740341b7d0fb05579428a1fb3cbce
8cec986c98ed309987fe8f4c99b1290b0c4e1324
refs/heads/master
2020-12-10T07:52:56.434865
2020-05-01T09:39:42
2020-05-01T09:39:42
233,540,293
0
0
null
null
null
null
UTF-8
C++
false
false
459
cc
main_BST.cc
#include<BST.h> int main() { bst< int , double, std::less<int>> t{}; auto x0 = std::pair<int,double>{42,0.123}; auto x1 = std::pair(55, 2.3); auto x2 = std::pair<int,double>{142,0.123}; t.insert(x0); t.insert(std::pair<int,double>{4,0.3}); t.insert(x1); t.insert(x2); std::cout << "The tree without smart pointers is " << t << std::endl; t.find(x0.first); t.find(1); t.clear(); return 0; }
39ed47952d18a9b4c2028e6cb994f48e29eb5022
9c5e51fc8f3ca0ad3f41cdbe25783a50b600c8bd
/Arduino Source/Solar_Tracking/Program_Manager.cpp
346319a1be05d3933d07e091a152adeee7520ef4
[]
no_license
quocbao238/SolarPannel-Tracking-IoT-ESP8266-MQTT-NodeRed
94f25ddf989f69791bf3eea4de10d6a3c9aaaaf0
39ce8059a2c824aadaf0c31977471419fcd815d3
refs/heads/master
2023-04-17T06:35:03.998663
2023-04-09T14:45:26
2023-04-09T14:45:26
234,499,786
0
0
null
null
null
null
UTF-8
C++
false
false
1,006
cpp
Program_Manager.cpp
#include "Program_Manager.h" /* Khai bao thu vien */ #include "helloWorld_Program.h" #include "blink_Program.h" #include "sensor_Program.h" #include "servo_Program.h" #include "ina219_Program.h" #include "button_Program.h" #include "buzzer_Program.h" #include "dht11_Program.h" #include "lcd_Program.h" /* List STATE */ Program_Adaptor_Class *p_ListProgram[LAST_PROGRAM_ID] = { &HelloWorld_Program, &Blink_Program, &Sensor_Program, &Servo_Program, &INA219_Program, &Buzzer_Program, &Button_Program, &DHT_Program, &LCD_Program, }; void programManager_setup(){ for(int cf = 0; cf < LAST_PROGRAM_ID; cf++){ p_ListProgram[cf]->setup(); } } void programManager_loop(){ ul_currentMililis = millis(); for(int cf = 0; cf < LAST_PROGRAM_ID; cf++){ if(ul_currentMililis - p_ListProgram[cf]->ul_lastMillis >= p_ListProgram[cf]->ul_timeRepeat){ p_ListProgram[cf]->ul_lastMillis = ul_currentMililis; p_ListProgram[cf]->loop(); } } }
0bc6c82d8ba425ad03cfb3d1079e5c7a0f6ade54
bc0945070d150c8af7cc56bf6e045a8c2cc7873d
/3214/2051329_WA.cpp
ad08cf9c0e2e706bbde8e5db361a8b70e9f175fd
[]
no_license
fengrenchang86/PKU
ab889d88cd62b3c0b3e00cde5d5c3a652a16221a
0c4adf6b740d2186b7f23124673cd56520d1c818
refs/heads/master
2021-01-10T12:12:18.100884
2016-03-07T14:14:33
2016-03-07T14:14:33
53,328,385
1
0
null
null
null
null
UTF-8
C++
false
false
976
cpp
2051329_WA.cpp
#include <iostream> #include <math.h> using namespace std; int v[25]; int f ( int x ) { int i = 0; while ( x > v[i] ) i++; if ( x == v[i] ) return 1; else return 0; } int main () { int n,m,p; int a,b; cin>>n; int c = 0; int *t = new int[pow(2,n)+1]; int i,j; v[0] = 1; for ( i = 1; i < 22; i++ ) v[i] = v[i-1]*2; for ( i = 1; i <= v[n]-1; i++ ) scanf("%d",&t[i]); a = v[n-1]+1; b = v[n]-1; for ( i = a; i <= b; i++ ) { if ( t[a] < t[a-1] ) { if ( a%2==0 ) t[a] += t[a-1]; else t[a] ++; c++; } } for ( i = n-1 ; i >= 1; i-- ) { a = v[i-1]-1; b = v[i]-1; if ( t[a] < t[a*2+1] ) { t[a] = t[a*2]+t[a*2+1]; c++; } for ( j = a; j <= b; j++ ) { m = p =0; if ( t[a] < t[a-1] ) { if ( a%2==0 ) m = t[a] + t[a-1]; else m = t[a]+1; } if ( t[a] < t[a*2+1] ) { p= t[a*2]+t[a*2+1]; } if ( m != 0 && p!=0 ) c++; t[a] = m>p?m:p; } } cout<<c<<endl; return 1; }
8f04bc17392e0e18b6daeb98c9479a97e56bfc4f
dc85c005fa80fee1ee649692cec1d5605e8bf9a9
/Jigsaw Puzzle/main.cpp
795e302d1b772280b5199b66bddca6b58a471274
[]
no_license
gt500girl/acmlib-zxd
38163efe0c550cfe68dab05bc7fc6e1e4416941b
50be5b9b4874130b8a7955d5c55f9823ea6f03b0
refs/heads/master
2021-01-10T10:57:16.491457
2009-05-09T00:41:35
2009-05-09T00:41:35
43,588,376
0
0
null
null
null
null
GB18030
C++
false
false
3,657
cpp
main.cpp
#include <iostream> using namespace std; //使用string类型存储方格状态 typedef char Jigsaw[10]; //初始状态 const Jigsaw st_state = "012345678"; //0-8的阶乘,打表存储,加快计算 const int fac[9][9] = {0,0,0,0,0,0,0,0,0, 0, 1, 2, 6, 24, 120, 720, 5040, 40320, 0, 2, 4, 12, 48, 240, 1440, 10080, 80640, 0, 3, 6, 18, }; //将状态依参数沿四个方向扩展 bool ch_state(Jigsaw& jigsaw, int ch) { int i0; for (i0 = 0; i0 < 9; i0++) if (jigsaw[i0] == '0') break; bool flag = false; switch (ch) { case 0: if (i0 - 3 >= 0) { jigsaw[i0] = jigsaw[i0-3]; jigsaw[i0-3] = '0'; flag = true; } break; case 1: if (i0 % 3 < 2) { jigsaw[i0] = jigsaw[i0+1]; jigsaw[i0+1] = '0'; flag = true; } break; case 2: if (i0 + 3 < 9) { jigsaw[i0] = jigsaw[i0+3]; jigsaw[i0+3] = '0'; flag = true; } break; case 3: if (i0 % 3 > 0) { jigsaw[i0] = jigsaw[i0-1]; jigsaw[i0-1] = '0'; flag = true; } break; } return flag; } //根据数字串在排列中的序号进行Hash编码 int hashcode(Jigsaw jigsaw) { bool app_flag[9] = {false}; int i, j; int code = 0; for (i = 0; i < 8; i++) { j = jigsaw[i] - 48; app_flag[j--] = true; int k = 0; for (; j >= 0; j--) { if (!app_flag[j]) k++; } code += k * fac[8-i]; } return code; } typedef struct Jigsaw_Que { Jigsaw jigsaw; int step; }; Jigsaw_Que state_que[362880]; int state_hash[362880]; int main() { freopen("input.txt", "r", stdin); freopen("out.txt", "w", stdout); //初始化哈希表 memset(state_hash, -1, sizeof(state_hash)); state_hash[0] = 0; //初始化队列 strcpy(state_que[0].jigsaw, st_state); int front = 0; int tail = 1; //接受输入前先打好Hash表 while (tail - front != 0) { //取出队头的状态 Jigsaw & cur_state = state_que[front].jigsaw; int step = state_que[front].step; front++; //步数加1 step++; //沿四个方向前进 for (int k = 0; k < 4; k++) { Jigsaw new_state; strcpy(new_state, cur_state); //判断前进是否成功 if (ch_state(new_state, k)) { //计算新状态的Hash码 int code = hashcode(new_state); //判断新状态是否出现过 if (state_hash[code] < 0) { //若新状态首次出现,则将其记入Hash表,并加入队列 state_hash[code] = step; strcpy(state_que[tail].jigsaw, new_state); state_que[tail].step = step; tail++; } } } } //临时接受输入的字符数组,用于scanf输入,加快速度 Jigsaw fi_state; //接受输入并从Hash表中查找值返回输出 while (scanf("%s", &fi_state) != EOF) { int code = hashcode(fi_state); //printf("%d\n", code); int step = state_hash[code]; if (step < 0) printf("NO\n"); else printf("%d\n", step); } return 0; }
9357f02ba392f7f91caf7ae719925294a12ef0b2
ad1b91e1536bcedb7a360d504473627e995cbd46
/src/server.hpp
af31e628fdff6e24414a19a3c202fc47be53eb64
[ "MIT" ]
permissive
lnfernal/LoopCube
f24031f0b72d7af6de6651d6f8fd6b0abddae36f
882296f32bfe3a8b1765950a9b8c9e24af75d009
refs/heads/master
2023-04-04T16:47:23.588432
2021-04-12T00:08:23
2021-04-12T00:08:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,117
hpp
server.hpp
#pragma once #include <iostream> #include <string> #include <memory> #include <vector> #include <thread> #include <sstream> #include <numeric> #include <iterator> #include <chrono> #include <mutex> #include <atomic> #include <algorithm> #include <cstring> #include <cstdint> #include <exception> #include <poll.h> #include <fcntl.h> #include "command_constants.hpp" #include "socketwrapper.hpp" #include "gameserver.hpp" #include "timer.hpp" #include "serverheader.hpp" struct Server; struct ServerThreadItem; struct ThreadData; struct NetworkError; // Error handling enum NERROR_TYPE { NRESOLUTION_ERROR = 1, NSOCKOPT_ERROR, NSOCKBIND_ERROR, NLISTEN_ERROR }; struct NetworkError: public std::exception { NetworkError(NERROR_TYPE type, const char* error) : std::exception(), type{type}, error{error} {}; virtual const char* what() const throw() { return error; }; NERROR_TYPE type; private: const char* error; }; // LOGGER (for server) namespace ServLog { bool warn(const std::string msg); bool error(const std::string msg); bool info(const std::string msg); bool log(const std::string msg); } // Server struct Server { Server(const uint32_t port, bool verbose = true); ~Server(); void startServer(const size_t threadCount = 1); // Note: Blocking void serverThread(const size_t index) noexcept; void startGameThread() noexcept; std::atomic<bool> exit; int fd; private: template <typename Iterator> std::string combineString(Iterator begin, Iterator end, const std::string delim = "") { std::stringstream str; for (std::vector<std::string>::iterator i = begin; i != end; ++i) { str << *i; if (i != end-1) str << delim; } return str.str(); } void removeConnection(ServerThreadItem& item, const size_t index); void handleCommand(ServerThreadItem& item, const size_t index); ServerThreadItem& minThreadCount(); #ifndef __NOIPLOG__ std::string getAddress(sockaddr* info); #endif // Commands void commandGetChunk(const int fd, const std::vector<unsigned char>& value); void commandPlaceBlockAbsolute(const int fd, const std::vector<ServerThreadItem>& threadPool, const std::vector<unsigned char>& value); void commandDestroyBlockAbsolute(const int fd, const std::vector<ServerThreadItem>& threadPool, const std::vector<unsigned char>& value); void commandPlayerPosition(const int fd, const std::vector<unsigned char>& value, const std::vector<ServerThreadItem>& threadPool, ConnectionData& connectionData); const uint32_t port; std::string address; // Threading std::vector<ServerThreadItem> threadPool; std::mutex tpLock; // threadPoolLock std::thread gameThread; fd_set checkaccept; // For accept checking GameServer game; addrinfo opts, *info; bool verbose; };
4b2cb60a65689cd297941d20facb7237bb4fb7f7
4070d3b1630a0b21c75e1d541bbb1de6a8347e6c
/UFT/SDK/WB_Notification_Button_classes.h
5295633ebb8558e475a59b39701f019c261db3d9
[]
no_license
Game-Academy-of-Sciences/AimGods
fa13b4a5a2bcbbf809a4be9f4f756e581edcdf51
3f91c8c2ef03f32451a51e701bee3e86823a5982
refs/heads/main
2023-02-17T06:30:49.301528
2021-01-01T00:52:43
2021-01-01T00:52:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,055
h
WB_Notification_Button_classes.h
#pragma once // Name: AimGods, Version: Beta 2 #ifdef _MSC_VER #pragma pack(push, 0x01) #endif /*!!HELPER_DEF!!*/ /*!!DEFINE!!*/ namespace UFT { //--------------------------------------------------------------------------- // Classes //--------------------------------------------------------------------------- // WidgetBlueprintGeneratedClass WB_Notification_Button.WB_Notification_Button_C // 0x0081 (FullSize[0x02B1] - InheritedSize[0x0230]) class UWB_Notification_Button_C : public UUserWidget { public: struct FPointerToUberGraphFrame UberGraphFrame; // 0x0230(0x0008) (ZeroConstructor, Transient, DuplicateTransient) class UWidgetAnimation* Ping; // 0x0238(0x0008) (BlueprintVisible, BlueprintReadOnly, ZeroConstructor, Transient, IsPlainOldData, RepSkip, NoDestructor, HasGetValueTypeHash) class UWidgetAnimation* PopInOut; // 0x0240(0x0008) (BlueprintVisible, BlueprintReadOnly, ZeroConstructor, Transient, IsPlainOldData, RepSkip, NoDestructor, HasGetValueTypeHash) class UWidgetAnimation* ClickedAnimation; // 0x0248(0x0008) (BlueprintVisible, BlueprintReadOnly, ZeroConstructor, Transient, IsPlainOldData, RepSkip, NoDestructor, HasGetValueTypeHash) class UWidgetAnimation* Hover; // 0x0250(0x0008) (BlueprintVisible, BlueprintReadOnly, ZeroConstructor, Transient, IsPlainOldData, RepSkip, NoDestructor, HasGetValueTypeHash) class UImage* BG; // 0x0258(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UButton* Button_1; // 0x0260(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UCanvasPanel* Canvas; // 0x0268(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UImage* Icon; // 0x0270(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UTextBlock* Quantity; // 0x0278(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class USizeBox* QuantityBox; // 0x0280(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UTexture2D* Texture; // 0x0288(0x0008) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData, NoDestructor, ExposeOnSpawn, HasGetValueTypeHash) struct FLinearColor Color; // 0x0290(0x0010) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData, NoDestructor, ExposeOnSpawn, HasGetValueTypeHash) struct FScriptMulticastDelegate Clicked; // 0x02A0(0x0010) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, BlueprintAssignable, BlueprintCallable) bool Displayed; // 0x02B0(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData, NoDestructor) static UClass* StaticClass() { static auto ptr = UObject::FindClass("WidgetBlueprintGeneratedClass WB_Notification_Button.WB_Notification_Button_C"); return ptr; } void Initialize(); void BndEvt__Button_0_K2Node_ComponentBoundEvent_0_OnButtonClickedEvent__DelegateSignature(); void BndEvt__Button_0_K2Node_ComponentBoundEvent_1_OnButtonHoverEvent__DelegateSignature(); void BndEvt__Button_0_K2Node_ComponentBoundEvent_2_OnButtonHoverEvent__DelegateSignature(); void SwapVisibility(bool Displayed, int Quantity); void Construct(); void PreConstruct(bool IsDesignTime); void ExecuteUbergraph_WB_Notification_Button(int EntryPoint); void Clicked__DelegateSignature(); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
f9ab28a83da2c17ec3bd34ab6a2f73955f46e8b5
3cb6e7bb308cadc44c795eb7c0addee34eb2349f
/c++/25A.cpp
a609d138eac91be537091e34dabf1dd7d64a923f
[]
no_license
lpy00511/Ccode
9e8300057979d6fe3554ad4b06fa0312a9be6ca0
fd038cb655aa9b280281efc4fb1ca194170987e8
refs/heads/master
2020-05-21T19:14:26.189377
2017-08-31T01:18:08
2017-08-31T01:18:08
53,333,077
0
0
null
null
null
null
UTF-8
C++
false
false
510
cpp
25A.cpp
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> using namespace std; int cnt[105]; int main() { int n, x, cnt1 = 0, cnt2=0; scanf("%d", &n); for(int i = 1; i <= n; i++) { scanf("%d", &cnt[i]); if(cnt[i] % 2 == 0) { cnt[i] = -1; cnt1++; } else cnt2++; } if(cnt1 == 1) { for(int i = 1; i <= n;i++) { if(cnt[i] == -1) printf("%d\n", i); } } else { for(int i = 1; i <= n;i++) { if(cnt[i] != -1) printf("%d\n", i); } } return 0; }
c0df59b90a908cbbba3d47aaf241c371c19fe972
c4bee399f9a6ff4f8581ac1ced4f83a17e4bf390
/C++/cpp/dynamic_space_in_function.cpp
cd38c563fd1b0a6a7e17c7faa80cc8c233948415
[]
no_license
siddharthcurious/Coding
c1ed1b53b4fd8a0f6c91fbeb13851fe18ffce4d5
39efcbd02e55a72d21bf5905b6067750d7e01c2d
refs/heads/master
2021-06-18T09:29:37.698893
2017-06-26T13:18:16
2017-06-26T13:18:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
245
cpp
dynamic_space_in_function.cpp
#include <iostream> using namespace std; int * fun(){ int *k = new int(10); //cout<<&k<<endl; return k; } int main(){ int *ptr = fun(); *ptr = 40; cout<<*ptr<<endl; int *nptr = fun(); cout<<*nptr<<endl; return 0; }
ccfd9beaf1604e14b3b8dd2b76990438b36a16c1
ac5af3d4a60ecec85ebed44502b70eece28f726f
/Kuangbin/Kuangbin专题一 简单搜索/qhb/H_other.cpp
fa6fddeff493e8f11a2a9d973925d6403fda67a0
[]
no_license
qhb1001/For-that-dream
29f473cb4301bba70985c1c6ac4a152e237598fe
624a21572e9d674f007d9f65d560e83d281d7497
refs/heads/master
2020-03-09T21:33:28.847612
2018-09-27T13:39:53
2018-09-27T13:39:53
129,012,092
4
1
null
null
null
null
UTF-8
C++
false
false
2,260
cpp
H_other.cpp
#include <iostream> #include <algorithm> using namespace std; #include <cstring> #include <queue> #include <stack> struct cup { int x, y; int step; int flag;//标记操作 cup *pre;//记录路径 }; queue<cup>Q; stack<int>R; int a, b, e; int vis[117][117]={0};//标记当前状态是否到达过 int ans; void BFS(int x, int y) { cup c; cup t[317];//目前瓶子里剩余的水量 c.x = 0, c.y = 0; c.flag = 0; c.pre = NULL; c.step = 0; Q.push(c); vis[x][y] = 1; int count = -1; while(!Q.empty()) { count++; t[count] = Q.front(); Q.pop(); for(int i = 1; i <= 6; i++) { switch(i) { case 1: //fill a c.x = a; c.y = t[count].y; c.flag = 1; break; case 2: //fill b c.x = t[count].x; c.y = b; c.flag = 2; break; case 3: //drop a c.x = 0; c.y = t[count].y; c.flag = 3; break; case 4: //drop b c.x = t[count].x; c.y = 0; c.flag = 4; break; case 5: //pour a to b if(t[count].x > b-t[count].y) { c.x = t[count].x-(b-t[count].y); c.y = b; } else { c.x = 0; c.y = t[count].y+t[count].x; } c.flag = 5; break; case 6: //pour b to a if(t[count].y > a-t[count].x) { c.y = t[count].y - (a-t[count].x); c.x = a; } else { c.x = t[count].x+t[count].y; c.y = 0; } c.flag = 6; break; } if(vis[c.x][c.y]) continue; vis[c.x][c.y] = 1; c.step = t[count].step+1; c.pre = &t[count]; if(c.x == e || c.y == e) { ans = c.step; while(c.pre) { R.push(c.flag); c = *c.pre; } return; } Q.push(c); } } } void print() { while(!R.empty()) { int i = R.top(); R.pop(); switch(i) { case 1:cout<<"FILL(1)"<<endl;break; case 2:cout<<"FILL(2)"<<endl;break; case 3:cout<<"DROP(1)"<<endl;break; case 4:cout<<"DROP(2)"<<endl;break; case 5:cout<<"POUR(1,2)"<<endl;break; case 6:cout<<"POUR(2,1)"<<endl;break; } } } int main() { freopen("input", "r", stdin); freopen("output.b", "w", stdout); cin >>a>>b>>e; BFS(0,0); if(ans == 0) cout<<"impossible"<<endl; else { cout<<ans<<endl; print(); } return 0; }
c1e96621cd94f72b1d395c8f0ab81441b627fe9f
19bad9e5b81d0124267c4037b329c9d62868a1f7
/Entity.cpp
65b1a8504be26c1686f0f91fbadac61a5536fa90
[]
no_license
OptixW/csgoInternal
ec7f31d46272596a946514831cfbf1010e80c852
44e4683fac099583f2e7ad6d60f85c28920cee0f
refs/heads/master
2023-09-05T21:40:00.693440
2021-11-20T17:57:00
2021-11-20T17:57:00
360,175,913
0
0
null
null
null
null
UTF-8
C++
false
false
3,142
cpp
Entity.cpp
#include "Entity.hpp" #include <cstdint> #include "Weapon.hpp" bool CBaseEntity::IsPlayer() { typedef bool(__thiscall* IsPlayerFn)(void*); return call_vfunc<IsPlayerFn>(this, 152)(this); } bool CBaseEntity::IsValid() { return (IsDead() == 0 && GetHealth() >= 1 && !IsDormant()) ? true : false; } bool CBaseEntity::IsDormant() { typedef bool(__thiscall* IsDormantFn)(void*); void* pNetworkable = GetNetworkable(); return call_vfunc<IsDormantFn>(pNetworkable, 9)(pNetworkable); } bool CBaseEntity::IsDead() { return *(bool*)(this + netvars::m_lifeState); } bool CBaseEntity::IsDefusing() { return *(bool*)(this + netvars::m_bIsDefusing); } int CBaseEntity::GetArmor() { return *(int*)(this + netvars::m_ArmorValue); } bool CBaseEntity::HasHelmet() { return *(bool*)(this + netvars::m_bHasHelmet); } int CBaseEntity::GetFlags() { return *(int*)(this + netvars::m_fFlags); } int CBaseEntity::GetHealth() { return *(int*)(this + netvars::m_iHealth); } int CBaseEntity::GetTeamNum() { return *(int*)(this + netvars::m_iTeamNum); } int CBaseEntity::GetTickBase() { return *(int*)(this + netvars::m_nTickBase); } int CBaseEntity::GetShotsFired() { return *(int*)(this + netvars::m_iShotsFired); } int CBaseEntity::GetCollisionGroup() { return *(int*)(this + netvars::m_CollisionGroup); } int CBaseEntity::GetCrosshairID() { return *(int*)(this + netvars::m_iCrosshairId); } Source::Vector3 CBaseEntity::GetAbsAngles() { Source::Vector3 angles; angles.x = *(float*)(this + netvars::m_angEyeAnglesX); angles.y = *(float*)(this + netvars::m_angEyeAnglesY); return angles; } DWORD_PTR CBaseEntity::GetActiveWeapon() { return *(uintptr_t*)(this + netvars::m_hActiveWeapon); } CBaseWeapon* CBaseEntity::GetBaseWeapon(IClientEntityList* lst) { return (CBaseWeapon*)lst->GetClientEntityFromHandle(GetActiveWeapon()); } Source::Vector3 CBaseEntity::GetPunchAngle() { return *(Source::Vector3*)(this + netvars::m_aimPunchAngle); } Source::Vector3 CBaseEntity::GetEyePosition() { return GetAbsOrigin() + GetViewOffset() + GetVelocity() * pServer->interval_per_tick; } Source::Vector3 CBaseEntity::GetAbsOrigin() { return *(Source::Vector3*)(this + netvars::m_vecOrigin); } Source::Vector3 CBaseEntity::GetBonePosition(int bone) { Source::matrix3x4_t matrix[128]; Source::Vector3 ret; if (!SetupBones(matrix, 128, 0x100, GetTickBase() * pServer->interval_per_tick)) return ret; ret.Init(matrix[bone][0][3], matrix[bone][1][3], matrix[bone][2][3]); return ret; } bool CBaseEntity::SetupBones(Source::matrix3x4_t* pMatrix, int nMaxBones, int nMask, float fTime) { typedef bool(__thiscall* SetupBonesFn)(void*, Source::matrix3x4_t*, int, int, float); return call_vfunc<SetupBonesFn>(GetRenderable(), 13)(GetRenderable(), pMatrix, nMaxBones, nMask, fTime); } Source::Vector3 CBaseEntity::GetViewOffset() { return *(Source::Vector3*)(this + netvars::m_vecViewOffset); } Source::Vector3 CBaseEntity::GetVelocity() { return *(Source::Vector3*)(this + netvars::m_vecVelocity); } void* CBaseEntity::GetRenderable() { return (void*)(this + 4); } void* CBaseEntity::GetNetworkable() { return (void*)(this + 8); }
9f0607745b5c996713f2626f1e67195d1ccd46e4
95d7fe2d932955d69acbfb049b690d38986243b1
/rendu/rendu1/MLAlgorithms/ML_Library/ML_Library/gradientDescent.cpp
83c2ce4f7f784ff1bf8cd47cda798835874649cc
[]
no_license
AlexisLib/AgeRecognition
9a9e496de0e05a2ee47b81d427823052a19c8e99
85bab5c1a2efd4b6569ba98950ccf92aa78bc7f0
refs/heads/main
2023-08-30T21:27:52.771711
2021-10-15T10:13:52
2021-10-15T10:13:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,263
cpp
gradientDescent.cpp
#include "include.h" extern "C" { SUPEREXPORT double fit_regression_gd( double* arrayWeight, double* XTrain, double* YTrain, int sampleCount, int inputCountPerSample ) { int nb_epoch = 100; double lr = 1.1; Eigen::MatrixXd X = convertArrayToMatrix(sampleCount, inputCountPerSample, XTrain); Eigen::MatrixXd Y = convertArrayToMatrix(sampleCount, 1, YTrain); Eigen::MatrixXd W = convertArrayToMatrix(inputCountPerSample, 1, arrayWeight); Eigen::MatrixXd mat(0, 0); Eigen::MatrixXd result = Eigen::MatrixXd::Constant(inputCountPerSample, 1, 0); //W << 0.1, 0.1, 0.1; for (int epo = 0; epo < nb_epoch; epo++) { result = Eigen::MatrixXd::Constant(inputCountPerSample, 1, 0); for (int j = 0; j < inputCountPerSample; j++) { for (int i = 0; i < sampleCount; i++) { mat = X.block(i, 0, 1, inputCountPerSample) * W; result(j, 0) += -X(i, j) * (Y(i, 0) - mat(0, 0)); } } for (int i = 0; i < inputCountPerSample; i++) { result(i, 0) = result(i, 0) * (float(1) / sampleCount); W(i, 0) = W(i, 0) - lr * result(i, 0); } } std::cout << "W : " << std::endl; std::cout << W << std::endl; std::cout << "--" << std::endl; convertMatrixToSimpleArray(W, arrayWeight); return 0.42; } }
543f17086f6073cfc59ae098decf9a8865a64b3b
28b8d06083bfdc39effb394e615c589e39864e18
/src/ProductGenerator.hpp
8c3464e5d7de513319b59815d070bfcd5895c752
[]
no_license
SeadogAhn/SimSemi
4da68c6564db99f5fcf5b7f40674b1b3f87ad535
325bfcb0081f330943e88b9f0ba565c1ae3e5d75
refs/heads/master
2021-01-25T11:27:17.724838
2018-11-07T07:02:56
2018-11-07T07:02:56
93,922,168
0
0
null
null
null
null
UTF-8
C++
false
false
1,287
hpp
ProductGenerator.hpp
#ifndef __PRODUCT_GENERATOR_HPP__ #define __PRODUCT_GENERATOR_HPP__ // SIMSEMI headers #include "Types.hpp" #include "Lot.hpp" #include "ProductSpecification.hpp" // standard libraries //! the namespace of the simulation for the manufacturing semiconductor process namespace SIMSEMI { //! Product Generator class CProductGenerator : public CProductSpecification { public: typedef std::vector< CLot > LotContainer; // key : partid = the number of the product, value : lot typedef std::map< int, LotContainer > ProductContainer; //! ;default constructor CProductGenerator(); //! destructor ~CProductGenerator(); //! initialize Master Plan /*! \param strFileName a file name of master plan */ void InitProductMasterPlan(const std::string& strFileName); //! add new demand product /*! \param nPart new demand product id \param nQuantity quantity of the product */ void AddNewDemand(int nPart, int nQuantity); //! Get the container of the products /*! \param Product Container */ const ProductContainer& GetProducts() const { return Products_; } private: //! make Lots LotContainer MakeLots(int nQuantity); ProductContainer Products_; ///< container of lots }; } #endif // __PRODUCT_GENERATOR_HPP__
81ad507c4a98f042e170b84b1eb298e1b0c06484
5d71240dce3897cbad3b2b2d9012ea1c0a0ddeab
/SnakeGame/HighScores.cpp
2cbb1360f53dde12312d5bc7980a9e531709c982
[]
no_license
tsucevic/SPA_SFML_Snake_TinSucevic
ac9e1a3b4be6dfca1b6eefe3e6dead4bdb5e37a4
f7fe6c8630e605305060c5457574f7fe4c571367
refs/heads/master
2022-06-09T21:10:00.871980
2020-05-11T13:25:00
2020-05-11T13:25:00
262,751,418
0
0
null
null
null
null
UTF-8
C++
false
false
1,197
cpp
HighScores.cpp
#include "HighScores.h" void HighScores::init(int width, int height) { if (!font.loadFromFile("arial.ttf")) { } savior.loadScores(); scores = savior.getHighScoreList(); //settings menu[0].setFont(font); menu[0].setFillColor(Color::Red); menu[0].setString("Menu"); menu[0].setPosition(Vector2f((width / 9) * 4, height / (MAX_NUMBER_OF_ITEMS + 1) * 1)); int i = 0; for (auto it = scores.begin(); it != scores.end(); ++it) { stringstream ss; ss << "ID: " << it->ID << " SCORE: " << it->score; menu[i].setFont(font); menu[i].setFillColor(Color::White); menu[i].setString(ss.str()); menu[i].setPosition(Vector2f((width / 9) * 4, height / (MAX_NUMBER_OF_ITEMS + 1) * i+1)); i++; } selectedItemIndex = 1; } void HighScores::draw(RenderWindow* window) { for (int i = 0; i < MAX_NUMBER_OF_ITEMS; i++) { window->draw(menu[i]); } } int HighScores::getPressedItem() { return selectedItemIndex; } int HighScores::keyPress(Keystroke key) { switch (key.value) { case sf::Keyboard::Return: switch (getPressedItem()) { case 0: std::cout << "Menu button has been pressed" << std::endl; return 1; break; default: break; } default: break; } }
cd7d9b42d7a6fc49d00c89f61c8235391e9b7d0e
9da899bf6541c6a0514219377fea97df9907f0ae
/Runtime/Renderer/Private/GenerateConservativeDepthBuffer.h
d48517a44d086747dcce610edbd056c0d0077aee
[]
no_license
peichangliang123/UE4
1aa4df3418c077dd8f82439ecc808cd2e6de4551
20e38f42edc251ee96905ed8e96e1be667bc14a5
refs/heads/master
2023-08-17T11:31:53.304431
2021-09-15T00:31:03
2021-09-15T00:31:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
497
h
GenerateConservativeDepthBuffer.h
// Copyright Epic Games, Inc. All Rights Reserved. /*============================================================================= GenerateConservativeDepth.h =============================================================================*/ #pragma once #include "RenderGraphResources.h" class FViewInfo; class FRDGBuilder; void AddGenerateConservativeDepthBufferPass(FViewInfo& View, FRDGBuilder& GraphBuilder, FRDGTextureRef ConservativeDepthTexture, int32 DestinationPixelSizeAtFullRes);
f10a98b76bdfd79afeff70ba24cf54f6dc2763ee
f7dc806f341ef5dbb0e11252a4693003a66853d5
/thirdparty/embree/kernels/common/accel.h
d24326ce92cd4855b5ee924455806321c8797fa3
[ "LicenseRef-scancode-free-unknown", "MIT", "CC-BY-4.0", "OFL-1.1", "Bison-exception-2.2", "CC0-1.0", "LicenseRef-scancode-nvidia-2002", "LicenseRef-scancode-other-permissive", "GPL-3.0-only", "LicenseRef-scancode-unknown-license-reference", "Unlicense", "BSL-1.0", "Apache-2.0", "BSD-3-Clause", "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unicode", "BSD-2-Clause", "FTL", "GPL-3.0-or-later", "Bitstream-Vera", "Zlib", "MPL-2.0", "MIT-Modern-Variant", "JSON", "Libpng" ]
permissive
godotengine/godot
8a2419750f4851d1426a8f3bcb52cac5c86f23c2
970be7afdc111ccc7459d7ef3560de70e6d08c80
refs/heads/master
2023-08-21T14:37:00.262883
2023-08-21T06:26:15
2023-08-21T06:26:15
15,634,981
68,852
18,388
MIT
2023-09-14T21:42:16
2014-01-04T16:05:36
C++
UTF-8
C++
false
false
23,319
h
accel.h
// Copyright 2009-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 #pragma once #include "default.h" #include "ray.h" #include "point_query.h" #include "context.h" namespace embree { class Scene; /*! Base class for the acceleration structure data. */ class AccelData : public RefCount { ALIGNED_CLASS_(16); public: enum Type { TY_UNKNOWN = 0, TY_ACCELN = 1, TY_ACCEL_INSTANCE = 2, TY_BVH4 = 3, TY_BVH8 = 4 }; public: AccelData (const Type type) : bounds(empty), type(type) {} /*! notifies the acceleration structure about the deletion of some geometry */ virtual void deleteGeometry(size_t geomID) {}; /*! clears the acceleration structure data */ virtual void clear() = 0; /*! returns normal bounds */ __forceinline BBox3fa getBounds() const { return bounds.bounds(); } /*! returns bounds for some time */ __forceinline BBox3fa getBounds(float t) const { return bounds.interpolate(t); } /*! returns linear bounds */ __forceinline LBBox3fa getLinearBounds() const { return bounds; } /*! checks if acceleration structure is empty */ __forceinline bool isEmpty() const { return bounds.bounds0.lower.x == float(pos_inf); } public: LBBox3fa bounds; // linear bounds Type type; }; /*! Base class for all intersectable and buildable acceleration structures. */ class Accel : public AccelData { ALIGNED_CLASS_(16); public: struct Intersectors; /*! Type of collide function */ typedef void (*CollideFunc)(void* bvh0, void* bvh1, RTCCollideFunc callback, void* userPtr); /*! Type of point query function */ typedef bool(*PointQueryFunc)(Intersectors* This, /*!< this pointer to accel */ PointQuery* query, /*!< point query for lookup */ PointQueryContext* context); /*!< point query context */ /*! Type of intersect function pointer for single rays. */ typedef void (*IntersectFunc)(Intersectors* This, /*!< this pointer to accel */ RTCRayHit& ray, /*!< ray to intersect */ IntersectContext* context); /*! Type of intersect function pointer for ray packets of size 4. */ typedef void (*IntersectFunc4)(const void* valid, /*!< pointer to valid mask */ Intersectors* This, /*!< this pointer to accel */ RTCRayHit4& ray, /*!< ray packet to intersect */ IntersectContext* context); /*! Type of intersect function pointer for ray packets of size 8. */ typedef void (*IntersectFunc8)(const void* valid, /*!< pointer to valid mask */ Intersectors* This, /*!< this pointer to accel */ RTCRayHit8& ray, /*!< ray packet to intersect */ IntersectContext* context); /*! Type of intersect function pointer for ray packets of size 16. */ typedef void (*IntersectFunc16)(const void* valid, /*!< pointer to valid mask */ Intersectors* This, /*!< this pointer to accel */ RTCRayHit16& ray, /*!< ray packet to intersect */ IntersectContext* context); /*! Type of intersect function pointer for ray packets of size N. */ typedef void (*IntersectFuncN)(Intersectors* This, /*!< this pointer to accel */ RTCRayHitN** ray, /*!< ray stream to intersect */ const size_t N, /*!< number of rays in stream */ IntersectContext* context /*!< layout flags */); /*! Type of occlusion function pointer for single rays. */ typedef void (*OccludedFunc) (Intersectors* This, /*!< this pointer to accel */ RTCRay& ray, /*!< ray to test occlusion */ IntersectContext* context); /*! Type of occlusion function pointer for ray packets of size 4. */ typedef void (*OccludedFunc4) (const void* valid, /*!< pointer to valid mask */ Intersectors* This, /*!< this pointer to accel */ RTCRay4& ray, /*!< ray packet to test occlusion. */ IntersectContext* context); /*! Type of occlusion function pointer for ray packets of size 8. */ typedef void (*OccludedFunc8) (const void* valid, /*!< pointer to valid mask */ Intersectors* This, /*!< this pointer to accel */ RTCRay8& ray, /*!< ray packet to test occlusion. */ IntersectContext* context); /*! Type of occlusion function pointer for ray packets of size 16. */ typedef void (*OccludedFunc16) (const void* valid, /*!< pointer to valid mask */ Intersectors* This, /*!< this pointer to accel */ RTCRay16& ray, /*!< ray packet to test occlusion. */ IntersectContext* context); /*! Type of intersect function pointer for ray packets of size N. */ typedef void (*OccludedFuncN)(Intersectors* This, /*!< this pointer to accel */ RTCRayN** ray, /*!< ray stream to test occlusion */ const size_t N, /*!< number of rays in stream */ IntersectContext* context /*!< layout flags */); typedef void (*ErrorFunc) (); struct Collider { Collider (ErrorFunc error = nullptr) : collide((CollideFunc)error), name(nullptr) {} Collider (CollideFunc collide, const char* name) : collide(collide), name(name) {} operator bool() const { return name; } public: CollideFunc collide; const char* name; }; struct Intersector1 { Intersector1 (ErrorFunc error = nullptr) : intersect((IntersectFunc)error), occluded((OccludedFunc)error), name(nullptr) {} Intersector1 (IntersectFunc intersect, OccludedFunc occluded, const char* name) : intersect(intersect), occluded(occluded), pointQuery(nullptr), name(name) {} Intersector1 (IntersectFunc intersect, OccludedFunc occluded, PointQueryFunc pointQuery, const char* name) : intersect(intersect), occluded(occluded), pointQuery(pointQuery), name(name) {} operator bool() const { return name; } public: static const char* type; IntersectFunc intersect; OccludedFunc occluded; PointQueryFunc pointQuery; const char* name; }; struct Intersector4 { Intersector4 (ErrorFunc error = nullptr) : intersect((IntersectFunc4)error), occluded((OccludedFunc4)error), name(nullptr) {} Intersector4 (IntersectFunc4 intersect, OccludedFunc4 occluded, const char* name) : intersect(intersect), occluded(occluded), name(name) {} operator bool() const { return name; } public: static const char* type; IntersectFunc4 intersect; OccludedFunc4 occluded; const char* name; }; struct Intersector8 { Intersector8 (ErrorFunc error = nullptr) : intersect((IntersectFunc8)error), occluded((OccludedFunc8)error), name(nullptr) {} Intersector8 (IntersectFunc8 intersect, OccludedFunc8 occluded, const char* name) : intersect(intersect), occluded(occluded), name(name) {} operator bool() const { return name; } public: static const char* type; IntersectFunc8 intersect; OccludedFunc8 occluded; const char* name; }; struct Intersector16 { Intersector16 (ErrorFunc error = nullptr) : intersect((IntersectFunc16)error), occluded((OccludedFunc16)error), name(nullptr) {} Intersector16 (IntersectFunc16 intersect, OccludedFunc16 occluded, const char* name) : intersect(intersect), occluded(occluded), name(name) {} operator bool() const { return name; } public: static const char* type; IntersectFunc16 intersect; OccludedFunc16 occluded; const char* name; }; struct IntersectorN { IntersectorN (ErrorFunc error = nullptr) : intersect((IntersectFuncN)error), occluded((OccludedFuncN)error), name(nullptr) {} IntersectorN (IntersectFuncN intersect, OccludedFuncN occluded, const char* name) : intersect(intersect), occluded(occluded), name(name) {} operator bool() const { return name; } public: static const char* type; IntersectFuncN intersect; OccludedFuncN occluded; const char* name; }; struct Intersectors { Intersectors() : ptr(nullptr), leafIntersector(nullptr), collider(nullptr), intersector1(nullptr), intersector4(nullptr), intersector8(nullptr), intersector16(nullptr), intersectorN(nullptr) {} Intersectors (ErrorFunc error) : ptr(nullptr), leafIntersector(nullptr), collider(error), intersector1(error), intersector4(error), intersector8(error), intersector16(error), intersectorN(error) {} void print(size_t ident) { if (collider.name) { for (size_t i=0; i<ident; i++) std::cout << " "; std::cout << "collider = " << collider.name << std::endl; } if (intersector1.name) { for (size_t i=0; i<ident; i++) std::cout << " "; std::cout << "intersector1 = " << intersector1.name << std::endl; } if (intersector4.name) { for (size_t i=0; i<ident; i++) std::cout << " "; std::cout << "intersector4 = " << intersector4.name << std::endl; } if (intersector8.name) { for (size_t i=0; i<ident; i++) std::cout << " "; std::cout << "intersector8 = " << intersector8.name << std::endl; } if (intersector16.name) { for (size_t i=0; i<ident; i++) std::cout << " "; std::cout << "intersector16 = " << intersector16.name << std::endl; } if (intersectorN.name) { for (size_t i=0; i<ident; i++) std::cout << " "; std::cout << "intersectorN = " << intersectorN.name << std::endl; } } void select(bool filter) { if (intersector4_filter) { if (filter) intersector4 = intersector4_filter; else intersector4 = intersector4_nofilter; } if (intersector8_filter) { if (filter) intersector8 = intersector8_filter; else intersector8 = intersector8_nofilter; } if (intersector16_filter) { if (filter) intersector16 = intersector16_filter; else intersector16 = intersector16_nofilter; } if (intersectorN_filter) { if (filter) intersectorN = intersectorN_filter; else intersectorN = intersectorN_nofilter; } } __forceinline bool pointQuery (PointQuery* query, PointQueryContext* context) { assert(intersector1.pointQuery); return intersector1.pointQuery(this,query,context); } /*! collides two scenes */ __forceinline void collide (Accel* scene0, Accel* scene1, RTCCollideFunc callback, void* userPtr) { assert(collider.collide); collider.collide(scene0->intersectors.ptr,scene1->intersectors.ptr,callback,userPtr); } /*! Intersects a single ray with the scene. */ __forceinline void intersect (RTCRayHit& ray, IntersectContext* context) { assert(intersector1.intersect); intersector1.intersect(this,ray,context); } /*! Intersects a packet of 4 rays with the scene. */ __forceinline void intersect4 (const void* valid, RTCRayHit4& ray, IntersectContext* context) { assert(intersector4.intersect); intersector4.intersect(valid,this,ray,context); } /*! Intersects a packet of 8 rays with the scene. */ __forceinline void intersect8 (const void* valid, RTCRayHit8& ray, IntersectContext* context) { assert(intersector8.intersect); intersector8.intersect(valid,this,ray,context); } /*! Intersects a packet of 16 rays with the scene. */ __forceinline void intersect16 (const void* valid, RTCRayHit16& ray, IntersectContext* context) { assert(intersector16.intersect); intersector16.intersect(valid,this,ray,context); } /*! Intersects a stream of N rays in SOA layout with the scene. */ __forceinline void intersectN (RTCRayHitN** rayN, const size_t N, IntersectContext* context) { assert(intersectorN.intersect); intersectorN.intersect(this,rayN,N,context); } #if defined(__SSE__) || defined(__ARM_NEON) __forceinline void intersect(const vbool4& valid, RayHitK<4>& ray, IntersectContext* context) { const vint<4> mask = valid.mask32(); intersect4(&mask,(RTCRayHit4&)ray,context); } #endif #if defined(__AVX__) __forceinline void intersect(const vbool8& valid, RayHitK<8>& ray, IntersectContext* context) { const vint<8> mask = valid.mask32(); intersect8(&mask,(RTCRayHit8&)ray,context); } #endif #if defined(__AVX512F__) __forceinline void intersect(const vbool16& valid, RayHitK<16>& ray, IntersectContext* context) { const vint<16> mask = valid.mask32(); intersect16(&mask,(RTCRayHit16&)ray,context); } #endif template<int K> __forceinline void intersectN (RayHitK<K>** rayN, const size_t N, IntersectContext* context) { intersectN((RTCRayHitN**)rayN,N,context); } /*! Tests if single ray is occluded by the scene. */ __forceinline void occluded (RTCRay& ray, IntersectContext* context) { assert(intersector1.occluded); intersector1.occluded(this,ray,context); } /*! Tests if a packet of 4 rays is occluded by the scene. */ __forceinline void occluded4 (const void* valid, RTCRay4& ray, IntersectContext* context) { assert(intersector4.occluded); intersector4.occluded(valid,this,ray,context); } /*! Tests if a packet of 8 rays is occluded by the scene. */ __forceinline void occluded8 (const void* valid, RTCRay8& ray, IntersectContext* context) { assert(intersector8.occluded); intersector8.occluded(valid,this,ray,context); } /*! Tests if a packet of 16 rays is occluded by the scene. */ __forceinline void occluded16 (const void* valid, RTCRay16& ray, IntersectContext* context) { assert(intersector16.occluded); intersector16.occluded(valid,this,ray,context); } /*! Tests if a stream of N rays in SOA layout is occluded by the scene. */ __forceinline void occludedN (RTCRayN** rayN, const size_t N, IntersectContext* context) { assert(intersectorN.occluded); intersectorN.occluded(this,rayN,N,context); } #if defined(__SSE__) || defined(__ARM_NEON) __forceinline void occluded(const vbool4& valid, RayK<4>& ray, IntersectContext* context) { const vint<4> mask = valid.mask32(); occluded4(&mask,(RTCRay4&)ray,context); } #endif #if defined(__AVX__) __forceinline void occluded(const vbool8& valid, RayK<8>& ray, IntersectContext* context) { const vint<8> mask = valid.mask32(); occluded8(&mask,(RTCRay8&)ray,context); } #endif #if defined(__AVX512F__) __forceinline void occluded(const vbool16& valid, RayK<16>& ray, IntersectContext* context) { const vint<16> mask = valid.mask32(); occluded16(&mask,(RTCRay16&)ray,context); } #endif template<int K> __forceinline void occludedN (RayK<K>** rayN, const size_t N, IntersectContext* context) { occludedN((RTCRayN**)rayN,N,context); } /*! Tests if single ray is occluded by the scene. */ __forceinline void intersect(RTCRay& ray, IntersectContext* context) { occluded(ray, context); } /*! Tests if a packet of K rays is occluded by the scene. */ template<int K> __forceinline void intersect(const vbool<K>& valid, RayK<K>& ray, IntersectContext* context) { occluded(valid, ray, context); } /*! Tests if a packet of N rays in SOA layout is occluded by the scene. */ template<int K> __forceinline void intersectN(RayK<K>** rayN, const size_t N, IntersectContext* context) { occludedN(rayN, N, context); } public: AccelData* ptr; void* leafIntersector; Collider collider; Intersector1 intersector1; Intersector4 intersector4; Intersector4 intersector4_filter; Intersector4 intersector4_nofilter; Intersector8 intersector8; Intersector8 intersector8_filter; Intersector8 intersector8_nofilter; Intersector16 intersector16; Intersector16 intersector16_filter; Intersector16 intersector16_nofilter; IntersectorN intersectorN; IntersectorN intersectorN_filter; IntersectorN intersectorN_nofilter; }; public: /*! Construction */ Accel (const AccelData::Type type) : AccelData(type) {} /*! Construction */ Accel (const AccelData::Type type, const Intersectors& intersectors) : AccelData(type), intersectors(intersectors) {} /*! Virtual destructor */ virtual ~Accel() {} /*! makes the acceleration structure immutable */ virtual void immutable () {} /*! build acceleration structure */ virtual void build () = 0; public: Intersectors intersectors; }; #define DEFINE_COLLIDER(symbol,collider) \ Accel::Collider symbol() { \ return Accel::Collider((Accel::CollideFunc)collider::collide, \ TOSTRING(isa) "::" TOSTRING(symbol)); \ } #define DEFINE_INTERSECTOR1(symbol,intersector) \ Accel::Intersector1 symbol() { \ return Accel::Intersector1((Accel::IntersectFunc )intersector::intersect, \ (Accel::OccludedFunc )intersector::occluded, \ (Accel::PointQueryFunc)intersector::pointQuery,\ TOSTRING(isa) "::" TOSTRING(symbol)); \ } #define DEFINE_INTERSECTOR4(symbol,intersector) \ Accel::Intersector4 symbol() { \ return Accel::Intersector4((Accel::IntersectFunc4)intersector::intersect, \ (Accel::OccludedFunc4)intersector::occluded, \ TOSTRING(isa) "::" TOSTRING(symbol)); \ } #define DEFINE_INTERSECTOR8(symbol,intersector) \ Accel::Intersector8 symbol() { \ return Accel::Intersector8((Accel::IntersectFunc8)intersector::intersect, \ (Accel::OccludedFunc8)intersector::occluded, \ TOSTRING(isa) "::" TOSTRING(symbol)); \ } #define DEFINE_INTERSECTOR16(symbol,intersector) \ Accel::Intersector16 symbol() { \ return Accel::Intersector16((Accel::IntersectFunc16)intersector::intersect, \ (Accel::OccludedFunc16)intersector::occluded, \ TOSTRING(isa) "::" TOSTRING(symbol)); \ } #define DEFINE_INTERSECTORN(symbol,intersector) \ Accel::IntersectorN symbol() { \ return Accel::IntersectorN((Accel::IntersectFuncN)intersector::intersect, \ (Accel::OccludedFuncN)intersector::occluded, \ TOSTRING(isa) "::" TOSTRING(symbol)); \ } /* ray stream filter interface */ typedef void (*intersectStreamAOS_func)(Scene* scene, RTCRayHit* _rayN, const size_t N, const size_t stride, IntersectContext* context); typedef void (*intersectStreamAOP_func)(Scene* scene, RTCRayHit** _rayN, const size_t N, IntersectContext* context); typedef void (*intersectStreamSOA_func)(Scene* scene, char* rayN, const size_t N, const size_t streams, const size_t stream_offset, IntersectContext* context); typedef void (*intersectStreamSOP_func)(Scene* scene, const RTCRayHitNp* rayN, const size_t N, IntersectContext* context); typedef void (*occludedStreamAOS_func)(Scene* scene, RTCRay* _rayN, const size_t N, const size_t stride, IntersectContext* context); typedef void (*occludedStreamAOP_func)(Scene* scene, RTCRay** _rayN, const size_t N, IntersectContext* context); typedef void (*occludedStreamSOA_func)(Scene* scene, char* rayN, const size_t N, const size_t streams, const size_t stream_offset, IntersectContext* context); typedef void (*occludedStreamSOP_func)(Scene* scene, const RTCRayNp* rayN, const size_t N, IntersectContext* context); struct RayStreamFilterFuncs { RayStreamFilterFuncs() : intersectAOS(nullptr), intersectAOP(nullptr), intersectSOA(nullptr), intersectSOP(nullptr), occludedAOS(nullptr), occludedAOP(nullptr), occludedSOA(nullptr), occludedSOP(nullptr) {} RayStreamFilterFuncs(void (*ptr) ()) : intersectAOS((intersectStreamAOS_func) ptr), intersectAOP((intersectStreamAOP_func) ptr), intersectSOA((intersectStreamSOA_func) ptr), intersectSOP((intersectStreamSOP_func) ptr), occludedAOS((occludedStreamAOS_func) ptr), occludedAOP((occludedStreamAOP_func) ptr), occludedSOA((occludedStreamSOA_func) ptr), occludedSOP((occludedStreamSOP_func) ptr) {} RayStreamFilterFuncs(intersectStreamAOS_func intersectAOS, intersectStreamAOP_func intersectAOP, intersectStreamSOA_func intersectSOA, intersectStreamSOP_func intersectSOP, occludedStreamAOS_func occludedAOS, occludedStreamAOP_func occludedAOP, occludedStreamSOA_func occludedSOA, occludedStreamSOP_func occludedSOP) : intersectAOS(intersectAOS), intersectAOP(intersectAOP), intersectSOA(intersectSOA), intersectSOP(intersectSOP), occludedAOS(occludedAOS), occludedAOP(occludedAOP), occludedSOA(occludedSOA), occludedSOP(occludedSOP) {} public: intersectStreamAOS_func intersectAOS; intersectStreamAOP_func intersectAOP; intersectStreamSOA_func intersectSOA; intersectStreamSOP_func intersectSOP; occludedStreamAOS_func occludedAOS; occludedStreamAOP_func occludedAOP; occludedStreamSOA_func occludedSOA; occludedStreamSOP_func occludedSOP; }; typedef RayStreamFilterFuncs (*RayStreamFilterFuncsType)(); }
76198e11663914b22b0eff3085a2e7c5f50373cf
73eccbcd162bec577a2c060f8ce62848e1eb0c8a
/TestInteger.c++
b1430fec5e5740ae1bb3c48e82bb33c9f6f46daa
[]
no_license
asnguyen/cs371g-integer
b75a26e76840844a2baa6f2d5618241438cbf728
a5bfddb3ff7474e714b6d1238f5bcf2169088b88
refs/heads/master
2021-03-22T04:34:56.036903
2016-07-06T04:14:52
2016-07-06T04:14:52
62,312,243
0
0
null
null
null
null
UTF-8
C++
false
false
11,076
TestInteger.c++
#include <iostream> #include <sstream> #include <string> #include <vector> #include <deque> #include "gtest/gtest.h" #include "Integer.h" using namespace std; //Integer's operator == test begin TEST(IntegerFixture,equal_equal_test_1) { Integer<int> num1("11"); Integer<int> num2(11); ASSERT_TRUE(num1==num2); } TEST(IntegerFixture,equal_equal_test_2) { Integer<int> num1("0011"); Integer<int> num2(11); ASSERT_TRUE(num1==num2); } TEST(IntegerFixture,equal_equal_test_3) { Integer<int> num1("12"); Integer<int> num2(11); ASSERT_FALSE(num1==num2); } TEST(IntegerFixture,equal_equal_test_4) { Integer<int> num1(12); Integer<int> num2(12); ASSERT_TRUE(num1==num2); } TEST(IntegerFixture,equal_equal_test_5) { Integer<int> num1("12"); Integer<int> num2("12"); ASSERT_TRUE(num1==num2); } //Integer's operator == test end //Integer's operator < test begin TEST(IntegerFixture, less_than_test_1) { Integer<int> num1(12); Integer<int> num2(13); ASSERT_TRUE(num1 < num2); } TEST(IntegerFixture, less_than_test_2) { Integer<int> num1(13); Integer<int> num2(12); ASSERT_FALSE(num1 < num2); } TEST(IntegerFixture, less_than_test_3) { Integer<int> num1("012"); Integer<int> num2(100); ASSERT_TRUE(num1 < num2); } TEST(IntegerFixture, less_than_test_4) { Integer<int> num1("012"); Integer<int> num2("12"); ASSERT_FALSE(num1 < num2); } TEST(IntegerFixture, less_than_test_5) { Integer<int> num1("012"); Integer<int> num2("10000"); ASSERT_TRUE(num1 < num2); } //Integer's operator < test end //Integer's operator << test begin TEST(IntegerFixture, output_test_1) { Integer<int> num("000001"); ostringstream w; w << num; ASSERT_EQ("1",w.str()); } TEST(IntegerFixture, output_test_2) { Integer<int> num("1"); ostringstream w; w << num; ASSERT_EQ("1",w.str()); } TEST(IntegerFixture, output_test_3) { Integer<int> num("123456789"); ostringstream w; w << num; ASSERT_EQ("123456789",w.str()); } TEST(IntegerFixture, output_test_4) { Integer<int> num("0"); ostringstream w; w << num; ASSERT_EQ("0",w.str()); } TEST(IntegerFixture, output_test_5) { Integer<int> num("-123456789"); ostringstream w; w << num; ASSERT_EQ("-123456789",w.str()); } //Integer's operator << test end //Integer's valid test begin TEST(IntegerFixture, valid_1) { Integer<int> num("123456789"); ASSERT_TRUE(num.valid()); } TEST(IntegerFixture, valid_2) { Integer<int> num("a"); ASSERT_FALSE(num.valid()); } TEST(IntegerFixture, valid_3) { Integer<int> num("-123"); ASSERT_TRUE(num.valid()); } TEST(IntegerFixture, valid_4) { Integer<int> num("0"); ASSERT_TRUE(num.valid()); } TEST(IntegerFixture, valid_5) { Integer<int> num("-"); ASSERT_FALSE(num.valid()); } //Integer's valid test end //Integer(int value) test begin TEST(IntegerFixture, constructor_int_1) { Integer<int> num(123); ostringstream w; ASSERT_TRUE(num.valid()); w << num; ASSERT_EQ("123",w.str()); } TEST(IntegerFixture, constructor_int_2) { Integer<int> num(-123); ostringstream w; ASSERT_TRUE(num.valid()); w << num; ASSERT_EQ("-123",w.str()); } TEST(IntegerFixture, constructor_int_3) { Integer<int> num(10); ostringstream w; ASSERT_TRUE(num.valid()); w << num; ASSERT_EQ("10",w.str()); } TEST(IntegerFixture, constructor_int_4) { Integer<int> num(0); ostringstream w; ASSERT_TRUE(num.valid()); w << num; ASSERT_EQ("0",w.str()); } TEST(IntegerFixture, constructor_int_5) { Integer<int> num(1); ostringstream w; ASSERT_TRUE(num.valid()); w << num; ASSERT_EQ("1",w.str()); } //Integer(int value) test end //Integer(string value) test begin TEST(IntegerFixture, constructor_string_1) { Integer<int> num("123"); ostringstream w; ASSERT_TRUE(num.valid()); w << num; ASSERT_EQ("123",w.str()); } TEST(IntegerFixture, constructor_string_2) { Integer<int> num("-123"); ostringstream w; ASSERT_TRUE(num.valid()); w << num; ASSERT_EQ("-123",w.str()); } TEST(IntegerFixture, constructor_string_3) { Integer<int> num("0000000000000123"); ostringstream w; ASSERT_TRUE(num.valid()); w << num; ASSERT_EQ("123",w.str()); } TEST(IntegerFixture, constructor_string_4) { Integer<int> num("101010110101"); ostringstream w; ASSERT_TRUE(num.valid()); w << num; ASSERT_EQ("101010110101",w.str()); } TEST(IntegerFixture, constructor_string_5) { Integer<int> num("0000000000000"); ostringstream w; ASSERT_TRUE(num.valid()); w << num; ASSERT_EQ("0",w.str()); } //Integer(string value) test bend //Integer's operator - test begin TEST(IntegerFixture,negative_test_1) { Integer<int> num(2); num = -num; ostringstream w; w << num; ASSERT_EQ("-2",w.str()); } TEST(IntegerFixture,negative_test_2) { Integer<int> num(-2); num = -num; ostringstream w; w << num; ASSERT_EQ("2",w.str()); } TEST(IntegerFixture,negative_test_3) { Integer<int> num("2"); num = -num; ostringstream w; w << num; ASSERT_EQ("-2",w.str()); } TEST(IntegerFixture,negative_test_4) { Integer<int> num("-2"); num = -num; ostringstream w; w << num; ASSERT_EQ("2",w.str()); } TEST(IntegerFixture,negative_test_5) { Integer<int> num("-1"); num = -num; ostringstream w; w << num; ASSERT_EQ("1",w.str()); } //Integer's operator - test end //Integer's operator += test begin TEST(IntegerFixture, plus_equal_test_1) { ostringstream w; Integer<int> a("15"); Integer<int> b("100"); a+=b; w << a; ASSERT_EQ("115",w.str()); } TEST(IntegerFixture, plus_equal_test_2) { ostringstream w; Integer<int> a("6"); Integer<int> b("7"); a+=b; w << a; ASSERT_EQ("13",w.str()); } TEST(IntegerFixture, plus_equal_test_3) { ostringstream w; Integer<int> a("100"); Integer<int> b("3"); a+=b; w << a; ASSERT_EQ("103",w.str()); } TEST(IntegerFixture, plus_equal_test_4) { ostringstream w; Integer<int> a("999"); Integer<int> b("1"); a+=b; w << a; ASSERT_EQ("1000",w.str()); } TEST(IntegerFixture, plus_equal_test_5) { ostringstream w; Integer<int> a("1"); Integer<int> b("0"); a+=b; w << a; ASSERT_EQ("1",w.str()); } //Integer's operator += test end //Integer's operator -= test begin TEST(IntegerFixture, minus_equal_test_1) { ostringstream w; Integer<int> a("8"); Integer<int> b("3"); a-=b; w << a; ASSERT_EQ("5",w.str()); } TEST(IntegerFixture, minus_equal_test_2) { ostringstream w; Integer<int> a("100"); Integer<int> b("3"); a-=b; w << a; ASSERT_EQ("97",w.str()); } TEST(IntegerFixture, minus_equal_test_3) { ostringstream w; Integer<int> a(136); Integer<int> b(135); a-=b; w << a; ASSERT_EQ("1",w.str()); } TEST(IntegerFixture, minus_equal_test_4) { ostringstream w; Integer<int> a(136); Integer<int> b(136); a-=b; w << a; ASSERT_EQ("0",w.str()); } TEST(IntegerFixture, minus_equal_test_5) { ostringstream w; Integer<int> a("1000"); Integer<int> b("3"); a-=b; w << a; ASSERT_EQ("997",w.str()); } //Integer's operator -= test end //Integer's operator *= test begin TEST(IntegerFixture, multiply_equal_test_1) { ostringstream w; Integer<int> a(5); Integer<int> b(12); a*=b; w << a; ASSERT_EQ("60",w.str()); } TEST(IntegerFixture, multiply_equal_test_2) { ostringstream w; Integer<int> a(12); Integer<int> b(12); a*=b; w << a; ASSERT_EQ("144",w.str()); } TEST(IntegerFixture, multiply_equal_test_3) { ostringstream w; Integer<int> a(12); Integer<int> b(1); a*=b; w << a; ASSERT_EQ("12",w.str()); } TEST(IntegerFixture, multiply_equal_test_4) { ostringstream w; Integer<int> a(1); Integer<int> b(12); a*=b; w << a; ASSERT_EQ("12",w.str()); } TEST(IntegerFixture, multiply_equal_test_5) { ostringstream w; Integer<int> a(12); Integer<int> b(0); a*=b; w << a; ASSERT_EQ("0",w.str()); } //Integer's operator *= test end //Integer's operator /= test begin TEST(IntegerFixture, divide_equal_test_1) { ostringstream w; Integer<int> a(60); Integer<int> b(12); a/=b; w << a; ASSERT_EQ("5",w.str()); } TEST(IntegerFixture, divide_equal_test_2) { ostringstream w; Integer<int> a(101); Integer<int> b(4); a/=b; w << a; ASSERT_EQ("25",w.str()); } TEST(IntegerFixture, divide_equal_test_3) { ostringstream w; Integer<int> a(3); Integer<int> b(4); a/=b; w << a; ASSERT_EQ("0",w.str()); } TEST(IntegerFixture, divide_equal_test_4) { ostringstream w; Integer<int> a(60); Integer<int> b(60); a/=b; w << a; ASSERT_EQ("1",w.str()); } TEST(IntegerFixture, divide_equal_test_5) { ostringstream w; Integer<int> a(0); Integer<int> b(12); a/=b; w << a; ASSERT_EQ("0",w.str()); } //Integer's operator /= test end //Integer's operator %= test begin TEST(IntegerFixture, mod_equal_test_1) { ostringstream w; Integer<int> a(3); Integer<int> b(4); a%=b; w << a; ASSERT_EQ("3",w.str()); } TEST(IntegerFixture, mod_equal_test_2) { ostringstream w; Integer<int> a(5); Integer<int> b(4); a%=b; w << a; ASSERT_EQ("1",w.str()); } TEST(IntegerFixture, mod_equal_test_3) { ostringstream w; Integer<int> a(60); Integer<int> b(5); a%=b; w << a; ASSERT_EQ("0",w.str()); } TEST(IntegerFixture, mod_equal_test_4) { ostringstream w; Integer<int> a(10); Integer<int> b(4); a%=b; w << a; ASSERT_EQ("2",w.str()); } TEST(IntegerFixture, mod_equal_test_5) { ostringstream w; Integer<int> a(0); Integer<int> b(4); a%=b; w << a; ASSERT_EQ("0",w.str()); } //Integer's operator %= test end //Integer's operator <<= test begin TEST(IntegerFixture, left_shift_equal_test_1) { ostringstream w; Integer<int> num("123"); num<<=(1); w << num; ASSERT_EQ("1230",w.str()); } TEST(IntegerFixture, left_shift_equal_test_2) { ostringstream w; Integer<int> num("123"); num<<=(2); w << num; ASSERT_EQ("12300",w.str()); } TEST(IntegerFixture, left_shift_equal_test_3) { ostringstream w; Integer<int> num("123"); num<<=(0); w << num; ASSERT_EQ("123",w.str()); } //Integer's operator <<= test end //Integer's operator >>= test begin TEST(IntegerFixture, right_shift_equal_test_1) { ostringstream w; Integer<int> num("123"); num>>=(0); w << num; ASSERT_EQ("123",w.str()); } TEST(IntegerFixture, right_shift_equal_test_2) { ostringstream w; Integer<int> num("123"); num>>=(1); w << num; ASSERT_EQ("12",w.str()); } TEST(IntegerFixture, right_shift_equal_test_3) { ostringstream w; Integer<int> num("123"); num>>=(2); w << num; ASSERT_EQ("1",w.str()); } //Integer's operator >>= test end //Integer's abs test begin TEST(IntegerFixture, abs_1) { ostringstream w; Integer<int> num("123"); num = num.abs(); w << num; ASSERT_EQ("123",w.str()); } TEST(IntegerFixture, abs_2) { ostringstream w; Integer<int> num("-123"); num = num.abs(); w << num; ASSERT_EQ("123",w.str()); } TEST(IntegerFixture, abs_3) { ostringstream w; Integer<int> num(-123); num = num.abs(); w << num; ASSERT_EQ("123",w.str()); } //Integer's abs test end //Integer's pow test begin TEST(IntegerFixture, pow_1) { ostringstream w; Integer<int> num(2); num = num.pow(1); w << num; ASSERT_EQ("2",w.str()); } TEST(IntegerFixture, pow_2) { ostringstream w; Integer<int> num(2); num = num.pow(10); w << num; ASSERT_EQ("1024",w.str()); } TEST(IntegerFixture, pow_3) { ostringstream w; Integer<int> num(2); num = num.pow(0); w << num; ASSERT_EQ("1",w.str()); } //Integer's pow test end
78703167db995a1e7c35cea68b89699976f691ff
77a08ec51aa16191986a739267fd9d4379bbb208
/bc/48A.cpp
6f8ff9537a2b35764f255332af897cca0c107a6a
[]
no_license
cenariusxz/ACM-Coding
8f698203db802f79578921b311b38346950ef0ca
dc09ac9adfb4b80d463bdc93f52b479a957154e6
refs/heads/master
2023-06-24T13:12:13.279255
2021-07-26T01:24:36
2021-07-26T01:24:36
185,567,471
0
0
null
null
null
null
UTF-8
C++
false
false
599
cpp
48A.cpp
#include<stdio.h> #include<string.h> #include<algorithm> #include<math.h> using namespace std; int main(){ int T; scanf("%d",&T); while(T--){ bool f1=0,f2=0,f3=0,ff=0; char c=getchar(); while(c<'a'||c>'z')c=getchar(); while(c>='a'&&c<='z'){ // printf("%c",c); if(f1==0){ if(c=='w')f1=1; else if(ff){ if(c=='v')f1=1; else ff=0; } else if(c=='v')ff=1; } else{ if(f2==0){ if(c=='y')f2=1; } else{ if(f3==0){ if(c=='h')f3=1; } } } c=getchar(); } if(f3)printf("Yes\n"); else printf("No\n"); } return 0; }
4b2b7f7def87b5fec974fe0dc6f107b5d747c529
a464695e3f90e5ddc45d0f0e09cb9e22644687c6
/IppImage/MatDibFeature.h
cf9643d4254f3785692f697acc68c73740f752f5
[]
no_license
FalconYD/FalconEyes-Lite
c9a02f27d4ba47f797e6f04edc45aa07fadf5ee7
629cdcc271abaa5f46d77ce3bb93b1dc194b2661
refs/heads/master
2023-03-26T07:11:27.173996
2020-06-07T11:11:11
2020-06-07T11:11:11
270,246,043
0
0
null
null
null
null
UTF-8
C++
false
false
461
h
MatDibFeature.h
#pragma once #include "define_Class.h" #include "MatDib.h" #include "MatDibExt.h" void MatEdgeCanny(MatDib& Src, MatDib& Dst, float sigma, float th_low, float th_high); void MatHoughLine(MatDib& Src, std::vector<MatLineParam>& lines, int threshold = 60); void MatDrawLine(MatDib& Dst, MatLineParam line, BYTE c); void MatDrawLine(MatDib& img, int x1, int y1, int x2, int y2, BYTE c); void MatHarrisCorner(MatDib& Src, std::vector<Point>& corners, double th);
f7529c39fde7abe3b32c0fbbecef305bef2c0c53
88f82bc30351f3adfa426b7000e06d304f70f323
/catkin_ws/src/hd_map/include/hd_map/LaneGroup.h
6814160d24613496a85837df8a27ec2ec46bbb23
[]
no_license
MarcelSchmidt89/AutominySim
3edd773db1e3e72b248a42ab41aa9f4a485d51c5
b0d0db60fcf114a8b563b3ed60e582562506f362
refs/heads/master
2020-06-21T21:36:54.388822
2019-08-13T16:39:44
2019-08-13T16:39:44
197,557,890
1
1
null
null
null
null
UTF-8
C++
false
false
1,961
h
LaneGroup.h
#pragma once #include "Fwd.h" #include <vector> namespace hd_map { class LaneGroup { public: explicit LaneGroup(unsigned long id, Polyline2DPtr& leftBoundary, Polyline2DPtr& rightBoundary, std::vector<std::tuple<unsigned int, unsigned int>>& laneMappings); explicit LaneGroup(unsigned long id); const Polyline2DPtr& getLeftBoundary(); const Polyline2DPtr& getRightBoundary(); void setLeftBoundary(const Polyline2DPtr& leftBoundary); void setRightBoundary(const Polyline2DPtr& rightBoundary); const std::vector<LaneGroupPtr> getOutgoingLaneGroups(); const std::vector<LaneGroupPtr> getIncomingLaneGroups(); void setOutgoingLaneGroups(const std::vector<LaneGroupPtr>& outgoingLaneGroups); void setIncomingLaneGroups(const std::vector<LaneGroupPtr>& incomingLaneGroups); unsigned long getId(); const std::vector<LanePtr>& getLanes(); void addLane(const LanePtr& lane); /** * Gets a lane by id * @param id HERE lane id * @return LanePtr if found, else nullptr */ const LanePtr getLane(unsigned int id); const LaneGroupConnectorPtr& getStartConnector(); const LaneGroupConnectorPtr& getEndConnector(); void setStartConnector(const LaneGroupConnectorPtr& startConnector); void setEndConnector(const LaneGroupConnectorPtr& endConnector); std::vector<std::tuple<unsigned int, unsigned int>>& getLaneMapping(); bool isJunction(); private: unsigned long id; Polyline2DPtr leftBoundary; Polyline2DPtr rightBoundary; std::vector<LanePtr> lanes; std::vector<std::tuple<unsigned int, unsigned int>> laneMapping; std::vector<LaneGroupPtr> outgoingLaneGroups; std::vector<LaneGroupPtr> incomingLaneGroups; LaneGroupConnectorPtr startConnector; LaneGroupConnectorPtr endConnector; }; }
ce8a91be023b50474c2bb40306b4e17b4bc84481
b3d62a978b19665b799d81a9be1a29e955bf5be4
/Game/Source/GDKShooter/Public/Characters/Components/TeamComponent.h
7f84630ef7e96b3008341d9e6ca6e4651a822b7f
[ "MIT" ]
permissive
spatialos/UnrealGDKReferenceProject
5db816ee595dc4146e451c9b846c29be3739e3d5
f4cc3babfeaba4ea56aa570faa1b2c79c90e391b
refs/heads/master
2020-07-28T23:30:40.524885
2019-10-16T11:06:19
2019-10-16T11:06:19
209,577,165
2
4
MIT
2019-11-07T15:29:41
2019-09-19T14:37:53
C++
UTF-8
C++
false
false
1,350
h
TeamComponent.h
// Copyright (c) Improbable Worlds Ltd, All Rights Reserved #pragma once #include "CoreMinimal.h" #include "Components/ActorComponent.h" #include "Runtime/AIModule/Classes/GenericTeamAgentInterface.h" #include "TeamComponent.generated.h" DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FTeamChangedEvent, FGenericTeamId, Team); UCLASS( ClassGroup=(Custom), meta=(BlueprintSpawnableComponent) ) class GDKSHOOTER_API UTeamComponent : public UActorComponent { GENERATED_BODY() public: UTeamComponent(); UPROPERTY(BlueprintAssignable) FTeamChangedEvent TeamChanged; UFUNCTION(BlueprintPure) virtual bool CanDamageActor(AActor* OtherActor); UFUNCTION(BlueprintCallable) void SetTeam(FGenericTeamId NewTeamId) { TeamId = NewTeamId; } UFUNCTION(BlueprintPure) FGenericTeamId GetTeam() { return TeamId; } //Negative or Zero as a Team Id is not considered a valid team UFUNCTION(BlueprintPure) bool HasTeam() { return TeamId != FGenericTeamId::NoTeam; } UPROPERTY(BlueprintReadOnly, EditDefaultsOnly) bool bAllowFriendlyFire; protected: UPROPERTY(ReplicatedUsing = OnRep_TeamId, EditDefaultsOnly) FGenericTeamId TeamId = FGenericTeamId::NoTeam; UFUNCTION() void OnRep_TeamId() { TeamChanged.Broadcast(TeamId); }; virtual void GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const override; };
ad67a3eb1f3d7d7e29e53ae94e3566854393a850
32a6314c1b7ced58ff80e31224f4d3055ac068f1
/CourseDependencyGraph/sources/DependencyGraph.h
6658a531c9f6a021196a3ded81eb7c94b3655a29
[]
no_license
tsznokwong/CourseDependencyGraph
5f8bf160934a391787a01dae763a97dcbe51703d
7f7f16497f22641cb748ca30dc4e18aeb7c07f36
refs/heads/master
2020-04-05T15:18:05.654876
2018-12-02T09:56:58
2018-12-02T09:56:58
156,961,626
2
0
null
null
null
null
UTF-8
C++
false
false
4,161
h
DependencyGraph.h
#ifndef DEPENDENCYGRAPH_H #define DEPENDENCYGRAPH_H #include <vector> #include <set> #include "AVLTree.tpp" /*** * The DependencyGraph is a directed unweighted graph. * The graph has a focus node which must be specified during construction. * The graph is implemented with abstract adjacency list and set of nodes with AVLTree. * @Typename KeyType the datatype for the Key object (must have implemented comparison operators) * @Typename NodeType the datatype for the data mode object (must have implemented assignment operator) */ template <typename KeyType, typename NodeType> class DependencyGraph { public: /** * @brief The Direction enum. * PREVIOUS: Represent the initial node depends on the terminating node. * NEXT: Represent the terminating node depends on the initial node. */ enum Direction { PREVIOUS, NEXT }; /** * @brief The Node class is the vertex representation of the graph. * Each node has a key to identify and storing data. * Each node has a depth defined by the longest distance from focus node. * i.e. negative represents the focus node depends on the node. * positive represents the node depends on the focus node. * Each node points to its initial nodes in the graph which are roots contributed to largest magnitude of its depth. */ class Node { private: DependencyGraph* parent; KeyType key; NodeType data; int depth; std::vector<Node*> strongRoots; Direction direction; public: Node(DependencyGraph* parent, KeyType key, NodeType data, int depth = 0); // getter const KeyType& getKey() const; const NodeType& getNode() const; const int& getDepth() const; const std::vector<Node*>& getStrongRoots() const; const Direction& getDirection() const; // setter void setDepth(int depth); // Graph operation void update(int depth, Node* root); friend DependencyGraph; }; /** * @brief The Edge class is the edge representation of the graph. * Each edge has a target node which is the terminating node of edge. * The edge is strong if the edge contributed to largest magnitude of depth of the target node. */ class Edge { private: DependencyGraph* parent; Node *targetNode; Direction direction; bool isStrong; int type; public: Edge(DependencyGraph* parent, Node *targetNode, Direction direction, int type, bool isStrong = false); Edge() = default; Edge(const Edge& edge) = default; // getter const Node* getTargetNode() const; Node* getTargetNode(); const Direction& getDirection() const; const bool& getIsStrong() const; const int& getType() const; // setter void setIsStrong(bool isStrong); friend DependencyGraph; Edge& operator=(Edge&& rhs) = default; Edge& operator=(const Edge &rhs) = default; }; private: // Graph elements AVLTree<KeyType, std::vector<Edge> > adjacencyTree; AVLTree<KeyType, Node> nodeTree; Node focusNode; void updateIsStrongEdge(const KeyType &fromKey, const KeyType &toKey, bool isStrong); public: DependencyGraph() = delete; DependencyGraph(KeyType key, NodeType node); // getter Node* getNode(const KeyType &key); const AVLTree<KeyType, Node>& getNodes() const; void getEdgesFrom(const KeyType &key, std::vector<Edge> &edges) const; void getPreviousEdgesFrom(const KeyType &key, std::vector<Edge> &edges) const; void getNextEdgesFrom(const KeyType &key, std::vector<Edge> &edges) const; void getNodesInMap(AVLTree<int, std::vector<NodeType> > &map) const; // capacity bool contains(const KeyType &key) const; unsigned int size() const; bool isEmpty() const; void reset(KeyType key, NodeType node); // Graph operations void updateNodes(); bool addNode(KeyType key, NodeType node); bool addEdge(KeyType fromKey, KeyType toKey, Direction direction, int type); }; #endif // DEPENDENCYGRAPH_H
111e59f4f27d8cec13df83781cf6243c14a8c900
a827a80768a617b60e3bc32a9c1e85feff447c2a
/C++_II /DynoBag 2/dynobag.cpp
c2322ca828d93e5864cc2cd9a1030ba1aaeaaf79
[]
no_license
mariyaeggs/C_Methodology_Collection
f525e7ac07a2048e1039d64ac2c0472f39764d9d
61a7fa7c92667b9ba71361be3b1f6757a41a6a99
refs/heads/master
2020-05-21T06:31:13.447634
2017-03-11T19:19:07
2017-03-11T19:19:07
84,589,080
1
0
null
null
null
null
UTF-8
C++
false
false
2,269
cpp
dynobag.cpp
#include <iostream> #include <algorithm> #include "dynobag.h" using namespace std; const dynobag::size_type dynobag::DEFAULT_CAPACITY; //30 allowed items dynobag::dynobag(size_type initial_capacity) { data = new value_type[initial_capacity]; capacity = initial_capacity; used = 0; } dynobag::dynobag(const dynobag &source) { data = new value_type[source.capacity]; capacity = source.capacity; used = source.used; copy(source.data, source.data + used, data); } dynobag::~dynobag() { delete[] data; } void dynobag::reserve(size_type new_capacity) { value_type *larger_array; if (new_capacity == capacity) return; if (new_capacity < used) new_capacity = used; // only add to memmory that which we use larger_array = new value_type[new_capacity]; copy(data, data + used, larger_array); delete[] data; data = larger_array; capacity = new_capacity; } dynobag::size_type dynobag::erase(const value_type &target) { size_type index = 0; size_type many_removed = 0; while (index < used) { if (data[index] == target) { --used; data[index] = data[used]; ++many_removed; } else ++index; } return many_removed; } bool dynobag::erase_one(const value_type &target) { size_type index; // target index index = 0; while ((index < used) && (data[index] != target)) ++index; if (index == used) // target missing return false; --used; data[index] = data[used]; return true; } void dynobag::insert(const value_type &entry) { if (used == capacity) reserve(used + 1); data[used] = entry; ++used; } void dynobag::operator+=(const dynobag &addend) { if (used + addend.used > capacity) reserve(used + addend.used); copy(addend.data, addend.data + addend.used, data + used); used += addend.used; } void dynobag::operator=(const dynobag &source);
cb3c628c879a11928d7787ade1bcafd3c9877356
0d80c5a17613c9e5a0d28e70f9942f0d484bbef3
/tracer.cpp
c828b5b95bdcf7bfd53d22369240c3c613174cf0
[]
no_license
simonplantinga/contourtracer
4c15f9c23b668b88a4edcb89256ab2907cc40df1
990cbbdbea339c0381fa25385dc251c4426515c2
refs/heads/master
2020-03-10T05:46:35.053300
2018-04-12T09:14:45
2018-04-12T09:14:45
129,224,510
0
0
null
null
null
null
UTF-8
C++
false
false
5,812
cpp
tracer.cpp
#include "tracer.h" #include <math.h> #define K 0.5 // constant for contour corrector //#define REPORT // print results #ifdef REPORT #include <stdio.h> #endif //############################################################################ // ContourData members void ContourData::addpoint( Point &p ) { points.push_back( p ); if ( p.X() < minx ) minx = p.X(); if ( p.X() > maxx ) maxx = p.X(); if ( p.Y() < miny ) miny = p.Y(); if ( p.Y() > maxy ) maxy = p.Y(); if ( p.Z() < minz ) minz = p.Z(); if ( p.Z() > maxz ) maxz = p.Z(); } bool ContourData::isClose( Point &p, double eps ) { if ( p.X() < minx - eps ) return false; if ( p.X() > maxx + eps ) return false; if ( p.Y() < miny - eps ) return false; if ( p.Y() > maxy + eps ) return false; if ( p.Z() < minz - eps ) return false; if ( p.Z() > maxz + eps ) return false; for ( int i=0; i<points.size(); i++ ) { /* double dx = p.X() - points[i].X(); double dy = p.Y() - points[i].Y(); double dz = p.Z() - points[i].Z(); if ( dx*dx + dy*dy + dz*dz < eps*eps ) return true; */ if ( points[i].distsq(p) < eps*eps ) return true; } return false; } void ContourData::computebb() { minx = maxx = 0.0; miny = maxy = 0.0; minz = maxz = 0.0; for ( int i=0; i<points.size(); i++) { if ( points[i].X() < minx ) minx = points[i].X(); if ( points[i].X() > maxx ) maxx = points[i].X(); if ( points[i].Y() < miny ) miny = points[i].Y(); if ( points[i].Y() > maxy ) maxy = points[i].Y(); if ( points[i].Z() < minz ) minz = points[i].Z(); if ( points[i].Z() > maxz ) maxz = points[i].Z(); } } //############################################################################ // Tracer members bool Tracer::pointOnContour( Point &p ) { for ( int i=0; i<contours.size(); i++ ) if ( contours[i].isClose( p, epsilon ) ) return true; return false; } void Tracer::addContour( Surface *s, Point &p ) { double delta = 0.1; movetocg( s, p ); if ( pointOnContour( p ) ) return; ContourData contour; Point p0 = p; contour.addpoint( p0 ); while ( 1 ) { //########################## if ( contour.size() > 15000 ) break; //########################## // advance p delta = delta * 1.2; double x,y,z; while (1) { // compute new position (x,y,z) double fx = s->Fx( p.X(), p.Y(), p.Z() ); double fy = s->Fy( p.X(), p.Y(), p.Z() ); double fz = s->Fz( p.X(), p.Y(), p.Z() ); double fxz = s->Fxz( p.X(), p.Y(), p.Z() ); double fyz = s->Fyz( p.X(), p.Y(), p.Z() ); double fzz = s->Fzz( p.X(), p.Y(), p.Z() ); x = fy*fzz - fz*fyz; y = fz*fxz - fx*fzz; z = fx*fyz - fy*fxz; double gradsq = x*x+y*y+z*z; x = p.X() + delta * ( x / gradsq ); y = p.Y() + delta * ( y / gradsq ); z = p.Z() + delta * ( z / gradsq ); // compute bounding box (bx,by,bz) double dist = sqrt( (x-p.X())*(x-p.X()) + (y-p.Y())*(y-p.Y()) + (z-p.Z())*(z-p.Z()) ) * 1.1; Interval bx(p.X()-dist, p.X()+dist); Interval by(p.Y()-dist, p.Y()+dist); Interval bz(p.Z()-dist, p.Z()+dist); // compute w at p double wx = fy*fzz - fz*fyz; double wy = fz*fxz - fx*fzz; double wz = fx*fyz - fy*fxz; double nw = sqrt(wx*wx+wy*wy+wz*wz); wx = wx / nw; wy = wy / nw; wz = wz / nw; // compute w over box Interval ifx = s->Fx(bx,by,bz); Interval ify = s->Fy(bx,by,bz); Interval ifz = s->Fz(bx,by,bz); Interval ifxz = s->Fxz(bx,by,bz); Interval ifyz = s->Fyz(bx,by,bz); Interval ifzz = s->Fzz(bx,by,bz); Interval iwx = ify*ifzz - ifz*ifyz; Interval iwy = ifz*ifxz - ifx*ifzz; Interval iwz = ifx*ifyz - ify*ifxz; Interval inw = sqrt(sqr(iwx)+sqr(iwy)+sqr(iwz)); iwx = iwx / inw; iwy = iwy / inw; iwz = iwz / inw; Interval I = wx*iwx + wy*iwy + wz*iwz; // perform the interval test if ( I.inf() > 0.71 ) break; else delta = delta * 0.8; if (delta < 0.00001) // JUST TO BE SAFE!!! break; } p.set( x, y, z ); movetocg( s, p ); if ( contour.size() > 10 ) if ( p.distsq(p0) < delta*delta ) break; #ifdef REPORT printf("added (%f, %f, %f); %i points on contour\n",x,y,z,contour.size()); #endif // add to contour contour.addpoint( p ); } cout << "Contour size " << contour.size() << endl; // add contour to contour components contours.push_back( contour ); } void Tracer::movetocg( Surface *s, Point &p ) { double f; double fx,fy,fz,fxz,fyz,fzz; double x,y,z; double gs; x = p.X(); y = p.Y(); z = p.Z(); while ( fabs(s->F(x,y,z)) > PTCLOSE || fabs(s->Fz(x,y,z)) > PTCLOSE ) { f = s->F(x,y,z); if ( fabs(f) > PTCLOSE ) { fx = s->Fx(x,y,z); fy = s->Fy(x,y,z); fz = s->Fz(x,y,z); gs = fx*fx + fy*fy + fz*fz; x -= f * fx / gs; y -= f * fy / gs; z -= f * fz / gs; } fz = s->Fz(x,y,z); if ( fabs(fz) > PTCLOSE ) { fxz = s->Fxz(x,y,z); fyz = s->Fyz(x,y,z); fzz = s->Fzz(x,y,z); gs = fxz*fxz + fyz*fyz + fzz*fzz; x -= fz * fxz / gs; y -= fz * fyz / gs; z -= fz * fzz / gs; } } p.set( x, y, z); }
8fc51a9eaa149624345ef75536c687a05e4d5a46
c23b42b301b365f6c074dd71fdb6cd63a7944a54
/contest/ASC/ASC36/j.cpp
2ee8ab6a89da08d1e3e99f18ef1a3ef9cfcf327a
[]
no_license
NTUwanderer/PECaveros
6c3b8a44b43f6b72a182f83ff0eb908c2e944841
8d068ea05ee96f54ee92dffa7426d3619b21c0bd
refs/heads/master
2020-03-27T22:15:49.847016
2019-01-04T14:20:25
2019-01-04T14:20:25
147,217,616
1
0
null
2018-09-03T14:40:49
2018-09-03T14:40:49
null
UTF-8
C++
false
false
1,151
cpp
j.cpp
//by tzupengwang™ #include<bits/stdc++.h> using namespace std; #define FO(it,c) for (__typeof((c).begin()) it=(c).begin();it!=(c).end();it++) typedef long long ll; typedef pair<int,int> ii; int n , k ; vector< int > v ; void init() { scanf( "%d%d" , &n , &k ) ; for ( int i = 1 ; i * i < n ; i ++ ) { v.push_back( n - i * i ) ; } } int dp[ 32 ][ 200005 ] ; void process() { memset( dp , -1 , sizeof dp ) ; dp[ 0 ][ 0 ] = 0 ; for ( int i = 0 ; i < (int)v.size() ; i ++ ) { for ( int p = k - 1 ; p >= 0 ; p -- ) { for ( int j = n - v[ i ] ; j >= 0 ; j -- ) if ( dp[ p ][ j ] != -1 && dp[ p + 1 ][ j + v[ i ] ] == -1 ) { dp[ p + 1 ][ j + v[ i ] ] = j ; } } } if ( dp[ k ][ n ] == -1 ) puts( "NO" ) ; else { puts( "YES" ) ; int t = n ; while ( k ) { printf( "%d " , t - dp[ k ][ t ] ) ; t = dp[ k ][ t ] , k -- ; } puts( "" ) ; } } int main() { freopen( "squary.in" , "r" , stdin ) ; freopen( "squary.out" , "w" , stdout ) ; init() ; process() ; return 0 ; }
8718cd495f6a95c2525fe9ba78f6f073c10fe882
3761056d6334350a47455443557715c264eb72bf
/CONSTRUCT_RELEASE_VERSION_1.2/SRC/CONTROLLER/LOGINCONTROLLER/CPP/logincontroller.cpp
577073b976e35f4e3a8ef4668922ce6856ea19c3
[]
no_license
Poojithaeragamreddy/Postpaid
c8d4aaec73c8faa6516961d42ef3ced15eb46606
81bda8e30a9c84a9055e8dd8ffd2274e2c3052e6
refs/heads/master
2021-01-20T08:38:12.740342
2017-05-03T16:55:29
2017-05-03T16:55:29
90,172,214
0
0
null
null
null
null
UTF-8
C++
false
false
1,500
cpp
logincontroller.cpp
#include "./../INCLUDE/logincontroller.h" #include "./../../../CLASS/LOGIN/INCLUDE/login.h" #include "./../../../MODEL/LOGINMODEL/INCLUDE/model.h" #include "./../../../VIEW/MAINVIEW/INCLUDE/mainview.h" #include "./../../../VIEW/LOGINVIEW/INCLUDE/loginview.h" #include "./../../MANAGERCONTROLLER/INCLUDE/controlmanager.h" #include "./../../CRCONTROLLER/INCLUDE/crcontroller.h" string LoginController::startLogin() { LoginModel model; LoginView loginui; MainView mainui; string username; string password; string designation; username = loginui.getUserName(); password = loginui.getPassWord(); designation = loginui.getDesignation(); Login login(password, username, designation); int status = model.verifyLogin(login); if (status == 0) { mainui.displayMessage(" Login Success\n\n Welcome to QWE -Postpaid\n\n"); if (designation == "manager") { ManagerController c; c.showManagerMenu(); } else if (designation == "cr") { CustomerRepresentativeController c; c.customerRepresentativeMenu(); } } if (status < 0) { if (status == -1) { mainui.displayMessage("Invalid Username or Password"); mainui.displayMessage("enter valid username or password"); return startLogin(); } else if(status== -2) { mainui.displayMessage("Invalid Designation"); mainui.displayMessage("Enter valid Designation"); return startLogin(); } } }
6e8e2c66bc1d49db12380297246e81bff122f1f7
b79f35e8d4546f6e9a8650fc66e9a28e4b6245ed
/fcw2svg-0.2/UnknownShape.cpp
f7d50d631446b9baf674b9c80915b14d25dfc5f9
[]
no_license
bcholmes/fcw2svg
91c61417160a3f052089b4f7dcffef152eb270fe
90982608de8e5922dd3b6399982fe33ec87636cb
refs/heads/master
2021-01-22T20:44:33.251347
2017-10-01T19:28:54
2017-10-01T19:28:54
7,470,174
2
0
null
null
null
null
UTF-8
C++
false
false
364
cpp
UnknownShape.cpp
#include "UnknownShape.h" namespace bcholmes { namespace fcw2svg { UnknownShape::UnknownShape(CommonHeader header) : Shape(header) { }; UnknownShape::UnknownShape(const UnknownShape& shape) : Shape(shape) { } UnknownShape::~UnknownShape() { } Shape* UnknownShape::from(CommonHeader header) { return new UnknownShape(header); } } }
42a6674f4250d24d4d27dd93086a27979ebc2c21
182324358d8971c25fdda323eeef807ed0112c9c
/areaOfSquare.cpp
120c233546b1a58e7bd8fc89dfcd82cf3baf580b
[]
no_license
UCSB-CS16-F14/WIP-F14-lab03
ecc8c3ef36f1c6ffb359421f4bf9921e3e7511a5
522571a3c3a03c8ab10008bb7bea721627ec952d
refs/heads/master
2020-04-27T11:05:48.193231
2014-10-18T01:55:04
2014-10-18T01:55:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,854
cpp
areaOfSquare.cpp
// areaOfSquare.cpp --- cmd line arg program to compute area of square // P. Conrad for CS16, Fall 2014, UCSB CS Dept // THIS IS NOT TYPICAL OF THE COMMENTS YOU SHOULD HAVE IN YOUR CODE // IT IS WAY TOO MANY COMMENTS FOR TYPICAL CODE // This program has comments that are meant to be part of the "lesson" // comments that are teaching you about the code as you read it. // This is one of a pair programs (along with computeAreaOfSquare.cpp) that // provide a constrast between getting input using cin and getting input // from the command line. // In this program, we are using "int" variables only---because we want // to illustrate the technique with int variables first. // (Granted, for area of a square, a "double" variable would make more sense.) // First we indicate that we need iostream and namespace std // to get access to cout, cerr, endl #include <iostream> using namespace std; // Then we #include cstdlib because we are using atoi #include <cstdlib> // Next we define a function to compute the area of a square (using ints) int areaOfSquare(int sideLength) { return sideLength * sideLength; } // Next we have our main program that gets a value from the command line // and then gives back the answer int main(int argc, char *argv[]) // this is standard for cmd line arg programs { int side; // check usage of program if (argc!=2) // two things on command line { // cerr is used for error messages instead of cout // argv[0] is the command used to invoke the program cerr << "Usage: " << argv[0] << " sideLength" << endl; exit(1); // stop program, signal error condition } // convert command line argument from char * (ASCII) to int side = atoi(argv[1]); // compute and print answer cout << "Side: " << side << " Area: " << areaOfSquare(side) << endl; return 0; }
38559c2af1b5f4e4ffe7d1f31bce072d965d4ac2
b800b8c843c3490fc8a6bbbaf6828a8e13332ef0
/code/source/Material.cpp
08b54f92605eef725688be0cbce2302835d09eb8
[]
no_license
JorgeBarcena3/Ray-Tracing-Rendering
d5c5b76c82bfee88d1a6e6e905f7c808dd62e261
1e4e14afeb69e7efcd4482dfe3fc999566c6271c
refs/heads/master
2022-04-07T03:18:51.745526
2020-03-04T16:02:15
2020-03-04T16:02:15
179,563,683
0
0
null
null
null
null
UTF-8
C++
false
false
383
cpp
Material.cpp
#include "../headers/Material.hpp" Material::Material() { color = vec3(); diffuse = 1.f; specular = 0.f; } Material::~Material() { } vec3 Material::getPlaneColor(float x, float z) { //Conversion and delete the decimal numbers int square = (int)x + (int)z; vec3 color; if (square % 2 == 0) color = vec3(255, 0, 0); else color = vec3(255, 255, 0); return color; }
e69eaa61e82964c31377ef46af99e2719e4cc02b
9e78a9a50c236783e19bc0f679c9540a04398e92
/src/main.cpp
d23e9e06aa7a4e15ace851eedf38dc53ee29deda
[]
no_license
jaico22/CPPMultiThreadingExample
bd8bc6b956ff27899c66416450479dcf4e3df5c4
43518acb923b26826c1693907c407ffe99959c29
refs/heads/master
2020-04-28T01:50:23.737465
2019-03-10T22:06:29
2019-03-10T22:06:29
174,874,457
0
0
null
null
null
null
UTF-8
C++
false
false
1,673
cpp
main.cpp
#include <iostream> #include <thread> #include <vector> #include <random> #include <chrono> void thread_function(std::vector<int> v, int &acum) { for (int i = 0; i < v.size(); i++){ acum += v[i] * v[i]; } } int main() { // initialize random test vectors std::vector<int> v0; for (int i = 0; i < 100000; i++){ v0.push_back(rand()%100); } std::vector<int> v1; for (int i = 0; i < 100000; i++){ v1.push_back(rand()%100+1000); } // Serial Implemention int acum_0_s = 0; int acum_1_s = 0; std::chrono::high_resolution_clock::time_point t0 = std::chrono::high_resolution_clock::now(); thread_function(v0,acum_0_s); thread_function(v1,acum_1_s); std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::microseconds>(t1-t0).count(); // Threaded Implementation int acum_0 = 0; int acum_1 = 0; t0 = std::chrono::high_resolution_clock::now(); std::thread threadObj1(thread_function,v0,std::ref(acum_0)); std::thread threadObj2(thread_function,v1,std::ref(acum_1)); t1 = std::chrono::high_resolution_clock::now(); threadObj1.join(); threadObj2.join(); auto duration2 = std::chrono::duration_cast<std::chrono::microseconds>(t1-t0).count(); // Compare execution time and make sure results are the same std::cout << "Serial Implementation: " << duration << " ans = " << acum_0_s << "," << acum_1_s <<std::endl; std::cout << "Threaded Implementation: " << duration2 << " ans = " << acum_0 << "," << acum_1 <<std::endl; return 0; }
3abdd61ccf40487fa887df5623bc80b418d50e7d
0e765f81e4ce29c83a87aa7ebbd06c69e65d1ff4
/Lab 4/Wizard.cpp
e81b97c88bd8dec8a674ffa03a06e3cc1579cb4d
[]
no_license
Richard-Lynch/2E3-Labs
7d8d6f87fed7d36fce5c9c938c730bb2bb4cb50a
0660ba7ac1bd2bafcfac5cc0a6749cfdc8992226
refs/heads/master
2020-06-15T14:24:23.719048
2016-12-01T11:18:39
2016-12-01T11:18:39
75,283,417
0
0
null
null
null
null
UTF-8
C++
false
false
1,132
cpp
Wizard.cpp
// // Wizard.cpp // RPG Game // // Created by Richard Lynch on 03/11/2015. // Copyright © 2015 Richard. All rights reserved. // #include "Wizard.hpp" #include "Stats.hpp" #include "NPC.hpp" #include <iostream> using namespace::std; Wizard::Wizard()//constructs a wizard :NPC()//uses the NPC constructor as normal {cout << "wizard construced" << endl;}//the adds to it by outputting "wizard constructed" void Wizard::defend(int at)//new defend function just for wizard, overrides NPC defend { NPC::defend(at);//calls NPC defend as normal if(getStats().getStrength() <= 0)//if they were killed, as in strength is <=0, runs this little command that sets the stregth back to 1 and alive to true { cout << "The Boy Who Lived!" << endl;//outputs this so we know they've been revived setStats(Stats (1, (getStats().getSkill()), true));//sets stats to (st=1, sk=sk, alive=true) } } void Wizard::print()//overrides the normal NPC print { cout << "You're a Wizard Harry!" << endl;//outputs this so we know its a wizard being printed NPC_stats.print();//then uses the normal print funtion }
548691f8d024ffdb517a3f2a13fc7a6bab671136
9736960e430b709a04e661507f695ed8c0531530
/MyTask/createproblems.h
ca1c376fa9cb6a9651a1314f7dbcffa2893b2444
[]
no_license
cersys/MyTaskone
67faeea8d7ec7790c6020d59c9fd2faa91b13a9d
f53835559d339a004c452453bfeb527a8e059a0e
refs/heads/master
2020-07-25T23:16:24.256178
2018-10-07T16:55:55
2018-10-07T16:55:55
208,453,485
2
0
null
2019-09-14T14:40:51
2019-09-14T14:40:51
null
UTF-8
C++
false
false
995
h
createproblems.h
#ifndef CREATEPROBLEMS_H #define CREATEPROBLEMS_H #include <QDialog> #include <QString> #include "grade.h" #include <QStack> #include <QQueue> #include <QButtonGroup> namespace Ui { class createProblems; } class createProblems : public QDialog { Q_OBJECT public: int count,n,type=1; double fs=0.0; QString tempPro; QButtonGroup *ansGroup; explicit createProblems(QWidget *parent = 0); ~createProblems(); private: Ui::createProblems *ui; public slots: void on_next(); void on_ansGroup(); public: grade g; QString create(); QQueue<QString> Split(const QString& exp); //分离前缀 QQueue<QString> Transfer(QQueue<QString>& exp); //将中缀队列转换为后缀队列 QString Calculate(QQueue<QString>& exp); //将后缀队列计算出结果 QString Calculate(QString& l,QString& op,QString& r ); QString ValidNum(QString str); QString Result(const QString& exp); }; #endif // CREATEPROBLEMS_H
1cb90fa09aff642a637a41f22760f98961f88ae6
489623b7a30fa6494b258de063aabeecc95b0f66
/724-find-pivot-index/724-find-pivot-index.cpp
46b3a65ca82ab62a09f10491ea8ae2ea16089eaf
[]
no_license
giriteja94495/leetcodesolutions
9ce3e2190dcd0c0dc3d6069794f1e277a9d1cb7b
e0460e9ff03a3272f167098c1a207a721e4dc030
refs/heads/master
2022-12-11T08:22:25.853675
2022-12-01T04:36:15
2022-12-01T04:36:15
239,805,769
5
0
null
null
null
null
UTF-8
C++
false
false
1,058
cpp
724-find-pivot-index.cpp
class Solution { public: int pivotIndex(vector<int>& nums) { // int n = nums.size(); // // create 2 arrays and calculate the sum on each parts from left and right // vector<int> leftSum(n,0); // vector<int> rightSum(n,0); // for(int i=1;i<n;i++){ // leftSum[i] = (nums[i-1]+leftSum[i-1]); // } // for(int j=n-2; j>=0;j--){ // rightSum[j] =(nums[j+1]+rightSum[j+1]); // cout<<rightSum[j]; // } // // loop through the both arrays and find out at which index leftSum == rightSum // for(int i=0;i<n;i++){ // if(leftSum[i]==rightSum[i]) return i; // } // // if we didn't find any, then return -1 // return -1; int sumFromLeft =0; int sum=0; for(auto a:nums) sum+=a; for(int i=0;i<nums.size();i++){ if(sumFromLeft == sum - nums[i] -sumFromLeft) return i ; sumFromLeft+=nums[i]; } return -1; } };
03d6f368791745e643c3d6c40d050f601165afb4
49db500aeac669856f91b7541e91363efb73abf7
/dev/ibt/IBTParameter.h
d7aad44eaf7b3d74a6f3e435a216265cdaeb2786
[]
no_license
barthouse/Ardat
38aa3061352f34036800e3213c76782278e902b3
c34145e1181cd4b6eb5fbfc9c8589d48de9fbcdc
refs/heads/master
2020-03-23T21:14:45.383984
2019-08-30T05:23:23
2019-08-30T05:23:23
142,092,436
0
0
null
null
null
null
UTF-8
C++
false
false
1,164
h
IBTParameter.h
#pragma once class IBTParameter { public: IBTParameter(); ~IBTParameter(); void Set(char * inName, char * inDescription, char * inUnits, int inSampleCount, int inLineOffset, int inType, char * inBuffer, int inLineLength); bool Set(char * inName, char * inDescription, char * inUnits, int inSampleCount); void SetMinMax(double inMin, double inMax); void Clear(void); char * GetName(); char * GetMnemonic(); char * GetGroup(); char * GetUnits(); char * GetFormat(); char * GetDescription(); double GetMinValue(); double GetMaxValue(); int GetLineOffset(); int GetType(); double GetSample(int inTickIndex); void SetSample(int inTickIndex, double inValue); int GetSampleCount(); private: void CalculateMinMax(); static const int kMaxStringLength = 64; bool m_set; char m_name[kMaxStringLength]; char m_mnemonic[kMaxStringLength]; char m_group[kMaxStringLength]; char m_units[kMaxStringLength]; char m_description[kMaxStringLength]; char m_format[kMaxStringLength]; bool m_minMaxSet; double m_min; double m_max; int m_sampleCount; char * m_buffer; bool m_allocated; int m_lineOffset; int m_lineLength; int m_type; };
8ed4775af10890edd295549ec6872a18f45999e7
51df39e6300906b9640014a1d0dcc305da86a787
/decision_service/rlclientlib/utility/object_factory.h
34b0e29c18fa0c7b2886795b45b0912c46296b28
[]
no_license
arjun-krishna/vowpal_wabbit
f14f7524031d68b147c81f5c4a5af146de987d1b
0ff1cb90deb5a5824689cafc6c1ed4525643c7ff
refs/heads/master
2020-03-21T10:33:01.864050
2018-06-24T03:07:12
2018-06-24T03:07:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
757
h
object_factory.h
#pragma once #include "config_collection.h" #include <functional> #include <memory> namespace reinforcement_learning { namespace utility { template<class I> struct object_factory { using create_fn = std::function<I*(const config_collection&)>; void register_type(const std::string& name, create_fn fptr) { _creators[name] = fptr; } std::unique_ptr<I> create(const std::string& name, const config_collection& cc) { auto it = _creators.find(name); if (it != _creators.end()) return std::unique_ptr<I>((it->second)(cc)); throw std::runtime_error("type not registered with class factory"); } private: std::unordered_map<std::string, create_fn> _creators; }; } }
adf4522e7173216517d375165271421e971cfb51
bd5ec656dbe5c3450aa797395107bbdc39202e74
/maxValidBrac.cpp
f6e86f4172e4884686361df4f988f1957133c4c6
[]
no_license
nishikantparmariam/Solutions-to-Coding-Problems
5684d641a2f28aa6236b820a19ea8c87f19a7ed9
692557e8e36e802065d942950f85245263ac2cb6
refs/heads/master
2023-04-27T12:44:31.602224
2021-05-16T07:32:16
2021-05-16T07:32:16
235,786,592
0
0
null
null
null
null
UTF-8
C++
false
false
985
cpp
maxValidBrac.cpp
#include <bits/stdc++.h> using namespace std; typedef long long int ll; int main(){ int a = 1; string S;cin>>S; stack<ll> STACK; ll N = S.size(); ll dp[N]; ll longest = 0; ll numSubstrings = 0; for(ll i=0;i<N;i++){ if(S[i]=='('){ dp[i] = 0; STACK.push(i); } else { if(STACK.empty()){ dp[i] = 0; } else { ll index = STACK.top(); STACK.pop(); dp[i] = i-index+1; if(index-1>=0){ dp[i]+=dp[index-1]; } } } longest = max(longest, dp[i]); } ll i = N-1; while(i>=0){ if(dp[i]==0) i--; else { numSubstrings++; i-=dp[i]; } } if(numSubstrings==0){ cout << 0 << " " << 1 << endl; } else { cout << longest << " " << numSubstrings << endl; } return 0; }
75259d63a2d812b5d91e8b1fde3a87c91a25215e
6a27b6d484481ef6e7dc1c865331b1c8371b83e1
/be/src/olap/comparison_predicate.h
f953f196f2dcf4bddfb9c112c2daef897fff0134
[ "BSD-3-Clause", "GPL-2.0-only", "Apache-2.0", "LicenseRef-scancode-public-domain", "PSF-2.0", "dtoa", "MIT", "bzip2-1.0.6", "OpenSSL" ]
permissive
HappenLee/incubator-doris
6b011c57bd97464aa50221de277093895a2677b5
c74113773a33dbcba35763984b0789db90635191
refs/heads/master
2023-09-01T21:05:33.828221
2022-08-28T15:10:47
2022-08-29T03:31:16
264,080,199
2
5
Apache-2.0
2023-07-26T06:24:35
2020-05-15T02:51:56
C++
UTF-8
C++
false
false
21,777
h
comparison_predicate.h
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you 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. #pragma once #include <cstdint> #include "olap/column_predicate.h" #include "vec/columns/column_dictionary.h" namespace doris { template <PrimitiveType Type, PredicateType PT> class ComparisonPredicateBase : public ColumnPredicate { public: using T = typename PredicatePrimitiveTypeTraits<Type>::PredicateFieldType; ComparisonPredicateBase(uint32_t column_id, const T& value, bool opposite = false) : ColumnPredicate(column_id, opposite), _value(value) {} PredicateType type() const override { return PT; } void evaluate(ColumnBlock* block, uint16_t* sel, uint16_t* size) const override { uint16_t new_size = 0; if (block->is_nullable()) { for (uint16_t i = 0; i < *size; ++i) { uint16_t idx = sel[i]; sel[new_size] = idx; if constexpr (Type == TYPE_DATE) { T tmp_uint32_value = 0; memcpy((char*)(&tmp_uint32_value), block->cell(idx).cell_ptr(), sizeof(uint24_t)); auto result = (!block->cell(idx).is_null() && _operator(tmp_uint32_value, _value)); new_size += _opposite ? !result : result; } else { const T* cell_value = reinterpret_cast<const T*>(block->cell(idx).cell_ptr()); auto result = (!block->cell(idx).is_null() && _operator(*cell_value, _value)); new_size += _opposite ? !result : result; } } } else { for (uint16_t i = 0; i < *size; ++i) { uint16_t idx = sel[i]; sel[new_size] = idx; if constexpr (Type == TYPE_DATE) { T tmp_uint32_value = 0; memcpy((char*)(&tmp_uint32_value), block->cell(idx).cell_ptr(), sizeof(uint24_t)); auto result = _operator(tmp_uint32_value, _value); new_size += _opposite ? !result : result; } else { const T* cell_value = reinterpret_cast<const T*>(block->cell(idx).cell_ptr()); auto result = _operator(*cell_value, _value); new_size += _opposite ? !result : result; } } } *size = new_size; } void evaluate_or(ColumnBlock* block, uint16_t* sel, uint16_t size, bool* flags) const override { if (block->is_nullable()) { for (uint16_t i = 0; i < size; ++i) { if (flags[i]) { continue; } uint16_t idx = sel[i]; if constexpr (Type == TYPE_DATE) { T tmp_uint32_value = 0; memcpy((char*)(&tmp_uint32_value), block->cell(idx).cell_ptr(), sizeof(uint24_t)); auto result = (!block->cell(idx).is_null() && _operator(tmp_uint32_value, _value)); flags[i] = flags[i] | (_opposite ? !result : result); } else { const T* cell_value = reinterpret_cast<const T*>(block->cell(idx).cell_ptr()); auto result = (!block->cell(idx).is_null() && _operator(*cell_value, _value)); flags[i] = flags[i] | (_opposite ? !result : result); } } } else { for (uint16_t i = 0; i < size; ++i) { if (flags[i]) { continue; } uint16_t idx = sel[i]; if constexpr (Type == TYPE_DATE) { T tmp_uint32_value = 0; memcpy((char*)(&tmp_uint32_value), block->cell(idx).cell_ptr(), sizeof(uint24_t)); auto result = _operator(tmp_uint32_value, _value); flags[i] = flags[i] | (_opposite ? !result : result); } else { const T* cell_value = reinterpret_cast<const T*>(block->cell(idx).cell_ptr()); auto result = _operator(*cell_value, _value); flags[i] = flags[i] | (_opposite ? !result : result); } } } } void evaluate_and(ColumnBlock* block, uint16_t* sel, uint16_t size, bool* flags) const override { if (block->is_nullable()) { for (uint16_t i = 0; i < size; ++i) { if (!flags[i]) { continue; } uint16_t idx = sel[i]; if constexpr (Type == TYPE_DATE) { T tmp_uint32_value = 0; memcpy((char*)(&tmp_uint32_value), block->cell(idx).cell_ptr(), sizeof(uint24_t)); auto result = (!block->cell(idx).is_null() && _operator(tmp_uint32_value, _value)); flags[i] = flags[i] & (_opposite ? !result : result); } else { const T* cell_value = reinterpret_cast<const T*>(block->cell(idx).cell_ptr()); auto result = (!block->cell(idx).is_null() && _operator(*cell_value, _value)); flags[i] = flags[i] & (_opposite ? !result : result); } } } else { for (uint16_t i = 0; i < size; ++i) { if (flags[i]) { continue; } uint16_t idx = sel[i]; if constexpr (Type == TYPE_DATE) { T tmp_uint32_value = 0; memcpy((char*)(&tmp_uint32_value), block->cell(idx).cell_ptr(), sizeof(uint24_t)); auto result = _operator(tmp_uint32_value, _value); flags[i] = flags[i] & (_opposite ? !result : result); } else { const T* cell_value = reinterpret_cast<const T*>(block->cell(idx).cell_ptr()); auto result = _operator(*cell_value, _value); flags[i] = flags[i] & (_opposite ? !result : result); } } } } Status evaluate(BitmapIndexIterator* iterator, uint32_t num_rows, roaring::Roaring* bitmap) const override { if (iterator == nullptr) { return Status::OK(); } rowid_t ordinal_limit = iterator->bitmap_nums(); if (iterator->has_null_bitmap()) { ordinal_limit--; roaring::Roaring null_bitmap; RETURN_IF_ERROR(iterator->read_null_bitmap(&null_bitmap)); *bitmap -= null_bitmap; } roaring::Roaring roaring; bool exact_match; Status status = iterator->seek_dictionary(&_value, &exact_match); rowid_t seeked_ordinal = iterator->current_ordinal(); return _bitmap_compare(status, exact_match, ordinal_limit, seeked_ordinal, iterator, bitmap); } uint16_t evaluate(const vectorized::IColumn& column, uint16_t* sel, uint16_t size) const override { if (column.is_nullable()) { auto* nullable_column_ptr = vectorized::check_and_get_column<vectorized::ColumnNullable>(column); auto& nested_column = nullable_column_ptr->get_nested_column(); auto& null_map = reinterpret_cast<const vectorized::ColumnUInt8&>( nullable_column_ptr->get_null_map_column()) .get_data(); return _base_evaluate<true>(&nested_column, null_map.data(), sel, size); } else { return _base_evaluate<false>(&column, nullptr, sel, size); } } void evaluate_and(const vectorized::IColumn& column, const uint16_t* sel, uint16_t size, bool* flags) const override { _evaluate_bit<true>(column, sel, size, flags); } void evaluate_or(const vectorized::IColumn& column, const uint16_t* sel, uint16_t size, bool* flags) const override { _evaluate_bit<false>(column, sel, size, flags); } template <bool is_and> __attribute__((flatten)) void _evaluate_vec_internal(const vectorized::IColumn& column, uint16_t size, bool* flags) const { if (column.is_nullable()) { auto* nullable_column_ptr = vectorized::check_and_get_column<vectorized::ColumnNullable>(column); auto& nested_column = nullable_column_ptr->get_nested_column(); auto& null_map = reinterpret_cast<const vectorized::ColumnUInt8&>( nullable_column_ptr->get_null_map_column()) .get_data(); if (nested_column.is_column_dictionary()) { if constexpr (std::is_same_v<T, StringValue>) { auto* dict_column_ptr = vectorized::check_and_get_column<vectorized::ColumnDictI32>( nested_column); auto dict_code = _is_range() ? dict_column_ptr->find_code_by_bound( _value, _is_greater(), _is_eq()) : dict_column_ptr->find_code(_value); auto* data_array = dict_column_ptr->get_data().data(); _base_loop_vec<true, is_and>(size, flags, null_map.data(), data_array, dict_code); } else { LOG(FATAL) << "column_dictionary must use StringValue predicate."; } } else { auto* data_array = reinterpret_cast<const vectorized::PredicateColumnType<Type>&>( nested_column) .get_data() .data(); _base_loop_vec<true, is_and>(size, flags, null_map.data(), data_array, _value); } } else { if (column.is_column_dictionary()) { if constexpr (std::is_same_v<T, StringValue>) { auto* dict_column_ptr = vectorized::check_and_get_column<vectorized::ColumnDictI32>(column); auto dict_code = _is_range() ? dict_column_ptr->find_code_by_bound( _value, _is_greater(), _is_eq()) : dict_column_ptr->find_code(_value); auto* data_array = dict_column_ptr->get_data().data(); _base_loop_vec<false, is_and>(size, flags, nullptr, data_array, dict_code); } else { LOG(FATAL) << "column_dictionary must use StringValue predicate."; } } else { auto* data_array = vectorized::check_and_get_column<vectorized::PredicateColumnType<Type>>( column) ->get_data() .data(); _base_loop_vec<false, is_and>(size, flags, nullptr, data_array, _value); } } if (_opposite) { for (uint16_t i = 0; i < size; i++) { flags[i] = !flags[i]; } } } void evaluate_vec(const vectorized::IColumn& column, uint16_t size, bool* flags) const override { _evaluate_vec_internal<false>(column, size, flags); } void evaluate_and_vec(const vectorized::IColumn& column, uint16_t size, bool* flags) const override { _evaluate_vec_internal<true>(column, size, flags); } private: template <typename LeftT, typename RightT> bool _operator(const LeftT& lhs, const RightT& rhs) const { if constexpr (PT == PredicateType::EQ) { return lhs == rhs; } else if constexpr (PT == PredicateType::NE) { return lhs != rhs; } else if constexpr (PT == PredicateType::LT) { return lhs < rhs; } else if constexpr (PT == PredicateType::LE) { return lhs <= rhs; } else if constexpr (PT == PredicateType::GT) { return lhs > rhs; } else if constexpr (PT == PredicateType::GE) { return lhs >= rhs; } } constexpr bool _is_range() const { return PredicateTypeTraits::is_range(PT); } constexpr bool _is_greater() const { return _operator(1, 0); } constexpr bool _is_eq() const { return _operator(1, 1); } Status _bitmap_compare(Status status, bool exact_match, rowid_t ordinal_limit, rowid_t& seeked_ordinal, BitmapIndexIterator* iterator, roaring::Roaring* bitmap) const { roaring::Roaring roaring; if (status.is_not_found()) { if constexpr (PT == PredicateType::EQ || PT == PredicateType::GT || PT == PredicateType::GE) { *bitmap &= roaring; // set bitmap to empty } return Status::OK(); } if (!status.ok()) { return status; } if constexpr (PT == PredicateType::EQ || PT == PredicateType::NE) { if (exact_match) { RETURN_IF_ERROR(iterator->read_bitmap(seeked_ordinal, &roaring)); } } else if constexpr (PredicateTypeTraits::is_range(PT)) { rowid_t from = 0; rowid_t to = ordinal_limit; if constexpr (PT == PredicateType::LT) { to = seeked_ordinal; } else if constexpr (PT == PredicateType::LE) { to = seeked_ordinal + exact_match; } else if constexpr (PT == PredicateType::GT) { from = seeked_ordinal + exact_match; } else if constexpr (PT == PredicateType::GE) { from = seeked_ordinal; } RETURN_IF_ERROR(iterator->read_union_bitmap(from, to, &roaring)); } if constexpr (PT == PredicateType::NE) { *bitmap -= roaring; } else { *bitmap &= roaring; } return Status::OK(); } template <bool is_and> void _evaluate_bit(const vectorized::IColumn& column, const uint16_t* sel, uint16_t size, bool* flags) const { if (column.is_nullable()) { auto* nullable_column_ptr = vectorized::check_and_get_column<vectorized::ColumnNullable>(column); auto& nested_column = nullable_column_ptr->get_nested_column(); auto& null_map = reinterpret_cast<const vectorized::ColumnUInt8&>( nullable_column_ptr->get_null_map_column()) .get_data(); _base_evaluate_bit<true, is_and>(&nested_column, null_map.data(), sel, size, flags); } else { _base_evaluate_bit<false, is_and>(&column, nullptr, sel, size, flags); } } template <bool is_nullable, bool is_and, typename TArray, typename TValue> __attribute__((flatten)) void _base_loop_vec(uint16_t size, bool* __restrict bflags, const uint8_t* __restrict null_map, const TArray* __restrict data_array, const TValue& value) const { //uint8_t helps compiler to generate vectorized code uint8_t* flags = reinterpret_cast<uint8_t*>(bflags); if constexpr (is_and) { for (uint16_t i = 0; i < size; i++) { if constexpr (is_nullable) { flags[i] &= (uint8_t)(!null_map[i] && _operator(data_array[i], value)); } else { flags[i] &= (uint8_t)_operator(data_array[i], value); } } } else { for (uint16_t i = 0; i < size; i++) { if constexpr (is_nullable) { flags[i] = !null_map[i] && _operator(data_array[i], value); } else { flags[i] = _operator(data_array[i], value); } } } } template <bool is_nullable, bool is_and, typename TArray, typename TValue> void _base_loop_bit(const uint16_t* sel, uint16_t size, bool* flags, const uint8_t* __restrict null_map, const TArray* __restrict data_array, const TValue& value) const { for (uint16_t i = 0; i < size; i++) { if (is_and ^ flags[i]) { continue; } if constexpr (is_nullable) { if (_opposite ^ is_and ^ (!null_map[sel[i]] && _operator(data_array[sel[i]], value))) { flags[i] = !is_and; } } else { if (_opposite ^ is_and ^ _operator(data_array[sel[i]], value)) { flags[i] = !is_and; } } } } template <bool is_nullable, bool is_and> void _base_evaluate_bit(const vectorized::IColumn* column, const uint8_t* null_map, const uint16_t* sel, uint16_t size, bool* flags) const { if (column->is_column_dictionary()) { if constexpr (std::is_same_v<T, StringValue>) { auto* dict_column_ptr = vectorized::check_and_get_column<vectorized::ColumnDictI32>(column); auto* data_array = dict_column_ptr->get_data().data(); auto dict_code = _is_range() ? dict_column_ptr->find_code_by_bound( _value, _operator(1, 0), _operator(1, 1)) : dict_column_ptr->find_code(_value); _base_loop_bit<is_nullable, is_and>(sel, size, flags, null_map, data_array, dict_code); } else { LOG(FATAL) << "column_dictionary must use StringValue predicate."; } } else { auto* data_array = vectorized::check_and_get_column<vectorized::PredicateColumnType<Type>>(column) ->get_data() .data(); _base_loop_bit<is_nullable, is_and>(sel, size, flags, null_map, data_array, _value); } } template <bool is_nullable, typename TArray, typename TValue> uint16_t _base_loop(uint16_t* sel, uint16_t size, const uint8_t* __restrict null_map, const TArray* __restrict data_array, const TValue& value) const { uint16_t new_size = 0; for (uint16_t i = 0; i < size; ++i) { uint16_t idx = sel[i]; if constexpr (is_nullable) { if (_opposite ^ (!null_map[idx] && _operator(data_array[idx], value))) { sel[new_size++] = idx; } } else { if (_opposite ^ _operator(data_array[idx], value)) { sel[new_size++] = idx; } } } return new_size; } template <bool is_nullable> uint16_t _base_evaluate(const vectorized::IColumn* column, const uint8_t* null_map, uint16_t* sel, uint16_t size) const { if (column->is_column_dictionary()) { if constexpr (std::is_same_v<T, StringValue>) { auto* dict_column_ptr = vectorized::check_and_get_column<vectorized::ColumnDictI32>(column); auto* data_array = dict_column_ptr->get_data().data(); auto dict_code = _is_range() ? dict_column_ptr->find_code_by_bound( _value, _is_greater(), _is_eq()) : dict_column_ptr->find_code(_value); return _base_loop<is_nullable>(sel, size, null_map, data_array, dict_code); } else { LOG(FATAL) << "column_dictionary must use StringValue predicate."; return 0; } } else { auto* data_array = vectorized::check_and_get_column<vectorized::PredicateColumnType<Type>>(column) ->get_data() .data(); return _base_loop<is_nullable>(sel, size, null_map, data_array, _value); } } T _value; }; } //namespace doris
34a31ef5f6340f89185679aec34e0d70bc4230e3
2c9bf5587a6ab97959b8b8b393b5991670a03a3b
/Thor/trunk/software/emuThor/source/clsSevenSeg.h
12af5cbcda05b623621e1dbd624833259c4ab1ca
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
BigEd/Cores
0f1c07430ae6423324dafa8f8c7ebd69d967648e
c60f058a22b04f10b3967e17e5cb9d0c4e37a952
refs/heads/master
2021-01-24T02:54:19.037486
2017-07-23T09:49:06
2017-07-23T09:49:06
60,836,114
1
0
null
2017-06-07T22:18:16
2016-06-10T09:09:54
Verilog
UTF-8
C++
false
false
198
h
clsSevenSeg.h
#pragma once #include "clsDevice.h" class clsSevenSeg : public clsDevice { public: unsigned int dat; public: bool IsSelected(unsigned int ad); void Write(unsigned int ad, unsigned int dat); };
2a6c9deadaef6cb0fd0625db4de46b4391c68ec1
43e44092ae5fecc76b863e817f232a17a8fc8f94
/freeglutexampletemplate/tile.cpp
ade4f5a4c1969073b5aa2d6cdcb02dcc42a05897
[]
no_license
AndrewNico96/First2DGame
27153d336c9b49b09da04485ae3947655e0fb9c2
1e4e674fe89b7847aad6863c26cab42bc60c8bf8
refs/heads/master
2021-01-21T10:52:02.650399
2017-05-18T15:37:05
2017-05-18T15:37:05
91,706,401
0
0
null
null
null
null
UTF-8
C++
false
false
1,926
cpp
tile.cpp
#include "tile.h" tile::tile() { } tile::tile(vect2d centre, int length, material mat) { this->length = length; this->mat = mat; this->centre = centre; createTileArray(); } void tile::createTileArray() { for(int i=0; i<length; i++){ vect2d v = vect2d(centre.getX() + i * 20, centre.getY()); Platform * p = new Platform(v, 10, 10, (Platform::material)mat, "sky.png"); if (mat == DIRT) p = new Platform(v, 10, 10, (Platform::material)mat, "WinterTileset/Tiles/5.png"); if (mat == SNOW) p = new Platform(v, 10, 10, (Platform::material)mat, "WinterTileset/Tiles/2.png"); if (mat == ICE) p = new Platform(v, 10, 10, (Platform::material)mat, "WinterTileset/Object/IceBox.png"); platformTiles.push_back(p); } } void tile::draw(float r, float g, float b, vect2d player) { int count = 1; for (std::vector<Platform *>::iterator i = platformTiles.begin(); i != platformTiles.end(); ++i) { Platform * p = *i; p->draw(1.0, 1.0, 1.0, player); } } void tile::collision(Object2D * collider) { BoundBox b = BoundBox(); for (std::vector<Platform *>::iterator i = platformTiles.begin(); i != platformTiles.end(); ++i) { Platform * p = *i; //health check //distance culling if(p->getHealth() > 0 && collider->getHealth() > 0 && abs(p->getCentre().getX() - collider->getCentre().getX()) < 50 && abs(p->getCentre().getY() - collider->getCentre().getY()) < 50) b.platformCollision(p, collider); } } //culling is taken care of in projectileHit method void tile::projectileHitTile(projectile* pro) { BoundBox b = BoundBox(); for (std::vector<Platform *>::iterator i = platformTiles.begin(); i != platformTiles.end(); ++i) { Platform * p = *i; b.projectileHit(pro, p); } } void tile::clearCollisions(){ for (std::vector<Platform *>::iterator i = platformTiles.begin(); i != platformTiles.end(); ++i) { Platform * p = *i; p->setCollision(false); } } tile::~tile() { }
29698aaccf462084220b8010aa788a4e1c9e9e86
645a1b4e81b56db37b58ee776aa21e0aac9bc7f9
/Utils/OpenGL/OpenGLUtils.cpp
fa430792c5c095eac85a2798975b78e9a195ada4
[]
no_license
wbach/GameEngine
51783358bad9059d9343772fcf7d95ca2a402726
b21b16472972e355a1b5a7c0108839829cfc1781
refs/heads/master
2021-01-11T12:07:21.437421
2017-04-26T14:48:46
2017-04-26T14:48:46
79,482,032
0
0
null
null
null
null
UTF-8
C++
false
false
4,071
cpp
OpenGLUtils.cpp
#include "OpenGLUtils.h" void Utils::BindFrameBuffer(const int & frameBuffer, const int & width, const int & height) { glBindTexture(GL_TEXTURE_2D, 0); glBindFramebuffer(GL_DRAW_FRAMEBUFFER, frameBuffer); glViewport(0, 0, width, height); } int Utils::CreateFrameBuffer() { GLuint frame_buffer; glGenFramebuffers(1, &frame_buffer); glBindFramebuffer(GL_FRAMEBUFFER, frame_buffer); glDrawBuffer(GL_NONE); return frame_buffer; } int Utils::CreateDepthBufferAttachment(const int & width, const int & height) { GLuint texture; glGenTextures(1, &texture); glBindTexture(GL_TEXTURE_2D, texture); glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT32, width, height, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); //glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, texture, 0); glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, texture, 0); // Disable writes to the color buffer glDrawBuffer(GL_NONE); // Disable reads from the color buffer glReadBuffer(GL_NONE); return texture; } int Utils::CreateVao() { GLuint vao_id; glGenVertexArrays(1, &vao_id); glBindVertexArray(vao_id); return vao_id; } GLuint Utils::BindIndicesBuffer(const std::vector<unsigned short>& indices) { GLuint vbo_id; glGenBuffers(1, &vbo_id); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo_id); glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned short), &indices[0], GL_STATIC_DRAW); return vbo_id; } GLuint Utils::StoreDataInAttributesList(const int & attributeNumber, const int & coordinateSize, const std::vector<float>& data) { GLuint vbo_id; glGenBuffers(1, &vbo_id); glBindBuffer(GL_ARRAY_BUFFER, vbo_id); glBufferData(GL_ARRAY_BUFFER, data.size() * sizeof(float), &data[0], GL_STATIC_DRAW); glVertexAttribPointer(attributeNumber, coordinateSize, GL_FLOAT, false, 0, 0); glBindBuffer(GL_ARRAY_BUFFER, 0); return vbo_id; } void Utils::EnableVao(uint vao, const std::vector<uint>& attributes) { glBindVertexArray(vao); for (const auto& i : attributes) glEnableVertexAttribArray(i); } void Utils::DisableVao(const std::vector<uint>& attributes) { for (const auto& i : attributes) glDisableVertexAttribArray(i); glBindVertexArray(0); } void Utils::UnbindVao() { glBindVertexArray(0); } void Utils::EnableCulling() { glEnable(GL_CULL_FACE); glCullFace(GL_BACK); } void Utils::DisableCulling() { glDisable(GL_CULL_FACE); } void Utils::SimpleRenderVao(const GLuint & vao, int indices, int attributes, GLenum mode) { glBindVertexArray(vao); for (int x = 0; x < attributes; x++) glEnableVertexAttribArray(x); glDrawElements(mode, indices, GL_UNSIGNED_SHORT, 0); for (int x = attributes; x > 0; x--) glDisableVertexAttribArray(x); glBindVertexArray(0); } void Utils::CreateQuad(GLuint & vao, GLuint & vbo_indices, GLuint & vbo_vertex, GLuint & vbo_text_coord, int & indices_size) { //std::vector<float> vertex = { -0.5, 0.5, 0, -0.5, -0.5, 0, 0.5, -0.5, 0, 0.5, 0.5, 0 }; std::vector<float> vertex = { -1, 1, 0, -1, -1, 0, 1, -1, 0, 1, 1, 0 }; std::vector<float> text_coords = { 0, 0, 0, 1, 1, 1, 1, 0 }; std::vector<unsigned short> indices = { 0, 1, 3, 3, 1, 2 }; indices_size = indices.size(); vao = CreateVao(); vbo_indices = BindIndicesBuffer(indices); vbo_vertex = StoreDataInAttributesList(0, 3, vertex); vbo_text_coord = StoreDataInAttributesList(1, 2, text_coords); UnbindVao(); } void Utils::DeleteQuad(GLuint & vao, GLuint & vbo_indices, GLuint & vbo_vertex, GLuint & vbo_text_coord) { glDeleteBuffers(1, &vbo_indices); glDeleteBuffers(1, &vbo_vertex); glDeleteBuffers(1, &vbo_text_coord); glDeleteVertexArrays(1, &vao); }
8893ce23ea5f872fe2d9bcafd419cc8eddb3cdbd
e12e491479a46b9a2a6d99dc741bacc3b7bd3d6e
/codes/강현민/jungol_1106_장기(AC).cpp
04edc41725cbb90974b5cf7507ea191180fbcd7d
[]
no_license
datalabsogang/life-coding
3b93446936491d2871fe7e2c0b055f8e2f67c373
2d00eaaad5862da470f14794561f824b80575bae
refs/heads/master
2020-03-11T17:58:40.365757
2018-06-23T04:22:35
2018-06-23T04:22:35
130,163,120
5
5
null
2018-06-23T04:22:36
2018-04-19T05:25:24
C++
UTF-8
C++
false
false
1,192
cpp
jungol_1106_장기(AC).cpp
/************************************************************** Problem: 1106 User: wizny8206 Language: C++ Result: Success Time:1 ms Memory:1836 kb ****************************************************************/ #include <vector> #include <queue> #include <iostream> using namespace std; int jump[8][2] = { { -2, 1 },{ -2,-1 },{ -1, 2 },{ -1, -2 },{ 1, 2 },{ 1, -2 },{ 2, 1 },{ 2, -1 } }; struct rc { int r, c; int status; }; int malR, malC; int jolR, jolC; int R, C; int malpan[110][110]; int visited[110][110]; bool outside(int r, int c) { return r < 1 || r > R || c < 1 || c > C; } int solve() { queue<rc> q; q.push(rc{ malR, malC }); malpan[malR][malC] = 0; while (!q.empty()) { rc p = q.front(); q.pop(); if (p.r == jolR && p.c == jolC) return malpan[jolR][jolC]; for (int i = 0; i < 8; i++) { int r2 = p.r + jump[i][0]; int c2 = p.c + jump[i][1]; if (outside(r2, c2)) continue; if (visited[r2][c2] == 0) { visited[r2][c2] = 1; q.push(rc{ r2,c2 }); malpan[r2][c2] = malpan[p.r][p.c] + 1; } } } } int main() { cin >> R >> C; cin >> malR >> malC >> jolR >> jolC; cout << solve() << endl; return 0; }
ba530c913d2d2fc3e3273592806d6f0b9e3bb338
091afb7001e86146209397ea362da70ffd63a916
/inst/include/boost/simd/swar/include/functions/simd/interleave_first.hpp
5752323e50150bec25b430388d8dbeca99d04dff
[]
no_license
RcppCore/RcppNT2
f156b58c08863243f259d1e609c9a7a8cf669990
cd7e548daa2d679b6ccebe19744b9a36f1e9139c
refs/heads/master
2021-01-10T16:15:16.861239
2016-02-02T22:18:25
2016-02-02T22:18:25
50,460,545
15
1
null
2019-11-15T22:08:50
2016-01-26T21:29:34
C++
UTF-8
C++
false
false
574
hpp
interleave_first.hpp
#ifndef BOOST_SIMD_SWAR_INCLUDE_FUNCTIONS_SIMD_INTERLEAVE_FIRST_HPP_INCLUDED #define BOOST_SIMD_SWAR_INCLUDE_FUNCTIONS_SIMD_INTERLEAVE_FIRST_HPP_INCLUDED #include <boost/simd/swar/functions/interleave_first.hpp> #include <boost/simd/swar/functions/scalar/interleave_first.hpp> #include <boost/simd/swar/functions/simd/common/interleave_first.hpp> #include <boost/simd/swar/functions/simd/sse/avx/interleave_first.hpp> #include <boost/simd/swar/functions/simd/sse/sse2/interleave_first.hpp> #include <boost/simd/swar/functions/simd/vmx/altivec/interleave_first.hpp> #endif
0b78009fa87cac506187dc6b60ed88d694ac0cd4
09075581d202e37565b144b4119af1f94cb57d2f
/prog05UTPod_nia254/UTPodDriver.cpp
7e8b686a305050ea17cb53ff4c17988a9d65541c
[]
no_license
nafis2620/UTPod
07ff5540d4ad3d18ae2734568cdacc6197b00621
22d619de5dfac28649a716ccf0b2063d7a09f5a2
refs/heads/master
2020-09-01T21:14:43.048159
2019-11-12T03:20:19
2019-11-12T03:20:19
219,059,623
0
0
null
null
null
null
UTF-8
C++
false
false
2,195
cpp
UTPodDriver.cpp
/* utPod_driver.cpp Demo Driver for the UtPod. Nafis Akbar EE 312 10/29/19 This is a basic driver for the UtPod. You will want to do more complete testing. */ #include <cstdlib> #include <iostream> #include "Song.h" #include "UtPod.h" using namespace std; int main(int argc, char *argv[]) { UtPod t; Song s1("Travis Scott", "Goosebumps", 30) ; int result = t.addSong(s1); cout << "result = " << result << endl; t.showSongList(); Song s2("Gun's N Roses", "Paradise City", 20); result = t.addSong(s2); cout << "result = " << result << endl; t.showSongList(); cout << "memory = " << t.getRemainingMemory() << " MB" << endl; Song s3("Kid Cudi", "Mr. Rager", 25); result = t.addSong(s3); cout << "result = " << result << endl; Song s4("Rihanna", "Disturbia", 17); result = t.addSong(s4); cout << "result = " << result << endl; Song s5("MGMT", "Electric Feel", 44); result = t.addSong(s5); cout << "add result = " << result << endl; Song s6("Miguel", "Skywalker", 36); result = t.addSong(s6); Song s7("Red Hot Chili Peppers", "Californication", 71); result = t.addSong(s7); t.showSongList(); cout << "memory = " << t.getRemainingMemory() << " MB" << endl; t.shuffle(); t.showSongList(); cout << "memory = " << t.getRemainingMemory() << " MB" << endl; result = t.removeSong(s2); cout << "delete result = " << result << endl; result = t.removeSong(s3); cout << "delete result = " << result << endl; t.showSongList(); cout << "memory = " << t.getRemainingMemory() << " MB" << endl; result = t.removeSong(s1); cout << "delete result = " << result << endl; t.showSongList(); result = t.removeSong(s6); cout << "delete result = " << result << endl; t.showSongList(); result = t.removeSong(s4); cout << "delete result = " << result << endl; t.showSongList(); t.showSongList(); cout << "memory = " << t.getRemainingMemory() << " MB" << endl; }
5527f7f6881bf2db0d7c4ae68a3a6377954bf077
272251b2685e16bf073eb70d7b3baebe628a5211
/chat/Reactor.h
1217244c22b70c23c1849ad47be321c54cd6e7db
[]
no_license
huiliu/Learn
f33bef135fb7109e08a7144bada42231e4de952f
47456c3b2a2bc97ad30d202bc5c8c7d86586bdfc
refs/heads/master
2021-01-17T09:36:04.526501
2020-10-12T16:34:54
2020-10-12T16:34:54
41,966,395
0
0
null
null
null
null
UTF-8
C++
false
false
119
h
Reactor.h
#pragma once #include "iPublisher.h" class Reactor : public iPublisher { public: Reactor(); virtual ~Reactor(); };