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
6d47a7f2355c507b4c517deb2d12e1a08d486a9a
a661191cd6484d25394248bcd8dde8b7bdb4436a
/C++/Week-3/Assignment-1/3-ComplexNumbers.cc
c63d7b6f3aa1d70de0a59157a06b97a034f4da14
[]
no_license
achmurali/CDAC
103f7bfdde09a09f69bc367b5ebb78dfcd53e05e
30297c5352d6b768fad89bfa30cdb3619c64ee01
refs/heads/master
2021-10-22T22:57:13.307007
2019-03-13T10:02:09
2019-03-13T10:02:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
945
cc
3-ComplexNumbers.cc
#include<iostream> using namespace std; class Complex { int real; int imaginary; public: Complex() { real = 0; imaginary = 0; } Complex(int x) { real = x; imaginary = x; } Complex(int x,int y) { real = x; imaginary = y; } friend void AddComplex(Complex &c1,Complex &c2); friend void MultiplyComplex(Complex &c1,Complex &c2); }; void AddComplex(Complex &c1,Complex &c2) { printf("%d + i%d\n",c1.real + c2.real,c1.imaginary + c2.imaginary); return; } void MultiplyComplex(Complex &c1,Complex &c2) { int result1,result2; result1 = ((c1.real)*(c2.real)) - ((c2.imaginary)*(c1.imaginary)); result2 = (c1.real)*(c2.imaginary) + (c1.imaginary)*(c2.real); printf("%d + i%d\n",result1,result2); } int main() { Complex C1; Complex C2(3); Complex C3(4,5); AddComplex(C2,C3); MultiplyComplex(C2,C3); }
1b7ef8b989719c855690121fcde9815062051ad3
6ddcdda679089b228d55ef098addfe8193287d88
/cpp/leetcode/PermutationUnique.cpp
fa31bf7cfafdfc8a8336d5c5a8c64ae384727e36
[ "MIT" ]
permissive
danyfang/SourceCode
518e4715a062ed1ad071dea023ff4785ce03b068
8168f6058648f2a330a7354daf3a73a4d8a4e730
refs/heads/master
2021-06-06T16:36:50.999324
2021-04-23T08:52:20
2021-04-23T08:52:20
120,310,634
0
0
null
null
null
null
UTF-8
C++
false
false
1,395
cpp
PermutationUnique.cpp
//Leetcode Problem No 47. Permutations II //Solution written by Xuqiang Fang on 26 May, 2019 #include <iostream> #include <vector> #include <string> #include <algorithm> #include <unordered_map> #include <unordered_set> #include <stack> #include <queue> using namespace std; class Solution { public: vector<vector<int>> permuteUnique(vector<int>& nums) { const int n = nums.size(); sort(nums.begin(), nums.end()); vector<vector<int>> ans; vector<int> tmp, used(n,0); backtrack(ans, nums, tmp, used); return ans; } private: void backtrack(vector<vector<int>>& ans, const vector<int>& nums, vector<int>& tmp, vector<int>& used){ if(tmp.size() == nums.size()){ ans.push_back(tmp); } else{ for(int i=0; i<nums.size(); ++i){ if(used[i] || (i>0 && nums[i] == nums[i-1] && used[i-1])) continue; used[i] = 1; tmp.push_back(nums[i]); backtrack(ans, nums, tmp, used); used[i] = 0; tmp.pop_back(); } } } }; void print(vector<int>& nums){ for(auto n : nums){ cout << n << " "; } cout << endl; } int main(){ Solution s; vector<int> nums{9,9,8,8,7,6,3,2}; auto ans = s.permuteUnique(nums); for(auto a : ans){ print(a); } return 0; }
4e6a5c698941897c979582989c107098a05deb95
c7f58cefe640e6c920d553931503462d208e74cc
/String_sum.cpp
dab441a012a3c8b60cf71830758256eee55e2d62
[]
no_license
IAmBlackHacker/Algorithms
20b6ed270b9d76189caf53bea7c24ff5a53e48f2
40390144917eae7595a7dbe67e6e2c5968be4abc
refs/heads/master
2021-12-07T15:19:50.250123
2021-11-14T15:33:59
2021-11-14T15:33:59
85,853,685
1
2
null
null
null
null
UTF-8
C++
false
false
3,285
cpp
String_sum.cpp
#include<iostream> #include<conio.h> #include<stdio.h> #include<string.h> #include<math.h> #define MAX 10000 using namespace std; //name1>name2 int sadd(char name1[],char name2[],char name3[],int n1,int n2,int d,int rem=0) { int n=(n1+n2)/2; if(n1 != n2) rem=sadd(name1,name2,name3,n+1,n2,d,rem); if(n1==n) { rem=(((int)name1[n+d]+(int)name2[n])%48)+rem; name3[n+d+1]=(char)(rem%10+48); rem=rem/10; return rem; } if(n1 != n2) sadd(name1,name2,name3,n1,n,d,rem); } char *add(char name1[],char name2[],char name3[]) { int len1=strlen(name1),len2=strlen(name2),rem,i; if(len1>len2) { rem=sadd(name1,name2,name3,0,strlen(name2)-1,len1-len2); for(i=len1-len2;i>0;i--) { rem=((int)name1[i-1])%48+rem; name3[i]=(char)(rem%10+48); rem=rem/10; } name3[0]=char(rem+48); name3[len1+1]='\0'; } else { rem=sadd(name2,name1,name3,0,strlen(name1)-1,len2-len1); for(i=len2-len1;i>0;i--) { rem=((int)name2[i-1])%48+rem; name3[i]=(char)(rem%10+48); rem=rem/10; } name3[0]=char(rem+48); name3[len2+1]='\0'; } char *p=name3; for(i=0;i<strlen(name3)-1;i++) { if(name3[i]=='0') p++; else break; } return p; } int ssub(char name1[],char name2[],char name3[],int n1,int n2,int d,int rem=0) { int n=(n1+n2)/2; if(n1 != n2) rem=ssub(name1,name2,name3,n+1,n2,d,rem); if(n1==n) { rem=((int)name1[n+d]-(int)name2[n])-rem; name3[n+d]=(char)( ((rem<0)?(-rem):rem)%10+48 ); if(rem<0) rem=1; else rem=0; return rem; } if(n1 != n2) ssub(name1,name2,name3,n1,n,d,rem); } char *sub(char name1[],char name2[],char name3[]) { int len1=strlen(name1),len2=strlen(name2),rem,i; if(len1>=len2) { rem=ssub(name1,name2,name3,0,strlen(name2)-1,len1-len2); for(i=len1-len2;i>0;i--) { rem=((int)name1[i-1])%48-rem; name3[i-1]=(char)( ((rem<0)?(-rem):rem)%10+48); if(rem<0) rem=-1; else rem=0; } name3[len1]='\0'; } else { rem=ssub(name2,name1,name3,0,strlen(name1)-1,len2-len1); for(i=len2-len1;i>0;i--) { rem=((int)name2[i-1])%48-rem; name3[i-1]=(char)( ((rem<0)?(-rem):rem)%10+48); if(rem<0) rem=-1; else rem=0; } name3[len2]='\0'; } char *p=name3; for(i=0;i<strlen(name3)-1;i++) { if(name3[i]=='0') p++; else break; } return p; } int main() { char name1[MAX],name2[MAX],name3[MAX],name4[MAX]; cout<<"Enter1 : "; cin>>name1; cout<<"Enter2 : "; cin>>name2; strcpy(name3,sub(name1,name2,name3)); strcpy(name4,add(name1,name2,name4)); cout<<"sub = "<<name3; cout<<"\nadd = "<<name4; return 1; }
e2eae8709eda58f842b0f7fe84d931436ed49813
8795c9a13cf38a1b064203033d0b81ea9c23c2bb
/src/host/old/Iso14443aPicc.h
e194da37fa45cdc90d3e2b699f27b2155eba62cb
[]
no_license
0xee/NfcEmu
85dddedc31cb5d62a4b70debd34cfee446465a08
000554863342b73f8b3e7a2736eda5704af38a90
refs/heads/master
2021-01-23T11:09:10.478584
2014-12-05T17:48:10
2014-12-05T17:48:10
23,524,769
15
5
null
null
null
null
UTF-8
C++
false
false
1,449
h
Iso14443aPicc.h
/** * @file Iso14443aPicc.h * @author Lukas Schuller * @date Wed Aug 21 12:14:29 2013 * * @brief Nfc Sniffer class derived from abstract class NfcEmu * */ #ifndef ISO14443APICC_H #define ISO14443APICC_H #include "NfcEmuRole.h" #include <fstream> #include <boost/asio.hpp> using boost::asio::ip::tcp; class Iso14443aPicc : public NfcEmuRole { public: Iso14443aPicc(std::unique_ptr<NfcPacketTranslator> pTr) : NfcEmuRole(std::move(pTr)), readerSocket(ioService) { try { tcp::acceptor acceptor(ioService, tcp::endpoint(tcp::v4(), 1337)); acceptor.accept(readerSocket); boost::system::error_code ignored_error; } catch (std::exception& e) { std::cerr << e.what() << std::endl; } } ~Iso14443aPicc() { } virtual bool ProcessData() { auto pPacket = pDev->ReceivePacket(); if(!pPacket) return false; pPacket->Print(); if(pPacket->GetId() == UnitId::eL4CpuApdu) { std::cout << "iframe" << std::endl; boost::system::error_code ignored_error; boost::asio::write(readerSocket, boost::asio::buffer(pPacket->Data(),pPacket->Size())); } return true; } private: boost::asio::io_service ioService; tcp::socket readerSocket; }; #endif /* ISO14443APICC_H */
ae2e839f20e5aed1a89846a320e24a41f7b31b95
4b0ad6cd4917a6ce4fda0703515b4733c4cc84ac
/applications/NeuralNet/nets/src/similarities.cxx
8e25f7ba22746bb3b8f6e5fafbf816d099c13623
[]
no_license
tciodaro/sonar-analysis
8f089709590dbe6f329e504c69e72408e48c72bf
fd04bd77c63da962ba2b5ea3fab24f113a61a8c9
refs/heads/master
2021-09-06T00:56:33.825318
2018-02-01T04:08:58
2018-02-01T04:08:58
115,443,804
0
0
null
null
null
null
UTF-8
C++
false
false
1,943
cxx
similarities.cxx
#include "../inc/similarities.h" #include <cmath> using namespace std; using namespace nnet; double SquaredEuclidianSim::operator()(double *x,double *y,unsigned int ndim){ double out = 0; for(unsigned int i = 0; i < ndim; ++i){ out += (x[i]-y[i])*(x[i]-y[i]); } return out; } void SquaredEuclidianSim::operator()(double **x,double *y,unsigned int ndim, unsigned int nevt, double *out){ for(unsigned int i = 0; i < nevt; ++i){ out[i] = (*this)(x[i], y, ndim); } } double SquaredEuclidianSim::operator()(vector<double> *x,vector<double> *y){ double out = 0; for(unsigned int i = 0; i < x->size(); ++i){ out += (x->at(i)-y->at(i))*(x->at(i)-y->at(i)); } return out; } void SquaredEuclidianSim::operator()(vector<vector<double> > *x,vector<double> *y, vector<double> *out){ for(unsigned int i = 0; i < x->size(); ++i){ out->at(i) = (*this)(&x->at(i), y); } } //======================================================================================== double EuclidianSim::operator()(double *x, double *y,unsigned int ndim){ return sqrt(SquaredEuclidianSim::operator()(x, y, ndim)); } void EuclidianSim::operator()(double **x,double *y,unsigned int ndim, unsigned int nevt,double *out){ for(unsigned int i = 0; i < nevt; ++i){ out[i] = (*this)(x[i], y, ndim); } } double EuclidianSim::operator()(vector<double> *x,vector<double> *y){ return sqrt(SquaredEuclidianSim::operator()(x, y)); } void EuclidianSim::operator()(vector<vector<double> > *x,vector<double> *y, vector<double> *out){ for(unsigned int i = 0; i < x->size(); ++i){ out->at(i) = (*this)(&x->at(i), y); } }
4d5b590c643846f9669feea956215d0f5768eea0
275de18444d493ad2bde5b6fb41578f87bc65fae
/ExampleGame/src/ExampleNativeScript.h
fa5b0fa7dcd7de9048b9f26618952dbb4ce570f8
[ "MIT", "LicenseRef-scancode-public-domain" ]
permissive
00mjk/Cross-Platform-Game-Engine
4eda739d4dd43287e4204ea51cdd16edc2d14865
a2743314d2ca71fc7f722d03994e7850d26d83a3
refs/heads/master
2023-04-14T10:18:37.128338
2021-04-14T16:09:47
2021-04-14T16:09:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
242
h
ExampleNativeScript.h
#pragma once #include "Engine.h" class ExampleScript : public ScriptableEntity { public: void OnCreate() override; void OnDestroy() override; void OnUpdate(float deltaTime) override; private: static ScriptRegister<ExampleScript> reg; };
0f3ab11e26a4b2e98ad9c2b464e4fcce6060fd9d
242d2a4dcc810b5e89d1c110ea67101af7a840d0
/SortVisualizer/stdsort.cpp
b17047332bdbacfca905e9a4efa897537d64fe3d
[]
no_license
Dynamitos/SortVisualizer
c08a13357a57414d748d84d29b99bdd76f8f70aa
c24f41306623fc650b5841641eb6898bf0a36f20
refs/heads/master
2023-01-19T19:49:59.226706
2020-12-03T16:49:28
2020-12-03T16:49:28
109,870,700
1
1
null
null
null
null
UTF-8
C++
false
false
620
cpp
stdsort.cpp
#include "stdsort.h" StdSort::StdSort(bool mt, bool assembly, int delay) : SortAlgorithm(mt, assembly, delay) { this->name = "Std sort"; } void StdSort::sort(float* data, int size) { std::qsort(data, size, sizeof(float), [](const void* a, const void* b) { float arg1 = *static_cast<const float*>(a); float arg2 = *static_cast<const float*>(b); if (arg1 < arg2) return -1; if (arg1 > arg2) return 1; return 0; // return (arg1 > arg2) - (arg1 < arg2); // possible shortcut // return arg1 - arg2; // erroneous shortcut (fails if INT_MIN is present) }); //std::sort(data.begin(), data.end()); }
92335d58aaa980b6807714bb7ff5870efc0d8de4
ac0814e3310402883e8229c6b7cb05dcdaf28e08
/Game/GraphicsModule.hpp
ab81fc62f8711ebd5e978d23591f1fc33ecf8110
[]
no_license
KaiqueBressi/RPGSystem
e1cfb533685797b0bc05ccdfaf4455eebc70ded7
4bce336c488e01e2430549e2973f08834fce44f6
refs/heads/master
2021-05-26T18:20:38.515045
2014-03-04T15:41:08
2014-03-04T15:41:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
304
hpp
GraphicsModule.hpp
#ifndef GRAPHICS_H #define GRAPHICS_H #include <SFML/Graphics.hpp> #include <stdio.h> #include "ruby.h" #include "Sprite.hpp" class GraphicsModule { public: GraphicsModule(); void update(); void getFPS(); private: sf::RenderWindow window; sf::Event event; }; void graphicsInit(); #endif
29b62cf9580b7d60a468f129038bff5421623e7c
f966c5b7270bcd6acd324101747d20cb5f73a35a
/robinhood/People.h
25cce9785de55f791c1091478c0effb64194678e
[]
no_license
Enmar123/robinhood
a7f3e3a1155625558fef459e6604a26d043ead4b
17109da1abfdfc016096a12743b242eb1cfa76f4
refs/heads/master
2023-02-19T04:46:42.637905
2020-12-26T08:42:21
2020-12-26T08:42:21
322,810,439
0
0
null
null
null
null
UTF-8
C++
false
false
789
h
People.h
#pragma once #include <list> #include <string> #include "Node.h" struct Move { int x = 0; int y = 0; unsigned int steps = 1; }; class People { public: People(); People(int x, int y); People(int x, int y, int width, int height); void update(); void followMoves(); void followSteps(); int getX(); int getY(); int getWidth(); int getHeight(); std::string getSymbol(); void setSteps(std::list<Point> points); bool isAlive = true; int x, y; protected: bool loadedMoves = true; bool loadedSteps = false; int width, height; int speed; std::string symbol; std::list<Move> moves; // Move order, displacement based on speed std::list<Move> currentmoves; std::list<Point> steps; // Explicit locatios to be at evey timestep std::list<Point> currentsteps; };
dc7c70f7182b5f7c3cbc58b2230b9b815d6a46f4
1a8aec92ecaee35aa5be4f076af4dd4dd3655eab
/Contest9/bai01.cpp
82a6498c658c50fef339d941191a03afb228cb5d
[]
no_license
sonnhthtb/Algorithm
d94a74da80a1200c21af03e3cb161269bd184772
c06f3471cf701cb6d0450e4385fa041f4b84eb2b
refs/heads/master
2022-10-26T06:14:09.098776
2020-06-18T06:00:23
2020-06-18T06:00:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
698
cpp
bai01.cpp
#include <bits/stdc++.h> #define ll long long #define pb push_back using namespace std; vector<int> a[100000]; int e, v; void Input() { for (int i = 0; i < 100000; i++) a[i].clear(); cin >> v >> e; } void Solve() { for (int i = 0; i < e; i++) { int x, y; cin >> x >> y; a[x].push_back(y); a[y].push_back(x); } for (int i = 1; i <= v; i++) { cout << i << ": "; for (int j = 0; j < a[i].size(); j++) { cout << a[i][j] << " "; } cout << endl; } } int main() { int T = 1; cin >> T; while (T--) { Input(); Solve(); } return 0; }
a529ef4e92e58590a9d6d7ef489c8aed3cba0181
3959cd7ff411ac696c13cdb9351dc455c4a946c9
/C++/Root Finder GNU/solverMain.cc
3534d0e2706b67e81716b095da33dc85467f9f6b
[]
no_license
tmawyin/ScientificComputing
96a95d53d65489fb3625adf335effe1b1d34b378
f8751f5ffa2723529be9795ce482af07ff5b5955
refs/heads/master
2016-09-06T17:26:33.105884
2015-06-29T20:08:48
2015-06-29T20:08:48
38,267,499
0
0
null
null
null
null
UTF-8
C++
false
false
459
cc
solverMain.cc
// solverRoot main function - runs Newton's and False Position methods #include "solverRoot.h" // Main function int main() { double x_lo = 0.0; double x_hi = 10.0; double x_guess = -5.0; double fpos = solveFalsepos(x_lo, x_hi); double newt = solveNewton(x_guess); std::cout << "False position result = " << fpos << "\n"; std::cout << "Newtons method result = " << newt << "\n"; std::cout << "\n\n"; computeSolvers(0.0,10.0,1.0); return 0; }
9aafe1f468fbedcd19872c39d0ded7e10ad20b0a
1ae91db02db7635f1ee654cd51a3e184417d18c0
/vor-arduino/vor_light.cpp
27b751b539c506c2152bb59bc7017563381db8c7
[ "MIT" ]
permissive
rajibkumardas/vor
25d5f88dbffa69b365be0a3e166b9ecad49c0393
0397fea806478f61be37dff3af944e17c41b51d8
refs/heads/master
2021-01-02T23:11:16.097824
2017-02-02T10:00:10
2017-02-02T10:00:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
675
cpp
vor_light.cpp
/* AAnalog ambient light sensor. */ #include "vor_light.h" VorLight::VorLight(uint8_t pin) : VorSensor(pin, ANALOG_INPUT) { } float VorLight::process(int value) { // https://www.sparkfun.com/datasheets/Sensors/Imaging/TEMT6000.pdf // 10 K ohm resistor // 20 lx = 10 uA = 0.00001 A = 0.1 V // 100 lx = 50 uA = 0.00005 A = 0.5 V // 1000 lx = 500 uA = 0.00050 A = 5.0 V // // illuminance (lx) = 2000000 * (V / 10000 ohms) // this equation does not calculate illuminance correctly but the size of // the value should be about correct... float illuminance = 2000.0 * (value / MAX_ANALOG_INPUT_VALUE); return illuminance; }
10873c715eb93e45e3e86a93c77db285b218a176
8518ddf310e9e90a0219be96eeed776aa10844f2
/Prueba/diLeptonic/src/HistoListReader.h
281830d74ca36f6ba71241b641bb6852a52a3920
[]
no_license
iasincru/usercode
b803371b253f02cf18ef86f16f69ec75db7a05fc
9f97484258be07442263cab97dea959895f7a637
refs/heads/master
2021-01-17T13:15:24.899347
2016-09-21T13:18:10
2016-09-21T13:18:10
10,908,905
0
0
null
null
null
null
UTF-8
C++
false
false
1,392
h
HistoListReader.h
#ifndef HistoListReader_h #define HistoListReader_h #include <vector> #include <map> #include <TString.h> class TH1; struct PlotProperties { TString name; TString specialComment; TString ytitle; TString xtitle; int rebin; bool do_dyscale; bool logX; bool logY; double ymin; double ymax; double xmin; double xmax; int bins; std::vector<double> xbinbounds; std::vector<double> bincenters; //return a histogram with the binning and labels as defined in the properties TH1 *getHistogram(); //like getHistogram, but returns a clone, i.e. the caller must delete the histogram TH1 *getClonedHistogram(); PlotProperties(); ~PlotProperties(); private: TH1 *histo_; void MakeHisto(); }; class HistoListReader { const char *filename_; bool isZombie_; std::map<TString, PlotProperties> plots_; public: HistoListReader(const char *filename); bool IsZombie() const; PlotProperties& getPlotProperties(TString name); //rootcint does not like decltype! :-( //auto begin() -> decltype(plots_.begin()) { return plots_.begin(); } //auto end() -> decltype(plots_.end()) { return plots_.end(); } std::map <TString, PlotProperties >::iterator begin() { return plots_.begin(); } std::map <TString, PlotProperties >::iterator end() { return plots_.end(); } }; #endif
29a9174ae62785e4f1ac7e1a9dee0db5e2a94fd1
b85f5e054b72841375c1e2833c4edc860a42a161
/ADS_set.h
463d12f8c71e5acc77fcd194ca092abdb8b05e51
[]
no_license
biropost/extendible_hashing
cc3af6d6b9efba7df27a56f7f17fdb32ac740c74
ff8f4148faa9afcc7ca7dd2e23ff14094ae0e4d1
refs/heads/master
2020-03-29T16:42:47.484295
2018-09-24T15:34:08
2018-09-24T15:34:08
150,125,922
0
0
null
null
null
null
UTF-8
C++
false
false
14,472
h
ADS_set.h
#include <iostream> #include <exception> #include <cmath> #include <functional> #include <string> #include <stdexcept> #include <algorithm> #include <assert.h> #include <utility> using namespace std; class Person; template <typename Key,size_t N = 5> class ADS_set { public: class Forward_it; using value_type = Key; using key_type = Key; using reference = value_type&; using pointer = value_type*; using const_reference = const value_type&; using size_type = size_t; using difference_type = std::ptrdiff_t; using const_iterator = Forward_it; using iterator = const_iterator; using key_equal = std::equal_to<key_type>; // Hashing using hasher = std::hash<key_type>; // Hashing struct pai { value_type fi; bool se{false}; pai() : se (false) {} pai(value_type _fi) : fi(_fi), se(true){} value_type& first(){return fi;} bool second(){return se;} void set(value_type f){fi = f; se = true;} void del(){se = false;} value_type& operator * () { return fi; } }; class Forward_it { public: using value_type = ADS_set::value_type; using difference_type = ptrdiff_t; using reference = ADS_set::reference; using pointer = ADS_set::pointer; using iterator_category = std::forward_iterator_tag; private: pai* ptr; pai* end; public: Forward_it() : ptr(NULL), end(NULL) {} Forward_it (pai* _ptr, pai* _end) : ptr(_ptr), end(_end) {} Forward_it (pai& _ptr, pai& _end) : ptr(&_ptr), end(&_end) {} Forward_it (const iterator& _it) : ptr(_it.ptr), end(_it.end) {} friend difference_type operator-( iterator& lop, iterator& rop) { return lop.ptr-rop.ptr; } friend difference_type operator+( iterator& lop, iterator& rop) { return lop.ptr+rop.ptr; } friend iterator operator-( iterator& lop, difference_type rop) { return lop.ptr-rop; } friend iterator operator+( iterator& lop, difference_type rop) { return lop.ptr+rop; } friend pai& operator+(const iterator& lop, int rop) { return *(lop.ptr+rop); } friend pai& operator-(const iterator& lop, int rop) { return *(lop.ptr-rop); } friend pai& operator+( iterator& lop, int rop) { return *(lop.ptr+rop); } friend pai& operator-( iterator& lop, int rop) { return *(lop.ptr-rop); } friend difference_type operator-( const Forward_it& lop, pointer rop) { return lop.ptr-rop; } friend difference_type operator+( const iterator& lop, pointer rop) { return lop.ptr+rop; } friend bool operator<( iterator& lop, const iterator& rop) { return lop<rop; } friend bool operator>( iterator& lop, const iterator& rop) { return lop>rop; } friend bool operator<=( iterator& lop, const iterator& rop) { return lop<=rop; } friend bool operator>=( iterator& lop, const iterator& rop) { return lop>=rop; } friend bool operator ==( const iterator & lop, const iterator & rop) { return lop.ptr == rop.ptr; } friend bool operator ==( pai lop, pai rop) { return key_equal{}(lop->first(), rop->first()); } friend bool operator !=( const iterator & lop, const iterator & rop) { return !(lop == rop); } iterator & operator += (difference_type rop) const { *this += rop; return *this; } iterator & operator -= (difference_type rop) const { return this += -rop; } iterator & operator ++ () { if (ptr != end) ptr++; while (ptr != end && ptr->second()==false) ++ptr; return *this; } iterator operator ++ (int) { //postfix iterator copy(*this); if (ptr != end) ptr++; while (ptr != end && ptr->second()==false) ++ptr; return copy; } iterator & operator -- () { ptr--; while (ptr != end && ptr->second()==false) ptr--; return *this; } iterator operator -- (int) { iterator copy(*this); ptr--; while (ptr != end && ptr->second()==false) ptr--; return copy; } reference operator * () const { return (ptr->first()); } pointer operator->() const { return &(operator*()); } }; private: class Block { int d; pai* values; int sz{0}; public: Block() : sz(0) {} Block(pai* val, int _d) : d(_d), values(val), sz(0) {} Block(Block& other) : d(other.d), values(other.values), sz(other.sz) {} ~Block() {} value_type& operator [] (int nr) { return (values+nr)->first(); } value_type get (int nr){ return (values+nr)->first(); } void set(pai* ptr) {values=ptr;} void set_sz(int _sz){sz = _sz;} void clear () { for (int i=0; i<sz; ++i) values[i].del(); sz = 0; } int size(){ return sz; } int get_d(){ return d; } void set_d(int _d){ d = _d; } int add (const value_type val) { if (sz != 0 && contains(val)) return 1; if (sz==N) return 0; (values+sz)->set(val); ++sz; return 2; } size_type remove (const value_type& val){ //recoursion if (!contains(val))return 0; size_type ret_val = 0; if (N>1){ int nr = 0; for (int i=0; i<sz; ++i) { if (key_equal{}((values+i)->first(), val)) { nr = i; ret_val = 1; break; } } for (; nr < sz-1; ++nr) (values+nr)->set((values+nr+1)->first()); (values+sz-1)->del(); } else if (N ==1) { values->del(); ret_val = 1; } --sz; return ret_val; } bool contains (const value_type& val){ if (sz == 0) return 0; bool b = false; for (int i=0; i<sz; ++i) if (key_equal{}(val,(values+i)->first())) { b = true; break; } return b; } pai* contains_ptr (const value_type& val) const { pai* b = NULL; for (int i=0; i<sz; ++i) if (key_equal{}((values+i)->first(), val)) { b = (values+i); break; } return b; } }; Block** hash; pai* values; int t_sz{1}, b_sz{1}, max_b_sz{1}; int cntr{0}; int t{0}; /* int bucket_max_sz{1}; Block** bucket_ptr; */ public: ADS_set (){ hash = new Block*[1]; values = new pai[N]; hash[0] = new Block(&values[0], 0); //bucket_ptr = new Block*[1]; //bucket_ptr[0] = &*hash[0]; } ADS_set(std::initializer_list<value_type> ilist) { hash = new Block*[1]; values = new pai[N]; hash[0] = new Block(&values[0], 0); //bucket_ptr = new Block*[1]; //bucket_ptr[0] = &*hash[0]; insert(ilist); } template<typename InputIt> ADS_set(InputIt first, InputIt last){ hash = new Block*[1]; values = new pai[N]; hash[0] = new Block(&values[0], 0); //bucket_ptr = new Block*[1]; //bucket_ptr[0] = &*hash[0]; insert(first, last); } ADS_set(const ADS_set& other){ hash = new Block*[1]; values = new pai[N]; hash[0] = new Block(&values[0], 0); //bucket_ptr =NULL; operator=(other); } ~ADS_set(){ delete[] values; int n = 0; if (b_sz != 1) { while(b_sz){ if (hash[n] != NULL){ for(int i=n+1; i<t_sz; ++i){ if (hash[i] == hash[n]) hash[i] = NULL; } delete hash[n]; --b_sz; } ++n; } } else { delete hash[0]; } delete[] hash; } private: void index_expansion(){ Block** tmp_hash = new Block*[t_sz*10]; for (int i=0; i<t_sz; ++i) { tmp_hash[(int)(i+0*pow(10,t))] = tmp_hash[(int)(i+1*pow(10,t))] = tmp_hash[(int)(i+2*pow(10,t))] = tmp_hash[(int)(i+3*pow(10,t))] = tmp_hash[(int)(i+4*pow(10,t))] = tmp_hash[(int)(i+5*pow(10,t))] = tmp_hash[(int)(i+6*pow(10,t))] = tmp_hash[(int)(i+7*pow(10,t))] = tmp_hash[(int)(i+8*pow(10,t))] = tmp_hash[(int)(i+9*pow(10,t))] = hash[i]; } delete[] hash; hash=tmp_hash; t_sz = t_sz*10; ++t; } int hash_getter ( const value_type& val){ hasher hash_val; size_type _hasher = hash_val(val); int divisor = t>1?pow(10,t):10; return t==0?0:_hasher%divisor; } void split(size_type num){ value_type copy[N]; for (int i=0; i<(signed)N; ++i) copy[i] = hash[num]->get(i); if (max_b_sz == b_sz) { int sum = b_sz==1? b_sz*N*10: b_sz<10? b_sz*N*2:b_sz<100? (b_sz*N*1.8)-fmod((b_sz*N*1.8),N):b_sz<1000? (b_sz*N*1.23)-fmod((b_sz*N*1.23),N):b_sz<10000? (b_sz*N*1.15)-fmod((b_sz*N*1.15),N):(b_sz*N*1.07)-fmod((b_sz*N*1.07),N); pai* tmp_values = new pai[sum]; bool check = false; int sizer = 0; int b_fill = 0; for(int i=0; i<(signed)(b_sz*N); ++i) { if (i%N == 0 && values[i].second()) { check = true; ++b_fill; } if (check) { tmp_values[sizer++] = values[i]; if (i%N == 0) hash[hash_getter(tmp_values[sizer-1].first())]->set(&tmp_values[sizer-1]); if (i%N == N-1) check = false; } } sizer = 0; for (int i=0; i<t_sz; ++i){ if (hash[i]->size() == 0) { hash[i]->set(&tmp_values[b_fill*N]); hash[i]->set_sz(-1); ++b_fill; } if (b_fill == b_sz) break; } for (int i=0; i<t_sz; ++i){ if (hash[i]->size() == -1) hash[i]->set_sz(0); } max_b_sz = sum/N; delete[] values; values = tmp_values; //if (t==3) {dump();abort();} } hash[num]->clear(); cntr -= N; hash[num] = new Block(&values[b_sz*N], t); ++b_sz; for (int i=0; i<(signed)N; ++i) push(copy[i]); } void push(const value_type& _val){ int finder = hash_getter(_val); int test = hash[finder]->add(_val); if (test == 2){++cntr;} else if (test == 0) { if (hash[finder]->get_d()==t){ index_expansion(); push(_val); } else if (hash[finder]->get_d() < t) { split(finder); push(_val); } else { abort(); } } else if (test == 1){} else abort(); } bool push_b(const value_type& _val){ int finder = hash_getter(_val); int test = hash[finder]->add(_val); if (test == 2){++cntr; return true;} else if (test == 0) { if (hash[finder]->get_d()==t){ index_expansion(); push(_val); return true; } else if (hash[finder]->get_d() < t) { split(finder); push(_val); return true; } else { abort(); } } else if (test == 1){return false;} else abort(); } bool finder(const value_type& _val) const { hasher hash_val; return hash[hash_val(_val)%(int)pow(10,t)]->contains(_val); } pai* finder_ptr (const value_type& _val) const { hasher hash_val; return hash[hash_val(_val)%(int)pow(10,t)]->contains_ptr(_val); } public: void insert(std::initializer_list<value_type> ilist){ for (value_type it : ilist) { push(it); } } template<typename InputIt> void insert(InputIt first, InputIt last){ for (auto it = first; it != last; ++it) { push(*it); } } std::pair<iterator,bool> insert(const value_type& key){ bool b = push_b(key); std::pair <iterator,bool> p; p = std::make_pair(find(key), b); return p; } ADS_set& operator=(const ADS_set& other){ clear(); for (int i=0; i<(int)(other.b_sz*N); ++i){ if (other.values[i].second()){ push(other.values[i].first()); } } return *this; } ADS_set& operator=(std::initializer_list<value_type> ilist){ clear(); insert(ilist); return *this; } size_type size() const{ return cntr; } bool empty() const{ return cntr==0; } void clear(){ delete[] values; //if (bucket_ptr!=NULL) for (int i=0; i<b_sz; ++i) delete bucket_ptr[i]; //delete[] bucket_ptr; int n = 0; while(b_sz){ if (hash[n] != NULL){ for(int i=n+1; i<t_sz; ++i){ if (hash[i] == hash[n]) hash[i] = NULL; } delete hash[n]; --b_sz; } ++n; } delete[] hash; b_sz = 1; t_sz = 1; max_b_sz = 1; cntr = 0; t = 0; //bucket_max_sz = 1; hash = new Block*[1]; values = new pai[N]; hash[0] = new Block(&values[0], 0); //bucket_ptr = new Block*[1]; //bucket_ptr[0] = &*hash[0]; } size_type erase(const value_type& key){ if (!finder(key)) return 0; hash[hash_getter(key)]->remove(key); --cntr; //if ((cntr/(b_sz*N))<0.7) cerr<<"HALT "<<cntr<<"-"<<b_sz*N<<"-"<<max_b_sz<<endl; return 1; } void swap(ADS_set& other){ /*ADS_set tmp = other; other = *this; *this = tmp;*/ Block** tmp_hash = other.hash; pai* tmp_values = other.values; //Block** tmp_bucket_ptr = other.bucket_ptr; other.hash = hash; other.values = values; //other.bucket_ptr = bucket_ptr; hash = tmp_hash; values = tmp_values; //bucket_ptr = tmp_bucket_ptr; int tmp_t_sz = other.t_sz; int tmp_b_sz = other.b_sz; int tmp_max_b_sz = other.max_b_sz; int tmp_cntr = other.cntr; int tmpt = other.t; //int tmp_bucket_max_sz = other.bucket_max_sz; other.t_sz = t_sz; other.b_sz = b_sz; other.max_b_sz = max_b_sz; other.cntr = cntr; other.t = t; //other.bucket_max_sz = bucket_max_sz; t_sz = tmp_t_sz; b_sz = tmp_b_sz; max_b_sz = tmp_max_b_sz; cntr = tmp_cntr; t = tmpt; //bucket_max_sz = tmp_bucket_max_sz; } size_type count(const value_type& key) const{ return finder(key)?1:0; } iterator find(const key_type& key) const{ if (size()==0)return end(); pai* ptr = finder_ptr(key); iterator it((ptr==NULL?values[b_sz*N]:*ptr), values[b_sz*N]); return it; } iterator begin() const{ if (cntr == 0) { iterator it(values[0], values[0]); return it; } else { int i = 0; for(;i<(int)(b_sz*N);++i) if (values[i].second()==true) break; iterator it(values[i], values[b_sz*N]); return it; } } iterator end() const{ if (cntr == 0) { iterator it(values[0], values[0]); return it; } else { iterator it(values[b_sz*N], values[b_sz*N]); return it; } } void dump(std::ostream& o = std::cerr) const{ o<<"tsz: "<<t_sz<<" bsz: "<<b_sz<<" max_b_sz: "<<max_b_sz<<" t: "<<t<<" counter is: "<<cntr<<endl; //for (auto it = begin(); it != end(); ++it) o<<*it<<", "; for (auto it = begin(); it != end(); ++it) o<<*it<<" "; //o<<endl; auto it = begin(); for (int i = 0; i<(int)(max_b_sz * N); ++i){ if (i%10 == 0) o<<endl; o<<*(it+i)<<"("<<(it+i).second()<<") "; } o<<endl; //o<<N<<endl<<*begin()<<endl<<*(end()-1)<<endl<<std::distance(begin(), end())<<endl; for (int i=0; i<t_sz; ++i) { o<<i<<" – "<<"sz: "<<hash[i]->size()<< " ["; for (int n=0; n<hash[i]->size(); ++n) o<<hash[i]->get(n)<<" "; //for (int n=0; n<hash[i]->size(); ++n) o<<hash[i]->get(n)<<" "; o<<" ]"<<endl; } } value_type* get_values() const {return values;} }; template <typename Key, size_t N> bool operator==(const ADS_set<Key,N>& lhs, const ADS_set<Key,N>& rhs){ if (lhs.size()!=rhs.size()) return false; bool b = false; for (auto it_1 = lhs.begin(); it_1 != lhs.end() ; ++it_1){ for (auto it_2 = rhs.begin(); it_2 != rhs.end(); ++it_2) { if (equal_to<Key>{}(*it_1, *it_2)) { b = true; } } if (b==false) return false; b = false; } return true; } template <typename Key, size_t N> bool operator!=(const ADS_set<Key,N>& lhs, const ADS_set<Key,N>& rhs){ return !(lhs==rhs); } template <typename Key, size_t N> void swap(ADS_set<Key,N>& lhs, ADS_set<Key,N>& rhs){ lhs.swap(rhs); }
efee1a370dd03dce457e087cd85a42f232c6c87b
e4d601b0750bd9dcc0e580f1f765f343855e6f7a
/kaldi-wangke/src/rnnlm/rnnlm-training.cc
90e520557a12b8e6697174880679a811f7d269e6
[ "MIT", "Apache-2.0", "LicenseRef-scancode-public-domain" ]
permissive
PeiwenWu/Adaptation-Interspeech18
01b426cd6d6a2d7a896aacaf4ad01eb3251151f7
576206abf8d1305e4a86891868ad97ddfb2bbf84
refs/heads/master
2021-03-03T04:16:43.146100
2019-11-25T05:44:27
2019-11-25T05:44:27
245,930,967
1
0
MIT
2020-03-09T02:57:58
2020-03-09T02:57:57
null
UTF-8
C++
false
false
10,613
cc
rnnlm-training.cc
// rnnlm/rnnlm-training.cc // Copyright 2017 Daniel Povey // See ../../COPYING for clarification regarding multiple authors // // 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 // // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED // WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // See the Apache 2 License for the specific language governing permissions and // limitations under the License. #include "rnnlm/rnnlm-training.h" #include "nnet3/nnet-utils.h" namespace kaldi { namespace rnnlm { RnnlmTrainer::RnnlmTrainer(bool train_embedding, const RnnlmCoreTrainerOptions &core_config, const RnnlmEmbeddingTrainerOptions &embedding_config, const RnnlmObjectiveOptions &objective_config, const CuSparseMatrix<BaseFloat> *word_feature_mat, CuMatrix<BaseFloat> *embedding_mat, nnet3::Nnet *rnnlm): train_embedding_(train_embedding), core_config_(core_config), embedding_config_(embedding_config), objective_config_(objective_config), rnnlm_(rnnlm), core_trainer_(NULL), embedding_mat_(embedding_mat), embedding_trainer_(NULL), word_feature_mat_(word_feature_mat), num_minibatches_processed_(0), end_of_input_(false), previous_minibatch_empty_(1), current_minibatch_empty_(1) { int32 rnnlm_input_dim = rnnlm_->InputDim("input"), rnnlm_output_dim = rnnlm_->OutputDim("output"), embedding_dim = embedding_mat->NumCols(); if (rnnlm_input_dim != embedding_dim || rnnlm_output_dim != embedding_dim) KALDI_ERR << "Expected RNNLM to have input-dim and output-dim " << "equal to embedding dimension " << embedding_dim << " but got " << rnnlm_input_dim << " and " << rnnlm_output_dim; core_trainer_ = new RnnlmCoreTrainer(core_config_, objective_config_, rnnlm_); if (train_embedding) { embedding_trainer_ = new RnnlmEmbeddingTrainer(embedding_config, embedding_mat_); } else { embedding_trainer_ = NULL; } if (word_feature_mat_ != NULL) { int32 feature_dim = word_feature_mat_->NumCols(); if (feature_dim != embedding_mat_->NumRows()) { KALDI_ERR << "Word-feature mat (e.g. from --read-sparse-word-features) " "has num-cols/feature-dim=" << word_feature_mat_->NumCols() << " but embedding matrix has num-rows/feature-dim=" << embedding_mat_->NumRows() << " (mismatch)."; } } // Start a thread that calls run_background_thread(this). // That thread will be responsible for computing derived variables of // the minibatch, since that can be done independently of the main // training process. background_thread_ = std::thread(run_background_thread, this); } void RnnlmTrainer::Train(RnnlmExample *minibatch) { // check the minibatch for sanity. if (minibatch->vocab_size != VocabSize()) KALDI_ERR << "Vocabulary size mismatch: expected " << VocabSize() << ", got " << minibatch->vocab_size; // hand over 'minibatch' to the background thread to have its derived variable // computed, via the class variable 'current_minibatch_'. current_minibatch_empty_.Wait(); current_minibatch_.Swap(minibatch); current_minibatch_full_.Signal(); num_minibatches_processed_++; if (num_minibatches_processed_ == 1) { return; // The first time this function is called, return immediately // because there is no previous minibatch to train on. } previous_minibatch_full_.Wait(); TrainInternal(); previous_minibatch_empty_.Signal(); } void RnnlmTrainer::GetWordEmbedding(CuMatrix<BaseFloat> *word_embedding_storage, CuMatrix<BaseFloat> **word_embedding) { RnnlmExample &minibatch = previous_minibatch_; bool sampling = !minibatch.sampled_words.empty(); if (word_feature_mat_ == NULL) { // There is no sparse word-feature matrix. if (!sampling) { KALDI_ASSERT(active_words_.Dim() == 0); // There is no sparse word-feature matrix, so the embedding matrix is just // embedding_mat_ (the embedding matrix for all words). *word_embedding = embedding_mat_; KALDI_ASSERT(minibatch.vocab_size == embedding_mat_->NumRows()); } else { // There is sampling-- we're using a subset of the words so the user wants // an embedding matrix for just those rows. KALDI_ASSERT(active_words_.Dim() != 0); word_embedding_storage->Resize(active_words_.Dim(), embedding_mat_->NumCols(), kUndefined); word_embedding_storage->CopyRows(*embedding_mat_, active_words_); *word_embedding = word_embedding_storage; } } else { // There is a sparse word-feature matrix, so we need to multiply it by the // feature-embedding matrix in order to get the word-embedding matrix. const CuSparseMatrix<BaseFloat> &word_feature_mat = sampling ? active_word_features_ : *word_feature_mat_; word_embedding_storage->Resize(word_feature_mat.NumRows(), embedding_mat_->NumCols()); word_embedding_storage->AddSmatMat(1.0, word_feature_mat, kNoTrans, *embedding_mat_, 0.0); *word_embedding = word_embedding_storage; } } void RnnlmTrainer::TrainWordEmbedding( CuMatrixBase<BaseFloat> *word_embedding_deriv) { RnnlmExample &minibatch = previous_minibatch_; bool sampling = !minibatch.sampled_words.empty(); if (word_feature_mat_ == NULL) { // There is no sparse word-feature matrix. if (!sampling) { embedding_trainer_->Train(word_embedding_deriv); } else { embedding_trainer_->Train(active_words_, word_embedding_deriv); } } else { // There is a sparse word-feature matrix, so we need to multiply by it // to get the derivative w.r.t. the feature-embedding matrix. if (!sampling && word_feature_mat_transpose_.NumRows() == 0) word_feature_mat_transpose_.CopyFromSmat(*word_feature_mat_, kTrans); CuMatrix<BaseFloat> feature_embedding_deriv(embedding_mat_->NumRows(), embedding_mat_->NumCols()); const CuSparseMatrix<BaseFloat> &word_features_trans = (sampling ? active_word_features_trans_ : word_feature_mat_transpose_); feature_embedding_deriv.AddSmatMat(1.0, word_features_trans, kNoTrans, *word_embedding_deriv, 0.0); // TODO: eventually remove these lines. KALDI_VLOG(3) << "word-features-trans sum is " << word_features_trans.Sum() << ", word-embedding-deriv-sum is " << word_embedding_deriv->Sum() << ", feature-embedding-deriv-sum is " << feature_embedding_deriv.Sum(); embedding_trainer_->Train(&feature_embedding_deriv); } } void RnnlmTrainer::TrainInternal() { CuMatrix<BaseFloat> word_embedding_storage; CuMatrix<BaseFloat> *word_embedding; GetWordEmbedding(&word_embedding_storage, &word_embedding); CuMatrix<BaseFloat> word_embedding_deriv; if (train_embedding_) word_embedding_deriv.Resize(word_embedding->NumRows(), word_embedding->NumCols()); core_trainer_->Train(previous_minibatch_, derived_, *word_embedding, (train_embedding_ ? &word_embedding_deriv : NULL)); if (train_embedding_) TrainWordEmbedding(&word_embedding_deriv); } int32 RnnlmTrainer::VocabSize() { if (word_feature_mat_ != NULL) return word_feature_mat_->NumRows(); else return embedding_mat_->NumRows(); } void RnnlmTrainer::RunBackgroundThread() { while (true) { current_minibatch_full_.Wait(); if (end_of_input_) return; RnnlmExampleDerived derived; CuArray<int32> active_words_cuda; CuSparseMatrix<BaseFloat> active_word_features; CuSparseMatrix<BaseFloat> active_word_features_trans; if (!current_minibatch_.sampled_words.empty()) { std::vector<int32> active_words; RenumberRnnlmExample(&current_minibatch_, &active_words); active_words_cuda.CopyFromVec(active_words); if (word_feature_mat_ != NULL) { active_word_features.SelectRows(active_words_cuda, *word_feature_mat_); active_word_features_trans.CopyFromSmat(active_word_features, kTrans); } } GetRnnlmExampleDerived(current_minibatch_, train_embedding_, &derived); // Wait until the main thread is not currently processing // previous_minibatch_; once we get this semaphore we are free to write to // it and other related variables such as 'derived_'. previous_minibatch_empty_.Wait(); previous_minibatch_.Swap(&current_minibatch_); derived_.Swap(&derived); active_words_.Swap(&active_words_cuda); active_word_features_.Swap(&active_word_features); active_word_features_trans_.Swap(&active_word_features_trans); // The following statement signals that 'previous_minibatch_' // and related variables have been written to by this thread. previous_minibatch_full_.Signal(); // The following statement signals that 'current_minibatch_' // has been consumed by this thread and is no longer needed. current_minibatch_empty_.Signal(); } } RnnlmTrainer::~RnnlmTrainer() { // Train on the last minibatch, because Train() always trains on the previously // provided one (for threading reasons). if (num_minibatches_processed_ > 0) { previous_minibatch_full_.Wait(); TrainInternal(); } end_of_input_ = true; current_minibatch_full_.Signal(); background_thread_.join(); // Note: the following delete statements may cause some diagnostics to be // issued, from the destructors of those classes. if (core_trainer_) delete core_trainer_; if (embedding_trainer_) delete embedding_trainer_; KALDI_LOG << "Trained on " << num_minibatches_processed_ << " minibatches.\n"; } } // namespace rnnlm } // namespace kaldi
3a11bcc155badc9b3a771046a0083d979d0de324
8d61f433702f109ae7aa16c0b3e06b6d6c1b0501
/WeightCore.ino
0499b844b58c7a448fb41e537a732665d26c691c
[]
no_license
ashwah/WSProtoType
c5092dc90180463657570857dc43de43b567c80e
c7da0f31028f08bf9a5ddf21a99dd17f73e037a8
refs/heads/master
2020-04-04T13:52:51.129737
2018-11-03T13:03:53
2018-11-03T13:03:53
155,978,502
0
0
null
null
null
null
UTF-8
C++
false
false
4,848
ino
WeightCore.ino
/* WeightCore Arduino | HX711 --------+------- 2 | CLK 3 | DAT 5V | VCC GND | GND */ // Include libraries. #include "HX711.h" #include "WiFiEsp.h" #include "SoftwareSerial.h" // Define pins. #define CLK 2 #define DOUT 3 #define RX 4 #define TX 5 // RGB must be pins that function as analog. #define RRR 9 #define GGG 10 #define BBB 11 // Define states. #define INITIALISING 0 #define STABLE 1 #define CHANGING 2 #define SENDING 3 // Define calibration parameters. #define THRESHOLD_DIFFERENCE 0.15 #define THRESHOLD_PERCENT 0.05 #define CHANGE_STEPS 5 #define CALIBRATION_FACTOR -10550.0 // Instantiate hardware interfaces. SoftwareSerial esp8266(RX,TX); WiFiEspClient client; HX711 scale(DOUT, CLK); // Declare global variables. int state; float display_weight; float suggest_weight; float current_weight; char ssid[] = "xxx"; char pass[] = "xxx"; char server[] = "xxx"; /** * Setup. */ void setup() { Serial.begin(9600); esp8266.begin(9600); pinMode(RRR, OUTPUT); pinMode(GGG, OUTPUT); pinMode(RRR, OUTPUT); set_state(INITIALISING); WiFi.init(&esp8266); WiFi.begin(ssid, pass); Serial.println("WeightCore initalizing"); // Init scale. scale.set_scale(CALIBRATION_FACTOR); scale.tare(); set_state(CHANGING); } /** * Loop. */ void loop() { // In the STABLE state, continually check for a significant change in weight. If // there is one switch to the CHANGING state. if (state == STABLE) { delay(500); // Get the newest weight. current_weight = scale.get_units(); Serial.print("Weight: "); Serial.println(current_weight); // If the weight has changed a significant amount, change state to CHANGING. if (significant_change(current_weight, display_weight)) { suggest_weight = current_weight; set_state(CHANGING); } } if (state == CHANGING) { // Take a load of readings until we're happy it's a stable reading. for (int i = CHANGE_STEPS; i > 0; i--) { Serial.print("i=");Serial.println(i); delay(1000); // Refresh current weight. current_weight = scale.get_units(); // If there's a significant deviation from our suggestion, update the suggestion // to the current weight and start counting again. if (significant_change(current_weight, suggest_weight)) { suggest_weight = current_weight; return; } } // If there's no change from the display weight reset to STABLE. if (!significant_change(current_weight, display_weight)) { Serial.println("FALSE ALARM!"); set_state(STABLE); return; } Serial.print("SENDING TO API: "); Serial.println(suggest_weight, 1); display_weight = suggest_weight; // Do all the stuff for "actual" weight changes. set_state(SENDING); send_display_weight(display_weight); set_state(STABLE); } } /** * Helper function to calculate significant change. */ bool significant_change(float new_weight, float original_weight) { float difference; float percent_change; difference = fabs(new_weight - original_weight); if (fabs(original_weight) < THRESHOLD_DIFFERENCE) { return difference > THRESHOLD_DIFFERENCE; } percent_change = fabs(difference / original_weight); return difference > THRESHOLD_DIFFERENCE && percent_change > THRESHOLD_PERCENT; } void set_color(unsigned int red, unsigned int green, unsigned int blue) { // Deduct values from 255 as we are using a common anode LED. red = 255 - red; green = 255 - green; blue = 255 - blue; analogWrite(RRR, red); analogWrite(GGG, green); analogWrite(BBB, blue); } void set_state(int this_state) { switch (this_state) { case STABLE: set_color(0, 255, 0); state = STABLE; break; case CHANGING: set_color(255, 127, 0); state = CHANGING; break; case INITIALISING: set_color(255, 0, 0); state = INITIALISING; break; case SENDING: set_color(255, 0, 255); state = SENDING; break; } } void send_display_weight(float new_display_weight) { if (client.connect(server, 3000)) { Serial.println("Connected to server"); // Make a HTTP request String content = "{\"reading\":" + String(new_display_weight) + ",\"device_id\":99999,\"hub_id\":999999}"; client.println("POST /weights HTTP/1.1"); client.println("Host: 167.99.192.47:3000"); client.println("User-Agent: Arduino/1.0"); client.println("Connection: keep-alive"); client.println("Accept: */*"); client.println("Content-Length: " + String(content.length())); client.println("Content-Type: application/json"); client.println(); client.println(content); client.println("Connection: close"); client.println(); } }
308394ae46a65066a80336bfaa61fa8fbc6944d5
408fcfa54d3f5f3047cceed087f6e5057dc5a1bd
/src/libGBP/Media/MediaInterface.hpp
cde131cd883876e6346f6d6354c28a41c483ddeb
[ "MIT" ]
permissive
CD3/libGBP
a7010dc8a06be232916c6e4599a8f1fa4ebf5999
4fa9d00915f48c71049e714f3dd5f6cb6abca0bc
refs/heads/master
2023-06-28T04:49:46.451130
2022-09-18T16:05:54
2022-09-18T16:05:54
183,546,777
0
0
MIT
2023-06-09T20:32:02
2019-04-26T03:01:10
C++
UTF-8
C++
false
false
566
hpp
MediaInterface.hpp
#pragma once /** @file Media.hpp * @brief * @author C.D. Clark III * @date 07/27/16 */ namespace libGBP { template<typename LengthUnitType> class MediaInterface { public: virtual double getTransmission(boost::units::quantity<LengthUnitType> zi, boost::units::quantity<LengthUnitType> zf) const = 0; ///< returns percentage of power transmitted through absorber ///< between positions zi and zf. }; template<typename T> using Media_ptr = std::shared_ptr<MediaInterface<T> >; } // namespace libGBP
bf3e4e8959097b99cef7960228ce682daf8c48ba
f347eba10a7f3310b0a76cb3687f2e26aab3eb5a
/Classes/LevelLayer.h
c756e5d5f0f06e209d2878956610da821ad9859e
[]
no_license
smrutled/Tilter2dx
3e660a4168e6b05b60131b5399b25e9ca5d8d9b7
061479fe2d25d15f52ab5949a684227e41326401
refs/heads/master
2021-01-23T15:42:08.721850
2013-10-09T07:06:34
2013-10-09T07:06:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
995
h
LevelLayer.h
// // Level1LayerScene.h // Tilter2dx // // Created by Sean on 4/15/12. // Copyright __MyCompanyName__ 2012. All rights reserved. // #ifndef Tilter2dx_Level1Layer_h #define Tilter2dx_Level1Layer_h // When you import this file, you import all the cocos2d classes #include "cocos2d.h" #include "Box2D/Box2D.h" #include "GLES-Render.h" #include "EndZone.h" #include "Entity.h" class LevelLayer : public cocos2d::Layer { public: ~LevelLayer(); LevelLayer(); void initWorld(); // returns a Scene that contains the Level1Layer as the only child static cocos2d::Scene* scene(int lvl); virtual void draw(); virtual void onAcceleration(cocos2d::Acceleration* acceleration, cocos2d::Event* event); void tick(float dt); void pauseMenu(); void menuExitCallback(Object* psender); void menuPauseCallback(Object* pSender); private: b2World* world; bool paused; GLESDebugDraw *m_debugDraw; vector<Ball*> balls; vector<EndZone*>endzones; vector<Entity*>gameObjects; }; #endif
d8d00522100a6207e183bab59ea5bb0bbfb732d3
34ac3bdd061f3436c50bb23844aebd21c5a01620
/DuEngine/Init.hpp
cfd048434a9a493cbc351bddc6f226ea53ef0f2c
[ "MIT" ]
permissive
eduardo-gomes/DuEngine
08025648cac3dfc4d8f89073cecd58bdc1520de6
2dda88fd3fc9eec5dbced886ff2c4138e615f650
refs/heads/master
2022-11-29T02:52:50.886168
2020-07-27T22:49:11
2020-07-27T22:49:11
257,038,844
0
0
null
null
null
null
UTF-8
C++
false
false
388
hpp
Init.hpp
#include <string> #include <DuEngine/visibility.hpp> //Function to start and stop //Create Window with title WindowName and enter MainLoop //if fail return false bool DUENGEXT Start(const std::string &WindowName, int AUDIO = 0); //Exit mainLoop void DUENGEXT Stop(); //External init callback run after window creation and before enter mainloop void DUENGEXT SetSetup(void (*Setup)());
74f60a10ebbe3aa8a020e3384c3ab15f268b060e
e87b1b61da03291c68b890ec01e8ca6dbd7c1743
/src/main.cpp
c693a75b371724ff12a607bc02133037e674f207
[ "MIT" ]
permissive
jess-sys/nfc-mqtt
871f8f602e126f79fc9b3d319edb809568457007
de99e27dbb27493db20d76805c9dcbdb42b76abb
refs/heads/master
2023-01-01T21:37:41.310170
2020-10-24T00:30:20
2020-10-24T13:27:13
306,773,289
0
0
null
null
null
null
UTF-8
C++
false
false
695
cpp
main.cpp
#include <Arduino.h> #include <WiFi.h> #include <PubSubClient.h> #include "WiFiHandler.h" #include "MQTTHandler.h" #include "CustomTypes.h" // Create WiFI and MQTT objects WiFiClient WirelessClient; PubSubClient MQTTClient(WirelessClient); // Global variables - state, timestamp for async actions STATE_t state; long lastMessageTimestamp = 0; void setup() { state = STATE_BOOTING; setup_wifi(); setup_mqtt(MQTTClient); } void loop() { if (!MQTTClient.connected()) { reconnect(MQTTClient); } MQTTClient.loop(); long now = millis(); if (now - lastMessageTimestamp > 5000) { lastMessageTimestamp = now; MQTTClient.publish("", ""); } state = STATE_READY; }
75616648e9f0df2ac98955133c41cf6f58be1abc
92623f41efd452129cba9940556cca4fafb9e8fa
/Heap/06 - Merge K sorted linked lists_nklogk.cpp
d4d3209bc372521b799b82c7b5db566a42b7c118
[]
no_license
Vikas-Jethwani/Geeks4Geeks-Solutions
a693d4855f914cd6d2d594735524e742b9de8cb8
0118337870d6dab6bcda76aa04b9f2cf2bd149d7
refs/heads/master
2021-09-26T22:51:15.208863
2020-08-05T14:52:34
2020-08-05T14:52:34
192,599,371
0
0
null
null
null
null
UTF-8
C++
false
false
1,796
cpp
06 - Merge K sorted linked lists_nklogk.cpp
// Fall 7 times and Stand-up 8 #include <bits/stdc++.h> // StAn using namespace std; // A Linked List node struct Node { int data; Node* next; Node(int x) { data = x; next = NULL; } }; Node* mergeKLists(Node* arr[], int N); void printList(Node* node) { while (node != NULL) { printf("%d ", node->data); node = node->next; } cout<<endl; } int main() { int t; cin>>t; while(t--) { int N; cin>>N; struct Node *arr[N]; for(int j=0;j<N;j++) { int n; cin>>n; int x; cin>>x; arr[j]=new Node(x); Node *curr = arr[j]; n--; for(int i=0;i<n;i++) { cin>>x; Node *temp = new Node(x); curr->next =temp; curr=temp; } } Node *res = mergeKLists(arr,N); printList(res); } return 0; } /* arr[] is an array of pointers to heads of linked lists and N is size of arr[] */ Node* mergeKLists(Node *arr[], int N) { Node * head = NULL; Node * prev = NULL; priority_queue<pair<int, pair<Node*, int>>> pq; for (int i=0; i<N; i++) { if (arr[i] != NULL) { pq.push({-1*arr[i]->data, {arr[i], i}}); } } while (!pq.empty()) { Node * ptr = pq.top().second.first; int idx = pq.top().second.second; pq.pop(); if (prev != NULL) prev->next = ptr; prev = ptr; arr[idx] = arr[idx]->next; if (arr[idx] != NULL) pq.push({-1*arr[idx]->data, {arr[idx], idx}}); if (head == NULL) head = prev; } return head; }
56dc973844ac4df21547854f9b6e03219fea5a17
66880b4c06bf662d058b1184642e9f052779ea9e
/frameworks/compile/mclinker/lib/Script/Operator.cpp
e50a255149f309c05b6f13a4c4b227ea0a883086
[ "NCSA" ]
permissive
ParkHanbum/dex2ir
afa195163a048efa01c1cbd44c90ffd84565d053
a4cc0fe939146ca258c50a6b52b8fa09313f5eb4
refs/heads/master
2022-07-02T20:28:19.323269
2022-05-30T09:22:33
2022-05-30T09:22:33
247,693,944
51
16
null
null
null
null
UTF-8
C++
false
false
6,717
cpp
Operator.cpp
//===- Operator.cpp -------------------------------------------------------===// // // The MCLinker Project // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include <mcld/Script/Operator.h> #include <mcld/Script/NullaryOp.h> #include <mcld/Script/UnaryOp.h> #include <mcld/Script/BinaryOp.h> #include <mcld/Script/TernaryOp.h> #include <mcld/Script/Operand.h> #include <mcld/Support/raw_ostream.h> using namespace mcld; //===----------------------------------------------------------------------===// // Operator //===----------------------------------------------------------------------===// const char* Operator::OpNames[] = { "+", "-", "!", "~", "*", "/", "%", "+", "-", "<<", ">>", "<", "<=", ">", ">=", "==", "!=", "&", "^", "|", "&&", "||", "?:", "=", "+=", "-=", "*=", "/=", "&=", "|=", "<<=", ">>=", "ABSOLUTE", "ADDR", "ALIGN", "ALIGNOF", "BLOCK", "DATA_SEGMENT_ALIGN", "DATA_SEGMENT_END", "DATA_SEGMENT_RELRO_END", "DEFINED", "LENGTH", "LOADADDR", "MAX", "MIN", "NEXT", "ORIGIN", "SEGMENT_START", "SIZEOF", "SIZEOF_HEADERS", "MAXPAGESIZE", "COMMONPAGESIZE" }; Operator::Operator(Arity pArity, Type pType) : ExprToken(ExprToken::OPERATOR), m_Arity(pArity), m_Type(pType) { m_pIntOperand = IntOperand::create(0); } Operator::~Operator() { } void Operator::dump() const { mcld::outs() << OpNames[type()]; } /* Nullary operator */ template<> Operator& Operator::create<Operator::SIZEOF_HEADERS>() { static NullaryOp<Operator::SIZEOF_HEADERS> op; return op; } template<> Operator& Operator::create<Operator::MAXPAGESIZE>() { static NullaryOp<Operator::MAXPAGESIZE> op; return op; } template<> Operator& Operator::create<Operator::COMMONPAGESIZE>() { static NullaryOp<Operator::COMMONPAGESIZE> op; return op; } /* Unary operator */ template<> Operator& Operator::create<Operator::UNARY_PLUS>() { static UnaryOp<Operator::UNARY_PLUS> op; return op; } template<> Operator& Operator::create<Operator::UNARY_MINUS>() { static UnaryOp<Operator::UNARY_MINUS> op; return op; } template<> Operator& Operator::create<Operator::LOGICAL_NOT>() { static UnaryOp<Operator::LOGICAL_NOT> op; return op; } template<> Operator& Operator::create<Operator::BITWISE_NOT>() { static UnaryOp<Operator::BITWISE_NOT> op; return op; } template<> Operator& Operator::create<Operator::ABSOLUTE>() { static UnaryOp<Operator::ABSOLUTE> op; return op; } template<> Operator& Operator::create<Operator::ADDR>() { static UnaryOp<Operator::ADDR> op; return op; } template<> Operator& Operator::create<Operator::ALIGNOF>() { static UnaryOp<Operator::ALIGNOF> op; return op; } template<> Operator& Operator::create<Operator::DATA_SEGMENT_END>() { static UnaryOp<Operator::DATA_SEGMENT_END> op; return op; } template<> Operator& Operator::create<Operator::DEFINED>() { static UnaryOp<Operator::DEFINED> op; return op; } template<> Operator& Operator::create<Operator::LENGTH>() { static UnaryOp<Operator::LENGTH> op; return op; } template<> Operator& Operator::create<Operator::LOADADDR>() { static UnaryOp<Operator::LOADADDR> op; return op; } template<> Operator& Operator::create<Operator::NEXT>() { static UnaryOp<Operator::NEXT> op; return op; } template<> Operator& Operator::create<Operator::ORIGIN>() { static UnaryOp<Operator::ORIGIN> op; return op; } template<> Operator& Operator::create<Operator::SIZEOF>() { static UnaryOp<Operator::SIZEOF> op; return op; } /* Binary operator */ template<> Operator& Operator::create<Operator::MUL>() { static BinaryOp<Operator::MUL> op; return op; } template<> Operator& Operator::create<Operator::DIV>() { static BinaryOp<Operator::DIV> op; return op; } template<> Operator& Operator::create<Operator::MOD>() { static BinaryOp<Operator::MOD> op; return op; } template<> Operator& Operator::create<Operator::ADD>() { static BinaryOp<Operator::ADD> op; return op; } template<> Operator& Operator::create<Operator::SUB>() { static BinaryOp<Operator::SUB> op; return op; } template<> Operator& Operator::create<Operator::LSHIFT>() { static BinaryOp<Operator::LSHIFT> op; return op; } template<> Operator& Operator::create<Operator::RSHIFT>() { static BinaryOp<Operator::RSHIFT> op; return op; } template<> Operator& Operator::create<Operator::LT>() { static BinaryOp<Operator::LT> op; return op; } template<> Operator& Operator::create<Operator::LE>() { static BinaryOp<Operator::LE> op; return op; } template<> Operator& Operator::create<Operator::GT>() { static BinaryOp<Operator::GT> op; return op; } template<> Operator& Operator::create<Operator::GE>() { static BinaryOp<Operator::GE> op; return op; } template<> Operator& Operator::create<Operator::EQ>() { static BinaryOp<Operator::EQ> op; return op; } template<> Operator& Operator::create<Operator::NE>() { static BinaryOp<Operator::NE> op; return op; } template<> Operator& Operator::create<Operator::BITWISE_AND>() { static BinaryOp<Operator::BITWISE_AND> op; return op; } template<> Operator& Operator::create<Operator::BITWISE_XOR>() { static BinaryOp<Operator::BITWISE_XOR> op; return op; } template<> Operator& Operator::create<Operator::BITWISE_OR>() { static BinaryOp<Operator::BITWISE_OR> op; return op; } template<> Operator& Operator::create<Operator::LOGICAL_AND>() { static BinaryOp<Operator::LOGICAL_AND> op; return op; } template<> Operator& Operator::create<Operator::LOGICAL_OR>() { static BinaryOp<Operator::LOGICAL_OR> op; return op; } template<> Operator& Operator::create<Operator::ALIGN>() { static BinaryOp<Operator::ALIGN> op; return op; } template<> Operator& Operator::create<Operator::DATA_SEGMENT_RELRO_END>() { static BinaryOp<Operator::DATA_SEGMENT_RELRO_END> op; return op; } template<> Operator& Operator::create<Operator::MAX>() { static BinaryOp<Operator::MAX> op; return op; } template<> Operator& Operator::create<Operator::MIN>() { static BinaryOp<Operator::MIN> op; return op; } template<> Operator& Operator::create<Operator::SEGMENT_START>() { static BinaryOp<Operator::SEGMENT_START> op; return op; } /* Ternary operator */ template<> Operator& Operator::create<Operator::TERNARY_IF>() { static TernaryOp<Operator::TERNARY_IF> op; return op; } template<> Operator& Operator::create<Operator::DATA_SEGMENT_ALIGN>() { static TernaryOp<Operator::DATA_SEGMENT_ALIGN> op; return op; }
9f88b1a7e2fd64ff28177402dd9c37ab49cea131
a3ff6cc4a447fe058afca72c527e5737f4e3975b
/WellSimulator/WellSim/include/Typedefs.h
599aac72509c6961fa696cee45f65d46a97947aa
[ "MIT" ]
permissive
OpenSim-Technology/welldrift
120f64e31730d955281e2351e176ebe89dd080e5
57fe6c2f5a5caea18c5e29fb1b17f6f29a59a98e
refs/heads/master
2021-09-14T08:35:58.359507
2018-05-10T14:33:26
2018-05-10T14:33:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
293
h
Typedefs.h
#ifndef H_TYPEDEFS #define H_TYPEDEFS namespace WellSimulator { typedef double real_type; typedef unsigned int uint_type; //typedef WellSimulator::WellVector vector_type; typedef std::vector<double> vector_type; typedef NodeCoordinates coord_type; } #endif
f54562bddcfb52796ce349fd0f0928cc747c746b
3a313c1fb38fd79ecda5d78221cfe2892d50c7ab
/枚举/画家问题.cpp
b4db7c37cbf41a60a00c7ccb4c21ecd9b03b2d6e
[]
no_license
Zebartin/Practice_of_Programming
e87a9db33af209f12611a04e73a037f8c565f56b
91db1f9b182d9440b8b4947989b3eb5ea194a9c8
refs/heads/master
2021-01-18T21:20:32.588854
2016-05-19T15:49:23
2016-05-19T15:49:23
53,711,859
0
0
null
null
null
null
UTF-8
C++
false
false
1,389
cpp
画家问题.cpp
#include <stdio.h> #include <memory.h> using namespace std; int n,board[16][17],paint[16][17]; bool judge() { for(int i=1; i<n; ++i) for(int j=1; j<=n; ++j) paint[i+1][j]=(board[i][j]+paint[i][j]+paint[i-1][j]+paint[i][j-1]+paint[i][j+1])%2; for(int j=1; j<=n; ++j) if(board[n][j]!=(paint[n-1][j]+paint[n][j-1]+paint[n][j]+paint[n][j+1])%2) return false; return true; } int enumerate() { int c,step=-1; memset(paint,0,sizeof paint); while(1) { if(judge()) { int sum=0; for(int i=1; i<=n; ++i) for(int j=1; j<=n; ++j) sum+=paint[i][j]; if(step==-1||sum<step) step=sum; } ++paint[1][1]; c=1; while(paint[1][c]>1) { paint[1][c]=0; ++c; if(c<=n) ++paint[1][c]; else break; } if(c>n) break; } return step; } int main() { char c; scanf("%d",&n); for(int i=1; i<=n; ++i) for(int j=1; j<=n; ++j) { scanf("%c",&c); if(c=='\n') scanf("%c",&c); board[i][j]=(c=='y')?0:1; } int t=enumerate(); if(t+1) printf("%d\n",t); else printf("inf\n"); return 0; }
de352bb5569dd4ec35a97eb6a290878302412846
73236087397e024e14f9957af6955503b3466e7a
/src/http/HttpContext.h
94b6ede8ae7e0c200b3f92c1924aa6b58332521f
[ "MIT" ]
permissive
CinderoNE/TcpServer
88e886329c1659531113810ccd1f2afea7fdeac5
93c37e525105389c240b4de4f967cb66f0ead8b1
refs/heads/master
2023-07-17T07:27:34.563416
2021-08-27T09:45:11
2021-08-27T09:45:11
386,088,042
1
0
null
null
null
null
UTF-8
C++
false
false
1,610
h
HttpContext.h
#pragma once #ifndef _HTTP_CONTEXT_H_ #define _HTTP_CONTEXT_H_ #include"../Buffer.h" #include"../Timestamp.h" #include"../Timer.h" #include"HttpRequest.h" #include<memory> #include<iostream> class HttpContext { public: using ShutdownTimer = std::weak_ptr<Timer>; using SPTimer = std::shared_ptr<Timer>; enum HttpRequestParseState { kParseRequestLine, kParseHeaders, kParseBody, kParseFinish, }; HttpContext() :state_(kParseRequestLine) { } bool ParseRequest(Buffer* buf, Timestamp receiveTime); bool ParseFinish() const { return state_ == kParseFinish; } const HttpRequest& request() const { return request_; } HttpRequest& request() { return request_; } void reset() { state_ = kParseRequestLine; HttpRequest dummy; request_.swap(dummy); } void set_shutdown_timer(const SPTimer &timer) { shutdown_timer = timer; } void ResetShutdownTimer(double delay) { if (!shutdown_timer.expired()) { shutdown_timer.lock()->SetResetAt(NowAfterSeconds(delay), false); //重置关闭连接时间 } } bool ShutdownTimerExpired() const { return shutdown_timer.expired(); } private: //解析请求行 bool ParseRequestLine(const char* begin, const char* end); private: HttpRequestParseState state_; //当前解析状态 HttpRequest request_; //解析结果 ShutdownTimer shutdown_timer; //weak_ptr,避免循环引用 }; #endif // !_HTTP_CONTEXT_H_
a3e556bf931c4a3b3a572fa2aa0050e6e0097c60
2308d7c7950249e312c7ee0022e46be43d2d7112
/C_Workspace/ArrayPartition/ArrayPartition/main.cpp
04b9240fc2bf29ffc895ba4210d7322476b23b56
[]
no_license
EricWenyi/Eric_recent_work
7a46607b789477aa69fec398935b80adf2278af4
12bac03005358364df17fec3ad3b1e0302be1d91
refs/heads/master
2020-04-06T05:13:57.811363
2017-11-15T18:57:45
2017-11-15T18:57:45
44,515,624
0
0
null
null
null
null
UTF-8
C++
false
false
577
cpp
main.cpp
// // main.cpp // ArrayPartition // // Created by 邬文弈 on 2017/8/2. // Copyright © 2017年 Eric. All rights reserved. // #include <iostream> #include <vector> using namespace std; class Solution { public: int arrayPairSum(vector<int>& nums) { int res = 0; sort(nums.begin(),nums.end()); for(int i = 0; i < nums.size(); i += 2){ res += nums[i]; } return res; } }; int main(int argc, const char * argv[]) { // insert code here... std::cout << "Hello, World!\n"; return 0; }
cdec9a2a5f34af4d9bd745e047cf23558688ffdd
ac75c25f8a4092b124c19a9956f365b5bd7879ab
/HawaiianAlphabet.cpp
9cc32af58f43adeca8fd56c49619c874654eba49
[]
no_license
kaushcho/data_structures
4e58f4297d0cdfb8d5f783e3b2b989e42efc7e82
6edd0a981223e0a262bc3fd3785d7b1e903cb93a
refs/heads/master
2021-01-20T06:30:44.331617
2017-05-01T01:45:36
2017-05-01T01:45:36
89,888,021
0
0
null
null
null
null
UTF-8
C++
false
false
1,358
cpp
HawaiianAlphabet.cpp
#include <iostream> #include <string> #include <unistd.h> using namespace std; int main() { string Input; char *InputChar; bool flag = false; while(Input != "Ahuihou") { cout<<"\tEnter word (let's see if you know any Hawaiian words)"<<endl; cin>>Input; InputChar = const_cast<char*>(Input.c_str()); cout<<"\tProcessing word..."<<endl; sleep(1); while(*InputChar != '\0') { if((*InputChar == 'a') || (*InputChar == 'e') || (*InputChar == 'i') || (*InputChar == 'o') || (*InputChar == 'u') || (*InputChar == 'j') || (*InputChar == 'k') || (*InputChar == 'l') || (*InputChar == 'm') || (*InputChar == 'p') || (*InputChar == 'w') || (*InputChar == 'h') || (*InputChar == 'A') || (*InputChar == 'E') || (*InputChar == 'I') || (*InputChar == 'O') || (*InputChar == 'U') || (*InputChar == 'J') || (*InputChar == 'K') || (*InputChar == 'L') || (*InputChar == 'M') || (*InputChar == 'P') || (*InputChar == 'W') || (*InputChar == 'H')) { InputChar++; flag = true; } else { flag = false; break; } } if(flag) cout<<"\tAe"<<endl; else cout<<"\tNo"<<endl; } cout<<"\tOops! Looks like you entered the curse word. Program stopping..."<<endl; sleep(1); cout<<"\tGood Bye"<<endl; return 0; }
d7e8088b529db321941f86a928aa0482a4e20381
9f1c4be5e964218d161423f1eebcd43b548a5456
/QWinApp/QMainFrame.cpp
fb6c8b75f789aa82a79f048c31e2c92049795268
[]
no_license
Jeanhwea/WindowsProgramming
914f542b6e1555cb2118a63d1a24154bb52fe133
432545e5b5576d010fbbeb5ceacb310c73668cad
refs/heads/master
2021-01-10T16:34:34.183295
2016-02-24T12:21:25
2016-02-24T12:21:25
48,323,880
2
0
null
null
null
null
ISO-8859-7
C++
false
false
1,022
cpp
QMainFrame.cpp
#include "QMainFrame.h" QMainFrame::QMainFrame(void) { } QMainFrame::~QMainFrame(void) { } // message handler LRESULT QMainFrame::OnClose(WPARAM wParam, LPARAM lParam) { return ::DefWindowProc(m_hWnd, WM_CLOSE, wParam, lParam); } LRESULT QMainFrame::OnDestroy(WPARAM wParam, LPARAM lParam) { PostQuitMessage(0); return TRUE; } LRESULT QMainFrame::OnCreate(WPARAM wParam, LPARAM lParam) { // MessageBox(m_hWnd, TEXT("Receive WM_CREATE and OnCreate called"), TEXT("ΜαΚΎ"), 0); return TRUE; } LRESULT QMainFrame::OnPaint(WPARAM wParam, LPARAM lParam) { PAINTSTRUCT ps; HDC hdc = BeginPaint(&ps); assert(hdc); { RECT rect; //::FillRect(hdc, &ps.rcPaint, (HBRUSH) (COLOR_WINDOW)); ::GetClientRect(m_hWnd, &rect); COLORREF clrOld = ::SetTextColor(hdc, RGB(255,0,0)); TCHAR txt[] = TEXT("jeanhwea.github.io"); ::TextOut(hdc, 0, 0, txt, _tcslen(txt)); ::SetTextColor(hdc, clrOld); } EndPaint(&ps); return TRUE; }
6c98e54e268ea8ced090590539da2ed0ce3b16d6
bfc60cc7c4bf9255c0c1b82f759fee1eefa75253
/LEETCODE/Stack and Queue/Q739. Daily Temperatures.cpp
2315423850816ffc9ca5635cb6e7a995a9a81f09
[]
no_license
anushkaGurjar99/Data-Structure-and-Algorithms
aaffdd1dfaf0bdb27c070abd7f9b6b2ae540632a
c3d11d3b344b4041cd6137e857ce4d2cbef77daf
refs/heads/master
2023-01-03T22:52:22.919771
2020-10-19T12:01:48
2020-10-19T12:01:48
239,680,964
1
1
null
null
null
null
UTF-8
C++
false
false
1,346
cpp
Q739. Daily Temperatures.cpp
/* * Author : Anushka Gurjar * Date : March 2020 * flags : -std=c++14 */ #include<bits/stdc++.h> using namespace std; // Problem Statement: https://leetcode.com/problems/daily-temperatures class Solution{ public: vector<int> dailyTemperatures(vector<int>& T) { vector<int> result(T.size(), 0); if(T.size() < 1) return result; stack<int> countDays; for(int i = 0; i < T.size() - 1; i++){ if(T[i] < T[i+1]){ result[i] = 1; if(!countDays.empty()){ while(T[countDays.top()] < T[i+1]){ result[countDays.top()] = i - countDays.top() + 1; countDays.pop(); if(countDays.empty()) break; } } } else{ countDays.push(i); } } return result; } }; /* If curr+1 is greater than curr element, simple store 1 in result[i] loop{check curr+1 to top element of stack if it is having hotter temp (elements in stack are in incr order from top) if condition true then store the diff (i - top) in result[top] pop element from stack if stack empty then exit} else push curr element into stack. */
853641ee82832980ffd90afb53652274b8de216b
6d5875871454bbb65869774b6321ce5da0f1f893
/client/login.cpp
9a2607fbbb9b18dba5eaadbda9150c4bf062cf82
[]
no_license
Septerxy/BUPT_Program_Design_Practice
866ec6ff08c861f83e04a751d34deeb499ccd2d6
c231f5a97aa0a601172a78ae4d96aae7171ed69b
refs/heads/main
2023-02-12T10:31:32.944282
2021-01-09T12:37:41
2021-01-09T12:37:41
328,150,985
1
1
null
null
null
null
UTF-8
C++
false
false
5,459
cpp
login.cpp
/***************************************************************** * Copyright (c)2020, by Septer(Xiong Yu), Beijing University of Posts and Telecommunication * All rights reserved. * FileName: login.cpp * System: 2048 * SubSystem: 2048 * Author: Septer(Xiong Yu) * Date: 2020.11.1 * Version: 3.0 * Description: 定义Login类及类的成员函数 * * Last Modified: 2020.11.26, By Septer(Xiong Yu) *****************************************************************/ #include "login.h" #include "ui_login.h" #include "functions.h" #include <QDebug> #include <QLabel> #include <QLineEdit> #include <QStyleOption> #include <QPainter> #include <QStyle> #include <QString> #include <WinSock2.h> Login::Login(QWidget *parent) : QWidget(parent), ui(new Ui::Login) { ui->setupUi(this); this->setWindowTitle("Login"); ui->inputPswd->setEchoMode(QLineEdit::Password); /* 设置输入模式为密码模式 */ } Login::~Login() { delete ui; delete tcpClient; } ///////////////////////////////////////////////////////////////////// // Function: on_ready_clicked // Description: // 按下Ready键,请求登录 // Args: // 无参 // Return Values: // void // 无描述 ///////////////////////////////////////////////////////////////////// void Login::on_ready_clicked() { this->tcpClient = new QTcpSocket(this); this->tcpClient->abort(); connect(this->tcpClient,&QTcpSocket::readyRead,this,&Login::ReceiveData); connect(this->tcpClient,&QTcpSocket::disconnected,[](){qDebug()<< "Disconnected." ;}); QString ipAdd(QString::fromStdString(SERVER_IP)); //10.128.221.5 QString portd(QString::fromStdString(SERVER_PORT)); qDebug()<<"No error"; this->tcpClient->connectToHost(ipAdd,portd.toInt()); if(this->tcpClient->waitForConnected()) { qDebug()<<"System Ready!"; } else { //连接失败则尝试重连 qDebug()<<"Failed."<<this->tcpClient->errorString(); while(!this->tcpClient->waitForConnected()) { this->tcpClient->connectToHost(ipAdd,portd.toInt()); qDebug()<<"Retry connectToHost."; } qDebug()<<"System Ready!"; } char name[BUF_SIZE], pswd[BUF_SIZE]; /* 存储用户输入的用户名和密码 */ strcpy(name,this->ui->inputName->toPlainText().toLatin1().data()); strcpy(pswd,this->ui->inputPswd->text().toLatin1().data()); qDebug()<<name; qDebug()<<pswd; if((strlen(name)==0) || (strlen(name)>10) || (strlen(pswd)==0) || (strlen(pswd)==0)) { this->ui->notice->setPlaceholderText("用户名或密码不能为空"); } else { /* 刷新buffer */ ZeroMemory(buf, BUF_SIZE); /* 登录:Login 用户名 密码 */ strcat(buf,"Login "); strcat(buf,name); strcat(buf," "); strcat(buf,pswd); qDebug()<<buf; strcpy(this->name,name); /* 向服务器发送数据 */ this->tcpClient->write(QString::fromStdString(buf).toUtf8()); if (SOCKET_ERROR == retVal) { qDebug() << "send failed !"; } /* 刷新buffer */ ZeroMemory(buf, BUF_SIZE); } } ///////////////////////////////////////////////////////////////////// // Function: ReceiveData // Description: // 读取socket // Args: // 无参 // Return Values: // void // 无描述 ///////////////////////////////////////////////////////////////////// void Login::ReceiveData() { QString data = this->tcpClient->readAll(); if(QString::compare(data,"quit")==0) { qDebug() << "quit!" << endl; this->close(); } else if (QString::compare(data.mid(0,7),"success")==0) { this->ui->notice->setPlaceholderText("登录成功"); this->ui->inputPswd->clear(); this->ui->notice->clear(); this->tcpClient->disconnectFromHost(); this->tcpClient->close(); this->hide(); emit ShowGame(this->name,data.toLatin1().data()); } else { this->ui->notice->setPlaceholderText("用户名或密码错误"); this->tcpClient->disconnectFromHost(); this->tcpClient->close(); } } ///////////////////////////////////////////////////////////////////// // Function: on_back_clicked // Description: // 按下Back键,回到widget界面 // Args: // 无参 // Return Values: // void // 无描述 ///////////////////////////////////////////////////////////////////// void Login::on_back_clicked() { this->ui->inputPswd->clear(); this->ui->notice->clear(); this->hide(); emit ShowMain(); } ///////////////////////////////////////////////////////////////////// // Function: ReceiveShowLogin // Description: // 接收展示Login界面信号的槽函数 // Args: // 无参 // Return Values: // void // 无描述 ///////////////////////////////////////////////////////////////////// void Login::ReceiveShowLogin() { this->show(); } void Login::paintEvent(QPaintEvent *event) { QStyleOption opt; opt.init(this); QPainter p(this); style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this); }
51d15728f7a894a2ac686cfa161b45aacb840ca7
9df777c7033af22f9755fc50d712e783d9cabb6f
/mainwindow.cpp
2ebd13a08a0c7db9f6af96706a4f6b37a6700dbf
[]
no_license
WuMengJun/DogMonitor
090fc2ef0c9f21babb1dfb240e815f57084f5592
a45b8d838de6b3e9561be0a5440be34c5942be8c
refs/heads/master
2020-07-05T00:12:15.613419
2019-08-15T03:20:56
2019-08-15T03:20:56
202,465,638
0
0
null
null
null
null
UTF-8
C++
false
false
550
cpp
mainwindow.cpp
#include "mainwindow.h" #include "ui_mainwindow.h" void MainWindow::setMonitor(SystemDeviceMonitor *monitor) { m_monitor = monitor; handleDog(monitor->dogName()); connect(m_monitor, &SystemDeviceMonitor::dogFounded, this, &MainWindow::handleDog); } MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); } MainWindow::~MainWindow() { delete ui; } void MainWindow::handleDog(const QString &dogName) { ui->lblDogName->setText(dogName); }
5d2012bba07c334121a7ec942dcaa366a8e7d888
03b5b626962b6c62fc3215154b44bbc663a44cf6
/src/sql/sql_BEGIN.cpp
ffe248434d602b06c185841b239fd9c46200c0f4
[]
no_license
haochenprophet/iwant
8b1f9df8ee428148549253ce1c5d821ece0a4b4c
1c9bd95280216ee8cd7892a10a7355f03d77d340
refs/heads/master
2023-06-09T11:10:27.232304
2023-05-31T02:41:18
2023-05-31T02:41:18
67,756,957
17
5
null
2018-08-11T16:37:37
2016-09-09T02:08:46
C++
UTF-8
C++
false
false
175
cpp
sql_BEGIN.cpp
#include "sql_BEGIN.h" int Csql_BEGIN::my_init(void *p) { this->name = "Csql_BEGIN"; this->alias = "sql_BEGIN"; return 0; } Csql_BEGIN::Csql_BEGIN() { this->my_init(); }
8a88c4b4df3fc29c420ec01322e386d4d6b8a914
b1fdcab7f9026d8ea65cf2f3ccbb0070ebed395e
/question1042/C++/question1042.cpp
84f27ba2c1fafcefdc968ba6eaf11c3c39fa5dbc
[]
no_license
617076674/PAT-BASIC
84d46d164c885b12f1eab7bcf62f39bb71cd1b36
de490e89a2baab208f11da615e9c432ff6ff1106
refs/heads/master
2020-04-02T01:38:07.865896
2018-12-12T15:57:02
2018-12-12T15:57:02
153,866,955
4
0
null
null
null
null
UTF-8
C++
false
false
590
cpp
question1042.cpp
#include<iostream> #include<string> using namespace std; int main() { string input; getline(cin, input); int count[26]; for (int i = 0; i < 26; i++) { count[i] = 0; } for (int i = 0; i < input.length(); i++) { if (input[i] >= 'a' && input[i] <= 'z') { count[input[i] - 'a']++; }else if (input[i] >= 'A' && input[i] <= 'Z') { count[input[i] - 'A']++; } } int maxIndex = 0; for (int i = 1; i < 26; i++) { if (count[i] > count[maxIndex]) { maxIndex = i; } } char resultChar; resultChar = 'a' + maxIndex; cout << resultChar << " " << count[maxIndex]; }
f5af820f7155364949e47b4cf0fb95af29b7be42
85fe92521f2c47fb02d272edd92c5fccc3130212
/ent/src/yb/master/master_backup_service.cc
32cf2e468c8b2a81f7bf82ad4b6f456c8a6af8f5
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0", "OpenSSL" ]
permissive
ndeodhar/yugabyte-db
960de74644f7fb6d91acdb588191ceb79ddde2f7
2eff2f0690226750e5f36ecc590699a04cb017c7
refs/heads/master
2021-07-10T17:41:21.257610
2020-07-30T21:52:50
2020-07-30T21:52:50
170,206,692
0
0
Apache-2.0
2019-02-11T21:40:25
2019-02-11T21:40:25
null
UTF-8
C++
false
false
2,887
cc
master_backup_service.cc
// Copyright (c) YugaByte, 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 // // Unless required by applicable law or agreed to in writing, software distributed under the License // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express // or implied. See the License for the specific language governing permissions and limitations // under the License. #include "yb/master/master_backup_service.h" #include "yb/master/catalog_manager-internal.h" #include "yb/master/master.h" #include "yb/master/master_service_base-internal.h" namespace yb { namespace master { using rpc::RpcContext; MasterBackupServiceImpl::MasterBackupServiceImpl(Master* server) : MasterBackupServiceIf(server->metric_entity()), MasterServiceBase(server) { } void MasterBackupServiceImpl::CreateSnapshot(const CreateSnapshotRequestPB* req, CreateSnapshotResponsePB* resp, RpcContext rpc) { HandleIn(req, resp, &rpc, &enterprise::CatalogManager::CreateSnapshot); } void MasterBackupServiceImpl::ListSnapshots(const ListSnapshotsRequestPB* req, ListSnapshotsResponsePB* resp, RpcContext rpc) { HandleIn(req, resp, &rpc, &enterprise::CatalogManager::ListSnapshots); } void MasterBackupServiceImpl::ListSnapshotRestorations(const ListSnapshotRestorationsRequestPB* req, ListSnapshotRestorationsResponsePB* resp, RpcContext rpc) { HandleIn(req, resp, &rpc, &enterprise::CatalogManager::ListSnapshotRestorations); } void MasterBackupServiceImpl::RestoreSnapshot(const RestoreSnapshotRequestPB* req, RestoreSnapshotResponsePB* resp, RpcContext rpc) { HandleIn(req, resp, &rpc, &enterprise::CatalogManager::RestoreSnapshot); } void MasterBackupServiceImpl::DeleteSnapshot(const DeleteSnapshotRequestPB* req, DeleteSnapshotResponsePB* resp, RpcContext rpc) { HandleIn(req, resp, &rpc, &enterprise::CatalogManager::DeleteSnapshot); } void MasterBackupServiceImpl::ImportSnapshotMeta(const ImportSnapshotMetaRequestPB* req, ImportSnapshotMetaResponsePB* resp, RpcContext rpc) { HandleIn(req, resp, &rpc, &enterprise::CatalogManager::ImportSnapshotMeta); } } // namespace master } // namespace yb
af56c93fcfe3a969b77722e685c8c986f45c6880
77a370c418b4e1d6a573838cf71aebfc7c45c636
/managers/managerdevices.cpp
df1d905c6ea6695739babcc7e8653bd821a349fd
[]
no_license
maluginp/tsunami-optimus
8cc3a83f99d478c88da6a2874ec268adb0adbac0
a059ed6479c179692271760654e9f29ee7e2e0b5
refs/heads/master
2016-09-06T14:55:12.694739
2013-06-01T17:08:14
2013-06-01T17:08:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
69
cpp
managerdevices.cpp
#include "managerdevices.h" ManagerDevices::ManagerDevices(){ }
9fc42f28e135c373b7b31284c82e00af96e0b05f
242b22bc85b3ef88e7d541d3d62bd2a0f2ede363
/lib/generator/object/DoubleTallPlant.cpp
2c01672a4bdb7ffc206812fde1dc562ab9df4bae
[ "MIT" ]
permissive
ajunlonglive/ext-vanillagenerator
7df11a19d574f1c309ecd1c71611bf26c9afa786
56fc48ea1367e1d08b228dfa580b513fbec8ca31
refs/heads/master
2023-08-16T00:56:57.345612
2021-09-11T17:10:36
2021-09-11T17:10:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,087
cpp
DoubleTallPlant.cpp
#include <lib/objects/constants/BlockList.h> #include "DoubleTallPlant.h" bool DoubleTallPlant::Generate(ChunkManager &world, Random &random, int_fast32_t sourceX, int_fast32_t sourceY, int_fast32_t sourceZ) { int_fast32_t x, z; int_fast32_t y; bool placed = false; int_fast32_t height = world.GetMaxY(); for (int_fast32_t i = 0; i < 64; ++i) { x = sourceX + random.NextInt(8) - random.NextInt(8); z = sourceZ + random.NextInt(8) - random.NextInt(8); y = static_cast<int_fast32_t>(sourceY + random.NextInt(4) - random.NextInt(4)); MinecraftBlock block = world.GetBlockAt(x, y, z); MinecraftBlock topBlock = world.GetBlockAt(x, static_cast<int_fast32_t>(y + 1), z); if (y < height && block == AIR && topBlock == AIR && world.GetBlockAt(x, y - 1, z) == GRASS) { world.SetBlockAt(x, y, z, species_); world.SetBlockAt(x, y + 1, z, species_.MakeBlock(0x08, 0b1000)); placed = true; } } return placed; }
b6348980ee48ba4a456fa63f8a694e741c31e7f3
3312a73b934072b40e859287dea96fa43a674c27
/Solution/Hydra/WaypointManager.cpp
be217911113d9e3364b74ee7e04f0a2859aee225
[]
no_license
bullfrognz/Aegis
cfea2ffb185c728aa9f77fd877bc81daad8394e5
fd74317137f527ea8b95d1371f9c2ec02ddcd071
refs/heads/master
2020-12-24T14:35:24.287450
2014-05-25T02:41:32
2014-05-25T02:41:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,243
cpp
WaypointManager.cpp
// // Diploma of Interactive Gaming // Media Design School // Auckland // New Zealand // // (c) 2005 - 2011 Media Design School // // File Name : WaypointManager.cpp // Description : Definition of CWaypointManager // Author : Jade Abbott // Mail : jade.abbott@mediadesign.school.nz // // This include. #include "WaypointManager.h" // Local includes. #include "DeviceManager.h" #include "Utility.h" #include "VertexDiffuse.h" #include "WorldMatrix.h" // Library includes. #include <d3dx9.h> #include <cassert> CWaypointManager::CWaypointManager() : m_arrWaypoints(0) , m_uiNumWaypoints(0) { } CWaypointManager::~CWaypointManager() { Shutdown(); } /** * * Cleans up the waypoint manager, allowing it to be reinitialised. * * @author Jade Abbott * @return Void. * */ void CWaypointManager::Shutdown() { delete[] m_arrWaypoints; m_arrWaypoints = 0; m_uiNumWaypoints = 0; } /** * * This draw call is for debug purposes and is not designed for performance AT ALL! * Draws a line between each waypoint, allowing the path being followed to be viewed. * * @author Jade Abbott * @param _rDeviceManager Required to set render states, and draw the waypoints. * @return Void. * */ void CWaypointManager::Draw(CDeviceManager& _rDeviceManager) { if (m_uiNumWaypoints >= 2) { assert(m_arrWaypoints); // Create an array of vertices (this is purely to stop DirectX from throwing a psychospasm). CVertex* pVertices = new CVertex[m_uiNumWaypoints]; if (pVertices) { for (unsigned int ui = 0; ui < m_uiNumWaypoints; ++ui) { pVertices[ui].SetPos(m_arrWaypoints[ui].GetPosition()); } DWORD dwOriginalZState = _rDeviceManager.GetRenderStateValue(D3DRS_ZENABLE); if (dwOriginalZState != FALSE) _rDeviceManager.SetRenderState(D3DRS_ZENABLE, FALSE); _rDeviceManager.SetTransform(D3DTS_WORLD, &CWorldMatrix()); // CWorldMatrix is constructed as identity. D3DMATERIAL9 material; ZeroMemory(&material, sizeof(D3DMATERIAL9)); material.Emissive.r = 1.0f; _rDeviceManager.SetMaterial(&material); _rDeviceManager.SetFVF(D3DFVF_XYZ); _rDeviceManager.DrawPrimitiveUP(D3DPT_LINESTRIP, m_uiNumWaypoints - 1, pVertices, sizeof(CVertex)); if (dwOriginalZState != FALSE) _rDeviceManager.SetRenderState(D3DRS_ZENABLE, dwOriginalZState); delete[] pVertices; } } //if (m_uiNumWaypoints >= 2) //{ // assert(m_arrWaypoints); // DWORD dwOriginalZState = _rDeviceManager.GetRenderStateValue(D3DRS_ZENABLE); // if (dwOriginalZState != FALSE) // _rDeviceManager.SetRenderState(D3DRS_ZENABLE, FALSE); // CWorldMatrix matIdentity; // _rDeviceManager.SetTransform(D3DTS_WORLD, &matIdentity); // D3DMATERIAL9 material; // ZeroMemory(&material, sizeof(D3DMATERIAL9)); // material.Emissive.r = 1.0f; // _rDeviceManager.SetMaterial(&material); // _rDeviceManager.SetFVF(D3DFVF_XYZ); // _rDeviceManager.DrawPrimitiveUP(D3DPT_LINESTRIP, m_uiNumWaypoints - 1, m_arrWaypoints, sizeof(CWaypoint)); // if (dwOriginalZState != FALSE) // _rDeviceManager.SetRenderState(D3DRS_ZENABLE, dwOriginalZState); //} } /** * * Handles creation (and destruction of) waypoints. * * @author Jade Abbott * @param _keMethod The method used to create waypoints. * @param _rkVecPosition The area where the operation will be performed. * @return Void. * */ void CWaypointManager::WaypointCreation(const EWaypointCreation _keMethod, const D3DXVECTOR3& _rkVecPosition) { // Handle functions that do not involve creation of waypoints. if (_keMethod == WAYCRE_DELETE || _keMethod == WAYCRE_MOVE) { if (!m_uiNumWaypoints) return; // Find the nearest waypoint to the position provided. unsigned int uiClosest = Utility::INVALID_ID; // Element in the array that is closest. float fShortestDistanceSq = MathUtility::kMaxFloat; // Reference value. for (unsigned int ui = 0; ui < m_uiNumWaypoints; ++ui) { float fDistanceSq = D3DXVec3LengthSq(&(m_arrWaypoints[ui].GetPosition() - _rkVecPosition)); if (fDistanceSq < fShortestDistanceSq) { fShortestDistanceSq = fDistanceSq; uiClosest = ui; } } assert(uiClosest < m_uiNumWaypoints); switch (_keMethod) { case WAYCRE_DELETE: { RemoveWaypoint(uiClosest); } break; case WAYCRE_MOVE: { m_arrWaypoints[uiClosest].SetPosition(_rkVecPosition); } break; } return; } // Handle remaining functions (ones that involve creation of waypoints). CWaypoint* pWaypoint = new CWaypoint(_rkVecPosition); if (!pWaypoint) return; switch (_keMethod) { case WAYCRE_BEGIN: { AddWaypoint(*pWaypoint, 0); // Inserts a waypoint at the start. } break; case WAYCRE_END: { AddWaypoint(*pWaypoint, m_uiNumWaypoints); // Inserts a waypoint at the end. } break; case WAYCRE_INSERT: { // Handle creation method differently if there are not enough waypoints. if (m_uiNumWaypoints < 2) { WaypointCreation(WAYCRE_END, _rkVecPosition); break; } // Find the closest line to join the waypoint to. unsigned int uiClosestEnd = Utility::INVALID_ID; // Must use the end-waypoint as that is where the new waypoint will be inserted. float fReference = MathUtility::kMaxFloat; for (unsigned int ui = 0; ui < m_uiNumWaypoints - 1; ++ui) { const D3DXVECTOR3 kVecLine(m_arrWaypoints[ui + 1].GetPosition() - m_arrWaypoints[ui].GetPosition()); float fDistanceSq = D3DXVec3LengthSq(D3DXVec3Cross(&D3DXVECTOR3(), &kVecLine, &(m_arrWaypoints[ui].GetPosition() - _rkVecPosition))) / D3DXVec3LengthSq(&kVecLine); assert(fDistanceSq != MathUtility::kMaxFloat); if (fDistanceSq < fReference) { fReference = fDistanceSq; uiClosestEnd = ui + 1; } } assert(uiClosestEnd < m_uiNumWaypoints); // Covers Utility::INVALID_ID too. AddWaypoint(*pWaypoint, uiClosestEnd); } break; } delete pWaypoint; pWaypoint = 0; } /** * * Optimises waypoints and calculates measurement data. * Should be called at the end of waypoint creation. * * @author Jade Abbott * @return Void. * */ void CWaypointManager::PostCreate() { if (!m_uiNumWaypoints) return; // Remove waypoints with no distance in between (will create problems in the future anyway). // Also link waypoints (pointers to each other). for (unsigned int ui = 0; ui < m_uiNumWaypoints - 1; ++ui) { if (D3DXVec3LengthSq(&(m_arrWaypoints[ui + 1].GetPosition() - m_arrWaypoints[ui].GetPosition())) <= 0.0f) { RemoveWaypoint(ui + 1); --ui; // So the one after ui is not skipped when the loop continues. } else // Next waypoint is guaranteed to stay... { m_arrWaypoints[ui].SetNextWaypoint(&m_arrWaypoints[ui + 1]); } } // Find direction the entity must move to get from the old waypoint to the new waypoint (does not apply to first waypoint). for (unsigned int ui = 1; ui < m_uiNumWaypoints; ++ui) // Ignoring the first waypoint, as it is the spawnpoint and hence does not have a direction. { D3DXVECTOR3 vecOut; D3DXVec3Normalize(&vecOut, &(m_arrWaypoints[ui].GetPosition() - m_arrWaypoints[ui - 1].GetPosition())); m_arrWaypoints[ui].SetDirectionToThis(vecOut); } } /** * * Inserts the provided waypoint into the requested position. * If the position is occupied, the existing waypoint is shifted further down. * This function copies the provided waypoint, meaning it is up to the caller to clean up the original waypoint. * * @author Jade Abbott * @param _rkWaypoint The waypoint to insert. * @param _uiPosition The element in m_arrWaypoints where it will be inserted. Any existing element in that position will be moved +1. * @return Void. */ void CWaypointManager::AddWaypoint(const CWaypoint& _rkWaypoint, unsigned int _uiPosition) { assert(_uiPosition <= m_uiNumWaypoints); CWaypoint* pWaypoints = new CWaypoint[m_uiNumWaypoints + 1]; if (!pWaypoints) return; pWaypoints[_uiPosition] = _rkWaypoint; // Insert existing waypoints at the start. for (unsigned int ui = 0; ui < _uiPosition; ++ui) { pWaypoints[ui] = m_arrWaypoints[ui]; } // Insert existing waypoints at the end. for (unsigned int ui = _uiPosition; ui < m_uiNumWaypoints; ++ui) { pWaypoints[ui + 1] = m_arrWaypoints[ui]; } delete[] m_arrWaypoints; m_arrWaypoints = pWaypoints; ++m_uiNumWaypoints; } /** * * Deletes the waypoint requested. * * @author Jade Abbott * @param _uiWaypoint The position of the waypoint to delete (e.g. Zero deletes the first waypoint). * @return Void. * */ void CWaypointManager::RemoveWaypoint(unsigned int _uiWaypoint) { assert(_uiWaypoint < m_uiNumWaypoints); CWaypoint* pWaypoints = new CWaypoint[m_uiNumWaypoints - 1]; // Insert existing waypoints at the start. for (unsigned int ui = 0; ui < _uiWaypoint; ++ui) { if (pWaypoints) // Is only validated during insertion so that when the last element is deleted, it will remove the old array anyway. { pWaypoints[ui] = m_arrWaypoints[ui]; } } // Insert existing waypoints at the end. for (unsigned int ui = _uiWaypoint + 1; ui < m_uiNumWaypoints; ++ui) { if (pWaypoints) // Is only validated during insertion so that when the last element is deleted, it will remove the old array anyway. { pWaypoints[ui - 1] = m_arrWaypoints[ui]; } } delete[] m_arrWaypoints; m_arrWaypoints = pWaypoints; --m_uiNumWaypoints; }
a834e009aff02146e43e0f6161ecb66acedb9fd0
22ecb9fce47102845ff060eadcfa0e04391027e0
/Projekty Prata C++ CodeBlocks/5.7cw/main.cpp
7a87444e34c2c29aeda79ffeb43e82fc1c018787
[]
no_license
piterbuchcic1990/Programming-C-plus-plus
c0073d40678fda6b45f0de933ddabcd0a5458ed5
d3ecea0e72d77dbd03cf67a6c9f6176cc67e8298
refs/heads/master
2021-06-12T12:12:49.021473
2017-02-09T15:13:14
2017-02-09T15:13:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
585
cpp
main.cpp
#include <iostream> using namespace std; struct auta{ string marka; int rok_budowy; }; int main() { int ile; cout<<"Ile samopchodow chcesz skatalogowac? "; cin>>ile; auta *wsk=new auta[ile]; for(int i=0;i<ile;i++) { cout<<"samochod #"<<i+1<<":"<<endl; cout<<"prosze podac marke: "; cin>>(wsk+i)->marka; cout<<"rok produkcji: "; cin>>(wsk+i)->rok_budowy; } for(int i=0;i<ile;i++) { cout<<(wsk+i)->rok_budowy<<" "<<(wsk+i)->marka<<endl; } cout << "Hello world!" << endl; return 0; }
c44501b934a3c14ea86c21c1fb6e04137857c378
ac1c9fbc1f1019efb19d0a8f3a088e8889f1e83c
/out/release/gen/content/common/renderer.mojom-params-data.h
1220f158c652b3a1877911ceb536f0a86e8b63eb
[ "BSD-3-Clause" ]
permissive
xueqiya/chromium_src
5d20b4d3a2a0251c063a7fb9952195cda6d29e34
d4aa7a8f0e07cfaa448fcad8c12b29242a615103
refs/heads/main
2022-07-30T03:15:14.818330
2021-01-16T16:47:22
2021-01-16T16:47:22
330,115,551
1
0
null
null
null
null
UTF-8
C++
false
false
42,819
h
renderer.mojom-params-data.h
// content/common/renderer.mojom-params-data.h is auto generated by mojom_bindings_generator.py, do not edit // Copyright 2019 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 CONTENT_COMMON_RENDERER_MOJOM_PARAMS_DATA_H_ #define CONTENT_COMMON_RENDERER_MOJOM_PARAMS_DATA_H_ #include "base/logging.h" #include "base/macros.h" #include "mojo/public/cpp/bindings/lib/bindings_internal.h" #include "mojo/public/cpp/bindings/lib/buffer.h" #include "mojo/public/cpp/bindings/lib/validation_context.h" #if defined(__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunused-private-field" #elif defined(_MSC_VER) #pragma warning(push) #pragma warning(disable:4056) #pragma warning(disable:4065) #pragma warning(disable:4756) #endif namespace content { namespace mojom { namespace internal { class COMPONENT_EXPORT(MOJOM_SHARED_CONTENT_EXPORT) Renderer_CreateView_Params_Data { public: class BufferWriter { public: BufferWriter() = default; void Allocate(mojo::internal::Buffer* serialization_buffer) { serialization_buffer_ = serialization_buffer; index_ = serialization_buffer_->Allocate(sizeof(Renderer_CreateView_Params_Data)); new (data()) Renderer_CreateView_Params_Data(); } bool is_null() const { return !serialization_buffer_; } Renderer_CreateView_Params_Data* data() { DCHECK(!is_null()); return serialization_buffer_->Get<Renderer_CreateView_Params_Data>(index_); } Renderer_CreateView_Params_Data* operator->() { return data(); } private: mojo::internal::Buffer* serialization_buffer_ = nullptr; size_t index_ = 0; DISALLOW_COPY_AND_ASSIGN(BufferWriter); }; static bool Validate(const void* data, mojo::internal::ValidationContext* validation_context); mojo::internal::StructHeader header_; mojo::internal::Pointer<internal::CreateViewParams_Data> params; private: Renderer_CreateView_Params_Data(); ~Renderer_CreateView_Params_Data() = delete; }; static_assert(sizeof(Renderer_CreateView_Params_Data) == 16, "Bad sizeof(Renderer_CreateView_Params_Data)"); class COMPONENT_EXPORT(MOJOM_SHARED_CONTENT_EXPORT) Renderer_DestroyView_Params_Data { public: class BufferWriter { public: BufferWriter() = default; void Allocate(mojo::internal::Buffer* serialization_buffer) { serialization_buffer_ = serialization_buffer; index_ = serialization_buffer_->Allocate(sizeof(Renderer_DestroyView_Params_Data)); new (data()) Renderer_DestroyView_Params_Data(); } bool is_null() const { return !serialization_buffer_; } Renderer_DestroyView_Params_Data* data() { DCHECK(!is_null()); return serialization_buffer_->Get<Renderer_DestroyView_Params_Data>(index_); } Renderer_DestroyView_Params_Data* operator->() { return data(); } private: mojo::internal::Buffer* serialization_buffer_ = nullptr; size_t index_ = 0; DISALLOW_COPY_AND_ASSIGN(BufferWriter); }; static bool Validate(const void* data, mojo::internal::ValidationContext* validation_context); mojo::internal::StructHeader header_; int32_t view_id; uint8_t padfinal_[4]; private: Renderer_DestroyView_Params_Data(); ~Renderer_DestroyView_Params_Data() = delete; }; static_assert(sizeof(Renderer_DestroyView_Params_Data) == 16, "Bad sizeof(Renderer_DestroyView_Params_Data)"); class COMPONENT_EXPORT(MOJOM_SHARED_CONTENT_EXPORT) Renderer_CreateFrame_Params_Data { public: class BufferWriter { public: BufferWriter() = default; void Allocate(mojo::internal::Buffer* serialization_buffer) { serialization_buffer_ = serialization_buffer; index_ = serialization_buffer_->Allocate(sizeof(Renderer_CreateFrame_Params_Data)); new (data()) Renderer_CreateFrame_Params_Data(); } bool is_null() const { return !serialization_buffer_; } Renderer_CreateFrame_Params_Data* data() { DCHECK(!is_null()); return serialization_buffer_->Get<Renderer_CreateFrame_Params_Data>(index_); } Renderer_CreateFrame_Params_Data* operator->() { return data(); } private: mojo::internal::Buffer* serialization_buffer_ = nullptr; size_t index_ = 0; DISALLOW_COPY_AND_ASSIGN(BufferWriter); }; static bool Validate(const void* data, mojo::internal::ValidationContext* validation_context); mojo::internal::StructHeader header_; mojo::internal::Pointer<internal::CreateFrameParams_Data> params; private: Renderer_CreateFrame_Params_Data(); ~Renderer_CreateFrame_Params_Data() = delete; }; static_assert(sizeof(Renderer_CreateFrame_Params_Data) == 16, "Bad sizeof(Renderer_CreateFrame_Params_Data)"); class COMPONENT_EXPORT(MOJOM_SHARED_CONTENT_EXPORT) Renderer_CreateFrameProxy_Params_Data { public: class BufferWriter { public: BufferWriter() = default; void Allocate(mojo::internal::Buffer* serialization_buffer) { serialization_buffer_ = serialization_buffer; index_ = serialization_buffer_->Allocate(sizeof(Renderer_CreateFrameProxy_Params_Data)); new (data()) Renderer_CreateFrameProxy_Params_Data(); } bool is_null() const { return !serialization_buffer_; } Renderer_CreateFrameProxy_Params_Data* data() { DCHECK(!is_null()); return serialization_buffer_->Get<Renderer_CreateFrameProxy_Params_Data>(index_); } Renderer_CreateFrameProxy_Params_Data* operator->() { return data(); } private: mojo::internal::Buffer* serialization_buffer_ = nullptr; size_t index_ = 0; DISALLOW_COPY_AND_ASSIGN(BufferWriter); }; static bool Validate(const void* data, mojo::internal::ValidationContext* validation_context); mojo::internal::StructHeader header_; int32_t routing_id; int32_t render_view_routing_id; int32_t opener_routing_id; int32_t parent_routing_id; mojo::internal::Pointer<::content::mojom::internal::FrameReplicationState_Data> replication_state; mojo::internal::Pointer<::mojo_base::mojom::internal::UnguessableToken_Data> devtools_frame_token; private: Renderer_CreateFrameProxy_Params_Data(); ~Renderer_CreateFrameProxy_Params_Data() = delete; }; static_assert(sizeof(Renderer_CreateFrameProxy_Params_Data) == 40, "Bad sizeof(Renderer_CreateFrameProxy_Params_Data)"); class COMPONENT_EXPORT(MOJOM_SHARED_CONTENT_EXPORT) Renderer_OnNetworkConnectionChanged_Params_Data { public: class BufferWriter { public: BufferWriter() = default; void Allocate(mojo::internal::Buffer* serialization_buffer) { serialization_buffer_ = serialization_buffer; index_ = serialization_buffer_->Allocate(sizeof(Renderer_OnNetworkConnectionChanged_Params_Data)); new (data()) Renderer_OnNetworkConnectionChanged_Params_Data(); } bool is_null() const { return !serialization_buffer_; } Renderer_OnNetworkConnectionChanged_Params_Data* data() { DCHECK(!is_null()); return serialization_buffer_->Get<Renderer_OnNetworkConnectionChanged_Params_Data>(index_); } Renderer_OnNetworkConnectionChanged_Params_Data* operator->() { return data(); } private: mojo::internal::Buffer* serialization_buffer_ = nullptr; size_t index_ = 0; DISALLOW_COPY_AND_ASSIGN(BufferWriter); }; static bool Validate(const void* data, mojo::internal::ValidationContext* validation_context); mojo::internal::StructHeader header_; int32_t connection_type; uint8_t pad0_[4]; double max_bandwidth_mbps; private: Renderer_OnNetworkConnectionChanged_Params_Data(); ~Renderer_OnNetworkConnectionChanged_Params_Data() = delete; }; static_assert(sizeof(Renderer_OnNetworkConnectionChanged_Params_Data) == 24, "Bad sizeof(Renderer_OnNetworkConnectionChanged_Params_Data)"); class COMPONENT_EXPORT(MOJOM_SHARED_CONTENT_EXPORT) Renderer_OnNetworkQualityChanged_Params_Data { public: class BufferWriter { public: BufferWriter() = default; void Allocate(mojo::internal::Buffer* serialization_buffer) { serialization_buffer_ = serialization_buffer; index_ = serialization_buffer_->Allocate(sizeof(Renderer_OnNetworkQualityChanged_Params_Data)); new (data()) Renderer_OnNetworkQualityChanged_Params_Data(); } bool is_null() const { return !serialization_buffer_; } Renderer_OnNetworkQualityChanged_Params_Data* data() { DCHECK(!is_null()); return serialization_buffer_->Get<Renderer_OnNetworkQualityChanged_Params_Data>(index_); } Renderer_OnNetworkQualityChanged_Params_Data* operator->() { return data(); } private: mojo::internal::Buffer* serialization_buffer_ = nullptr; size_t index_ = 0; DISALLOW_COPY_AND_ASSIGN(BufferWriter); }; static bool Validate(const void* data, mojo::internal::ValidationContext* validation_context); mojo::internal::StructHeader header_; int32_t effective_connection_type; uint8_t pad0_[4]; mojo::internal::Pointer<::mojo_base::mojom::internal::TimeDelta_Data> http_rtt; mojo::internal::Pointer<::mojo_base::mojom::internal::TimeDelta_Data> transport_rtt; double bandwidth_kbps; private: Renderer_OnNetworkQualityChanged_Params_Data(); ~Renderer_OnNetworkQualityChanged_Params_Data() = delete; }; static_assert(sizeof(Renderer_OnNetworkQualityChanged_Params_Data) == 40, "Bad sizeof(Renderer_OnNetworkQualityChanged_Params_Data)"); class COMPONENT_EXPORT(MOJOM_SHARED_CONTENT_EXPORT) Renderer_SetWebKitSharedTimersSuspended_Params_Data { public: class BufferWriter { public: BufferWriter() = default; void Allocate(mojo::internal::Buffer* serialization_buffer) { serialization_buffer_ = serialization_buffer; index_ = serialization_buffer_->Allocate(sizeof(Renderer_SetWebKitSharedTimersSuspended_Params_Data)); new (data()) Renderer_SetWebKitSharedTimersSuspended_Params_Data(); } bool is_null() const { return !serialization_buffer_; } Renderer_SetWebKitSharedTimersSuspended_Params_Data* data() { DCHECK(!is_null()); return serialization_buffer_->Get<Renderer_SetWebKitSharedTimersSuspended_Params_Data>(index_); } Renderer_SetWebKitSharedTimersSuspended_Params_Data* operator->() { return data(); } private: mojo::internal::Buffer* serialization_buffer_ = nullptr; size_t index_ = 0; DISALLOW_COPY_AND_ASSIGN(BufferWriter); }; static bool Validate(const void* data, mojo::internal::ValidationContext* validation_context); mojo::internal::StructHeader header_; uint8_t suspend : 1; uint8_t padfinal_[7]; private: Renderer_SetWebKitSharedTimersSuspended_Params_Data(); ~Renderer_SetWebKitSharedTimersSuspended_Params_Data() = delete; }; static_assert(sizeof(Renderer_SetWebKitSharedTimersSuspended_Params_Data) == 16, "Bad sizeof(Renderer_SetWebKitSharedTimersSuspended_Params_Data)"); class COMPONENT_EXPORT(MOJOM_SHARED_CONTENT_EXPORT) Renderer_SetUserAgent_Params_Data { public: class BufferWriter { public: BufferWriter() = default; void Allocate(mojo::internal::Buffer* serialization_buffer) { serialization_buffer_ = serialization_buffer; index_ = serialization_buffer_->Allocate(sizeof(Renderer_SetUserAgent_Params_Data)); new (data()) Renderer_SetUserAgent_Params_Data(); } bool is_null() const { return !serialization_buffer_; } Renderer_SetUserAgent_Params_Data* data() { DCHECK(!is_null()); return serialization_buffer_->Get<Renderer_SetUserAgent_Params_Data>(index_); } Renderer_SetUserAgent_Params_Data* operator->() { return data(); } private: mojo::internal::Buffer* serialization_buffer_ = nullptr; size_t index_ = 0; DISALLOW_COPY_AND_ASSIGN(BufferWriter); }; static bool Validate(const void* data, mojo::internal::ValidationContext* validation_context); mojo::internal::StructHeader header_; mojo::internal::Pointer<mojo::internal::String_Data> user_agent; private: Renderer_SetUserAgent_Params_Data(); ~Renderer_SetUserAgent_Params_Data() = delete; }; static_assert(sizeof(Renderer_SetUserAgent_Params_Data) == 16, "Bad sizeof(Renderer_SetUserAgent_Params_Data)"); class COMPONENT_EXPORT(MOJOM_SHARED_CONTENT_EXPORT) Renderer_SetUserAgentMetadata_Params_Data { public: class BufferWriter { public: BufferWriter() = default; void Allocate(mojo::internal::Buffer* serialization_buffer) { serialization_buffer_ = serialization_buffer; index_ = serialization_buffer_->Allocate(sizeof(Renderer_SetUserAgentMetadata_Params_Data)); new (data()) Renderer_SetUserAgentMetadata_Params_Data(); } bool is_null() const { return !serialization_buffer_; } Renderer_SetUserAgentMetadata_Params_Data* data() { DCHECK(!is_null()); return serialization_buffer_->Get<Renderer_SetUserAgentMetadata_Params_Data>(index_); } Renderer_SetUserAgentMetadata_Params_Data* operator->() { return data(); } private: mojo::internal::Buffer* serialization_buffer_ = nullptr; size_t index_ = 0; DISALLOW_COPY_AND_ASSIGN(BufferWriter); }; static bool Validate(const void* data, mojo::internal::ValidationContext* validation_context); mojo::internal::StructHeader header_; mojo::internal::Pointer<::blink::mojom::internal::UserAgentMetadata_Data> metadata; private: Renderer_SetUserAgentMetadata_Params_Data(); ~Renderer_SetUserAgentMetadata_Params_Data() = delete; }; static_assert(sizeof(Renderer_SetUserAgentMetadata_Params_Data) == 16, "Bad sizeof(Renderer_SetUserAgentMetadata_Params_Data)"); class COMPONENT_EXPORT(MOJOM_SHARED_CONTENT_EXPORT) Renderer_UpdateScrollbarTheme_Params_Data { public: class BufferWriter { public: BufferWriter() = default; void Allocate(mojo::internal::Buffer* serialization_buffer) { serialization_buffer_ = serialization_buffer; index_ = serialization_buffer_->Allocate(sizeof(Renderer_UpdateScrollbarTheme_Params_Data)); new (data()) Renderer_UpdateScrollbarTheme_Params_Data(); } bool is_null() const { return !serialization_buffer_; } Renderer_UpdateScrollbarTheme_Params_Data* data() { DCHECK(!is_null()); return serialization_buffer_->Get<Renderer_UpdateScrollbarTheme_Params_Data>(index_); } Renderer_UpdateScrollbarTheme_Params_Data* operator->() { return data(); } private: mojo::internal::Buffer* serialization_buffer_ = nullptr; size_t index_ = 0; DISALLOW_COPY_AND_ASSIGN(BufferWriter); }; static bool Validate(const void* data, mojo::internal::ValidationContext* validation_context); mojo::internal::StructHeader header_; mojo::internal::Pointer<internal::UpdateScrollbarThemeParams_Data> params; private: Renderer_UpdateScrollbarTheme_Params_Data(); ~Renderer_UpdateScrollbarTheme_Params_Data() = delete; }; static_assert(sizeof(Renderer_UpdateScrollbarTheme_Params_Data) == 16, "Bad sizeof(Renderer_UpdateScrollbarTheme_Params_Data)"); class COMPONENT_EXPORT(MOJOM_SHARED_CONTENT_EXPORT) Renderer_OnSystemColorsChanged_Params_Data { public: class BufferWriter { public: BufferWriter() = default; void Allocate(mojo::internal::Buffer* serialization_buffer) { serialization_buffer_ = serialization_buffer; index_ = serialization_buffer_->Allocate(sizeof(Renderer_OnSystemColorsChanged_Params_Data)); new (data()) Renderer_OnSystemColorsChanged_Params_Data(); } bool is_null() const { return !serialization_buffer_; } Renderer_OnSystemColorsChanged_Params_Data* data() { DCHECK(!is_null()); return serialization_buffer_->Get<Renderer_OnSystemColorsChanged_Params_Data>(index_); } Renderer_OnSystemColorsChanged_Params_Data* operator->() { return data(); } private: mojo::internal::Buffer* serialization_buffer_ = nullptr; size_t index_ = 0; DISALLOW_COPY_AND_ASSIGN(BufferWriter); }; static bool Validate(const void* data, mojo::internal::ValidationContext* validation_context); mojo::internal::StructHeader header_; int32_t aqua_color_variant; uint8_t pad0_[4]; mojo::internal::Pointer<mojo::internal::String_Data> highlight_text_color; mojo::internal::Pointer<mojo::internal::String_Data> highlight_color; private: Renderer_OnSystemColorsChanged_Params_Data(); ~Renderer_OnSystemColorsChanged_Params_Data() = delete; }; static_assert(sizeof(Renderer_OnSystemColorsChanged_Params_Data) == 32, "Bad sizeof(Renderer_OnSystemColorsChanged_Params_Data)"); class COMPONENT_EXPORT(MOJOM_SHARED_CONTENT_EXPORT) Renderer_UpdateSystemColorInfo_Params_Data { public: class BufferWriter { public: BufferWriter() = default; void Allocate(mojo::internal::Buffer* serialization_buffer) { serialization_buffer_ = serialization_buffer; index_ = serialization_buffer_->Allocate(sizeof(Renderer_UpdateSystemColorInfo_Params_Data)); new (data()) Renderer_UpdateSystemColorInfo_Params_Data(); } bool is_null() const { return !serialization_buffer_; } Renderer_UpdateSystemColorInfo_Params_Data* data() { DCHECK(!is_null()); return serialization_buffer_->Get<Renderer_UpdateSystemColorInfo_Params_Data>(index_); } Renderer_UpdateSystemColorInfo_Params_Data* operator->() { return data(); } private: mojo::internal::Buffer* serialization_buffer_ = nullptr; size_t index_ = 0; DISALLOW_COPY_AND_ASSIGN(BufferWriter); }; static bool Validate(const void* data, mojo::internal::ValidationContext* validation_context); mojo::internal::StructHeader header_; mojo::internal::Pointer<internal::UpdateSystemColorInfoParams_Data> params; private: Renderer_UpdateSystemColorInfo_Params_Data(); ~Renderer_UpdateSystemColorInfo_Params_Data() = delete; }; static_assert(sizeof(Renderer_UpdateSystemColorInfo_Params_Data) == 16, "Bad sizeof(Renderer_UpdateSystemColorInfo_Params_Data)"); class COMPONENT_EXPORT(MOJOM_SHARED_CONTENT_EXPORT) Renderer_PurgePluginListCache_Params_Data { public: class BufferWriter { public: BufferWriter() = default; void Allocate(mojo::internal::Buffer* serialization_buffer) { serialization_buffer_ = serialization_buffer; index_ = serialization_buffer_->Allocate(sizeof(Renderer_PurgePluginListCache_Params_Data)); new (data()) Renderer_PurgePluginListCache_Params_Data(); } bool is_null() const { return !serialization_buffer_; } Renderer_PurgePluginListCache_Params_Data* data() { DCHECK(!is_null()); return serialization_buffer_->Get<Renderer_PurgePluginListCache_Params_Data>(index_); } Renderer_PurgePluginListCache_Params_Data* operator->() { return data(); } private: mojo::internal::Buffer* serialization_buffer_ = nullptr; size_t index_ = 0; DISALLOW_COPY_AND_ASSIGN(BufferWriter); }; static bool Validate(const void* data, mojo::internal::ValidationContext* validation_context); mojo::internal::StructHeader header_; uint8_t reload_pages : 1; uint8_t padfinal_[7]; private: Renderer_PurgePluginListCache_Params_Data(); ~Renderer_PurgePluginListCache_Params_Data() = delete; }; static_assert(sizeof(Renderer_PurgePluginListCache_Params_Data) == 16, "Bad sizeof(Renderer_PurgePluginListCache_Params_Data)"); class COMPONENT_EXPORT(MOJOM_SHARED_CONTENT_EXPORT) Renderer_SetProcessState_Params_Data { public: class BufferWriter { public: BufferWriter() = default; void Allocate(mojo::internal::Buffer* serialization_buffer) { serialization_buffer_ = serialization_buffer; index_ = serialization_buffer_->Allocate(sizeof(Renderer_SetProcessState_Params_Data)); new (data()) Renderer_SetProcessState_Params_Data(); } bool is_null() const { return !serialization_buffer_; } Renderer_SetProcessState_Params_Data* data() { DCHECK(!is_null()); return serialization_buffer_->Get<Renderer_SetProcessState_Params_Data>(index_); } Renderer_SetProcessState_Params_Data* operator->() { return data(); } private: mojo::internal::Buffer* serialization_buffer_ = nullptr; size_t index_ = 0; DISALLOW_COPY_AND_ASSIGN(BufferWriter); }; static bool Validate(const void* data, mojo::internal::ValidationContext* validation_context); mojo::internal::StructHeader header_; int32_t background_state; int32_t visible_state; private: Renderer_SetProcessState_Params_Data(); ~Renderer_SetProcessState_Params_Data() = delete; }; static_assert(sizeof(Renderer_SetProcessState_Params_Data) == 16, "Bad sizeof(Renderer_SetProcessState_Params_Data)"); class COMPONENT_EXPORT(MOJOM_SHARED_CONTENT_EXPORT) Renderer_SetSchedulerKeepActive_Params_Data { public: class BufferWriter { public: BufferWriter() = default; void Allocate(mojo::internal::Buffer* serialization_buffer) { serialization_buffer_ = serialization_buffer; index_ = serialization_buffer_->Allocate(sizeof(Renderer_SetSchedulerKeepActive_Params_Data)); new (data()) Renderer_SetSchedulerKeepActive_Params_Data(); } bool is_null() const { return !serialization_buffer_; } Renderer_SetSchedulerKeepActive_Params_Data* data() { DCHECK(!is_null()); return serialization_buffer_->Get<Renderer_SetSchedulerKeepActive_Params_Data>(index_); } Renderer_SetSchedulerKeepActive_Params_Data* operator->() { return data(); } private: mojo::internal::Buffer* serialization_buffer_ = nullptr; size_t index_ = 0; DISALLOW_COPY_AND_ASSIGN(BufferWriter); }; static bool Validate(const void* data, mojo::internal::ValidationContext* validation_context); mojo::internal::StructHeader header_; uint8_t keep_active : 1; uint8_t padfinal_[7]; private: Renderer_SetSchedulerKeepActive_Params_Data(); ~Renderer_SetSchedulerKeepActive_Params_Data() = delete; }; static_assert(sizeof(Renderer_SetSchedulerKeepActive_Params_Data) == 16, "Bad sizeof(Renderer_SetSchedulerKeepActive_Params_Data)"); class COMPONENT_EXPORT(MOJOM_SHARED_CONTENT_EXPORT) Renderer_SetIsLockedToSite_Params_Data { public: class BufferWriter { public: BufferWriter() = default; void Allocate(mojo::internal::Buffer* serialization_buffer) { serialization_buffer_ = serialization_buffer; index_ = serialization_buffer_->Allocate(sizeof(Renderer_SetIsLockedToSite_Params_Data)); new (data()) Renderer_SetIsLockedToSite_Params_Data(); } bool is_null() const { return !serialization_buffer_; } Renderer_SetIsLockedToSite_Params_Data* data() { DCHECK(!is_null()); return serialization_buffer_->Get<Renderer_SetIsLockedToSite_Params_Data>(index_); } Renderer_SetIsLockedToSite_Params_Data* operator->() { return data(); } private: mojo::internal::Buffer* serialization_buffer_ = nullptr; size_t index_ = 0; DISALLOW_COPY_AND_ASSIGN(BufferWriter); }; static bool Validate(const void* data, mojo::internal::ValidationContext* validation_context); mojo::internal::StructHeader header_; private: Renderer_SetIsLockedToSite_Params_Data(); ~Renderer_SetIsLockedToSite_Params_Data() = delete; }; static_assert(sizeof(Renderer_SetIsLockedToSite_Params_Data) == 8, "Bad sizeof(Renderer_SetIsLockedToSite_Params_Data)"); class COMPONENT_EXPORT(MOJOM_SHARED_CONTENT_EXPORT) Renderer_EnableV8LowMemoryMode_Params_Data { public: class BufferWriter { public: BufferWriter() = default; void Allocate(mojo::internal::Buffer* serialization_buffer) { serialization_buffer_ = serialization_buffer; index_ = serialization_buffer_->Allocate(sizeof(Renderer_EnableV8LowMemoryMode_Params_Data)); new (data()) Renderer_EnableV8LowMemoryMode_Params_Data(); } bool is_null() const { return !serialization_buffer_; } Renderer_EnableV8LowMemoryMode_Params_Data* data() { DCHECK(!is_null()); return serialization_buffer_->Get<Renderer_EnableV8LowMemoryMode_Params_Data>(index_); } Renderer_EnableV8LowMemoryMode_Params_Data* operator->() { return data(); } private: mojo::internal::Buffer* serialization_buffer_ = nullptr; size_t index_ = 0; DISALLOW_COPY_AND_ASSIGN(BufferWriter); }; static bool Validate(const void* data, mojo::internal::ValidationContext* validation_context); mojo::internal::StructHeader header_; private: Renderer_EnableV8LowMemoryMode_Params_Data(); ~Renderer_EnableV8LowMemoryMode_Params_Data() = delete; }; static_assert(sizeof(Renderer_EnableV8LowMemoryMode_Params_Data) == 8, "Bad sizeof(Renderer_EnableV8LowMemoryMode_Params_Data)"); } // namespace internal class Renderer_CreateView_ParamsDataView { public: Renderer_CreateView_ParamsDataView() {} Renderer_CreateView_ParamsDataView( internal::Renderer_CreateView_Params_Data* data, mojo::internal::SerializationContext* context) : data_(data), context_(context) {} bool is_null() const { return !data_; } inline void GetParamsDataView( CreateViewParamsDataView* output); template <typename UserType> WARN_UNUSED_RESULT bool ReadParams(UserType* output) { auto* pointer = data_->params.Get(); return mojo::internal::Deserialize<::content::mojom::CreateViewParamsDataView>( pointer, output, context_); } private: internal::Renderer_CreateView_Params_Data* data_ = nullptr; mojo::internal::SerializationContext* context_ = nullptr; }; class Renderer_DestroyView_ParamsDataView { public: Renderer_DestroyView_ParamsDataView() {} Renderer_DestroyView_ParamsDataView( internal::Renderer_DestroyView_Params_Data* data, mojo::internal::SerializationContext* context) : data_(data) {} bool is_null() const { return !data_; } int32_t view_id() const { return data_->view_id; } private: internal::Renderer_DestroyView_Params_Data* data_ = nullptr; }; class Renderer_CreateFrame_ParamsDataView { public: Renderer_CreateFrame_ParamsDataView() {} Renderer_CreateFrame_ParamsDataView( internal::Renderer_CreateFrame_Params_Data* data, mojo::internal::SerializationContext* context) : data_(data), context_(context) {} bool is_null() const { return !data_; } inline void GetParamsDataView( CreateFrameParamsDataView* output); template <typename UserType> WARN_UNUSED_RESULT bool ReadParams(UserType* output) { auto* pointer = data_->params.Get(); return mojo::internal::Deserialize<::content::mojom::CreateFrameParamsDataView>( pointer, output, context_); } private: internal::Renderer_CreateFrame_Params_Data* data_ = nullptr; mojo::internal::SerializationContext* context_ = nullptr; }; class Renderer_CreateFrameProxy_ParamsDataView { public: Renderer_CreateFrameProxy_ParamsDataView() {} Renderer_CreateFrameProxy_ParamsDataView( internal::Renderer_CreateFrameProxy_Params_Data* data, mojo::internal::SerializationContext* context) : data_(data), context_(context) {} bool is_null() const { return !data_; } int32_t routing_id() const { return data_->routing_id; } int32_t render_view_routing_id() const { return data_->render_view_routing_id; } int32_t opener_routing_id() const { return data_->opener_routing_id; } int32_t parent_routing_id() const { return data_->parent_routing_id; } inline void GetReplicationStateDataView( ::content::mojom::FrameReplicationStateDataView* output); template <typename UserType> WARN_UNUSED_RESULT bool ReadReplicationState(UserType* output) { auto* pointer = data_->replication_state.Get(); return mojo::internal::Deserialize<::content::mojom::FrameReplicationStateDataView>( pointer, output, context_); } inline void GetDevtoolsFrameTokenDataView( ::mojo_base::mojom::UnguessableTokenDataView* output); template <typename UserType> WARN_UNUSED_RESULT bool ReadDevtoolsFrameToken(UserType* output) { auto* pointer = data_->devtools_frame_token.Get(); return mojo::internal::Deserialize<::mojo_base::mojom::UnguessableTokenDataView>( pointer, output, context_); } private: internal::Renderer_CreateFrameProxy_Params_Data* data_ = nullptr; mojo::internal::SerializationContext* context_ = nullptr; }; class Renderer_OnNetworkConnectionChanged_ParamsDataView { public: Renderer_OnNetworkConnectionChanged_ParamsDataView() {} Renderer_OnNetworkConnectionChanged_ParamsDataView( internal::Renderer_OnNetworkConnectionChanged_Params_Data* data, mojo::internal::SerializationContext* context) : data_(data) {} bool is_null() const { return !data_; } template <typename UserType> WARN_UNUSED_RESULT bool ReadConnectionType(UserType* output) const { auto data_value = data_->connection_type; return mojo::internal::Deserialize<::content::mojom::NetworkConnectionType>( data_value, output); } ::content::mojom::NetworkConnectionType connection_type() const { return static_cast<::content::mojom::NetworkConnectionType>(data_->connection_type); } double max_bandwidth_mbps() const { return data_->max_bandwidth_mbps; } private: internal::Renderer_OnNetworkConnectionChanged_Params_Data* data_ = nullptr; }; class Renderer_OnNetworkQualityChanged_ParamsDataView { public: Renderer_OnNetworkQualityChanged_ParamsDataView() {} Renderer_OnNetworkQualityChanged_ParamsDataView( internal::Renderer_OnNetworkQualityChanged_Params_Data* data, mojo::internal::SerializationContext* context) : data_(data), context_(context) {} bool is_null() const { return !data_; } template <typename UserType> WARN_UNUSED_RESULT bool ReadEffectiveConnectionType(UserType* output) const { auto data_value = data_->effective_connection_type; return mojo::internal::Deserialize<::network::mojom::EffectiveConnectionType>( data_value, output); } ::network::mojom::EffectiveConnectionType effective_connection_type() const { return static_cast<::network::mojom::EffectiveConnectionType>(data_->effective_connection_type); } inline void GetHttpRttDataView( ::mojo_base::mojom::TimeDeltaDataView* output); template <typename UserType> WARN_UNUSED_RESULT bool ReadHttpRtt(UserType* output) { auto* pointer = data_->http_rtt.Get(); return mojo::internal::Deserialize<::mojo_base::mojom::TimeDeltaDataView>( pointer, output, context_); } inline void GetTransportRttDataView( ::mojo_base::mojom::TimeDeltaDataView* output); template <typename UserType> WARN_UNUSED_RESULT bool ReadTransportRtt(UserType* output) { auto* pointer = data_->transport_rtt.Get(); return mojo::internal::Deserialize<::mojo_base::mojom::TimeDeltaDataView>( pointer, output, context_); } double bandwidth_kbps() const { return data_->bandwidth_kbps; } private: internal::Renderer_OnNetworkQualityChanged_Params_Data* data_ = nullptr; mojo::internal::SerializationContext* context_ = nullptr; }; class Renderer_SetWebKitSharedTimersSuspended_ParamsDataView { public: Renderer_SetWebKitSharedTimersSuspended_ParamsDataView() {} Renderer_SetWebKitSharedTimersSuspended_ParamsDataView( internal::Renderer_SetWebKitSharedTimersSuspended_Params_Data* data, mojo::internal::SerializationContext* context) : data_(data) {} bool is_null() const { return !data_; } bool suspend() const { return data_->suspend; } private: internal::Renderer_SetWebKitSharedTimersSuspended_Params_Data* data_ = nullptr; }; class Renderer_SetUserAgent_ParamsDataView { public: Renderer_SetUserAgent_ParamsDataView() {} Renderer_SetUserAgent_ParamsDataView( internal::Renderer_SetUserAgent_Params_Data* data, mojo::internal::SerializationContext* context) : data_(data), context_(context) {} bool is_null() const { return !data_; } inline void GetUserAgentDataView( mojo::StringDataView* output); template <typename UserType> WARN_UNUSED_RESULT bool ReadUserAgent(UserType* output) { auto* pointer = data_->user_agent.Get(); return mojo::internal::Deserialize<mojo::StringDataView>( pointer, output, context_); } private: internal::Renderer_SetUserAgent_Params_Data* data_ = nullptr; mojo::internal::SerializationContext* context_ = nullptr; }; class Renderer_SetUserAgentMetadata_ParamsDataView { public: Renderer_SetUserAgentMetadata_ParamsDataView() {} Renderer_SetUserAgentMetadata_ParamsDataView( internal::Renderer_SetUserAgentMetadata_Params_Data* data, mojo::internal::SerializationContext* context) : data_(data), context_(context) {} bool is_null() const { return !data_; } inline void GetMetadataDataView( ::blink::mojom::UserAgentMetadataDataView* output); template <typename UserType> WARN_UNUSED_RESULT bool ReadMetadata(UserType* output) { auto* pointer = data_->metadata.Get(); return mojo::internal::Deserialize<::blink::mojom::UserAgentMetadataDataView>( pointer, output, context_); } private: internal::Renderer_SetUserAgentMetadata_Params_Data* data_ = nullptr; mojo::internal::SerializationContext* context_ = nullptr; }; class Renderer_UpdateScrollbarTheme_ParamsDataView { public: Renderer_UpdateScrollbarTheme_ParamsDataView() {} Renderer_UpdateScrollbarTheme_ParamsDataView( internal::Renderer_UpdateScrollbarTheme_Params_Data* data, mojo::internal::SerializationContext* context) : data_(data), context_(context) {} bool is_null() const { return !data_; } inline void GetParamsDataView( UpdateScrollbarThemeParamsDataView* output); template <typename UserType> WARN_UNUSED_RESULT bool ReadParams(UserType* output) { auto* pointer = data_->params.Get(); return mojo::internal::Deserialize<::content::mojom::UpdateScrollbarThemeParamsDataView>( pointer, output, context_); } private: internal::Renderer_UpdateScrollbarTheme_Params_Data* data_ = nullptr; mojo::internal::SerializationContext* context_ = nullptr; }; class Renderer_OnSystemColorsChanged_ParamsDataView { public: Renderer_OnSystemColorsChanged_ParamsDataView() {} Renderer_OnSystemColorsChanged_ParamsDataView( internal::Renderer_OnSystemColorsChanged_Params_Data* data, mojo::internal::SerializationContext* context) : data_(data), context_(context) {} bool is_null() const { return !data_; } int32_t aqua_color_variant() const { return data_->aqua_color_variant; } inline void GetHighlightTextColorDataView( mojo::StringDataView* output); template <typename UserType> WARN_UNUSED_RESULT bool ReadHighlightTextColor(UserType* output) { auto* pointer = data_->highlight_text_color.Get(); return mojo::internal::Deserialize<mojo::StringDataView>( pointer, output, context_); } inline void GetHighlightColorDataView( mojo::StringDataView* output); template <typename UserType> WARN_UNUSED_RESULT bool ReadHighlightColor(UserType* output) { auto* pointer = data_->highlight_color.Get(); return mojo::internal::Deserialize<mojo::StringDataView>( pointer, output, context_); } private: internal::Renderer_OnSystemColorsChanged_Params_Data* data_ = nullptr; mojo::internal::SerializationContext* context_ = nullptr; }; class Renderer_UpdateSystemColorInfo_ParamsDataView { public: Renderer_UpdateSystemColorInfo_ParamsDataView() {} Renderer_UpdateSystemColorInfo_ParamsDataView( internal::Renderer_UpdateSystemColorInfo_Params_Data* data, mojo::internal::SerializationContext* context) : data_(data), context_(context) {} bool is_null() const { return !data_; } inline void GetParamsDataView( UpdateSystemColorInfoParamsDataView* output); template <typename UserType> WARN_UNUSED_RESULT bool ReadParams(UserType* output) { auto* pointer = data_->params.Get(); return mojo::internal::Deserialize<::content::mojom::UpdateSystemColorInfoParamsDataView>( pointer, output, context_); } private: internal::Renderer_UpdateSystemColorInfo_Params_Data* data_ = nullptr; mojo::internal::SerializationContext* context_ = nullptr; }; class Renderer_PurgePluginListCache_ParamsDataView { public: Renderer_PurgePluginListCache_ParamsDataView() {} Renderer_PurgePluginListCache_ParamsDataView( internal::Renderer_PurgePluginListCache_Params_Data* data, mojo::internal::SerializationContext* context) : data_(data) {} bool is_null() const { return !data_; } bool reload_pages() const { return data_->reload_pages; } private: internal::Renderer_PurgePluginListCache_Params_Data* data_ = nullptr; }; class Renderer_SetProcessState_ParamsDataView { public: Renderer_SetProcessState_ParamsDataView() {} Renderer_SetProcessState_ParamsDataView( internal::Renderer_SetProcessState_Params_Data* data, mojo::internal::SerializationContext* context) : data_(data) {} bool is_null() const { return !data_; } template <typename UserType> WARN_UNUSED_RESULT bool ReadBackgroundState(UserType* output) const { auto data_value = data_->background_state; return mojo::internal::Deserialize<::content::mojom::RenderProcessBackgroundState>( data_value, output); } RenderProcessBackgroundState background_state() const { return static_cast<RenderProcessBackgroundState>(data_->background_state); } template <typename UserType> WARN_UNUSED_RESULT bool ReadVisibleState(UserType* output) const { auto data_value = data_->visible_state; return mojo::internal::Deserialize<::content::mojom::RenderProcessVisibleState>( data_value, output); } RenderProcessVisibleState visible_state() const { return static_cast<RenderProcessVisibleState>(data_->visible_state); } private: internal::Renderer_SetProcessState_Params_Data* data_ = nullptr; }; class Renderer_SetSchedulerKeepActive_ParamsDataView { public: Renderer_SetSchedulerKeepActive_ParamsDataView() {} Renderer_SetSchedulerKeepActive_ParamsDataView( internal::Renderer_SetSchedulerKeepActive_Params_Data* data, mojo::internal::SerializationContext* context) : data_(data) {} bool is_null() const { return !data_; } bool keep_active() const { return data_->keep_active; } private: internal::Renderer_SetSchedulerKeepActive_Params_Data* data_ = nullptr; }; class Renderer_SetIsLockedToSite_ParamsDataView { public: Renderer_SetIsLockedToSite_ParamsDataView() {} Renderer_SetIsLockedToSite_ParamsDataView( internal::Renderer_SetIsLockedToSite_Params_Data* data, mojo::internal::SerializationContext* context) : data_(data) {} bool is_null() const { return !data_; } private: internal::Renderer_SetIsLockedToSite_Params_Data* data_ = nullptr; }; class Renderer_EnableV8LowMemoryMode_ParamsDataView { public: Renderer_EnableV8LowMemoryMode_ParamsDataView() {} Renderer_EnableV8LowMemoryMode_ParamsDataView( internal::Renderer_EnableV8LowMemoryMode_Params_Data* data, mojo::internal::SerializationContext* context) : data_(data) {} bool is_null() const { return !data_; } private: internal::Renderer_EnableV8LowMemoryMode_Params_Data* data_ = nullptr; }; inline void Renderer_CreateView_ParamsDataView::GetParamsDataView( CreateViewParamsDataView* output) { auto pointer = data_->params.Get(); *output = CreateViewParamsDataView(pointer, context_); } inline void Renderer_CreateFrame_ParamsDataView::GetParamsDataView( CreateFrameParamsDataView* output) { auto pointer = data_->params.Get(); *output = CreateFrameParamsDataView(pointer, context_); } inline void Renderer_CreateFrameProxy_ParamsDataView::GetReplicationStateDataView( ::content::mojom::FrameReplicationStateDataView* output) { auto pointer = data_->replication_state.Get(); *output = ::content::mojom::FrameReplicationStateDataView(pointer, context_); } inline void Renderer_CreateFrameProxy_ParamsDataView::GetDevtoolsFrameTokenDataView( ::mojo_base::mojom::UnguessableTokenDataView* output) { auto pointer = data_->devtools_frame_token.Get(); *output = ::mojo_base::mojom::UnguessableTokenDataView(pointer, context_); } inline void Renderer_OnNetworkQualityChanged_ParamsDataView::GetHttpRttDataView( ::mojo_base::mojom::TimeDeltaDataView* output) { auto pointer = data_->http_rtt.Get(); *output = ::mojo_base::mojom::TimeDeltaDataView(pointer, context_); } inline void Renderer_OnNetworkQualityChanged_ParamsDataView::GetTransportRttDataView( ::mojo_base::mojom::TimeDeltaDataView* output) { auto pointer = data_->transport_rtt.Get(); *output = ::mojo_base::mojom::TimeDeltaDataView(pointer, context_); } inline void Renderer_SetUserAgent_ParamsDataView::GetUserAgentDataView( mojo::StringDataView* output) { auto pointer = data_->user_agent.Get(); *output = mojo::StringDataView(pointer, context_); } inline void Renderer_SetUserAgentMetadata_ParamsDataView::GetMetadataDataView( ::blink::mojom::UserAgentMetadataDataView* output) { auto pointer = data_->metadata.Get(); *output = ::blink::mojom::UserAgentMetadataDataView(pointer, context_); } inline void Renderer_UpdateScrollbarTheme_ParamsDataView::GetParamsDataView( UpdateScrollbarThemeParamsDataView* output) { auto pointer = data_->params.Get(); *output = UpdateScrollbarThemeParamsDataView(pointer, context_); } inline void Renderer_OnSystemColorsChanged_ParamsDataView::GetHighlightTextColorDataView( mojo::StringDataView* output) { auto pointer = data_->highlight_text_color.Get(); *output = mojo::StringDataView(pointer, context_); } inline void Renderer_OnSystemColorsChanged_ParamsDataView::GetHighlightColorDataView( mojo::StringDataView* output) { auto pointer = data_->highlight_color.Get(); *output = mojo::StringDataView(pointer, context_); } inline void Renderer_UpdateSystemColorInfo_ParamsDataView::GetParamsDataView( UpdateSystemColorInfoParamsDataView* output) { auto pointer = data_->params.Get(); *output = UpdateSystemColorInfoParamsDataView(pointer, context_); } } // namespace mojom } // namespace content #if defined(__clang__) #pragma clang diagnostic pop #elif defined(_MSC_VER) #pragma warning(pop) #endif #endif // CONTENT_COMMON_RENDERER_MOJOM_PARAMS_DATA_H_
ddda67a8db6478b8b5b1ef077e6ba20fe6eefae0
09ecd4326593aa43126461ebbd45de265536ea5e
/LongestValidParenthesis.cpp
d50875ea5fe2d96272dab3abb6bbd370d5876be3
[]
no_license
Shivamj075/CodeForBetter
ad47e0875144191124becce672ca579091b77254
0815c50bec4b2a354b2adeeb9f928727cf5eedb4
refs/heads/master
2020-09-15T18:34:22.990538
2020-04-15T06:45:53
2020-04-15T06:45:53
223,528,241
0
0
null
null
null
null
UTF-8
C++
false
false
922
cpp
LongestValidParenthesis.cpp
int Solution::longestValidParentheses(string A) { //stack<char> s; vector<int> dp(A.size(),0); dp.clear(); int i=0,n=A.size(); while(i<n){ if(A[i]=='('){ i++; continue; } else if(i>0 and A[i]==')'){ if(A[i-1]=='('){ if(i-2>=0) dp[i] = dp[i-2]+2; else dp[i]+=(dp[i-1]+2); } else if(dp[i-1]!=0){ int indx = i-dp[i-1]-1; if(indx>=0){ if(A[indx]=='('){ if(indx-1>=0) dp[i]+=dp[i-1]+dp[indx-1]+2; else dp[i] = dp[i-1]+2; } } } } i++; } int ans=0; for(int i=0;i<n;i++){ ans =max(ans,dp[i]); // cout<<dp[i]<<" "; } // cout<<endl; return ans; }
0ae5a43373bd1fdf19fe3298a084d7da3ecbdc2f
ca98fb67c9b92aea3ee818b53de7a2bb11b9f38f
/Assignments/one_Zhang Zhexian_1001214/distrib/curve.cpp
01544c03a3bc54af128433bafaa38cf736030dcc
[]
no_license
zhexxian/SUTD-Graphics-and-Visualisation
878c0b5b1794d323c5f6e4827385393407d4db14
b7cd889dcee453712a6e38a1e2ac7659e1d08567
refs/heads/master
2021-06-13T16:24:24.018846
2017-05-05T07:50:07
2017-05-05T07:50:07
90,349,964
1
0
null
null
null
null
UTF-8
C++
false
false
11,727
cpp
curve.cpp
#include "curve.h" #include "extra.h" #ifdef WIN32 #include <windows.h> #endif #include <GL/gl.h> using namespace std; namespace { // Approximately equal to. We don't want to use == because of // precision issues with floating point. inline bool approx( const Vector3f& lhs, const Vector3f& rhs ) { const float eps = 1e-8f; return ( lhs - rhs ).absSquared() < eps; } } Curve evalBezier( const vector< Vector3f >& P, unsigned steps, unsigned dimension ) { // Check if( P.size() < 4 || P.size() % 3 != 1 ) { cerr << "evalBezier must be called with 3n+1 control points." << endl; exit( 0 ); } if( steps == 0 ) { cerr << "steps must not be zero" << endl; } // TODO: // You should implement this function so that it returns a Curve // (e.g., a vector< CurvePoint >). The variable "steps" tells you // the number of points to generate on each piece of the spline. // At least, that's how the sample solution is implemented and how // the SWP files are written. But you are free to interpret this // variable however you want, so long as you can control the // "resolution" of the discretized spline curve with it. // Make sure that this function computes all the appropriate // Vector3fs for each CurvePoint: V,T,N,B. // [NBT] should be unit and orthogonal. // Also note that you may assume that all Bezier curves that you // receive have G1 continuity. Otherwise, the TNB will not be // be defined at points where this does not hold. cerr << "\t>>> evalBezier has been called with the following input:" << endl; cerr << "\t>>> Control points (type vector< Vector3f >): "<< endl; for( unsigned i = 0; i < P.size(); ++i ) { cerr << "\t>>> " << P[i] << endl; } cerr << "\t>>> Steps (type steps): " << steps << endl; unsigned numberOfPieces = (P.size()-1)/3; cout << "\t>>>numberOfPieces: " << numberOfPieces << endl; Curve resultCurve = Curve(); for( unsigned i = 0; i < numberOfPieces; i++ ) { Vector3f p1 = P[i*3]; Vector3f p2 = P[i*3+1]; Vector3f p3 = P[i*3+2]; Vector3f p4 = P[i*3+3]; Vector3f previousB = Vector3f(P[0][0],P[0][1]+1,1); for( unsigned j = 0; j <= steps; j++ ){ float t = (float)j/(float)steps; /* //x, y, z float vx = p1[0]*pow(1-t, 3) + p2[0]*(3*t*pow(1-t, 2)) + p3[0]*3*pow(t, 2)*(1-t) + p4[0]*pow(t, 3); float vy = p1[1]*pow(1-t, 3) + p2[1]*(3*t*pow(1-t, 2)) + p3[1]*3*pow(t, 2)*(1-t) + p4[1]*pow(t, 3); float vz = p1[2]*pow(1-t, 3) + p2[2]*(3*t*pow(1-t, 2)) + p3[2]*3*pow(t, 2)*(1-t) + p4[2]*pow(t, 3); */ //x', y', z' float dvx = -3*p1[0]*pow(1-t, 2) + p2[0]*(9*pow(t, 2)-12*t+3) + p3[0]*3*t*(2-3*t) + 3*p4[0]*pow(t, 2); float dvy = -3*p1[1]*pow(1-t, 2) + p2[1]*(9*pow(t, 2)-12*t+3) + p3[1]*3*t*(2-3*t) + 3*p4[1]*pow(t, 2); float dvz = -3*p1[2]*pow(1-t, 2) + p2[2]*(9*pow(t, 2)-12*t+3) + p3[2]*3*t*(2-3*t) + 3*p4[2]*pow(t, 2); Matrix4f bezierControlPoints = Matrix4f( p1[0],p2[0],p3[0],p4[0], p1[1],p2[1],p3[1],p4[1], p1[2],p2[2],p3[2],p4[2], 0, 0, 0, 0 ); Matrix4f bBezier = Matrix4f( 1, -3, 3, -1, 0, 3, -6, 3, 0, 0, 3, -3, 0, 0, 0, 1 ); Matrix4f power = Matrix4f( pow(t,0), 0, 0, 0, pow(t,1), 0, 0, 0, pow(t,2), 0, 0, 0, pow(t,3), 0, 0, 0 ); Matrix4f combinedPower = bBezier*power; Matrix4f resultV = bezierControlPoints * combinedPower; /* float vx = Vector4f().dot(bezierControlPoints.getRow(0),combinedPower.getCol(0)); float vy = Vector4f().dot(bezierControlPoints.getRow(1),combinedPower.getCol(0)); float vz = Vector4f().dot(bezierControlPoints.getRow(2),combinedPower.getCol(0)); */ float vx = resultV.getCol(0)[0]; float vy = resultV.getCol(0)[1]; float vz = resultV.getCol(0)[2]; Vector3f newV; Vector3f newT; Vector3f newN; if(dimension == 2) { newV = Vector3f(vx, vy, 0); newT = Vector3f(dvx, dvy, 0).normalized(); newN = Vector3f().cross(previousB,newT).normalized(); newN[2]=0; } else{ newV = Vector3f(vx, vy, vz); newT = Vector3f(dvx, dvy, dvz).normalized(); newN = Vector3f().cross(previousB,newT).normalized(); } Vector3f newB = Vector3f().cross(newT,newN).normalized(); previousB = newB; CurvePoint newCurvePoint = CurvePoint(); newCurvePoint.V=newV; newCurvePoint.T=newT; newCurvePoint.N=newN; newCurvePoint.B=newB; if(dimension == 2) { newCurvePoint.V[2] = 0; newCurvePoint.T[2] = 0; newCurvePoint.N[2] = 0; } resultCurve.push_back(newCurvePoint); } } return resultCurve; } Curve evalBspline( const vector< Vector3f >& P, unsigned steps, unsigned dimension ) { // Check if( P.size() < 4 ) { cerr << "evalBspline must be called with 4 or more control points." << endl; exit( 0 ); } // TODO: // It is suggested that you implement this function by changing // basis from B-spline to Bezier. That way, you can just call // your evalBezier function. cerr << "\t>>> evalBSpline has been called with the following input:" << endl; cerr << "\t>>> Control points (type vector< Vector3f >): "<< endl; for( unsigned i = 0; i < P.size(); ++i ) { cerr << "\t>>> " << P[i] << endl; } cerr << "\t>>> Steps (type steps): " << steps << endl; Matrix4f bBezier = Matrix4f( 1, -3, 3, -1, 0, 3, -6, 3, 0, 0, 3, -3, 0, 0, 0, 1 ); float bBSplieCoefficient = float(1)/float(6); Matrix4f bBSpline = Matrix4f( 1*bBSplieCoefficient, -3*bBSplieCoefficient, 3*bBSplieCoefficient, -1*bBSplieCoefficient, 4*bBSplieCoefficient, 0*bBSplieCoefficient, -6*bBSplieCoefficient, 3*bBSplieCoefficient, 1*bBSplieCoefficient, 3*bBSplieCoefficient, 3*bBSplieCoefficient, -3*bBSplieCoefficient, 0*bBSplieCoefficient, 0*bBSplieCoefficient, 0*bBSplieCoefficient, 1*bBSplieCoefficient ); Matrix4f changeBasis = bBSpline*bBezier.inverse(); vector<Vector3f> newControlPoints; if(P.size() == 4){ Matrix4f bSplineControlPoints = Matrix4f( P[0][0],P[1][0],P[2][0],P[3][0], P[0][1],P[1][1],P[2][1],P[3][1], P[0][2],P[1][2],P[2][2],P[3][2], 0, 0, 0, 0 ); Matrix4f bezierControlPoints = bSplineControlPoints*changeBasis; Vector3f newP1 = Vector3f(bezierControlPoints.getCol(0)[0], bezierControlPoints.getCol(0)[1], bezierControlPoints.getCol(0)[2]); Vector3f newP2 = Vector3f(bezierControlPoints.getCol(1)[0], bezierControlPoints.getCol(1)[1], bezierControlPoints.getCol(1)[2]); Vector3f newP3 = Vector3f(bezierControlPoints.getCol(2)[0], bezierControlPoints.getCol(2)[1], bezierControlPoints.getCol(2)[2]); Vector3f newP4 = Vector3f(bezierControlPoints.getCol(3)[0], bezierControlPoints.getCol(3)[1], bezierControlPoints.getCol(3)[2]); newControlPoints.push_back(newP1); newControlPoints.push_back(newP2); newControlPoints.push_back(newP3); newControlPoints.push_back(newP4); } else { for(int i=0; i<=P.size()-3; i++){ Matrix4f bSplineControlPoints = Matrix4f( P[i][0],P[i+1][0],P[i+2][0],P[i+3][0], P[i][1],P[i+1][1],P[i+2][1],P[i+3][1], P[i][2],P[i+1][2],P[i+2][2],P[i+3][2], 0, 0, 0, 0 ); Matrix4f bezierControlPoints = bSplineControlPoints*changeBasis; Vector3f newP1 = Vector3f(bezierControlPoints.getCol(0)[0], bezierControlPoints.getCol(0)[1], bezierControlPoints.getCol(0)[2]); Vector3f newP2 = Vector3f(bezierControlPoints.getCol(1)[0], bezierControlPoints.getCol(1)[1], bezierControlPoints.getCol(1)[2]); Vector3f newP3 = Vector3f(bezierControlPoints.getCol(2)[0], bezierControlPoints.getCol(2)[1], bezierControlPoints.getCol(2)[2]); Vector3f newP4 = Vector3f(bezierControlPoints.getCol(3)[0], bezierControlPoints.getCol(3)[1], bezierControlPoints.getCol(3)[2]); if(i==0){ newControlPoints.push_back(newP1); newControlPoints.push_back(newP2); newControlPoints.push_back(newP3); newControlPoints.push_back(newP4); } else if(i==(P.size()-3)){ newControlPoints.push_back(newP2); newControlPoints.push_back(newP3); newControlPoints.push_back(newP3); } else { newControlPoints.push_back(newP2); newControlPoints.push_back(newP3); newControlPoints.push_back(newP4); } } } int extraControlPointCount = (P.size()-1)%3; if(extraControlPointCount!=0){ int j = P.size()-4; Matrix4f bSplineControlPoints = Matrix4f( P[j][0],P[j+1][0],P[j+2][0],P[j+3][0], P[j][1],P[j+1][1],P[j+2][1],P[j+3][1], P[j][2],P[j+1][2],P[j+2][2],P[j+3][2], 0, 0, 0, 0 ); Matrix4f bezierControlPoints = bSplineControlPoints*changeBasis; Vector3f newP1 = Vector3f(bezierControlPoints.getCol(0)[0], bezierControlPoints.getCol(0)[1], bezierControlPoints.getCol(0)[2]); Vector3f newP2 = Vector3f(bezierControlPoints.getCol(1)[0], bezierControlPoints.getCol(1)[1], bezierControlPoints.getCol(1)[2]); Vector3f newP3 = Vector3f(bezierControlPoints.getCol(2)[0], bezierControlPoints.getCol(2)[1], bezierControlPoints.getCol(2)[2]); Vector3f newP4 = Vector3f(bezierControlPoints.getCol(3)[0], bezierControlPoints.getCol(3)[1], bezierControlPoints.getCol(3)[2]); newControlPoints.push_back(newP2); newControlPoints.push_back(newP3); newControlPoints.push_back(newP3); } cout << "number of control points for b spline: " << newControlPoints.size() << endl; Curve bsplineCurve = evalBezier(newControlPoints, steps, dimension); return bsplineCurve; } Curve evalCircle( float radius, unsigned steps ) { // This is a sample function on how to properly initialize a Curve // (which is a vector< CurvePoint >). // Preallocate a curve with steps+1 CurvePoints Curve R( steps+1 ); // Fill it in counterclockwise for( unsigned i = 0; i <= steps; ++i ) { // step from 0 to 2pi float t = 2.0f * M_PI * float( i ) / steps; // Initialize position // We're pivoting counterclockwise around the y-axis R[i].V = radius * Vector3f( cos(t), sin(t), 0 ); // Tangent vector is first derivative R[i].T = Vector3f( -sin(t), cos(t), 0 ); // Normal vector is second derivative R[i].N = Vector3f( -cos(t), -sin(t), 0 ); // Finally, binormal is facing up. R[i].B = Vector3f( 0, 0, 1 ); } return R; } void drawCurve( const Curve& curve, float framesize ) { // Save current state of OpenGL glPushAttrib( GL_ALL_ATTRIB_BITS ); // Setup for line drawing glDisable( GL_LIGHTING ); glColor4f( 1, 1, 1, 1 ); glLineWidth( 1 ); // Draw curve glBegin( GL_LINE_STRIP ); for( unsigned i = 0; i < curve.size(); ++i ) { glVertex( curve[ i ].V ); } glEnd(); glLineWidth( 1 ); // Draw coordinate frames if framesize nonzero if( framesize != 0.0f ) { Matrix4f M; for( unsigned i = 0; i < curve.size(); ++i ) { M.setCol( 0, Vector4f( curve[i].N, 0 ) ); M.setCol( 1, Vector4f( curve[i].B, 0 ) ); M.setCol( 2, Vector4f( curve[i].T, 0 ) ); M.setCol( 3, Vector4f( curve[i].V, 1 ) ); glPushMatrix(); glMultMatrixf( M ); glScaled( framesize, framesize, framesize ); glBegin( GL_LINES ); glColor3f( 1, 0, 0 ); glVertex3d( 0, 0, 0 ); glVertex3d( 1, 0, 0 ); glColor3f( 0, 1, 0 ); glVertex3d( 0, 0, 0 ); glVertex3d( 0, 1, 0 ); glColor3f( 0, 0, 1 ); glVertex3d( 0, 0, 0 ); glVertex3d( 0, 0, 1 ); glEnd(); glPopMatrix(); } } // Pop state glPopAttrib(); }
0270cd21bf761920248c2fb523c5dccb117ec132
cdc21f32788027d73ebb21ea8e374ebdf9eb9926
/MonteCarlo/source/SEMonteCarloDescriptor.cpp
a467f6a4c9648c089ce366fc293b1c102d4193e8
[ "BSD-3-Clause" ]
permissive
1A-OneAngstrom/SAMSON-Developer-Tutorials
5d98d076cc349a2b66c27a2d6f0d6169a98b4fa8
a7261bf25591f68cc2e0471078680d68e0d89c93
refs/heads/master
2022-05-28T02:59:56.441474
2022-05-23T12:45:50
2022-05-23T12:45:50
159,808,214
4
0
null
null
null
null
UTF-8
C++
false
false
1,011
cpp
SEMonteCarloDescriptor.cpp
/// \headerfile SEMonteCarloStateUpdaterDescriptor.hpp "SEMonteCarloStateUpdaterDescriptor.hpp" #include "SEMonteCarloStateUpdaterDescriptor.hpp" /// \headerfile SEMonteCarloStateUpdaterPropertiesDescriptor.hpp "SEMonteCarloStateUpdaterPropertiesDescriptor.hpp" #include "SEMonteCarloStateUpdaterPropertiesDescriptor.hpp" // Describe the SAMSON Extension // SAMSON Extension generator pro tip: modify the information below if necessary // (for example when a new class is added, when the version number changes, to describe categories more precisely, etc.) SB_ELEMENT_DESCRIPTION("This SAMSON Extension implements a Monte Carlo state updater."); SB_ELEMENT_DOCUMENTATION("Resource/Documentation/doc.html"); SB_ELEMENT_VERSION_NUMBER("2.0.0"); SB_ELEMENT_CLASSES_BEGIN; SB_ELEMENT_CLASS(SEMonteCarloStateUpdater); SB_ELEMENT_CLASS(SEMonteCarloStateUpdaterProperties); SB_ELEMENT_CLASSES_END; SB_ELEMENT_CATEGORIES_BEGIN; SB_ELEMENT_CATEGORY(SBClass::Category::General); SB_ELEMENT_CATEGORIES_END;
b4f5ceb2814fdb813eeab36dc072fdf554524d49
850a39e68e715ec5b3033c5da5938bbc9b5981bf
/drgraf4_0/Allheads/Inter_c1.h
04f250a1d1fc060d0b79ad5848571476b794e5af
[]
no_license
15831944/drProjects
8cb03af6d7dda961395615a0a717c9036ae1ce0f
98e55111900d6a6c99376a1c816c0a9582c51581
refs/heads/master
2022-04-13T12:26:31.576952
2020-01-04T04:18:17
2020-01-04T04:18:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,914
h
Inter_c1.h
// Inter_C1.h : header file // #ifndef _INTER_C1_H #define _INTER_C1_H //#undef AFX_DATA //#define AFX_DATA AFX_EXT_DATA #include "drcurve.h" //#include "DListMgr.h" #include "Def_Type.h" #include "Def_CuPS.h" ///////////////////////////////////////////////////////////////////////////// // CMouse view ////////////////////////////////////////////////////// class CInter_C1 : public CObject { public: CInter_C1(); ////////////////////////////////////// DECLARE_SERIAL(CInter_C1) ////////////////////////////////////// // Attributes // Operations public: // Implementation public: ////////////////////////////////////////////////////////// virtual int Interpolate(); ////////////////////////////////////////////////////////// Info virtual void SetnData_S(int d){m_nData_S = d;}; // GIVEN: # of Data virtual void SetnOrder_S(int d){m_nOrder_S = d;}; // k virtual void SetbClosed_S(BOOL bC){m_bClosed_S = bC;}; // virtual void SetCurveType(CTyp); ////////////////////////////////////////////////////////// virtual void SetnDegree_S(int d){m_nDegree_S = d;}; // k -1 virtual void SetnSeg_DT_S(int d){m_nSeg_DT_S = d;}; // L virtual void SetnCon_BS_S(int d){m_nCon_BS_S = d;}; virtual void SetnCon_BZ_S(int d){m_nCon_BZ_S = d;}; ////////////////////////////////////////////////////////////// Memory virtual pWORLD GetpData(){return m_pData;}; virtual pWORLD GetpCon_BS_S(){return m_pCon_BS_S;}; virtual pWORLD GetpCon_BZ_S(){return m_pCon_BZ_S;}; virtual void SetpData(pWORLD m){m_pData = m;}; virtual void SetpCon_BS_S(pWORLD m){m_pCon_BS_S = m;}; virtual void SetpCon_BZ_S(pWORLD m){m_pCon_BZ_S = m;}; ////////////////////////////////////////////////////////// protected: //////////////////////////////////////////////////////////////// SetUp int FillUpSpline(pWORLD Con,pWORLD Data,int L,BOOL bClosed); int FillUpBezier(pWORLD Con,pWORLD Data,int L,BOOL bClosed); ///////////////////////////////////////////////////////////////// protected: // Attributes protected: /////////////////////////////////////////// Curve // CDrCurve* m_pDrCurve; // CDListMgr* m_pINodeList; // CURVETYPE m_CurveType; BOOL m_bClosed_S; int m_nOrder_S; // k int m_nDegree_S; // k -1 int m_nData_S; // GIVEN: # of Data int m_nSeg_DT_S; // L int m_nSeg_BS_S; // n int m_nCon_BS_S; // n + 1: #of Spline Controls int m_nCon_BZ_S; // (k-1) * L + 1 int m_nSegs; //////////////////////////////////////////////// Memory int m_MemErr; pWORLD m_pData; pWORLD m_pCon_BS_S; pWORLD m_pCon_BZ_S; //Operations public: ~CInter_C1(); virtual void Serialize(CArchive& ar); /* // Generated message map functions //{{AFX_MSG(CInter_C1) //}}AFX_MSG DECLARE_MESSAGE_MAP() */ }; //#undef AFX_DATA //#define AFX_DATA ////////////////////////////////////// #endif
41affa9c52398064087013f7fd359edcf7e30b0d
128f421b78732df43558ba1b3e34837060667fbc
/HyperchainCore/plugins/common/noui.h
41eebbf494c372d680d46dccd03bbc9f30f94566
[ "MIT" ]
permissive
paralism/Paralism
8cdaa4e5ddc97ffce77dd5bfb74874a2d420cc44
4dcffd7389193a18064c26dd285c19ccf5a44531
refs/heads/master
2023-07-19T13:14:58.480765
2023-07-11T01:18:09
2023-07-11T01:18:09
159,655,918
1
0
null
2020-08-09T09:36:44
2018-11-29T11:31:13
C++
UTF-8
C++
false
false
3,584
h
noui.h
/*Copyright 2016-2022 hyperchain.net (Hyperchain) Distributed under the MIT software license, see the accompanying file COPYING or?https://opensource.org/licenses/MIT. 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. */ // Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2011 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file license.txt or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_NOUI_H #define BITCOIN_NOUI_H #include <string> #include <boost/function.hpp> #include "wallet.h" typedef void wxWindow; #define wxYES 0x00000002 #define wxOK 0x00000004 #define wxNO 0x00000008 #define wxYES_NO (wxYES|wxNO) #define wxCANCEL 0x00000010 #define wxAPPLY 0x00000020 #define wxCLOSE 0x00000040 #define wxOK_DEFAULT 0x00000000 #define wxYES_DEFAULT 0x00000000 #define wxNO_DEFAULT 0x00000080 #define wxCANCEL_DEFAULT 0x80000000 #define wxICON_EXCLAMATION 0x00000100 #define wxICON_HAND 0x00000200 #define wxICON_WARNING wxICON_EXCLAMATION #define wxICON_ERROR wxICON_HAND #define wxICON_QUESTION 0x00000400 #define wxICON_INFORMATION 0x00000800 #define wxICON_STOP wxICON_HAND #define wxICON_ASTERISK wxICON_INFORMATION #define wxICON_MASK (0x00000100|0x00000200|0x00000400|0x00000800) #define wxFORWARD 0x00001000 #define wxBACKWARD 0x00002000 #define wxRESET 0x00004000 #define wxHELP 0x00008000 #define wxMORE 0x00010000 #define wxSETUP 0x00020000 inline int MyMessageBox(const std::string& message, const std::string& caption="Message", int style=wxOK, wxWindow* parent=NULL, int x=-1, int y=-1) { //printf("%s: %s\n", caption.c_str(), message.c_str()); fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str()); return 4; } #define wxMessageBox MyMessageBox inline int ThreadSafeMessageBox(const std::string& message, const std::string& caption, int style=wxOK, wxWindow* parent=NULL, int x=-1, int y=-1) { return MyMessageBox(message, caption, style, parent, x, y); } inline bool ThreadSafeAskFee(int64 nFeeRequired, const std::string& strCaption, wxWindow* parent) { return true; } inline void CalledSetStatusBar(const std::string& strText, int nField) { } inline void UIThreadCall(boost::function0<void> fn) { } inline void MainFrameRepaint() { } #endif
118eb31b3863b43773690cc9e06244061b354f08
9dc808a1bee9f599deccec477b72c0354fb9d858
/Bridge/v2drawing.hpp
6ea191905a6e0b72322644b8e8eb8bee2bc7471e
[]
no_license
juliazhuzhu/cplusplus_study
739705c084a6a22f752b5e0be6c20971c271b0d8
a173a27eed79f903e20c9604969cbaf11d7725df
refs/heads/master
2021-05-12T11:33:16.119304
2020-02-13T04:02:53
2020-02-13T04:02:53
117,391,081
0
0
null
null
null
null
UTF-8
C++
false
false
417
hpp
v2drawing.hpp
#ifndef __V2DRAWING__HPP #define __V2DRAWING__HPP #include <stdio.h> #include "drawing.hpp" class V2Drawing: public Drawing{ public: virtual void drawLine(double x1, double y1, double x2, double y2){ printf("printf v2 drawLine %f %f %f %f\n", x1, y1,x2, y2 ); } virtual void drawCircle(double x, double y, double r){ printf("printf v2 drawCircle %f %f %f \n", x, y, r); } }; #endif
46272e67b2a7c8bad6008b572648009f311637fb
0aa7354541daa958f1d88a31cde06fbba66a2260
/include/km/RsaKey.hpp
8584786df704b21c75797a9f081923b99692442f
[ "MIT" ]
permissive
Wicker25/keymaker-alpha
e7749ff1316dfde189e51c5a67480c75ff97e5c1
ffe5310ed1304654ff4ae3a7025fff34b629588b
refs/heads/master
2021-06-17T13:10:08.997204
2017-06-08T17:53:18
2017-06-08T17:53:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
930
hpp
RsaKey.hpp
/*! * Title ---- km/RsaKey.hpp * Author --- Giacomo Trudu aka `Wicker25` - wicker25[at]gmail[dot]com * * Copyright (C) 2017 by Giacomo Trudu. * All rights reserved. * * This file is part of KeyMaker software. */ #ifndef __KM_RSA_KEY_HPP__ #define __KM_RSA_KEY_HPP__ #include <km.hpp> #include <km/Exception.hpp> #include <memory> #include <boost/filesystem.hpp> #include <openssl/bn.h> #include <openssl/rsa.h> #include <openssl/pem.h> #include <openssl/err.h> namespace km { // Begin main namespace class Encrypter; /*! * The RSA key. */ class RsaKey { friend class Encrypter; public: /*! * Constructor method. */ RsaKey(); /*! * Destructor method. */ virtual ~RsaKey(); protected: /*! * The RSA data. */ std::shared_ptr<RSA> mRsa; }; } // End of main namespace #endif /* __KM_RSA_KEY_HPP__ */ // Include inline methods #include <km/RsaKey-inl.hpp>
daa0da828de446f3102b68174fa21599333d69c1
fc3bca040602fd6cb1f208369d0dcb59ac261584
/R3_Source/Hazards/MagnitudeModels/RUserDefinedMagnitudeModel.h
89dbe99fd13dc601d1018cd0d48cc1a8eda663c0
[]
no_license
rccosta1/R3
907cc42fe541609f3e76c9e23d6d6aed0362642b
082542ee1d0d1461814a44c3b4ebc55a73918616
refs/heads/main
2023-06-03T17:56:54.415562
2021-06-29T20:33:22
2021-06-29T20:33:22
381,476,642
0
0
null
null
null
null
UTF-8
C++
false
false
1,065
h
RUserDefinedMagnitudeModel.h
#ifndef RUserDefinedMagnitudeModel_H #define RUserDefinedMagnitudeModel_H #include "RModel.h" #include "RContinuousRandomVariable.h" #include "RParameter.h" #include "RResponse.h" #include "RTime.h" class RUserDefinedMagnitudeModel : public RModel { Q_OBJECT Q_PROPERTY(QString XPoints READ getXPoints WRITE setXPoints) Q_PROPERTY(QString PDFPoints READ getPDFPoints WRITE setPDFPoints) Q_PROPERTY(QObject *Occurrence READ getOccurrence WRITE setOccurrence) public: RUserDefinedMagnitudeModel(QObject *parent, QString name); ~RUserDefinedMagnitudeModel(); QString getXPoints(); void setXPoints(QString value); QString getPDFPoints(); void setPDFPoints(QString value); QObject *getOccurrence() const; void setOccurrence(QObject *value); int evaluateModel(); private: QPointer<RContinuousRandomVariable> theStandardNormalRandomVariable; QString theXPoints; QString thePDFPoints; RResponse *theMagnitude; QPointer<RParameter> theOccurrence; }; #endif
bf43dc795c4a453ea3863eaca499f91e75e51291
604838d93fc6c9a7df1db59856126da74abc2853
/Game/Entities/CastLight.cpp
d0adeda938d90ae58012ce541b5c61e6127eab1c
[]
no_license
mbellman/dungeon-crawler
b7a4f78e418eda7dd47b0a549d05e213b0fc059a
b73afbffdad6d300f70ce37b61c18735f8932c38
refs/heads/master
2020-04-28T07:11:30.848512
2019-05-11T16:17:59
2019-05-11T16:17:59
175,083,562
0
0
null
null
null
null
UTF-8
C++
false
false
1,279
cpp
CastLight.cpp
#include <Entities/CastLight.h> #include <GameUtils.h> #include <SoftEngine.h> #include <Helpers.h> /** * CastLight * --------- */ CastLight::CastLight(const Soft::Vec3& spawnPosition, const Soft::Vec3& direction, const Soft::Camera* camera, Soft::TextureBuffer* texture) { this->spawnPosition = spawnPosition; this->direction = direction; this->camera = camera; this->texture = texture; } void CastLight::initialize() { Soft::Light* light = new Soft::Light(); light->setColor({ 0, 0, 255 }); light->position = spawnPosition + direction * 100.0f; light->power = 4.0f; light->range = GameUtils::CAST_LIGHT_RANGE; light->power.tweenTo(0.0f, GameUtils::CAST_LIGHT_LIFETIME, Soft::Ease::quadInOut); light->onUpdate = [=](int dt) { light->position += direction * (float)dt * getSpeedFactor(); }; Soft::Billboard* orb = new Soft::Billboard(15.0f, 15.0f); orb->lockTo(light); orb->rotate({ camera->pitch, 0.0f, 0.0f }); orb->alwaysFaceToward(camera); orb->setTexture(texture); orb->hasLighting = false; orb->onUpdate = [=](int dt) { orb->scale(0.99f); }; add(light); add(orb); } float CastLight::getSpeedFactor() { float speedFactor = 1.0f - ((float)getAge() / GameUtils::CAST_LIGHT_COOLDOWN_TIME); return FAST_CLAMP(speedFactor, 0.0f, 1.0f); }
38c22b9e14a26b2bace3ed969142d115288d13ff
454e2f3fa0c95cc8d63ad393cba26f8724724eb4
/lab-05-abstract-factory-pattern-applefactory/floor.cpp
5553ad090d79bd96f6869c660eaf30a8aeb59a2e
[]
no_license
gojiman23/stuff
fade970d47e00d0c7a5fd24a36cb8a8a980aba79
3f45360f8a703aab7c980343a22c2c4a043b28df
refs/heads/master
2021-05-03T14:20:41.660994
2018-02-22T03:19:28
2018-02-22T03:19:28
120,523,330
0
0
null
null
null
null
UTF-8
C++
false
false
165
cpp
floor.cpp
#include "floor.h" #include <math.h> Floor::Floor(Base *data){ this -> data = data -> evaluate(); } double Floor::evaluate(){ return floor(this -> data); }
dc18178e59cd5bc86dce1d84d852cc869e771904
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/httpd/gumtree/httpd_new_log_5350.cpp
f0328db82e255132c54b0fe0a66041945ab20a3d
[]
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
169
cpp
httpd_new_log_5350.cpp
ap_log_error(APLOG_MARK, APLOG_CRIT, rv, ap_server_conf, APLOGNO(00279) "apr_thread_join: unable to join the start " "thread");
fe5ca1e8d895d667a7e95bdf30f5520bb410b53b
1d6175b89c9b7a1de6d97ac83fc31660c18aa880
/src/MoveBehavior.cpp
f12577d9e9c90361bbf34c04bd2e78767a8aa4e1
[]
no_license
rayy1218/game_study
53af641a30499c94271e8d6eb3f6d7dde82e4320
3fa089ae09f17fcf798d8dd65f4a080a93862ed0
refs/heads/main
2023-06-24T08:15:36.407615
2021-07-19T14:41:46
2021-07-19T14:41:46
362,331,876
0
0
null
null
null
null
UTF-8
C++
false
false
292
cpp
MoveBehavior.cpp
#include "main.hpp" MoveBehavior::MoveBehavior(Entity *self): self(self) {} MoveBehavior::~MoveBehavior() {} bool MoveBehavior::doMoveEntity(int to_x, int to_y) { if (!game.map->canWalk(to_x, to_y)) {return false;} self->setX(to_x); self->setY(to_y); return true; }
331bb2919b7d2e99c9eca12d450ba4097ed58526
ea89e225c1946d3f6aae6995d003449d52f88c56
/manage_grade.h
72aa876c0b93a55fe25f65c0aebbca29c5701c96
[]
no_license
hooray1998/SC_System
cc698c08f1f5c2d393ac41dbb490ef2d35cd73d4
c09bb210634b37ee162fb99923a55ad0676332ab
refs/heads/master
2020-05-30T12:16:27.706483
2019-06-01T12:28:00
2019-06-01T12:28:00
189,729,186
4
0
null
null
null
null
UTF-8
C++
false
false
515
h
manage_grade.h
#ifndef SCOREMANAGE_H #define SCOREMANAGE_H #include <QWidget> namespace Ui { class manage_grade; } class manage_grade : public QWidget { Q_OBJECT public: explicit manage_grade(QWidget *parent = 0); ~manage_grade(); private slots: void on_insertButton_clicked(); void on_deleteButton_clicked(); void on_updateButton_clicked(); void on_seeAllButton_clicked(); void on_backButton_clicked(); private: Ui::manage_grade *ui; QStringList headers; }; #endif // SCOREMANAGE_H
f6ec25ff3971de61fe750cf716b74306f7fe1e8e
04b1803adb6653ecb7cb827c4f4aa616afacf629
/remoting/base/grpc_support/grpc_authenticated_executor.h
d28d92ebab04cbca260885af512d3bdbf0eecb56
[ "BSD-3-Clause" ]
permissive
Samsung/Castanets
240d9338e097b75b3f669604315b06f7cf129d64
4896f732fc747dfdcfcbac3d442f2d2d42df264a
refs/heads/castanets_76_dev
2023-08-31T09:01:04.744346
2021-07-30T04:56:25
2021-08-11T05:45:21
125,484,161
58
49
BSD-3-Clause
2022-10-16T19:31:26
2018-03-16T08:07:37
null
UTF-8
C++
false
false
1,536
h
grpc_authenticated_executor.h
// Copyright 2019 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 REMOTING_BASE_GRPC_SUPPORT_GRPC_AUTHENTICATED_EXECUTOR_H_ #define REMOTING_BASE_GRPC_SUPPORT_GRPC_AUTHENTICATED_EXECUTOR_H_ #include <memory> #include <string> #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "remoting/base/grpc_support/grpc_executor.h" #include "remoting/base/oauth_token_getter.h" namespace remoting { class GrpcAsyncRequest; // Class to execute gRPC request with OAuth authentication. class GrpcAuthenticatedExecutor final : public GrpcExecutor { public: // |token_getter| must outlive |this|. explicit GrpcAuthenticatedExecutor(OAuthTokenGetter* token_getter); ~GrpcAuthenticatedExecutor() override; // GrpcExecutor implementation. void ExecuteRpc(std::unique_ptr<GrpcAsyncRequest> request) override; void CancelPendingRequests() override; private: friend class GrpcAuthenticatedExecutorTest; void ExecuteRpcWithFetchedOAuthToken( std::unique_ptr<GrpcAsyncRequest> request, OAuthTokenGetter::Status status, const std::string& user_email, const std::string& access_token); OAuthTokenGetter* token_getter_; std::unique_ptr<GrpcExecutor> executor_; base::WeakPtrFactory<GrpcAuthenticatedExecutor> weak_factory_; DISALLOW_COPY_AND_ASSIGN(GrpcAuthenticatedExecutor); }; } // namespace remoting #endif // REMOTING_BASE_GRPC_SUPPORT_GRPC_AUTHENTICATED_EXECUTOR_H_
728ab0a327a2f31d47fa27b362cb376035539a15
dcfa321edefa923991b81f6157031d435fad7180
/Engine/Graphics-Engine/src/shape.h
6a7b27ea965e689761a2c8bab6f805d03fcf22e4
[]
no_license
Hernibyte/-Graphics-Engine
01254c447c11fa7351f451ec3b8701036531a494
e9d3c7a78b4c58e9921e578b10126b381dca197e
refs/heads/master
2023-02-04T04:17:00.436459
2020-12-18T12:05:50
2020-12-18T12:05:50
289,265,680
0
0
null
null
null
null
UTF-8
C++
false
false
269
h
shape.h
#ifndef SHAPE_H #define SHAPE_H #include "Includes.h" #include "Entity2D.h" class GENGINE_API Shape : public Entity2D{ private: int type; int tam; public: Shape(Renderer* _render, int _type); ~Shape(); void setBufferData(); }; #endif // !SHAPE_H
6a68a6ff50cab31eb6e69fc5422aa46950992b8c
6196a0b5b3555630f00263ff5ebb2ae6254ea9f7
/FEBioMech/FESymmetryPlane.cpp
3a85137ebdb2a4333bf814d6749d7c537c8244ce
[ "MIT" ]
permissive
davidlni/FEBio
433f8125dea040232ffaa1fd9657f26781b04a53
c94a1c30e0bae5f285c0daae40a7e893e63cff3c
refs/heads/master
2023-08-15T22:19:19.334333
2021-09-28T21:18:26
2021-09-28T21:18:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,868
cpp
FESymmetryPlane.cpp
/*This file is part of the FEBio source code and is licensed under the MIT license listed below. See Copyright-FEBio.txt for details. Copyright (c) 2020 University of Utah, The Trustees of Columbia University in the City of New York, and others. 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.*/ #include "stdafx.h" #include "FESymmetryPlane.h" #include "FECore/FECoreKernel.h" #include <FECore/FEModel.h> //----------------------------------------------------------------------------- FESymmetryPlane::FESymmetryPlane(FEModel* pfem) : FELinearConstraintSet(pfem), m_surf(pfem) { m_binit = false; } //----------------------------------------------------------------------------- //! Initializes data structures. void FESymmetryPlane::Activate() { // don't forget to call base class FELinearConstraintSet::Activate(); FEModel& fem = *FELinearConstraintSet::GetFEModel(); DOFS& dofs = fem.GetDOFS(); // evaluate the nodal normals int N = m_surf.Nodes(); vec3d nu(0,0,0); // loop over all elements to get average surface normal // (assumes that surface elements are all on same plane) for (int i=0; i<m_surf.Elements(); ++i) { FESurfaceElement& el = m_surf.Element(i); nu += m_surf.SurfaceNormal(el, 0); } nu.unit(); // create linear constraints // for a symmetry plane the constraint on (ux, uy, uz) is // nx*ux + ny*uy + nz*uz = 0 for (int i=0; i<N; ++i) { FENode node = m_surf.Node(i); if ((node.HasFlags(FENode::EXCLUDE) == false) && (node.m_rid == -1)) { FEAugLagLinearConstraint* pLC = new FEAugLagLinearConstraint; for (int j=0; j<3; ++j) { FEAugLagLinearConstraint::DOF dof; dof.node = node.GetID() - 1; // zero-based switch (j) { case 0: dof.bc = dofs.GetDOF("x"); dof.val = nu.x; break; case 1: dof.bc = dofs.GetDOF("y"); dof.val = nu.y; break; case 2: dof.bc = dofs.GetDOF("z"); dof.val = nu.z; break; default: break; } pLC->m_dof.push_back(dof); } // add the linear constraint to the system add(pLC); } } // for nodes that belong to shells, also constraint the shell bottom face displacements for (int i=0; i<N; ++i) { FENode node = m_surf.Node(i); if ((node.HasFlags(FENode::EXCLUDE) == false) && (node.HasFlags(FENode::SHELL)) && (node.m_rid == -1)) { FEAugLagLinearConstraint* pLC = new FEAugLagLinearConstraint; for (int j=0; j<3; ++j) { FEAugLagLinearConstraint::DOF dof; dof.node = node.GetID() - 1; // zero-based switch (j) { case 0: dof.bc = dofs.GetDOF("sx"); dof.val = nu.x; break; case 1: dof.bc = dofs.GetDOF("sy"); dof.val = nu.y; break; case 2: dof.bc = dofs.GetDOF("sz"); dof.val = nu.z; break; default: break; } pLC->m_dof.push_back(dof); } // add the linear constraint to the system add(pLC); } } } //----------------------------------------------------------------------------- bool FESymmetryPlane::Init() { // initialize surface return m_surf.Init(); }
83d01a999182f0e85b340e59b96f3e567e16b63c
1ec567d20c92990ea731f4eb3aaf5443dcae62bd
/src/entity.h
03f7970fdc4364c215e0b66518c7df8ca267dee2
[]
no_license
CollazzoD/2d-Shoot-Em-Up
7ff330464d59e9b94abe6ad23135e28da9870144
3515a287fb9d9439b9fffa600122317516ae8ee2
refs/heads/master
2022-09-14T07:12:04.295696
2020-05-25T17:24:02
2020-05-25T17:24:02
263,990,531
0
0
null
null
null
null
UTF-8
C++
false
false
900
h
entity.h
#ifndef ENTITY_H #define ENTITY_H #include "texture.h" #include <SDL2/SDL.h> #include <string> class Entity { public: Entity(Texture *texture, const float &x = 0, const float &y = 0, const int &speed = 0, const float &dx = 0, const float &dy = 0, const int &health = 1); ~Entity(); Entity(const Entity &source) = default; Entity &operator=(const Entity &source) = default; Entity(Entity &&source); Entity &operator=(Entity &&source); int GetWidth() const { return width; } int GetHeight() const { return height; } float GetX() const { return x; } float GetY() const { return y; } int GetHealth() const { return health; } Texture *GetTexture() const { return texture; } virtual void Update() = 0; void Hit(); protected: float x; float y; float dx; float dy; int speed; int health; int width; int height; Texture *texture; }; #endif
07f7bd8bd036920fefb4ffa0d259dd2bf86eb77b
aadf84f38c77e9b0894492301499e8f95e1ef114
/string/string_out_write_triangle.cpp
6b479dcaa9b3c5f2c3c3858a82905e1cf4011185
[]
no_license
linrakesh/cpp
9310c8d28d488c42b93c0552c08d1ec2f4c25c4f
d176d9c42502d315d931600cabaf01dad54d9d7a
refs/heads/master
2020-03-11T23:42:27.246353
2019-12-18T14:45:48
2019-12-18T14:45:48
130,329,672
0
2
null
null
null
null
UTF-8
C++
false
false
257
cpp
string_out_write_triangle.cpp
#include<iostream> using namespace std; int main() { char string[100]="ProgrammingFun"; int i; for(i=1;i<=14;i++) { cout.write(string,i); cout<<endl; } for(i;i>=1;i--) { cout.write(string,i); cout<<endl; } return 0; }
f2840d7379102f7aba3653e94d0a9df929849361
31d24ee6b69aa2905ce5de5077443eb0de41b575
/LinkedList/SINGLY LINKED LIST/Practice Problems/Segregate Even & Odd Nodes In Linked List.CPP
8c34cb31c3c9deeff15bff8b7c95307627525060
[]
no_license
imthearchitjain/Data-Structures
07149c12258babdc5527399d366014db875304a0
1ae0820d4988117f453a306ffc5081cff2c82201
refs/heads/master
2020-07-22T08:20:48.260575
2019-11-14T06:18:53
2019-11-14T06:18:53
207,129,127
0
0
null
null
null
null
UTF-8
C++
false
false
1,852
cpp
Segregate Even & Odd Nodes In Linked List.CPP
#include <iostream> using namespace std; class node { public: int data; node *next; }; int length(node *head) { int length = 0; while (head != nullptr) { length++; head = head->next; } return length; } void printlist(node *head) { while (head != nullptr) { cout << head->data << " -> "; head = head->next; if (head == nullptr) cout << "NULL"; } cout << endl; } void push(node **head, int data) { node *newnode = new node(); newnode->data = data; newnode->next = *head; *head = newnode; } void reverse(node **head) { node *prev = nullptr; node *curr = *head; node *next = nullptr; while (curr != nullptr) { next = curr->next; curr->next = prev; prev = curr; curr = next; } *head = prev; } void segregate_even_odd(node **head) { node *even = new node(); node *odd = new node(); even = nullptr; odd = nullptr; node *temp = *head; while (temp != nullptr) { if(temp->data%2==0) push(&even, temp->data); else push(&odd, temp->data); temp = temp->next; } reverse(&even); reverse(&odd); temp = even; while (temp->next != nullptr) temp = temp->next; temp->next = odd; *head = even; } int main() { int n; cout << "\nEnter the no of nodes in list :"; cin >> n; int data; node *head1 = new node(); head1 = nullptr; cout << "\nEnter list :\n"; for (int i = 0; i < n; i++) { cout << "\nEnter the data :"; cin >> data; push(&head1, data); } reverse(&head1); segregate_even_odd(&head1); printlist(head1); }
907a4baa127ea6a20d54623028b26c1536698dd9
dc46998ed26cdcb6346226866d26192f80f3c763
/CodeSpinalCordArduino/sketch_SnakeSpinalCord07/sketch_SnakeSpinalCord07.ino
c40358b47d0cd0f8de8fcf5153431494c0bdb46c
[ "Apache-2.0" ]
permissive
manukautech/XMSnakeRobot
309a68368aa69e982d78fafe7927ae75b0209415
894c0febdcca47c9c2dfb425312bc2915ff33587
refs/heads/master
2021-10-21T16:17:18.876058
2019-03-05T05:31:00
2019-03-05T05:31:00
112,919,380
0
0
null
null
null
null
UTF-8
C++
false
false
6,557
ino
sketch_SnakeSpinalCord07.ino
//SnakeSpinalCord - Version07 is for the 3 Arduino Nanos in this snake robot //Variations for 'A', 'B' and 'C' are coded in. //Edit the const byte THIS_BOARD line below before uploading. #include <Servo.h> const byte THIS_BOARD = 'B'; String thisBoardId; // assigned to "A", "B" or "C" below //20171105 JPC started John Calder 05 Nov 2017 //20171201 JPC bring in servo testing and lose SoftwareSerial //20171208 JPC edit and update comments //20171221 JPC begin testing on completed snake robot hardware //20171223 JPC remove i2c code and attempt SoftwareSerial again //20171228 JPC remove all SoftwareSerial - use Serial for monitoring one Nano at a time //Robot snake has a smartphone or smartwatch "brain" in its head //The "body" has 10 segments. Each segment has 2 servos - //- one for vertical and one for horizontal movement. // //The "brain" sends serial commands by bluetooth. // The "spinal cord" is an HC-05 unit receiving these commands // and passing them on from its "TX" pin to the "RX" pins of 3 x Arduino Nano. // each Nano receives all signals but can identify the first byte 'A' 'B' or 'C' and act on its signals only // 20171228 serial line for sending back responses by Bluetooth. // - can be plugged in to one of 'A', 'B' or 'C' //Serial command protocol by example: // "A3-050"-- "Attention Nano 'A' - set servo number '3' to 'minus 50 degrees from mid position". // "C0+000" -- "Attention Nano 'C' - set servo number '0' to 'mid' position". // Config for servos - fine adjustment to "mid" position Servo servosArray[8]; // Default Config for servos - fine adjustment to "mid" position - see configA(), configB(), configC() below int offset[8] = {0,0,0,0,0,0,0,0}; // Config for servos - direction switch values 1 or -1 int dir[8] = {1,1,1,1,1,1,1,1}; bool isAssembling = false; int servoNumber = 0; //0 to 7 - on pins 4 to 11 int posNeg = 1; int signalPlace = 0; int val = 0; bool isStartupTesting = true; int nServos = 6; //default for A and B. C has 8 see config below int pinOffset = 4; //default for Arduino Nano use pins 4,5,6 ... //The code in configA(), configB(), config(C) needs custom editing for each snake robot //with values from test results. Example values here are from snake "Harald" as at Dec 2017. void configA() { thisBoardId = "A"; offset[0] = 5; dir[0] = 1; offset[1] = -5; dir[1] = -1; //20171226 JPC change from 15 to 0 offset[2] = 0; dir[2] = -1; offset[3] = -15; dir[3] = 1; offset[4] = 0; dir[4] = 1; offset[5] = 25; dir[5] = -1; offset[6] = 0; dir[6] = 1; offset[7] = 0; dir[7] = 1; } void configB() { thisBoardId = "B"; offset[0] = -5; dir[0] = 1; offset[1] = 0; dir[1] = 1; offset[2] = -10; dir[2] = 1; offset[3] = 25; dir[3] = -1; offset[4] = -5; dir[4] = 1; //20171228 JPC adjustment needed for a new servo change from 0 to 15 offset[5] = 15; dir[5] = 1; offset[6] = 0; dir[6] = 1; offset[7] = 0; dir[7] = 1; } void configC() { thisBoardId = "C"; nServos = 8; offset[0] = -30; dir[0] = 1; offset[1] = -20; dir[1] = 1; offset[2] = 20; dir[2] = -1; offset[3] = 30; dir[3] = -1; //20171226 JPC correction 20 to -20 offset[4] = -20; dir[4] = 1; offset[5] = -25; dir[5] = 1; offset[6] = 0; dir[6] = 1; offset[7] = 17; dir[7] = -1; } void setup() { // HC-05 is reconfigured from 9600 to 38400 Serial.begin(38400); //TESTING Serial.println("Startup " + thisBoardId); //config by THIS_BOARD if(THIS_BOARD == 'A') { configA(); }else if(THIS_BOARD == 'B') { configB(); }else if(THIS_BOARD == 'C') { configC(); } else { Serial.println("ERROR: Board Id"); //TODO solder on coloured LEDS for cases like this } //Setup 6 or 8 servos for(int i = 0; i < nServos; i++) { servosArray[i].attach(i+pinOffset); } // Apply offset settings for(int i = 0; i < nServos; i++) { servosArray[i].write((offset[i] * dir[i]) + 90); } // test on startup by flashing light pattern. pinMode(LED_BUILTIN, OUTPUT); } void loop() { //On Startup or Reset run a 3-flash-then-pause indication twice if(isStartupTesting) { flashTest(); flashTest(); isStartupTesting = false; } // Keep reading from HC-05 while (Serial.available()) { byte c = Serial.read(); //TESTING - echo back for monitor //Serial.write(c); //listen for 'A', 'B', or 'C' if(c == THIS_BOARD) { isAssembling = true; signalPlace = 0; val = 0; Serial.println("recv " + thisBoardId ); }else if(c == 'x') { //character for time delay delay(500); }else if(isAssembling) { signalPlace += 1; assemble(c); } } } void assemble(byte c) { if(signalPlace == 1) { servoNumber = c - 48; }else if(signalPlace == 2) { if(c == '-') { posNeg = -1; }else if(c == '+') { posNeg = 1; }else { //error condition, stop processing and if debugging send a signal isAssembling = false; Serial.print("ERROR: ch2 = "); Serial.println((char)c); return; } }else if(signalPlace == 3) { val = (c - 48) * 100; }else if(signalPlace == 4) { val = val + (c - 48) * 10; }else if(signalPlace == 5) { val = val + (c - 48); process(); //return to listening mode isAssembling = false; } } void process() { val = val * posNeg; if(val > 50)val = 50; if(val < -50) val = -50; Serial.print("value: "); Serial.println(val); //20171226 JPC apply offset and direction corrections for each servo (includes bug-fix) val = (val + offset[servoNumber]) * dir[servoNumber]; val = val + 90 ; servosArray[servoNumber].write(val); } void flashTest() { //call this on startup - gives 3 flashes then a pause digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level) delay(300); // wait for a second digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW delay(300); digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level) delay(300); // wait for a second digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW delay(300); digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level) delay(300); // wait for a second digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW delay(3000); }
717c04e4979da060b6ec34d5253f52cad18a6cfd
169418265b359c848a82d58949337331d0116622
/ydcx.h
6ee9a023df3a567397f5f71b87faab95d9b8ffcd
[]
no_license
Subenle/BUPT-ydcx
da59fea98818eccf6582a5684d43ab933bd421bc
04bfe5b32e8acc5e2d408e7c62c7818ee0ca8c55
refs/heads/master
2021-06-05T02:50:39.531483
2016-10-12T12:44:56
2016-10-12T12:44:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
527
h
ydcx.h
#ifndef YDCX_H #define YDCX_H #include <QDialog> class QNetworkReply; class QLabel; class QLineEdit; class QPushButton; class QNetworkAccessManager; namespace Ui { class ydcx; } class ydcx : public QDialog { Q_OBJECT public: explicit ydcx(QWidget *parent = 0); ~ydcx(); protected slots: void bt_search_clicked(); void request_website(); void replyFinished(QNetworkReply *); void htmlAnalyze(QString &html); private: Ui::ydcx *ui; QNetworkAccessManager *manager; }; #endif // YDCX_H
ef1e249ef2fbe7809d4b8f5e99313cd3c636ce2a
3816c7370eb5b6c3fe6eaf5ac20319a416888137
/ExamUI/Exam/Trees/AVLTree.h
4f812dffec88d13ef9f292dc1086b35a1bfe4a6b
[]
no_license
WAG13/Exam_OOP_summer
a3bd8ebbe4fea1a9d4588de09b05f703d0d8ed6e
f5ea8da650348dc8c8e5732933a226ce3e0f667f
refs/heads/master
2022-10-11T12:07:19.227606
2020-06-10T22:35:11
2020-06-10T22:35:11
270,332,646
0
0
null
null
null
null
UTF-8
C++
false
false
16,839
h
AVLTree.h
#ifndef AVLTREE #define AVLTREE #include "SearchTree.h" #include <compare> #include <iostream> #include <functional> #include <queue> #include <vector> #include <stack> #include <exception> namespace lists { template<typename T, typename Key> class AVLTree : public SearchTree<T, Key> { public: AVLTree(GetKeyFunc<T, Key> getKeyFunc, Comparator<Key> comparatorFunc) : SearchTree(getKeyFunc, comparatorFunc), getKeyFunc(getKeyFunc), comparatorFunc(comparatorFunc) {} virtual ~AVLTree() override; void add(const T& element) override; //void printAll(std::ostream& os) const override; bool remove(const Key& key) override; T& get(const Key& key) override; bool contains(const Key& key) override; std::vector<T> find_all(const Key& min, const Key& max) const /*override*/; void forEach(std::function<void(const T&)> func) const override; //void print_as_tree(std::ostream& os) const; private: static const signed char LEFT_HEAVY = -1; static const signed char BALANCED = 0; static const signed char RIGHT_HEAVY = 1; GetKeyFunc<T, Key> getKeyFunc; Comparator<Key> comparatorFunc; struct Node { char balance = BALANCED; Node* left = nullptr; Node* right = nullptr; T value; Node(const T& value) : value(value) {} //void print(std::ostream& os, bool& first_element) const; //void print_as_tree(std::ostream& os, int levels) const; void forEach(std::function<void(const T&)> func) const; }; Node* root = nullptr; //returns true if height has changed static bool rotate_left(Node*& node); static bool rotate_right(Node*& node); static void rotate_right_left(Node*& node); static void rotate_left_right(Node*& node); void add(Node*& current_node, Node* new_node, bool& recalculate_balance); bool remove_standard_bst(const Key& key, std::stack<Node**>& path); void remove_node_standard_bst(Node** node, std::stack<Node**>& path); }; template<typename T> class AVLTreeSimple : public AVLTree<T, T> { public: AVLTreeSimple() : AVLTree(detail::getValueAsKey<T>, detail::lessThan<T>) {} }; template<typename T, typename Key> AVLTree<T, Key>::~AVLTree() { std::queue<Node*> queue; if (root) queue.push(root); while (!queue.empty()) { Node* root = queue.front(); queue.pop(); if (root->left) queue.push(root->left); if (root->right) queue.push(root->right); delete root; } } template<typename T, typename Key> bool AVLTree<T, Key>::rotate_left(Node*& node) { #if DEBUG std::cout << "rotate left "; std::cout << node->value << std::endl; #endif // DEBUG Node* right_child = node->right; bool height_changed = true; if (right_child->balance == BALANCED) //only happens with deletion { right_child->balance = LEFT_HEAVY; node->balance = RIGHT_HEAVY; height_changed = false; } else { right_child->balance = BALANCED; node->balance = BALANCED; } node->right = right_child->left; right_child->left = node; node = right_child; return height_changed; } template<typename T, typename Key> bool AVLTree<T, Key>::rotate_right(Node*& node) { #if DEBUG std::cout << "rotate right "; std::cout << node->value << std::endl; #endif // DEBUG Node* left_child = node->left; bool height_changed = true; if (left_child->balance == BALANCED) //only happens with deletion { left_child->balance = RIGHT_HEAVY; node->balance = LEFT_HEAVY; height_changed = false; } else { left_child->balance = BALANCED; node->balance = BALANCED; } node->left = left_child->right; left_child->right = node; node = left_child; return height_changed; } template<typename T, typename Key> void AVLTree<T, Key>::rotate_left_right(Node*& node) { #if DEBUG std::cout << "rotate left right "; std::cout << node->value << std::endl; #endif // DEBUG Node* left_child = node->left; Node* new_parent = left_child->right; if (new_parent->balance == RIGHT_HEAVY) { node->balance = BALANCED; left_child->balance = LEFT_HEAVY; } else if (new_parent->balance == BALANCED) { node->balance = BALANCED; left_child->balance = BALANCED; } else { node->balance = RIGHT_HEAVY; left_child->balance = BALANCED; } new_parent->balance = BALANCED; left_child->right = new_parent->left; new_parent->left = left_child; node->left = new_parent->right; new_parent->right = node; node = new_parent; } template<typename T, typename Key> void AVLTree<T, Key>::rotate_right_left(Node*& node) { #if DEBUG std::cout << "rotate right left "; std::cout << node->value << std::endl; #endif // DEBUG Node* right_child = node->right; Node* new_parent = right_child->left; if (new_parent->balance == LEFT_HEAVY) { node->balance = BALANCED; right_child->balance = RIGHT_HEAVY; } else if (new_parent->balance == BALANCED) { node->balance = BALANCED; right_child->balance = BALANCED; } else { node->balance = LEFT_HEAVY; right_child->balance = BALANCED; } new_parent->balance = BALANCED; right_child->left = new_parent->right; new_parent->right = right_child; node->right = new_parent->left; new_parent->left = node; node = new_parent; } template<typename T, typename Key> void AVLTree<T, Key>::add(const T& element) { if (!root) { root = new Node(element); return; } bool temp = false; // std::cout << "ADDING " << element << '\n'; add(root, new Node(element), temp); // printAll(std::cout); // std::cout << "\n\n\n"; } //Entirely recursive algorithm https://cis.stvincent.edu/html/tutorials/swd/avltrees/avltrees.html //The advantage is that we don't have to calculate the height when rebalancing template<typename T, typename Key> void AVLTree<T, Key>::add(Node*& current_node, Node* new_node, bool& recalculate_balance) { if (!current_node) { current_node = new_node; recalculate_balance = true; return; } bool should_rebalance_current = false; if (comparatorFunc(getKeyFunc(new_node->value), getKeyFunc(current_node->value))) { add(current_node->left, new_node, should_rebalance_current); if (should_rebalance_current) { if (current_node->balance == BALANCED) { current_node->balance = LEFT_HEAVY; recalculate_balance = true; } else if (current_node->balance == RIGHT_HEAVY) { current_node->balance = BALANCED; recalculate_balance = false; } else { //Rebalance // std::cout << "\nBEFORE:\n\n"; // print_as_tree(std::cout); // std::cout << "current: " << current_node->value << ", inserting: " << new_node->value << std::endl; if (current_node->left->balance == LEFT_HEAVY) { rotate_right(current_node); recalculate_balance = false; } else { rotate_left_right(current_node); // recalculate_balance = true; recalculate_balance = false; } // std::cout << "\n\nAFTER:\n\n"; // print_as_tree(std::cout); } } else recalculate_balance = false; } else { add(current_node->right, new_node, should_rebalance_current); if (should_rebalance_current) { if (current_node->balance == BALANCED) { current_node->balance = RIGHT_HEAVY; recalculate_balance = true; } else if (current_node->balance == LEFT_HEAVY) { current_node->balance = BALANCED; recalculate_balance = false; } else { //Rebalance // std::cout << "\nBEFORE:\n\n"; // print_as_tree(std::cout); // std::cout << "current: " << current_node->value << ", inserting: " << new_node->value << std::endl; if (current_node->right->balance == RIGHT_HEAVY) { rotate_left(current_node); recalculate_balance = false; } else { rotate_right_left(current_node); // recalculate_balance = true; recalculate_balance = false; } // std::cout << "\n\nAFTER:\n\n"; // print_as_tree(std::cout); } } else recalculate_balance = false; } } //iterative approach template<typename T, typename Key> bool AVLTree<T, Key>::remove(const Key& key) { #if DEBUG std::cout << "REMOVING " << element << '\n'; print_all(std::cout); std::cout << "\n\n"; #endif // DEBUG std::stack<Node**> path; //step 1: standard BST remove if (!remove_standard_bst(key, path)) return false; #if DEBUG std::cout << "Path length: " << path.size() << std::endl; print_all(std::cout); std::cout << "\n\n"; #endif //step 2: rebalance, starting from removed node's parent //note that at this point, balance values haven't been updated while (path.size() > 1) { Node** current_node = path.top(); #if DEBUG std::cout << "current " << *current_node << "\n"; #endif path.pop(); Node** parent = path.top(); if (current_node == &(*parent)->left) //parent's left child height decreased by 1 { #if DEBUG std::cout << "decreased height on the left, parent " << (*parent)->value << std::endl; #endif // DEBUG if ((*parent)->balance == RIGHT_HEAVY) { #if DEBUG std::cout << "BEFORE\n"; print_all(std::cout); std::cout << "\n\n\n"; #endif // DEBUG bool height_changed = true; Node* right_child = (*parent)->right; if (right_child->balance != LEFT_HEAVY) height_changed = rotate_left(*parent); else rotate_right_left(*parent); if (!height_changed) break; } else if ((*parent)->balance == BALANCED) { (*parent)->balance = RIGHT_HEAVY; break; //parent absorbs the height decrease } else { (*parent)->balance = BALANCED; } } else //parent's right child height decreased by 1 { #if DEBUG std::cout << "decreased height on the right, parent " << (*parent)->value << "\n"; std::cout << "current " << *current_node << "\n"; #endif if ((*parent)->balance == LEFT_HEAVY) { #if DEBUG std::cout << "BEFORE\n"; print_all(std::cout); std::cout << "\n\n\n"; #endif // DEBUG bool height_changed = true; Node* left_child = (*parent)->left; if (left_child->balance != RIGHT_HEAVY) height_changed = rotate_right(*parent); else rotate_left_right(*parent); if (!height_changed) break; } else if ((*parent)->balance == BALANCED) { (*parent)->balance = LEFT_HEAVY; break; //parent absorbs the height decrease } else { (*parent)->balance = BALANCED; } } //parent might've changed if we rotated path.pop(); path.push(parent); } #if DEBUG std::cout << "REMOVED " << element << "\n"; print_all(std::cout); std::cout << "\n\n\n"; #endif // DEBUG return true; } template<typename T, typename Key> bool AVLTree<T, Key>::remove_standard_bst(const Key& key, std::stack<Node**>& path) { if (!root) { return false; } Node** current_node = &root; while (current_node) { if (key == getKeyFunc((*current_node)->value)) { remove_node_standard_bst(current_node, path); return true; } bool keyLess = comparatorFunc(key, getKeyFunc((*current_node)->value)); if (keyLess && (*current_node)->left) { path.push(current_node); current_node = &(*current_node)->left; } else if (!keyLess && (*current_node)->right) { path.push(current_node); current_node = &(*current_node)->right; } else { #if DEBUG std::cout << "NOT FOUND\n\n"; #endif // DEBUG return false; } } return false; } //Returns true if deleted right child, false is left template<typename T, typename Key> void AVLTree<T, Key>::remove_node_standard_bst(Node** node, std::stack<Node**>& path) { if ((*node)->left) { if (!(*node)->right) //only left child { Node* temp = *node; *node = (*node)->left; delete temp; path.push(node); } else //both children { path.push(node); Node** min_node = &(*node)->right; while ((*min_node)->left) { path.push(min_node); min_node = &(*min_node)->left; } (*node)->value = (*min_node)->value; remove_node_standard_bst(min_node, path); } } else { if ((*node)->right) { Node* temp = *node; *node = (*node)->right; path.push(node); // path.push(&(*node)->right); delete temp; } else { Node* temp = *node; *node = nullptr; path.push(node); delete temp; } } } /*template<typename T, typename Key> void AVLTree<T, Key>::Node::print(std::ostream& os, bool& first_element) const { if (left) left->print(os, first_element); if (first_element) first_element = false; else os << ", "; os << value; if (right) right->print(os, first_element); }*/ //template<typename T, typename Key> //void AVLTree<T, Key>::printAll(std::ostream& os) const //{ // os << "[ "; // if (root) // { // bool first_element = true; // root->print(os, first_element); // } // os << " ]" << std::endl; // // #if DEBUG // print_as_tree(os); // // #endif // DEBUG //} /*template<typename T, typename Key> void AVLTree<T, Key>::Node::print_as_tree(std::ostream& os, int levels) const { for (int i = 0; i < levels; i++) os << " - "; os << value << " balance: " << (int)balance; os << " address: " << this << '\n'; if (left) { for (int i = 0; i < levels; i++) os << " - "; os << "Left:\n"; left->print_as_tree(os, levels + 1); } if (right) { for (int i = 0; i < levels; i++) os << " - "; os << "Right:\n"; right->print_as_tree(os, levels + 1); } }*/ /*template<typename T, typename Key> void AVLTree<T, Key>::print_as_tree(std::ostream& os) const { std::queue<Node*> queue; if (root) root->print_as_tree(os, 0); else os << "Empty tree!\n"; }*/ template<typename T, typename Key> void AVLTree<T, Key>::Node::forEach(std::function<void(const T&)> func) const { if (left) left->forEach(func); func(value); if (right) right->forEach(func); } template<typename T, typename Key> void AVLTree<T, Key>::forEach(std::function<void(const T&)> func) const { if (root) root->forEach(func); } template<typename T, typename Key> T& AVLTree<T, Key>::get(const Key& key) { // int searches = 0; std::vector<T> result; std::queue<Node*> bfs_queue; if (root) bfs_queue.push(root); while (!bfs_queue.empty()) { // searches++; Node* current_node = bfs_queue.front(); Key current_key = getKeyFunc(current_node->value); bfs_queue.pop(); if (key == current_key) { // std::cout << "(searches: " << searches << ")\n"; return current_node->value; } else if (comparatorFunc(key, current_key)) { if (current_node->left) bfs_queue.push(current_node->left); } else if (current_node->right) bfs_queue.push(current_node->right); } throw std::out_of_range("key not found"); } template<typename T, typename Key> std::vector<T> AVLTree<T, Key>::find_all(const Key& min, const Key& max) const { std::vector<T> result; std::queue<Node*> bfs_queue; if (root) bfs_queue.push(root); while (!bfs_queue.empty()) { Node* current_node = bfs_queue.front(); bfs_queue.pop(); if (!comparatorFunc(getKeyFunc(current_node->value), min) && current_node->left) bfs_queue.push(current_node->left); if (!comparatorFunc(max, getKeyFunc(current_node->value))) { if (current_node->right) bfs_queue.push(current_node->right); if (!comparatorFunc(getKeyFunc(current_node->value), min)) result.push_back(current_node->value); } } return result; } template<typename T, typename Key> bool AVLTree<T, Key>::contains(const Key& key) { try { get(key); return true; } catch (const std::out_of_range& e) { return false; } } } #endif // AVLTREE
213d1baa1793f92613b3104d39773dba067e932c
9dcba7fb9ac1159106e89d03d6b09d3bafc8971f
/CPOOA/annuaire/annuaire/Annuaire.cpp
bc56e934d7f6cdd771441ee783163378f90fc9c9
[]
no_license
andy-metz/L3
57f346f7719d1551faa4b86dfbe0c00534d024ec
c8f9beb27ad8294c50e6548a18cc0aea5efd3584
refs/heads/master
2020-12-29T00:01:11.631141
2016-09-27T21:47:26
2016-09-27T21:47:26
68,396,590
0
0
null
null
null
null
UTF-8
C++
false
false
2,523
cpp
Annuaire.cpp
#include "Annuaire.h" #include "ExTP1.h" #include <string.h> #include <string.h> Annuaire::Annuaire() : nom(_strdup("")), c(NULL), nb(0){} Annuaire::Annuaire(const char* nom) : nom(_strdup(nom)), c(NULL), nb(0) {} Annuaire::Annuaire(const Annuaire &a): nom(_strdup(a.nom)), c(NULL), nb(0){ if (a.nb){ c = new Contact[a.nb]; for (int i = 0; i < a.nb; i++) c[i] = a.c[i]; nb = a.nb; } } Annuaire::~Annuaire(){ free(nom); delete[] c; } const char * Annuaire::getNom() const{ return nom; } void Annuaire::setNom(const char *n){ free(nom); nom = _strdup(n); } int Annuaire::getNb() const{ return nb; } const Contact & Annuaire::recherche(const char *prenom, const char *nom) const{ string s; for (int i = 0; i < nb; i++) if (!strcmp(nom, c[i].getNom()) && !strcmp(prenom, c[i].getPrenom())) return c[i]; s = s + prenom + nom + " n'est pas dans l'annuaire"; throw exTP1(s); } const Contact & Annuaire::operator[](int i) const{ if (i < 0 || i > nb - 1) throw exTP1("Index hors limite"); return c[i]; } void Annuaire::supprime(const Contact &ct){ int i; string s; for (i = 0; i < nb; i++) if (!strcmp(c[i].getNom(), ct.getNom()) && !strcmp(c[i].getPrenom(), ct.getPrenom())) break; if (i == nb){ s = s + ct.getPrenom() + ct.getNom() + " n'est pas dans l'annuaire"; throw exTP1(s); } for (; i < nb - 1; i++) c[i] = c[i + 1]; nb--; } void Annuaire::supprime(int i){ if ((i < 0) || (i >= nb)) throw exTP1("Indice hors limite"); for (int j = i; j < nb - 1; j++) c[i] = c[i + 1]; nb--; } Annuaire Annuaire::operator + (const Contact &c) const{ if (contient(c.getPrenom(), c.getNom())){ string s; s = s + c.getPrenom() + " " + c.getNom() + " existe deja dans l'annuaire"; throw exTP1(s); } Annuaire a(nom); Contact * c2 = new Contact[nb + 1]; for (int i = 0; i < nb; i++) c2[i] = this->c[i]; c2[nb] = c; a.c = c2; a.nb = nb + 1; return a; } bool Annuaire::contient(const char * prenom, const char * nom) const{ for (int i = 0; i < nb; i++) if (!strcmp(nom, c[i].getNom()) && !strcmp(prenom, c[i].getPrenom())) return true; return false; } const Annuaire & Annuaire::operator = (const Annuaire &a){ if (this != &a){ free(nom); nom = _strdup(a.nom); nb = a.nb; delete[] c; c = new Contact[a.nb]; for (int i = 0; i < a.nb; i++) c[i] = a.c[i]; } return *this; } ostream & operator << (ostream & f, const Annuaire &a){ f << a.nom << " :" << endl; for (int i = 0; i < a.nb; i++) f << "\t" << a.c[i] << endl; return f; }
a6f41a03f63b339342f079de2119f3b21257aa66
76efa9d8e4912473579fb50c962069d012f0fe20
/src/xbee.cpp
88fada08b47a3845e6fb9d928c815533ef5a6acc
[ "MIT" ]
permissive
mjhsoet/F.Domotica-Qt-Application
25e9bc078126ebb401b15eec47c03d1d90e4932c
48748364c92abd79ce8367ac3d7370befe89e8e9
refs/heads/master
2020-04-17T22:28:52.092638
2019-01-24T18:42:11
2019-01-24T18:42:11
166,996,007
0
0
null
null
null
null
UTF-8
C++
false
false
6,633
cpp
xbee.cpp
#include "xbee.h" #include <QDebug> #include <QList> #include <QThread> #include <QMutex> #include <QMutexLocker> #include <QTimer> #include <stdlib.h> #include <string.h> #include "xbee/serial.h" #include "xbee/atcmd.h" #include "xbee/device.h" #include "xbee/wpan.h" #include "xbee/discovery.h" #include "wpan/aps.h" #include "zigbee/zcl.h" static QMutex discoveryMutex; const xbee_dispatch_table_entry_t xbee_frame_handlers[] = { XBEE_FRAME_HANDLE_LOCAL_AT, XBEE_FRAME_HANDLE_REMOTE_AT, XBEE_FRAME_HANDLE_ATND_RESPONSE, XBEE_FRAME_HANDLE_RX_EXPLICIT, XBEE_FRAME_TABLE_END }; static wpan_cluster_table_entry_t zcl_cluster_table[] { XBEE_DISC_DIGI_DATA_CLUSTER_ENTRY, WPAN_CLUST_ENTRY_LIST_END }; static wpan_endpoint_table_entry_t endpoints[] { { WPAN_ENDPOINT_DIGI_DATA, WPAN_PROFILE_DIGI, nullptr, nullptr, 0x0000, 0x0, zcl_cluster_table }, WPAN_ENDPOINT_TABLE_END }; static QMap<int,xbee_node_id_t> discoNodeMap; static void node_discovered(xbee_dev_t *xbee, const xbee_node_id_t *rec) { QMutexLocker locker(&discoveryMutex); XBEE_UNUSED_PARAMETER(xbee); if(xbee->wpan_dev.address.network != rec->network_addr) { discoNodeMap[rec->network_addr] = *rec; } } Xbee::Xbee(QString portname, QObject *parent) : QObject(parent) { xbee_serial_t xbeePort; initXbeeSerPort(&xbeePort, portname); xbeeStatusError |= xbee_dev_init(&xbee, &xbeePort, nullptr, nullptr); xbee_dev_flowcontrol(&xbee, false); xbee_wpan_init(&xbee, endpoints); if(xbeeStatusError == 0) { /* * Setup a thread to receive data */ threadRun = true; tickThread = QThread::create([&] {tick();}); tickThread->start(); /* * Get local device information (address and name) */ xbee_cmd_query_device(&xbee,0); while((xbeeStatusError = xbee_cmd_query_status(&xbee)) != 0) { if(xbeeStatusError == -EINVAL || xbeeStatusError == -ETIMEDOUT) { threadRun = false; return; } } xbee_disc_add_node_id_handler(&xbee,node_discovered); /* * Setup Network discovery with a timer */ discoverNodes(); discoveryTimer = new QTimer(this); connect(discoveryTimer,SIGNAL(timeout()),this,SLOT(discoverNodes())); discoveryTimer->start(10000); } } Xbee::~Xbee() { xbee_ser_close(&xbee.serport); //Closing handles or FD's if(discoveryTimer != nullptr) { discoveryTimer->stop(); delete discoveryTimer; } if(tickThread != nullptr) { threadRun = false; while(tickThread->isRunning()); delete tickThread; } } int Xbee::getXbeeError() { return xbeeStatusError; } void Xbee::discoverNodes() { QMutexLocker locker(&discoveryMutex); discoNodeMap.clear(); xbee_disc_discover_nodes(&xbee,nullptr); } void Xbee::updateNodeMap() { QMutexLocker locker(&discoveryMutex); QMap<int,xbee_node_id_t> tempNodeMap; for(auto node : discoNodeMap) { if(nodeMap.contains(node.network_addr)) { tempNodeMap[node.network_addr] = nodeMap[node.network_addr]; } else { tempNodeMap[node.network_addr] = node; } } nodeMap.swap(tempNodeMap); } QMap<int, QString> Xbee::getNodeAddressMap() { QMap<int, QString> nodeAddressMap; auto end = nodeMap.cend(); for(auto node = nodeMap.cbegin(); node != end; ++node) { nodeAddressMap[node.key()] = node.value().node_info; } return nodeAddressMap; } QString Xbee::getNodeType(int nwk_addr) { uint8_t type = nodeMap[nwk_addr].device_type; switch(type) { case XBEE_ND_DEVICE_TYPE_COORD: return "Coordinator"; case XBEE_ND_DEVICE_TYPE_ROUTER: return "Router"; case XBEE_ND_DEVICE_TYPE_ENDDEV: return "End Device"; default: return "Unknown"; } } QString Xbee::getNodeIEEE(int nwk_addr) { char buffer[ADDR64_STRING_LENGTH]; addr64_format(buffer,&nodeMap[nwk_addr].ieee_addr_be); return buffer; } void Xbee::toggleLed(int nwk_addr,LED led) { wpan_envelope_t envelope; uint8_t payload = 0x03; wpan_envelope_create(&envelope,&xbee.wpan_dev,WPAN_IEEE_ADDR_UNDEFINED,uint16_t(nwk_addr)); envelope.dest_endpoint = led; envelope.source_endpoint = 0xE8; envelope.profile_id = WPAN_PROFILE_DIGI; envelope.payload = &payload; envelope.length = 1; wpan_envelope_send(&envelope); } void Xbee::setButton(int sensor_nwk_addr,int actuator_nwk_addr, LED led) { uint16_t actuator_nwk_addr_be = htobe16(uint16_t(actuator_nwk_addr)); uint8_t *actuator_nwk_addr_be_pointer = reinterpret_cast<uint8_t *>(&actuator_nwk_addr_be); wpan_envelope_t envelope; uint8_t payload[3] = {actuator_nwk_addr_be_pointer[0],actuator_nwk_addr_be_pointer[1],uint8_t(led)}; wpan_envelope_create(&envelope,&xbee.wpan_dev,WPAN_IEEE_ADDR_UNDEFINED,uint16_t(sensor_nwk_addr)); envelope.dest_endpoint = 0x04; envelope.source_endpoint = 0xE8; envelope.profile_id = WPAN_PROFILE_DIGI; envelope.payload = &payload; envelope.length = 3; wpan_envelope_send(&envelope); } void Xbee::renameNode(int nwk_addr, QString name) { int16_t handle; strncpy(nodeMap[nwk_addr].node_info,name.toLocal8Bit().data(),sizeof(nodeMap[nwk_addr].node_info)); handle = xbee_cmd_create(&xbee,"NI"); xbee_cmd_set_target(handle,WPAN_IEEE_ADDR_UNDEFINED,uint16_t(nwk_addr)); xbee_cmd_set_param_str(handle,name.toLocal8Bit().data()); xbee_cmd_send(handle); handle = xbee_cmd_create(&xbee,"WR"); xbee_cmd_set_target(handle,WPAN_IEEE_ADDR_UNDEFINED,uint16_t(nwk_addr)); xbee_cmd_send(handle); handle = xbee_cmd_create(&xbee,"AC"); xbee_cmd_set_target(handle,WPAN_IEEE_ADDR_UNDEFINED,uint16_t(nwk_addr)); xbee_cmd_send(handle); } void Xbee::tick() { while(threadRun) { wpan_tick(&xbee.wpan_dev); } } void Xbee::initXbeeSerPort(xbee_serial_t *xbeePort, QString portname) { memset(xbeePort,0,sizeof(xbee_serial_t)); xbeePort->baudrate=9600; #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) snprintf(xbeePort->device,sizeof(xbeePort->device),"/dev/%s",portname.toLocal8Bit().data()); #elif defined WIN32 || defined _WIN32 || defined _WIN32_ || defined __WIN32__ \ || defined __CYGWIN32__ || defined MINGW32 xbeePort->comport=portname.remove(0,3).toInt(); #endif }
e332cd5008a3cce2080e9bc5832dafe1da7478a0
b23ce919e5e841f6563c6a89d0fd8c01476806e0
/Framework/fw/DomainShader.h
1201cf3a1393c4e64c669a9fbc2e5d45ad17c735
[]
no_license
jparimaa/dx-fx
bb53acfd0343d4b6f4a53385713a0990fe0f1d29
18b180e957ba3f0d09eaebb30d276daaaaead559
refs/heads/master
2023-09-02T19:20:39.086472
2020-11-21T19:17:30
2020-11-21T19:17:30
89,373,796
0
0
null
2020-06-04T16:54:21
2017-04-25T15:00:20
C++
UTF-8
C++
false
false
310
h
DomainShader.h
#pragma once #include <d3d11.h> namespace fw { class DomainShader { public: DomainShader(); ~DomainShader(); bool create(WCHAR* fileName, LPCSTR entryPoint, LPCSTR shaderModel); ID3D11DomainShader* get() const; private: ID3D11DomainShader* domainShader = nullptr; }; } // namespace fw
52d07c32b6524f354e4a42dbad79ff546a39f350
ca11db7f1a7ab9031456f5a74cabe6b962d828dc
/fork/shm.cpp
9ce01c460176baf816edb1c2aff1f8821de6094c
[]
no_license
qingdujun/basic
f4cabfa87f48b0ba3fc6a5789744e69fc547bca9
a3c7df850d5d9df695fbe6496fc74e72834fd71d
refs/heads/master
2020-04-27T12:05:30.188916
2019-08-05T13:11:17
2019-08-05T13:11:17
174,320,636
0
0
null
null
null
null
UTF-8
C++
false
false
1,454
cpp
shm.cpp
#include <sys/ipc.h> #include <sys/shm.h> #include <unistd.h> #include <iostream> using namespace std; typedef struct { char name[4]; int age; } people; int main(int argc, char const* argv[]) { int shm_id = shmget((key_t)2022, 4096, IPC_CREAT | 0666); if (shm_id < 0) { cerr << "shmget error" << endl; exit(0); } people* p_map = (people*)shmat(shm_id, nullptr, 0); if (p_map == (people*)-1) { cerr << "shamt error" << endl; exit(0); } pid_t pid = fork(); if (pid == 0) { sleep(2); for (int i = 0; i < 10; ++i) { cout << "name: "<<(*(p_map+i)).name <<" age: " << (*(p_map+i)).age <<endl; } if (shmdt(p_map) < 0) { cout << "shmdt error" << endl; } } else if (pid > 0) { char c = 'a'; for (int i = 0; i < 10; ++i) { c += 1; memcpy((*(p_map + i)).name, &c, 2); (*(p_map + i)).age = 20 + i; } if (shmdt(p_map) < 0) { cerr << "shmdt error" << endl; } } else { cerr << "fork error" << endl; } wait(nullptr); return 0; } /** * MacBook-Pro:fork qingdujun$ g++ shm.cpp * MacBook-Pro:fork qingdujun$ ./a.out * name: b age: 20 * name: c age: 21 * name: d age: 22 * name: e age: 23 * name: f age: 24 * name: g age: 25 * name: h age: 26 * name: i age: 27 * name: j age: 28 * name: k age: 29 */
471efeb07321c7a00774215923e68d7bf99e54cd
78e6f8b29560c70ca9e1eedcfff6f1111f7370c8
/OpenGL 3D Game/src/engine/platform/vulkan/texture/VkTexture.cpp
464cab02e66af3ead75ee5a0ed7a9ebf69da5184
[]
no_license
Andrispowq/OpenGL-3D-Game
511104617e403a5f8c448390e5ee411a47697e8e
8f0fcf1edcea7673b36e09f177aa75c4416a2d05
refs/heads/master
2023-01-29T04:34:12.471328
2020-12-01T13:42:51
2020-12-01T13:42:51
242,340,559
1
0
null
null
null
null
UTF-8
C++
false
false
8,092
cpp
VkTexture.cpp
#include "engine/prehistoric/core/util/Includes.hpp" #include "VkTexture.h" VKTexture::VKTexture(VKPhysicalDevice* physicalDevice, VKDevice* device, uint32_t width, uint32_t height, ImageFormat format, ImageType type) : physicalDevice(physicalDevice), device(device), Texture(width, height, format, type) { this->mipLevels = (uint32_t)(std::floor(std::log2(std::max(width, height)))) + 1; } VKTexture::VKTexture(VKPhysicalDevice* physicalDevice, VKDevice* device) : physicalDevice(physicalDevice), device(device), mipLevels(1) { } VKTexture::~VKTexture() { vkDestroySampler(device->getDevice(), textureSampler, nullptr); vkDestroyImageView(device->getDevice(), textureImageView, nullptr); vkDestroyImage(device->getDevice(), textureImage, nullptr); vkFreeMemory(device->getDevice(), textureImageMemory, nullptr); } void VKTexture::UploadTextureData(unsigned char* pixels, ImageFormat format) { uint8_t channels = (format == R8G8B8_LINEAR || format == R8G8B8_SRGB) ? 3 : 4; size_t size = width * height * channels; //TODO: hardcoded 4 should be removed VKUtil::CreateBuffer(physicalDevice->getPhysicalDevice(), device->getDevice(), size, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, stagingBuffer, stagingBufferMemory); this->format = format; void* data; vkMapMemory(device->getDevice(), stagingBufferMemory, 0, size, 0, &data); memcpy(data, pixels, size); vkUnmapMemory(device->getDevice(), stagingBufferMemory); } void VKTexture::Generate() { //We can create the image new based on the staging buffer's data VKUtil::CreateImage(physicalDevice->getPhysicalDevice(), device, width, height, mipLevels, VK_SAMPLE_COUNT_1_BIT, getFormat(format), VK_IMAGE_TILING_OPTIMAL, VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, textureImage, textureImageMemory); VKUtil::TransitionImageLayout(device, textureImage, /*GetFormat(format)*/VK_FORMAT_R8G8B8A8_UNORM, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, mipLevels); VKUtil::CopyBufferToImage(device, stagingBuffer, textureImage, width, height); //VKUtil::TransitionImageLayout(*device, textureImage, GetFormat(format), VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, mipLevels); VKUtil::GenerateMipmaps(physicalDevice->getPhysicalDevice(), device, textureImage, getFormat(format), width, height, mipLevels); //We're no longer in need of the staging buffers vkDestroyBuffer(device->getDevice(), stagingBuffer, nullptr); vkFreeMemory(device->getDevice(), stagingBufferMemory, nullptr); //We can now create the image view VKUtil::CreateImageView(device, textureImage, getFormat(format), VK_IMAGE_ASPECT_COLOR_BIT, mipLevels, textureImageView); //Creating the sampler, which is based on bilinear sampling with 16x anisotropy filtering, which is a mode likely to be used, but at any time it can be //recreate with the method SamplerProperties(SamplerFilter, TextureWrapMode) VkSamplerCreateInfo samplerInfo = {}; samplerInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO; samplerInfo.magFilter = VK_FILTER_LINEAR; samplerInfo.minFilter = VK_FILTER_LINEAR; samplerInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT; samplerInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT; samplerInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT; samplerInfo.anisotropyEnable = VK_TRUE; samplerInfo.maxAnisotropy = 16; samplerInfo.borderColor = VK_BORDER_COLOR_INT_OPAQUE_BLACK; samplerInfo.unnormalizedCoordinates = VK_FALSE; samplerInfo.compareEnable = VK_FALSE; samplerInfo.compareOp = VK_COMPARE_OP_ALWAYS; samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR; samplerInfo.minLod = 0; samplerInfo.maxLod = (float) mipLevels; samplerInfo.mipLodBias = 0; if (vkCreateSampler(device->getDevice(), &samplerInfo, nullptr, &textureSampler) != VK_SUCCESS) { PR_LOG_RUNTIME_ERROR("Failed to create texture sampler!\n"); } } void VKTexture::SamplerProperties(SamplerFilter filter, TextureWrapMode wrapMode) { //We recreate the sampler vkDestroySampler(device->getDevice(), textureSampler, nullptr); VkSamplerCreateInfo samplerInfo = {}; samplerInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO; samplerInfo.borderColor = VK_BORDER_COLOR_INT_OPAQUE_BLACK; samplerInfo.unnormalizedCoordinates = VK_FALSE; samplerInfo.compareEnable = VK_FALSE; samplerInfo.compareOp = VK_COMPARE_OP_ALWAYS; switch (filter) { case Nearest: samplerInfo.magFilter = VK_FILTER_NEAREST; samplerInfo.minFilter = VK_FILTER_NEAREST; samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST; samplerInfo.minLod = 0; samplerInfo.maxLod = 0; samplerInfo.mipLodBias = 0; samplerInfo.anisotropyEnable = VK_FALSE; samplerInfo.maxAnisotropy = 1; break; case Bilinear: samplerInfo.magFilter = VK_FILTER_LINEAR; samplerInfo.minFilter = VK_FILTER_LINEAR; samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST; samplerInfo.minLod = 0; samplerInfo.maxLod = 0; samplerInfo.mipLodBias = 0; samplerInfo.anisotropyEnable = VK_FALSE; samplerInfo.maxAnisotropy = 1; break; case Trilinear: samplerInfo.magFilter = VK_FILTER_LINEAR; samplerInfo.minFilter = VK_FILTER_LINEAR; samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR; samplerInfo.minLod = 0; samplerInfo.maxLod = (float)mipLevels; samplerInfo.mipLodBias = 0; samplerInfo.anisotropyEnable = VK_FALSE; samplerInfo.maxAnisotropy = 1; break; case Anisotropic: samplerInfo.magFilter = VK_FILTER_LINEAR; samplerInfo.minFilter = VK_FILTER_LINEAR; samplerInfo.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR; samplerInfo.minLod = 0; samplerInfo.maxLod = (float)mipLevels; samplerInfo.mipLodBias = 0; samplerInfo.anisotropyEnable = VK_TRUE; samplerInfo.maxAnisotropy = 16; break; default: break; } switch (wrapMode) { case ClampToEdge: samplerInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; samplerInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; samplerInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; break; case ClampToBorder: samplerInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER; samplerInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER; samplerInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER; break; case Repeat: samplerInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_REPEAT; samplerInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_REPEAT; samplerInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_REPEAT; break; case MirrorRepeat: samplerInfo.addressModeU = VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT; samplerInfo.addressModeV = VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT; samplerInfo.addressModeW = VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT; break; default: break; } if (vkCreateSampler(device->getDevice(), &samplerInfo, nullptr, &textureSampler) != VK_SUCCESS) { PR_LOG_RUNTIME_ERROR("Failed to create texture sampler!\n"); } } VkFormat VKTexture::getFormat(ImageFormat format) const { //TODO: See which formats are available, return if it is, and return VK_FORMAT_R8G8B8A8_SRGB if it's not switch (format) { case R8G8B8A8_SRGB: return VK_FORMAT_R8G8B8A8_SRGB; case R8G8B8_SRGB: return VK_FORMAT_R8G8B8_SRGB; case D32_SFLOAT: return VK_FORMAT_D32_SFLOAT; case R16_SFLOAT: return VK_FORMAT_R16_SFLOAT; case R32_SFLOAT: return VK_FORMAT_R32_SFLOAT; case R8_SRGB: return VK_FORMAT_R8_SRGB; case R8G8_SRGB: return VK_FORMAT_R8G8_SRGB; case R16G16_SFLOAT: return VK_FORMAT_R16G16_SFLOAT; case R8G8B8A8_LINEAR: return VK_FORMAT_R8G8B8A8_UNORM; case R8G8B8_LINEAR: return VK_FORMAT_R8G8B8_UNORM; case D32_LINEAR: return VK_FORMAT_D32_SFLOAT_S8_UINT; //Not sure about that one case R16_LINEAR: return VK_FORMAT_R16_UNORM; case R32_LINEAR: return VK_FORMAT_R32_UINT; case R8_LINEAR: return VK_FORMAT_R8_UNORM; case R8G8_LINEAR: return VK_FORMAT_R8G8_UNORM; case R16G16_LINEAR: return VK_FORMAT_R16G16_UNORM; default: return VK_FORMAT_R8G8B8A8_SRGB; } }
5bae576edd6f74dcc530cdcab276d0503ff85fc9
bd9d2329feb1ed59466fd1357647e46875e211f9
/code/t4/mrx_t4server.h
d083276e9f8acb5eea26276fdaa0dfeaa58e9011
[]
no_license
ww4u/megarobo_app_server
927fb6b734528190c3f95ac68a530b74d08eb05d
90f24ee567056bfcd7a8f3329241aa10f202b003
refs/heads/master
2022-12-21T11:30:21.665921
2019-05-17T14:57:58
2019-05-17T14:57:58
296,256,550
0
0
null
null
null
null
UTF-8
C++
false
false
533
h
mrx_t4server.h
#ifndef MRX_T4SERVER_H #define MRX_T4SERVER_H #include "../mappserver.h" #include "t4para.h" class MRX_T4Server : public MAppServer, public T4Para { public: MRX_T4Server( int portBase=2345, int cnt = 1, QObject *pParent = nullptr ); public: virtual int start(); virtual int open(); virtual void close(); virtual MAppServer::ServerStatus status(); virtual void on_dislink(); virtual bool isLinked(); public: int load(); }; #endif // MRX_T4SERVER_H
2452776726e25b50673f08051dffba240606d421
6e665dcd74541d40647ebb64e30aa60bc71e610c
/600/VoipLib/include/util/io/VFileBrowser.hxx
2a81fda17f13a533ca078859d8551ed56cac46ef
[]
no_license
jacklee032016/pbx
b27871251a6d49285eaade2d0a9ec02032c3ec62
554149c134e50db8ea27de6a092934a51e156eb6
refs/heads/master
2020-03-24T21:52:18.653518
2018-08-04T20:01:15
2018-08-04T20:01:15
143,054,776
0
0
null
null
null
null
UTF-8
C++
false
false
2,580
hxx
VFileBrowser.hxx
#ifndef VFileBrowser_hxx #define VFileBrowser_hxx /* * $Id: VFileBrowser.hxx,v 1.2 2007/03/01 20:04:30 lizhijie Exp $ */ #include <pthread.h> #include <list> #include <string> #ifndef WIN32 #include <utime.h> #endif #include "VFile.hxx" #include "VIoException.hxx" class VFileBrowser { public: typedef list < VFile > DirList; ///Constructor initialises to the root directory VFileBrowser(const string& root); ///Constructor initialises to the root directory VFileBrowser(): _root("/") { } ; ///Returns list of files in directory, relative to the root directory DirList directory(const string& dirName) throw (VIoException&); ///Makes a directory defined by the path, NOP when dir exits void mkDir(const string& dirPath) throw (VIoException&); ///Writes a file in the given path, relative to _root void writeFile(const string& filePath, const string& contents) throw (VIoException); ///Writes a file in the given path, relative to _root // sets modification time to be timestamp void writeFile(const string& filePath, const string& contents, time_t timestamp) throw (VIoException); ///Writes a file in the given path, relative to _root // retunrs modification time as timestamp void writeFile(const string& filePath, const string& contents, time_t *timestamp) throw (VIoException); //Atomic write, write the contents to a temporary location first //and then move the file to the actual location void atomicWrite(const string& fileName, const string& contents); ///Checks if a directory exists bool dirExists(const string& dirName); ///Rename a file void rename(const string& oldPath, const string& newPath) throw (VIoException&); ///Remove a file void remove(const string& filePath) throw (VIoException&); ///Remove a file/directory and anything under it void removeAll(const string& filePath) throw (VIoException&); static bool fileExists(const VFile& file); static int fileSize(const VFile& file); private: static int pftw(const char* fName, const struct stat* sb, int flag); static int addnode(const char* fName, const struct stat* sb, int flag); string _root; static DirList _dirList; static pthread_mutex_t _lock; static list < string > _toDel; }; #endif
a9c743c405ac576c189517aa931163d8ab01afff
dba70d101eb0e52373a825372e4413ed7600d84d
/Demo/QuickStart/PerformanceTester.cpp
6a0d62fdd93738ca7d1d0f52cdba1337e1e1e191
[]
no_license
nustxujun/simplerenderer
2aa269199f3bab5dc56069caa8162258e71f0f96
466a43a1e4f6e36e7d03722d0d5355395872ad86
refs/heads/master
2021-03-12T22:38:06.759909
2010-10-02T03:30:26
2010-10-02T03:30:26
32,198,944
0
0
null
null
null
null
UTF-8
C++
false
false
1,797
cpp
PerformanceTester.cpp
#include "PerformanceTester.h" #include <windows.h> #pragma comment(lib,"winmm.lib") const int sampleSize = 10; PerformanceTester* PerformanceTester::mSingleton = NULL; PerformanceTester::PerformanceTester() { mSingleton = this; } void PerformanceTester::addItem(const std::string& item) { std::pair<ResultList::iterator,bool> result = mResultList.insert(ResultList::value_type(item,Result())); if (result.second) result.first->second.sample.resize(sampleSize); } void PerformanceTester::begin(const std::string& testItem) { ResultList::iterator result = mResultList.find(testItem); if (result != mResultList.end()) { mTimerStack.push_back(std::make_pair(&result->second,timeGetTime())); } else { mTimerStack.push_back(std::make_pair((Result*)NULL,timeGetTime())); } } const PerformanceTester::Result& PerformanceTester::end() { Result* current = mTimerStack[mTimerStack.size() - 1].first; unsigned int timer = mTimerStack[mTimerStack.size() - 1].second; timer = timeGetTime() - timer; mTimerStack.pop_back(); if (timer == 0) return *current; float time = (float)timer / 1000.f; float frame = 1.0f / time; current->maxValue = current->maxValue > frame? current->maxValue:frame; current->minValue = current->minValue < frame? current->minValue:frame; current->sample.push_back(frame / (float)sampleSize); current->average = current->average - (*current->sample.begin()); current->average += (*current->sample.rbegin()); current->sample.pop_front(); return *current; } const PerformanceTester::Result& PerformanceTester::getResult(const std::string& item) { return mResultList.find(item)->second; } const PerformanceTester::ResultList& PerformanceTester::getResultList() { return mResultList; }
03a127382bffc3f0a18cf888c63380e8b776c9e0
6c8e5b2c6cde71420698e7415fab1d53fc60711d
/CBullet.cpp
5721bcea657c8f9a59aebc27121f1b3c98ec41e5
[]
no_license
IIvanov21/Bob-s-Adventure
9c568331d855ba8384d404856f200cd310d99c99
408f5f7e768e869a91051d26374bd6d2d69b07a1
refs/heads/master
2020-06-04T10:47:48.919393
2019-06-14T18:26:37
2019-06-14T18:26:37
191,988,907
0
0
null
null
null
null
UTF-8
C++
false
false
5,073
cpp
CBullet.cpp
// File: CBullet.cpp // Date: 03-02-2019 // Last Edited: 21-03-2019 #include "CBullet.hpp" CBullet::CBullet(I3DEngine* engine) { fireBulletBuffer.loadFromFile("laserGunShoot.wav"); fireBullet.setBuffer(fireBulletBuffer); fireBullet.setVolume(30.0f); // 0 to 100 fireBullet.setPitch(1.0f); fireBullet.setLoop(false); collisionBulletBuffer.loadFromFile("bulletHit.wav"); collisionBullet.setBuffer(collisionBulletBuffer); collisionBullet.setVolume(30.0f); // 0 to 100 collisionBullet.setPitch(1.0f); collisionBullet.setLoop(false); myEngine = engine; } void CBullet::CreateModel(IMesh* bulletMesh, IModel* player, bulletDetails level1BulletPosition[]) { for (int i = 0; i < kNumBullets; i++) { myBullets[i].Model = bulletMesh->CreateModel(level1BulletPosition[i].xPos, level1BulletPosition[i].yPos, level1BulletPosition[i].zPos); myBullets[i].Model->SetSkin("laser.png"); } } void CBullet::DeleteModel(IMesh* bulletMesh) { for (int i = 0; i < kNumBullets; i++) { bulletMesh->RemoveModel(myBullets[i].Model); } } void CBullet::Update(playerMovement currentDirection, IModel* player, float frameTime) { if (myEngine->KeyHit(Key_Space)) { Fire(currentDirection, player); } for (int i = 0; i < kNumBullets; ++i) { oldBulletX[i] = myBullets[i].Model->GetX(); oldBulletZ[i] = myBullets[i].Model->GetZ(); if (myBullets[i].fired == true) { switch (myBullets[i].firingDirection) { case UP: myBullets[i].Model->MoveZ(bulletSpeed * frameTime); break; case DOWN: myBullets[i].Model->MoveZ(-bulletSpeed * frameTime); break; case LEFT: myBullets[i].Model->MoveX(-bulletSpeed * frameTime); break; case RIGHT: myBullets[i].Model->MoveX(bulletSpeed * frameTime); break; } } } Reset(); } void CBullet::Fire(playerMovement currentDirection, IModel* player) { for (int i = 0; i < kNumBullets; ++i) { if (myBullets[i].fired == false) { myBullets[i].fired = true; float tmp[16]; player->GetMatrix(tmp); myBullets[i].Model->SetMatrix(tmp); myBullets[i].Model->SetY(10.0f); myBullets[i].Model->SetZ(player->GetZ() - 4.4f); myBullets[i].Model->Scale(0.2f); myBullets[i].firingDirection = currentDirection; if (currentDirection == UP || currentDirection == DOWN) { myBullets[i].Model->RotateY(90.0f); } fireBullet.play(); return; } } } void CBullet::Reset() { /****************************************** temporary reset of bullets ************************************************/ for (int i = 0; i < kNumBullets; ++i) { if (myBullets[i].Model->GetX() > 500.0f || myBullets[i].Model->GetX() < -500.0f) { myBullets[i].fired = false; myBullets[i].Model->SetY(-10.0f); // Move out of view } if (myBullets[i].Model->GetZ() > 500.0f || myBullets[i].Model->GetLocalZ() < -500.0f) { myBullets[i].fired = false; myBullets[i].Model->SetLocalY(10.0f); // Move out of view myBullets[i].Model->RotateY(-90.0f); } if (myBullets[i].Model->GetY() < 10.0f) { myBullets[i].fired = false; myBullets[i].Model->SetY(-10.0f); } } // Reset bullet when collision } void CBullet::level1WallCollision(wallDetails level1Walls[kNumLevel1Walls], CPlayer* player) { for (int i = 0; i < kNumLevel1Walls; i++) { for (int j = 0; j < kNumBullets; j++) { if (collisionDetector->sphere2Box(myBullets[j].Model->GetX(), myBullets[j].Model->GetZ(), 1.0f, level1Walls[i].xPos, level1Walls[i].zPos, 10.0f, 10.0f)) { myBullets[j].Model->SetPosition(player->GetModel()->GetX(), -11.0f, player->GetModel()->GetZ()); } } } } void CBullet::level2WallCollision(wallDetails level2Walls[kNumLevel2Walls], CPlayer* player) { for (int i = 0; i < kNumLevel2Walls; i++) { for (int j = 0; j < kNumBullets; j++) { if (collisionDetector->sphere2Box(myBullets[j].Model->GetX(), myBullets[j].Model->GetZ(), 1.0f, level2Walls[i].xPos, level2Walls[i].zPos, 10.0f, 10.0f)) { myBullets[j].Model->SetPosition(player->GetModel()->GetX(), -11.0f, player->GetModel()->GetZ()); } } } } void CBullet::level1DoorCollision(keyDetails level1DoorPosition[kNumLevel1Doors], CPlayer* player) { for (int i = 0; i < kNumLevel1Doors; i++) { for (int j = 0; j < kNumBullets; j++) { if (collisionDetector->sphere2Box(myBullets[j].Model->GetX(), myBullets[j].Model->GetZ(), 1.0f, level1DoorPosition[i].xPos, level1DoorPosition[i].zPos, 10.0f, 10.0f)) { myBullets[j].Model->SetPosition(player->GetModel()->GetX(), -11.0f, player->GetModel()->GetZ()); Reset(); } } } } void CBullet::level2DoorCollision(keyDetails level2DoorPosition[kNumLevel2Doors], CPlayer* player) { for (int i = 0; i < kNumLevel2Doors; i++) { for (int j = 0; j < kNumBullets; j++) { if (collisionDetector->sphere2Box(myBullets[j].Model->GetX(), myBullets[j].Model->GetZ(), 1.0f, level2DoorPosition[i].xPos, level2DoorPosition[i].zPos, 10.0f, 10.0f)) { myBullets[j].Model->SetPosition(player->GetModel()->GetX(), -11.0f, player->GetModel()->GetZ()); Reset(); } } } }
93dad8745dc7f26403e6124f35e1bf0253ff8db1
11c1f05125684db84f79d811188ae74b8e826a66
/Voice.cpp
35935621bb135f2f2df227b1e4a8f657c2062bc8
[]
no_license
creel904/Connect-Four-with-OpenCV
e9c3de5f110b6e3e2ca6a8a35ddc138aeffd48f3
cd4d42ff179ac8bde9ebe74a2ac5a301c7edbcba
refs/heads/master
2023-02-22T06:01:30.414800
2019-09-23T04:54:54
2019-09-23T04:54:54
210,264,237
0
0
null
null
null
null
UTF-8
C++
false
false
1,842
cpp
Voice.cpp
#include "Voice.h" void Voice::printBoard(GameState gameState) { text.printBoard(gameState); } void Voice::badMove() { text.badMove(); PlaySound(TEXT("audio/badmove.wav"), NULL, SND_ALIAS | SND_APPLICATION | SND_ASYNC); } void Voice::requestMove(int column) { text.requestMove(column); const char *filename; switch (column) { case 1: filename = "audio/pleasemoveincolumn1.wav"; break; case 2: filename = "audio/pleasemoveincolumn2.wav"; break; case 3: filename = "audio/pleasemoveincolumn3.wav"; break; case 4: filename = "audio/pleasemoveincolumn4.wav"; break; case 5: filename = "audio/pleasemoveincolumn5.wav"; break; case 6: filename = "audio/pleasemoveincolumn6.wav"; break; case 7: filename = "audio/pleasemoveincolumn7.wav"; break; default: filename = "audio/badmove.wav"; break; } PlaySound(TEXT(filename), NULL, SND_ALIAS | SND_APPLICATION | SND_ASYNC); } void Voice::announceWinner(int player) { if (player == 1) { std::cout << "Player 1 has won the game!" << std::endl; } else if (player == 2) { std::cout << "Player 2 has won the game!" << std::endl; } else { std::cout << "Stalemate!" << std::endl; } const char *filename; if (player == 1) filename = ("audio/redwins.wav"); else if(player == 2) filename = ("audio/yellowwins.wav"); else { filename = ("audio/stalemate.wav"); } PlaySound(TEXT(filename), NULL, SND_ALIAS | SND_APPLICATION); } void Voice::visionError() { text.visionError(); PlaySound(TEXT("audio/visionerror.wav"), NULL, SND_ALIAS | SND_APPLICATION); } void Voice::promptMove(int player) { std::cout << std::endl << "Enter " << ((player == 1) ? "Red" : "Yellow") << " player's move column: "; PlaySound(TEXT("audio/promptmove.wav"), NULL, SND_ALIAS | SND_APPLICATION | SND_ASYNC); }
e0d8e5063ad10cd8b9b06dcfe8b775c55952c895
ccb6d2726b7522af43004875e2e233bc1088774a
/carma/antenna/common/Encoder.h
e17009d67608356debe042c315653c8135f58912
[ "FSFUL" ]
permissive
mpound/carma
a9ab28ed45b3114972d3f72bcc522c0010e80b42
9e317271eec071c1a53dca8b11af31320f69417b
refs/heads/master
2020-06-01T11:43:47.397953
2019-06-07T15:05:57
2019-06-07T15:05:57
190,763,870
2
0
null
null
null
null
UTF-8
C++
false
false
1,010
h
Encoder.h
// $Id: Encoder.h,v 1.2 2005/04/27 20:56:48 rick Exp $ #ifndef CARMA_ANTENNA_COMMON_ENCODER_H #define CARMA_ANTENNA_COMMON_ENCODER_H #include "carma/services/Angle.h" /** * @file Encoder.h * * Tagged: Wed Sep 15 16:15:33 PDT 2004 * * @version: $Revision: 1.2 $, $Date: 2005/04/27 20:56:48 $ * * @author Rick Hobbs */ namespace carma { namespace antenna { namespace common { /** * Manages Encoder parameters. * (e.g. zero points, calibration, counts per turn) */ class Encoder { public: /** * Constructor. */ Encoder(); /** * Destructor. */ virtual ~Encoder(); virtual void setZero(const carma::services::Angle& zero) = 0; virtual const carma::services::Angle& getZero() = 0; private: }; // End class Encoder } // End namespace common } // End namespace antenna } // End namespace carma #endif // End #ifndef CARMA_ANTENNA_COMMON_ENCODER_H
9f7a216453c08f331cd31d597e2a41a9de1dbbfd
6e262ab77dbf4262ab086a3e0fb41e7b72e667e5
/TomyGateway/src/ClientSendTask.cpp
5c4bf18a49fdc5618380a9a9b9b4a834c7fd67ee
[]
no_license
lattic/MQTT-S-Gateway
7e44f8ef221210849f733cf5d66d118a9d890926
f3d472992adc027cae7274370a94be304631872c
refs/heads/master
2023-08-07T20:07:16.738485
2014-04-20T13:23:43
2014-04-20T13:23:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,713
cpp
ClientSendTask.cpp
/* * ClientSendTask.cpp * * Copyright (c) 2013, tomy-tech.com * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * * Created on: 2013/10/19 * Updated on: 2014/03/20 * Author: Tomoaki YAMAGUCHI * Version: 2.0.0 * */ #include "ClientSendTask.h" #include "GatewayResourcesProvider.h" #include "libmq/ProcessFramework.h" #include "libmq/Messages.h" #include "libmq/ErrorMessage.h" #include <unistd.h> #include <iostream> #include <fcntl.h> ClientSendTask::ClientSendTask(GatewayResourcesProvider* res){ _res = res; _res->attach(this); } ClientSendTask::~ClientSendTask(){ } void ClientSendTask::run(){ if(_sp.begin(_res->getArgv()[ARGV_DEVICE_NAME], B57600, O_WRONLY) == -1){ THROW_EXCEPTION(ExFatal, ERRNO_SYS_02, "can't open device."); // ABORT } _zb.setSerialPort(&_sp); while(true){ Event* ev = _res->getClientSendQue()->wait(); if(ev->getEventType() == EtClientSend){ MQTTSnMessage msg = MQTTSnMessage(); ClientNode* clnode = ev->getClientNode(); msg.absorb( clnode->getClientSendMessage() ); _zb.unicast(clnode->getAddress64Ptr(), clnode->getAddress16(), msg.getMessagePtr(), msg.getMessageLength()); }else if(ev->getEventType() == EtBroadcast){ MQTTSnMessage msg = MQTTSnMessage(); msg.absorb( ev->getMqttSnMessage() ); _zb.broadcast(msg.getMessagePtr(), msg.getMessageLength()); } delete ev; } }
a7e05a711915b3310adf04685594b0e9002b482c
74837c92508b3190f8639564eaa7fa4388679f1d
/xic/src/extract/ext_devsel.cc
fe33586e01890aae285fa6c435404c80804c1be9
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
frankhoff/xictools
35d49a88433901cc9cb88b1cfd3e8bf16ddba71c
9ff0aa58a5f5137f8a9e374a809a1cb84bab04fb
refs/heads/master
2023-03-21T13:05:38.481014
2022-09-18T21:51:41
2022-09-18T21:51:41
197,598,973
1
0
null
2019-07-18T14:07:13
2019-07-18T14:07:13
null
UTF-8
C++
false
false
26,205
cc
ext_devsel.cc
/*========================================================================* * * * Distributed by Whiteley Research Inc., Sunnyvale, California, USA * * http://wrcad.com * * Copyright (C) 2017 Whiteley Research Inc., all rights reserved. * * Author: Stephen R. Whiteley, except as indicated. * * * * As fully as possible recognizing licensing terms and conditions * * imposed by earlier work from which this work was derived, if any, * * this work is released under the Apache License, Version 2.0 (the * * "License"). You may not use this file except in compliance with * * the License, and compliance with inherited licenses which are * * specified in a sub-header below this one if applicable. A copy * * of the License is provided with this distribution, or you may * * obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * See the License for the specific language governing permissions * * and limitations under the License. * * * * 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 NON- * * INFRINGEMENT. IN NO EVENT SHALL WHITELEY RESEARCH INCORPORATED * * OR STEPHEN R. WHITELEY 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. * * * *========================================================================* * XicTools Integrated Circuit Design System * * * * Xic Integrated Circuit Layout and Schematic Editor * * * *========================================================================* $Id:$ *========================================================================*/ #include "main.h" #include "ext.h" #include "ext_extract.h" #include "edit.h" #include "cd_netname.h" #include "dsp_tkif.h" #include "dsp_color.h" #include "dsp_layer.h" #include "dsp_inlines.h" #include "events.h" #include "layertab.h" #include "tech.h" #include "tech_layer.h" #include "promptline.h" #include "undolist.h" #include "errorlog.h" #include "ghost.h" #include "menu.h" namespace { namespace ext_devsel { struct DvselState : public CmdState { DvselState(const char*, const char*); virtual ~DvselState(); void setCaller(GRobject c) { Caller = c; } void halt(); void b1down(); void b1up(); void b1up_altw(); void esc(); private: void handle_selection(const BBox*); GRobject Caller; int Refx, Refy; bool B1Dn; }; DvselState *DvselCmd; } } using namespace ext_devsel; bool cExt::selectDevices(GRobject caller) { if (DvselCmd) { if (!caller || !Menu()->GetStatus(caller)) DvselCmd->esc(); return (true); } else if (caller && !Menu()->GetStatus(caller)) return (true); if (!XM()->CheckCurCell(false, true, Physical)) return (false); EV()->InitCallback(); if (!EX()->extract(CurCell(Physical))) { PL()->ShowPrompt("Extraction failed!"); return (false); } // Associate for duality, not an error if this fails, but electrical // dual selections and comparison won't work. if (!EX()->associate(CurCell(Physical))) PL()->ShowPrompt("Association failed!"); DvselCmd = new DvselState("DEVSEL", "xic:dvsel"); DvselCmd->setCaller(caller); if (!EV()->PushCallback(DvselCmd)) { delete DvselCmd; return (false); } PL()->ShowPrompt("Click on devices to select."); return (true); } DvselState::DvselState(const char *nm, const char *hk) : CmdState(nm, hk) { Caller = 0; Refx = Refy = 0; B1Dn = false; } DvselState::~DvselState() { DvselCmd = 0; } // Bail out of the command, called when clearing groups. Like the esc() // method, but don't clear the prompt line. // void DvselState::halt() { if (B1Dn) { Gst()->SetGhost(GFnone); XM()->SetCoordMode(CO_ABSOLUTE); } EX()->queueDevice(0); EV()->PopCallback(this); Menu()->Deselect(Caller); EX()->PopUpDevices(0, MODE_UPD); delete this; } // Anchor corner of box and start ghosting. // void DvselState::b1down() { EV()->Cursor().get_raw(&Refx, &Refy); XM()->SetCoordMode(CO_RELATIVE, Refx, Refy); Gst()->SetGhostAt(GFbox, Refx, Refy); EV()->DownTimer(GFbox); B1Dn = true; } // If the user clicks, call the extraction function. If a drag, // process the rectangle. If pressed and held, look for the next // press. // void DvselState::b1up() { Gst()->SetGhost(GFnone); XM()->SetCoordMode(CO_ABSOLUTE); B1Dn = false; if (EV()->Cursor().is_release_ok() && EV()->CurrentWin()) { EX()->queueDevice(0); int x, y; EV()->Cursor().get_release(&x, &y); BBox AOI(Refx, Refy, x, y); AOI.fix();; if (AOI.left == AOI.right && AOI.bottom == AOI.top) { int delta = 1 + (int)(DSP()->PixelDelta()/EV()->CurrentWin()->Ratio()); AOI.bloat(delta); } handle_selection(&AOI); } } void DvselState::b1up_altw() { if (EV()->CurrentWin()->CurCellName() != DSP()->MainWdesc()->CurCellName()) return; BBox AOI; EV()->Cursor().get_alt_down(&AOI.left, &AOI.bottom); EV()->Cursor().get_alt_up(&AOI.right, &AOI.top); AOI.fix(); if (AOI.left == AOI.right && AOI.bottom == AOI.top) { int delta = 1 + (int)(DSP()->PixelDelta()/EV()->CurrentWin()->Ratio()); AOI.bloat(delta); } handle_selection(&AOI); } // Esc entered, clean up and abort. // void DvselState::esc() { if (B1Dn) { Gst()->SetGhost(GFnone); XM()->SetCoordMode(CO_ABSOLUTE); } EX()->queueDevice(0); PL()->ErasePrompt(); EV()->PopCallback(this); Menu()->Deselect(Caller); EX()->PopUpDevices(0, MODE_UPD); delete this; } namespace { void measure(sDevInst *di, const BBox *AOI, double *area, double *cxdist) { *area = di->bBB()->width(); *area *= di->bBB()->height(); double cxd = CDinfinity; for (sDevContactInst *c = di->contacts(); c; c = c->next()) { int dx = ((c->cBB()->left + c->cBB()->right) - (AOI->left + AOI->right))/2; int dy = ((c->cBB()->bottom + c->cBB()->top) - (AOI->bottom + AOI->top))/2; double dst = sqrt(dx*(double)dx + dy*(double)dy); if (dst < cxd) cxd = dst; } *cxdist = cxd; } } void DvselState::handle_selection(const BBox *AOI) { CDcbin cbin(DSP()->CurCellName()); if (!cbin.phys()) return; cGroupDesc *gd = cbin.phys()->groups(); if (!gd) return; sDevInst *di = 0; if (EV()->CurrentWin()->Mode() == Electrical) { if (EV()->CurrentWin()->CurCellDesc(Electrical) != cbin.elec()) return; // showing symbolic if (cbin.elec()) { CDg gdesc; gdesc.init_gen(cbin.elec(), CellLayer(), AOI); CDc *cdesc; while ((cdesc = (CDc*)gdesc.next()) != 0) { if (cdesc->isDevice()) { // If cdesc is vectorized, match just the 0'th // element. di = gd->find_dual_dev(cdesc, 0); if (di) break; } } } } else { sDevInstList *dv = gd->find_dev(0, 0, 0, AOI); if (dv) { // Choose the smaller device, or the one where the AOI is // closer to a contact. double area, cxd; measure(dv->dev, AOI, &area, &cxd); di = dv->dev; for (sDevInstList *d = dv->next; d; d = d->next) { double a, c; measure(d->dev, AOI, &a, &c); if (a < .75 * area) { area = a; cxd = c; di = d->dev; } else if (a < 1.25 * area && c < .75 * cxd) { area = a; cxd = c; di = d->dev; } } } sDevInstList::destroy(dv); } if (di) { EX()->queueDevice(di); if (EX()->isDevselCompute()) { char *s; bool ret = di->net_line(&s, di->desc()->netline1(), PSPM_physical); if (s && *s) { char buf[32]; sLstr lstr; lstr.add(s); lstr.add(" ("); int cnt = di->count_sections(); if (cnt > 1) { sprintf(buf, "%d sects, ", cnt); lstr.add(buf); } for (sDevContactInst *c = di->contacts(); c; c = c->next()) { lstr.add(Tstring(c->cont_name())); lstr.add_c(':'); sprintf(buf, "%d", c->group()); lstr.add(buf); lstr.add_c(c->next() ? ' ' : ')'); } PL()->ShowPrompt(lstr.string()); } else { if (ret) PL()->ShowPromptV( "Found instance of %s, no print format specified", di->desc()->name()); else PL()->ShowPrompt( "Exception occurred, operation aborted."); } delete [] s; } if (EX()->isDevselCompare()) { char buf[256]; if (di->dual()) { if (EV()->Cursor().get_downstate() & GR_SHIFT_MASK) { if (cbin.elec()) { ED()->ulListCheck("exset", cbin.elec(), false); di->set_properties(); ED()->ulCommitChanges(); } } sLstr lstr; char *instname = di->dual()->instance_name(); sprintf(buf, "Device %s %d --- %s (%s)\n", TstringNN(di->desc()->name()), di->index(), instname, TstringNN(di->dual()->cdesc()->cellname())); delete [] instname; lstr.add(buf); lstr.add("Parameters:\n"); di->print_compare(&lstr, 0, 0); DSPmainWbag(PopUpInfo(MODE_ON, lstr.string())) } else { sprintf(buf, "Device %s %d is not associated.", TstringNN(di->desc()->name()), di->index()); DSPmainWbag(PopUpInfo(MODE_ON, buf)) } } return; } if (EX()->isDevselCompute() || EX()->isDevselCompare()) PL()->ShowPrompt("No device found."); } //------------------------------------------------------------------------- // These implement a blinking selection capability for devices. //------------------------------------------------------------------------- // If command is active, abort. // void cExt::clearDeviceSelection() { if (DvselCmd) DvselCmd->halt(); } // Set a single selected device, and erase any previous device // selections. The selected device is shown blinking. // void cExt::queueDevice(sDevInst *di) { sDevInstList *dv = di ? new sDevInstList(di, 0) : 0; queueDevices(dv); sDevInstList::destroy(dv); } // Select the devices in the list passed, and erase any previous // selections. The selected devices are shown blinking. // void cExt::queueDevices(sDevInstList *dv) { if (ext_selected_devices) { sDevInstList *tdv = ext_selected_devices; ext_selected_devices = 0; for (sDevInstList *d = tdv; d; d = d->next) { WindowDesc *wd; WDgen wgen(WDgen::MAIN, WDgen::CDDB); while ((wd = wgen.next()) != 0) { BBox BB(CDnullBB); d->dev->show(wd, &BB); wd->Redisplay(&BB); } } sDevInstList::destroy(tdv); } sDevInstList *de = 0; for (sDevInstList *d = dv; d; d = d->next) { if (!ext_selected_devices) ext_selected_devices = de = new sDevInstList(d->dev, 0); else { de->next = new sDevInstList(d->dev, 0); de = de->next; } } } // Called from the color timer to display the selected devices // void cExt::showSelectedDevices(WindowDesc *wd) { if (!wd->Wdraw()) return; if (ext_selected_devices) { wd->Wdraw()->SetColor(DSP()->SelectPixel()); for (sDevInstList *d = ext_selected_devices; d; d = d->next) d->dev->show(wd); wd->Wdraw()->SetColor(dsp_prm(LT()->CurLayer())->pixel()); } } //------------------------------------------------------------------------- // Command to draw a highlighting box, while the electrical // parameters are measured and reported for the box dimensions. //------------------------------------------------------------------------- namespace { namespace ext_devsel { struct MeasState : public CmdState { friend bool cExt::measureLayerElectrical(GRobject); friend void cExt::paintMeasureBox(); MeasState(const char*, const char*); virtual ~MeasState(); void setCaller(GRobject c) { Caller = c; } const BBox *active_box() { return (BBactive ? &BBarea : 0); } private: void b1down(); void b1up(); void esc(); bool key(int, const char*, int); void undo(); void redo(); bool paint_box(); void SetLevel1() { Level = 1; } void SetLevel2() { Level = 2; } GRobject Caller; int State; int Refx, Refy; BBox BBarea; bool BBactive; }; MeasState *MeasCmd; } } bool cExt::measureLayerElectrical(GRobject caller) { if (MeasCmd) { if (!caller || !Menu()->GetStatus(caller)) MeasCmd->esc(); return (true); } else if (caller && !Menu()->GetStatus(caller)) return (true); if (!XM()->CheckCurCell(false, true, Physical)) return (false); EV()->InitCallback(); MeasCmd = new MeasState("LYRMEAS", "xic:dvsel"); MeasCmd->setCaller(caller); Ulist()->ListCheck(MeasCmd->StateName, CurCell(Physical), false); if (!EV()->PushCallback(MeasCmd)) { delete MeasCmd; return (false); } PL()->ShowPrompt( "Click/drag to define box for measurement, press 'p' fo paint box."); return (true); } MeasState::MeasState(const char *nm, const char *hk) : CmdState(nm, hk) { Caller = 0; State = 0; Refx = Refy = 0; BBactive = false; SetLevel1(); } MeasState::~MeasState() { MeasCmd = 0; if (BBactive) DSPmainWbag(PopUpInfo(MODE_OFF, 0)) } // Anchor corner of box and start ghosting. // void MeasState::b1down() { if (Level == 1) { EV()->Cursor().get_xy(&Refx, &Refy); State = 1; XM()->SetCoordMode(CO_RELATIVE, Refx, Refy); Gst()->SetGhostAt(GFmeasbox, Refx, Refy); DSP()->MainWdesc()->SetAccumMode(WDaccumStart); EV()->DownTimer(GFmeasbox); } else { State = 3; Gst()->SetGhost(GFnone); DSP()->MainWdesc()->GhostFinalUpdate(); int x, y; EV()->Cursor().get_xy(&x, &y); EX()->showElectrical(abs(x - Refx), abs(y - Refy)); EX()->showMeasureBox(0, ERASE); BBarea = BBox(x, y, Refx, Refy); BBarea.fix(); BBactive = true; EX()->showMeasureBox(0, DISPLAY); XM()->SetCoordMode(CO_ABSOLUTE); EX()->PopUpDevices(0, MODE_UPD); } } void MeasState::b1up() { if (Level == 1) { if (EV()->Cursor().is_release_ok() && EV()->CurrentWin()) { EX()->queueDevice(0); if (!EV()->UpTimer()) { int x, y; EV()->Cursor().get_release(&x, &y); EV()->CurrentWin()->Snap(&x, &y); if (x != Refx || y != Refy) { Gst()->SetGhost(GFnone); DSP()->MainWdesc()->GhostFinalUpdate(); EX()->showElectrical(abs(x - Refx), abs(y - Refy)); EX()->showMeasureBox(0, ERASE); BBarea = BBox(x, y, Refx, Refy); BBarea.fix(); BBactive = true; EX()->showMeasureBox(0, DISPLAY); XM()->SetCoordMode(CO_ABSOLUTE); EX()->PopUpDevices(0, MODE_UPD); return; } } SetLevel2(); return; } } else { // If a box was defined, reset the state for the next box. // if (State == 3) { State = 2; SetLevel1(); } } } // Esc entered, clean up and abort. // void MeasState::esc() { EX()->showMeasureBox(0, ERASE); Gst()->SetGhost(GFnone); DSP()->MainWdesc()->GhostFinalUpdate(); XM()->SetCoordMode(CO_ABSOLUTE); PL()->ErasePrompt(); EV()->PopCallback(this); Menu()->Deselect(Caller); EX()->PopUpDevices(0, MODE_UPD); delete this; } // Handle entering 'p' to paint measure box with current layer. // bool MeasState::key(int, const char *text, int) { if (text && *text) { if (*text == 'p') { if (BBactive) { if (!paint_box()) PL()->ShowPrompt("Painting operation failed!"); } else PL()->ShowPrompt("No measure box to paint!"); return (true); } } return (false); } void MeasState::undo() { if (Level != 1) { // Undo the corner anchor. // Gst()->SetGhost(GFnone); DSP()->MainWdesc()->GhostFinalUpdate(); XM()->SetCoordMode(CO_ABSOLUTE); if (State == 2) State = 3; SetLevel1(); } else ED()->ulUndoOperation(); } // Redo undone corner anchor or operation. // void MeasState::redo() { if (Level == 1) { if (State == 1 || State == 3) { XM()->SetCoordMode(CO_RELATIVE, Refx, Refy); Gst()->SetGhostAt(GFmeasbox, Refx, Refy); DSP()->MainWdesc()->SetAccumMode(WDaccumStart); State = 2; SetLevel2(); } else ED()->ulRedoOperation(); } else if (State == 2) { Gst()->SetGhost(GFnone); DSP()->MainWdesc()->GhostFinalUpdate(); XM()->SetCoordMode(CO_ABSOLUTE); ED()->ulRedoOperation(); SetLevel1(); } } // Actually create the box. Returns true on success. // bool MeasState::paint_box() { if (!BBactive) return (false); CDs *cursd = CurCell(Physical); if (!cursd) return (false); CDl *ld = LT()->CurLayer(); if (!ld) return (false); if (BBarea.width() == 0 || BBarea.height() == 0) return (false); CDo *newbox = cursd->newBox(0, &BBarea, ld, 0); if (!newbox) { Errs()->add_error("newBox failed"); Log()->ErrorLog(mh::ObjectCreation, Errs()->get_error()); return (false); } if (!cursd->mergeBoxOrPoly(newbox, true)) { Errs()->add_error("mergeBoxOrPoly failed"); Log()->ErrorLog(mh::ObjectCreation, Errs()->get_error()); } Ulist()->CommitChanges(true); return (true); } // End of MeasState functions. void cExt::paintMeasureBox() { if (MeasCmd && MeasCmd->active_box()) MeasCmd->paint_box(); } // Pop of an Info window showing the electrical parameters of the // current layer applied to the passed rectangle. // void cExt::showElectrical(int width, int height) { CDl *ld = LT()->CurLayer(); if (!ld) { DSPmainWbag(PopUpInfo(MODE_ON, "No current layer!")) return; } double wid = MICRONS(abs(width)); double hei = MICRONS(abs(height)); if (wid <= 0 || hei <= 0) { DSPmainWbag(PopUpInfo(MODE_ON, "Measure box has zero width or height!")) return; } sLstr lstr; lstr.add("Layer: "); lstr.add(ld->name()); lstr.add_c('\n'); char tbuf[256]; bool found = false; double rsh = cTech::GetLayerRsh(ld); if (rsh > 0.0) { sprintf(tbuf, "Resistance: %g (L to R), %g (B to T)\n", rsh*wid/hei, rsh*hei/wid); lstr.add(tbuf); found = true; } double cpa = tech_prm(ld)->cap_per_area(); double cpp = tech_prm(ld)->cap_per_perim(); if (cpa > 0.0 || cpp > 0.0) { sprintf(tbuf, "Capacitance: %g\n", cpa*wid*hei + cpp*2.0*(wid+hei)); lstr.add(tbuf); found = true; } double params[8]; if (cTech::GetLayerTline(ld, params)) { // filled in: // params[0] = linethick(); // params[1] = linepenet(); // params[2] = gndthick(); // params[3] = gndpenet(); // params[4] = dielthick(); // params[5] = dielconst(); char c; double o[4]; if (wid > hei) { params[6] = hei; params[7] = wid; c = 'X'; } else { params[6] = wid; params[7] = hei; c = 'Y'; } sline(params, o); sprintf(tbuf, "Along %c: L=%g C=%g Z=%g T=%g\n", c, o[0], o[1], o[2], o[3]); lstr.add(tbuf); found = true; } if (!found) lstr.add("No resistance, capacitance, or transmission line\n" "parameters defined for layer.\n"); DSPmainWbag(PopUpInfo(MODE_ON, lstr.string())) } // Display measure area highlighting box. // void cExt::showMeasureBox(WindowDesc *wdesc, bool d_or_e) { if (!MeasCmd || !MeasCmd->active_box()) return; if (!wdesc) { WDgen wgen(WDgen::MAIN, WDgen::CDDB); while ((wdesc = wgen.next()) != 0) showMeasureBox(wdesc, d_or_e); return; } if (!wdesc->Wdraw()) return; if (!wdesc->IsSimilar(Physical, DSP()->MainWdesc())) return; if (dspPkgIf()->IsDualPlane()) wdesc->Wdraw()->SetXOR(d_or_e ? GRxHlite : GRxUnhlite); else { if (d_or_e) wdesc->Wdraw()->SetColor( DSP()->Color(HighlightingColor, Physical)); else { wdesc->Redisplay(MeasCmd->active_box()); return; } } const BBox *BB = MeasCmd->active_box(); wdesc->ShowLineW(BB->left, BB->bottom, BB->left, BB->top); wdesc->ShowLineW(BB->left, BB->top, BB->right, BB->top); wdesc->ShowLineW(BB->right, BB->top, BB->right, BB->bottom); wdesc->ShowLineW(BB->right, BB->bottom, BB->left, BB->bottom); if (dspPkgIf()->IsDualPlane()) wdesc->Wdraw()->SetXOR(GRxNone); else if (LT()->CurLayer()) wdesc->Wdraw()->SetColor(dsp_prm(LT()->CurLayer())->pixel()); } // Function to show the measurement results on-screen. // void cExtGhost::showGhostMeasure(int map_x, int map_y, int ref_x, int ref_y, bool erase) { CDl *ld = LT()->CurLayer(); if (!ld) return; double wid = MICRONS(abs(map_x - ref_x)); double hei = MICRONS(abs(map_y - ref_y)); if (wid <= 0 || hei <= 0) return; sLstr lstr; char tbuf[256]; double rsh = cTech::GetLayerRsh(ld); if (rsh > 0.0) { sprintf(tbuf, "Resistance: %g (L to R), %g (B to T) ", rsh*wid/hei, rsh*hei/wid); lstr.add(tbuf); } double cpa = tech_prm(ld)->cap_per_area(); double cpp = tech_prm(ld)->cap_per_perim(); if (cpa > 0.0 || cpp > 0.0) { sprintf(tbuf, "Capacitance: %g ", cpa*wid*hei + cpp*2.0*(wid+hei)); lstr.add(tbuf); } double params[8]; if (cTech::GetLayerTline(ld, params)) { // filled in: // params[0] = linethick(); // params[1] = linepenet(); // params[2] = gndthick(); // params[3] = gndpenet(); // params[4] = dielthick(); // params[5] = dielconst(); char c; double o[4]; if (wid > hei) { params[6] = hei; params[7] = wid; c = 'X'; } else { params[6] = wid; params[7] = hei; c = 'Y'; } sline(params, o); sprintf(tbuf, "Tline along %c: L=%g C=%g Z=%g T=%g", c, o[0], o[1], o[2], o[3]); lstr.add(tbuf); } if (lstr.string() && *lstr.string()) { int x = 4; int y = DSP()->MainWdesc()->ViewportHeight() - 5; if (erase) { int w = 0, h = 0; DSPmainDraw(TextExtent(lstr.string(), &w, &h)) BBox BB(x, y, x + w, y - h); DSP()->MainWdesc()->GhostUpdate(&BB); } else DSPmainDraw(Text(lstr.string(), x, y, 0, 1, 1)); } }
8290345ed8ca54e466409eed87b55b1686761d56
2e52538ad6fe2625da4380c78b3e5e9874e13536
/Project1/CIS22A_EC1_WartDaniel.cpp
1dd2cfcb70b161385d651fa1a096882d26fa2118
[]
no_license
onein50million/CIS22A
82c645782bad9d747250f103b1646e0520f26c03
65c8fdfb7d5640ea02c9c8e0160f95cf52ccb92f
refs/heads/master
2021-01-19T21:37:38.523441
2017-06-23T07:00:11
2017-06-23T07:00:11
88,678,718
0
0
null
null
null
null
UTF-8
C++
false
false
992
cpp
CIS22A_EC1_WartDaniel.cpp
/* Daniel Wart CIS 22A Spring 2017 EC1 - Extra Credit Simple Calculator */ #include <iostream> #include <string> #include <cmath> int calculate(char op, int num1, int num2){ switch (op){ case '+': return num1 + num2; case '-': return num1 - num2; case '/': return num1 / num2; case '*': return num1 * num2; case '%': return num1 % num2; case '^': return std::pow(num1, num2); default: return 0; } } int main(){ int number1, number2; char calcOperator; std::string input; std::cout << "Enter operator as + - / * % ^\n"; std::getline(std::cin, input); calcOperator = input.at(0); //getline returns a string so we need to get the first character std::cout << "First Integer: "; std::getline(std::cin, input); number1 = stoi(input); std::cout << "Second Integer: "; std::getline(std::cin, input); number2 = stoi(input); std::cout << "Result: " << calculate(calcOperator, number1, number2) << "\n"; std::cout << "Hit <Enter> to quit"; std::cin.get(); return 0; }
0397ab3680e2ce76eec15179455181981203d59e
eb77b7e6744e7380db2b4835a0faeddca479619b
/ops/c/src/sycl/ops_sycl_rt_support_kernels.cpp
78ae5e75cfb049c454221a59ca6685f9f74af728
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
OP-DSL/OPS
b4fea672de28973acc9a1ae611fd4fd475d04dd9
73d0dd431ea70be98b27f49275c43840fd3073ca
refs/heads/develop
2023-08-16T23:05:22.584318
2023-08-14T22:37:16
2023-08-15T11:26:12
16,912,507
44
34
NOASSERTION
2023-09-10T18:40:12
2014-02-17T12:44:34
C++
UTF-8
C++
false
false
13,859
cpp
ops_sycl_rt_support_kernels.cpp
/* * Open source copyright declaration based on BSD open source template: * http://www.opensource.org/licenses/bsd-license.php * * This file is part of the OPS distribution. * * Copyright (c) 2013, Mike Giles and others. Please see the AUTHORS file in * the main source directory for a full list of copyright holders. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * The name of Mike Giles may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY Mike Giles ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL Mike Giles BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** @file * @brief OPS cuda specific runtime support functions * @author Gihan Mudalige * @details Implements cuda backend runtime support functions */ // // header files // #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ops_device_rt_support.h> #include <ops_sycl_rt_support.h> #include <ops_lib_core.h> void ops_halo_copy_tobuf(char *dest, int dest_offset, ops_dat src, int rx_s, int rx_e, int ry_s, int ry_e, int rz_s, int rz_e, int x_step, int y_step, int z_step, int buf_strides_x, int buf_strides_y, int buf_strides_z) { ops_block block = src->block; // dest += dest_offset; <- a kernelen belül kell int thr_x = abs(rx_s - rx_e); int blk_x = 1; if (abs(rx_s - rx_e) > 8) { blk_x = (thr_x - 1) / 8 + 1; thr_x = 8; } int thr_y = abs(ry_s - ry_e); int blk_y = 1; if (abs(ry_s - ry_e) > 8) { blk_y = (thr_y - 1) / 8 + 1; thr_y = 8; } int thr_z = abs(rz_s - rz_e); int blk_z = 1; if (abs(rz_s - rz_e) > 8) { blk_z = (thr_z - 1) / 8 + 1; thr_z = 8; } //dim3 grid(blk_x, blk_y, blk_z); //dim3 tblock(thr_x, thr_y, thr_z); int size_x = src->size[0]; int size_y = src->size[1]; int size_z = src->size[2]; int type_size = src->type_size; int dim = src->dim; int OPS_soa = block->instance->OPS_soa; char *src_buff = src->data_d; block->instance->sycl_instance->queue->submit([&](cl::sycl::handler &cgh) { //Queue->Submit //nd_range elso argumentume a teljes méret, nem a blokkok száma: https://docs.oneapi.com/versions/latest/dpcpp/iface/nd_range.html cgh.parallel_for<class copy_tobuf>(cl::sycl::nd_range<3>(cl::sycl::range<3>(blk_z*thr_z,blk_y*thr_y,blk_x*thr_x),cl::sycl::range<3>(thr_z,thr_y,thr_x)), [=](cl::sycl::nd_item<3> item) { //get x dimension id cl::sycl::cl_int global_x_id = item.get_global_id()[2]; //get y dimension id cl::sycl::cl_int global_y_id = item.get_global_id()[1]; //get z dimension id cl::sycl::cl_int global_z_id = item.get_global_id()[0]; cl::sycl::cl_int d_offset = dest_offset; cl::sycl::cl_int s_offset = 0; int idx_z = rz_s + z_step * global_z_id; int idx_y = ry_s + y_step * global_y_id; int idx_x = rx_s + x_step * global_x_id; if ((x_step == 1 ? idx_x < rx_e : idx_x > rx_e) && (y_step == 1 ? idx_y < ry_e : idx_y > ry_e) && (z_step == 1 ? idx_z < rz_e : idx_z > rz_e)) { if (OPS_soa) s_offset += (idx_z * size_x * size_y + idx_y * size_x + idx_x) * type_size; else s_offset += (idx_z * size_x * size_y + idx_y * size_x + idx_x) * type_size * dim; d_offset += ((idx_z - rz_s) * z_step * buf_strides_z + (idx_y - ry_s) * y_step * buf_strides_y + (idx_x - rx_s) * x_step * buf_strides_x) * type_size * dim; for (int d = 0; d < dim; d++) { memcpy(&dest[d_offset + d*type_size], &src_buff[s_offset], type_size); if (OPS_soa) s_offset += size_x * size_y * size_z * type_size; else s_offset += type_size; } } }); }); } void ops_halo_copy_frombuf(ops_dat dest, char *src, int src_offset, int rx_s, int rx_e, int ry_s, int ry_e, int rz_s, int rz_e, int x_step, int y_step, int z_step, int buf_strides_x, int buf_strides_y, int buf_strides_z) { ops_block block = dest->block; // src += src_offset; int thr_x = abs(rx_s - rx_e); int blk_x = 1; if (abs(rx_s - rx_e) > 8) { blk_x = (thr_x - 1) / 8 + 1; thr_x = 8; } int thr_y = abs(ry_s - ry_e); int blk_y = 1; if (abs(ry_s - ry_e) > 8) { blk_y = (thr_y - 1) / 8 + 1; thr_y = 8; } int thr_z = abs(rz_s - rz_e); int blk_z = 1; if (abs(rz_s - rz_e) > 8) { blk_z = (thr_z - 1) / 8 + 1; thr_z = 8; } int size_x = dest->size[0]; int size_y = dest->size[1]; int size_z = dest->size[2]; int type_size = dest->type_size; int dim = dest->dim; int OPS_soa = block->instance->OPS_soa; char* dest_buff = dest->data_d; block->instance->sycl_instance->queue->submit([&](cl::sycl::handler &cgh) { //Accessors cgh.parallel_for<class copy_frombuf1>(cl::sycl::nd_range<3>(cl::sycl::range<3>(blk_z*thr_z,blk_y*thr_y,blk_x*thr_x),cl::sycl::range<3>(thr_z,thr_y,thr_x)), [=](cl::sycl::nd_item<3> item) { //get x dimension id cl::sycl::cl_int global_x_id = item.get_global_id()[2]; //get y dimension id cl::sycl::cl_int global_y_id = item.get_global_id()[1]; //get z dimension id cl::sycl::cl_int global_z_id = item.get_global_id()[0]; cl::sycl::cl_int d_offset = 0; cl::sycl::cl_int s_offset = src_offset; int idx_z = rz_s + z_step * global_z_id; int idx_y = ry_s + y_step * global_y_id; int idx_x = rx_s + x_step * global_x_id; if ((x_step == 1 ? idx_x < rx_e : idx_x > rx_e) && (y_step == 1 ? idx_y < ry_e : idx_y > ry_e) && (z_step == 1 ? idx_z < rz_e : idx_z > rz_e)) { if (OPS_soa) d_offset += (idx_z * size_x * size_y + idx_y * size_x + idx_x) * type_size; else d_offset += (idx_z * size_x * size_y + idx_y * size_x + idx_x) * type_size * dim; s_offset += ((idx_z - rz_s) * z_step * buf_strides_z + (idx_y - ry_s) * y_step * buf_strides_y + (idx_x - rx_s) * x_step * buf_strides_x) * type_size * dim; for (int d = 0; d < dim; d++) { memcpy(&dest_buff[d_offset], &src[s_offset + d*type_size], type_size); if (OPS_soa) d_offset += size_x * size_y * size_z * type_size; else d_offset += type_size; } } }); }); dest->dirty_hd = 2; } template <int dir> void ops_internal_copy_device_kernel(char * dat0_p, char *dat1_p, int s0, int s01, int start0, int end0, #if OPS_MAX_DIM>1 int s1, int s11, int start1, int end1, #if OPS_MAX_DIM>2 int s2, int s21, int start2, int end2, #if OPS_MAX_DIM>3 int s3, int s31, int start3, int end3, #if OPS_MAX_DIM>4 int s4, int s41, int start4, int end4, #endif #endif #endif #endif int dim, int type_size, int OPS_soa, cl::sycl::nd_item<3> item) { int i = start0 + item.get_global_id()[2]; int j = start1 + item.get_global_id()[1]; int rest = item.get_global_id()[0]; int mult = OPS_soa ? type_size : dim*type_size; long fullsize = s0; long fullsize1 = s01; long idx = i*mult; long idx1 = i*mult; #if OPS_MAX_DIM>1 fullsize *= s1; fullsize1 *= s11; idx += j * s0 * mult; idx1 += j * s01 * mult; #endif #if OPS_MAX_DIM>2 fullsize *= s2; fullsize1 *= s21; const int sz2 = end2-start2; int nextSize = rest / sz2; int k = start2+rest - nextSize*sz2; rest = nextSize; idx += k * s0 * s1 * mult; idx1 += k * s01 * s11 * mult; #endif #if OPS_MAX_DIM>3 fullsize *= s3; fullsize1 *= s31; const int sz3 = end3-start3; nextSize = rest / sz3; int l = start3 + rest - nextSize*sz3; rest = nextSize; idx += l * s0 * s1 * s2 * mult; idx1 += l * s01 * s11 * s21 * mult; #endif #if OPS_MAX_DIM>4 fullsize *= s4; fullsize1 *= s41; const int sz4 = end4-start4; nextSize = rest / sz4; int m = start4 + rest - nextSize*sz4; idx += m * s0 * s1 * s2 * s3 * mult; idx1 += m * s01 * s11 * s21 * s31 * mult; #endif if (i<end0 #if OPS_MAX_DIM>1 && j < end1 #if OPS_MAX_DIM>2 && k < end2 #if OPS_MAX_DIM>3 && l < end3 #if OPS_MAX_DIM>4 && m < end4 #endif #endif #endif #endif ) { if (OPS_soa) { for (int d = 0; d < dim; d++) for (int c = 0; c < type_size; c++) { if (dir == 0) dat1_p[idx1+d*fullsize1*type_size+c] = dat0_p[idx+d*fullsize*type_size+c]; else dat0_p[idx+d*fullsize*type_size+c] = dat1_p[idx1+d*fullsize1*type_size+c]; } } else { for (int d = 0; d < dim*type_size; d++) { if (dir == 0) dat1_p[idx1+d] = dat0_p[idx+d]; else dat0_p[idx+d] = dat1_p[idx1+d]; } } } } void ops_internal_copy_device(ops_kernel_descriptor *desc) { int reverse = strcmp(desc->name, "ops_internal_copy_device_reverse")==0; int range[2*OPS_MAX_DIM]={0}; for (int d = 0; d < desc->dim; d++) { range[2*d] = desc->range[2*d]; range[2*d+1] = desc->range[2*d+1]; } for (int d = desc->dim; d < OPS_MAX_DIM; d++) { range[2*d] = 0; range[2*d+1] = 1; } ops_dat dat0 = desc->args[0].dat; ops_dat dat1 = desc->args[1].dat; double __t1=0.0,__t2=0.0,__c1,__c2; if (dat0->block->instance->OPS_diags>1) { dat0->block->instance->OPS_kernels[-1].count++; ops_timers_core(&__c1,&__t1); } char *dat0_p = desc->args[0].data_d + desc->args[0].dat->base_offset; char *dat1_p = desc->args[1].data_d + desc->args[1].dat->base_offset; int s0 = dat0->size[0]; int s01 = dat1->size[0]; #if OPS_MAX_DIM>1 int s1 = dat0->size[1]; int s11 = dat1->size[1]; #if OPS_MAX_DIM>2 int s2 = dat0->size[2]; int s21 = dat1->size[2]; #if OPS_MAX_DIM>3 int s3 = dat0->size[3]; int s31 = dat1->size[3]; #if OPS_MAX_DIM>4 int s4 = dat0->size[4]; int s41 = dat1->size[4]; #endif #endif #endif #endif int dim = dat0->dim; int type_size = dat0->type_size; int OPS_soa = dat0->block->instance->OPS_soa; int blk_x = (range[2*0+1]-range[2*0] - 1) / dat0->block->instance->OPS_block_size_x + 1; int blk_y = (range[2*1+1]-range[2*1] - 1) / dat0->block->instance->OPS_block_size_y + 1; int blk_z = ((range[2*2+1]-range[2*2] - 1) / dat0->block->instance->OPS_block_size_z + 1) * (range[2*3+1]-range[2*3]) * (range[2*4+1]-range[2*4]); int thr_x = dat0->block->instance->OPS_block_size_x; int thr_y = dat0->block->instance->OPS_block_size_y; int thr_z = dat0->block->instance->OPS_block_size_z; if (blk_x>0 && blk_y>0 && blk_z>0) { if (reverse) dat0->block->instance->sycl_instance->queue->submit([&](cl::sycl::handler &cgh) { cgh.parallel_for<class copy_frombuf2>(cl::sycl::nd_range<3>(cl::sycl::range<3>(blk_z*thr_z,blk_y*thr_y,blk_x*thr_x),cl::sycl::range<3>(thr_z,thr_y,thr_x)), [=](cl::sycl::nd_item<3> item) { ops_internal_copy_device_kernel<1>( dat0_p, dat1_p, s0,s01, range[2*0], range[2*0+1], #if OPS_MAX_DIM>1 s1,s11, range[2*1], range[2*1+1], #if OPS_MAX_DIM>2 s2,s21, range[2*2], range[2*2+1], #if OPS_MAX_DIM>3 s3,s31, range[2*3], range[2*3+1], #if OPS_MAX_DIM>4 s4,s41, range[2*4], range[2*4+1], #endif #endif #endif #endif dim, type_size, OPS_soa, item); }); }); else dat0->block->instance->sycl_instance->queue->submit([&](cl::sycl::handler &cgh) { cgh.parallel_for<class copy_frombuf3>(cl::sycl::nd_range<3>(cl::sycl::range<3>(blk_z*thr_z,blk_y*thr_y,blk_x*thr_x),cl::sycl::range<3>(thr_z,thr_y,thr_x)), [=](cl::sycl::nd_item<3> item) { ops_internal_copy_device_kernel<0>( dat0_p, dat1_p, s0,s01, range[2*0], range[2*0+1], #if OPS_MAX_DIM>1 s1,s11, range[2*1], range[2*1+1], #if OPS_MAX_DIM>2 s2,s21, range[2*2], range[2*2+1], #if OPS_MAX_DIM>3 s3,s31, range[2*3], range[2*3+1], #if OPS_MAX_DIM>4 s4,s41, range[2*4], range[2*4+1], #endif #endif #endif #endif dim, type_size, OPS_soa, item );});}); } if (dat0->block->instance->OPS_diags>1) { ops_device_sync(dat0->block->instance); ops_timers_core(&__c2,&__t2); int start[OPS_MAX_DIM]; int end[OPS_MAX_DIM]; for ( int n=0; n<desc->dim; n++ ){ start[n] = range[2*n];end[n] = range[2*n+1]; } dat0->block->instance->OPS_kernels[-1].time += __t2-__t1; dat0->block->instance->OPS_kernels[-1].transfer += ops_compute_transfer(desc->dim, start, end, &desc->args[0]); dat0->block->instance->OPS_kernels[-1].transfer += ops_compute_transfer(desc->dim, start, end, &desc->args[1]); } }
4de9e603f354bef36556f0064d1df31d27916c63
9c0e056baca0c09b137c7e551e46460f55903085
/cycle 3/addate.cpp
75f233b7e3a006dcf5aa642722468dd597d5675d
[]
no_license
hana-2000/LAB
1f969408ae6747d9a6dc03c0f26e953cbf333abc
72f4bef1b3dd3d6b8c84ee13fa8a4fa55f9d88fc
refs/heads/main
2023-08-18T19:24:05.323966
2021-09-28T07:16:45
2021-09-28T07:16:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,006
cpp
addate.cpp
#include <iostream> using namespace std; class dates { int day,month,year,last; int mon[12]={31,28,31,30,31,30,31,31,30,31,30,31}; public: int key; dates(){} dates(int d,int m,int y){ day=d; month=m; year=y; } void outPut(); dates operator +(dates d); void Month(); void Day(); int valid(); }; void dates::outPut() { cout<< "Result is = "<<day<<"/"<<month<<"/"<<year<<endl; } void dates::Month() { if (month > 0 && month <= 12) { if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) { last = 31; Day(); } else if (month == 4 || month == 6 || month == 9 || month == 11) { last = 30; Day(); } else if (month == 2) { if ((year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0)) { last = 29; Day(); } else { last = 28; Day(); } } } else cout << "Invalid Date"; } void dates::Day() { if (day > 0 && day <= last) { valid(); } else cout << "Invalid Date"; } int dates::valid() { return key=1; } dates dates::operator+(dates d){ dates m; int i; m.day= day+d.day; i=month-1; m.month=0; m.year=year; if(i==1){ if ((m.year % 4 == 0) && (m.year % 100 != 0) || (m.year % 400 == 0)) { mon[1] = 29; } } if((m.day-mon[i])>0){ while((m.day-mon[i])>0){ if ((m.year % 4 == 0) && (m.year % 100 != 0) || (m.year % 400 == 0)) { mon[1] = 29; } m.day=m.day-mon[i]; month++; i++; if((month-1)%12==0) {i=0; m.year++; } } if(month>12) { if (month%12==0) m.month=12; else m.month=month%12; }else m.month=month; i++; }else{ m.month=month; m.year=year; } return m; } int main() { int d,m,y,n; cout<<"Enter the date :\n"; cin>>d>>m>>y; cout<<"Enter the day to be added \n"; cin>>n; dates d1(d,m,y),d2(n,0,0),d3; d1.Month(); if(d1.key==1){ d3 = d1+d2; d3.outPut(); } return 0; }
e23e3168aae992cef7e8baef649510005b3a33c5
0dd103b765a1ffa795203cfa74f7aa4eae18a785
/AiSD/Drzewa/main.cpp
5051cb16e26820c762de444a5b086f241c8d58b0
[]
no_license
JedrzejKuczynski/Studia2015-2018
44e1a97fadbc4f16e521b74cfebe1aedec60c358
c6cf6b07d571e297219e6fdde6396b1125ff9ef0
refs/heads/master
2022-02-22T22:01:31.981257
2019-10-17T09:12:11
2019-10-17T09:12:11
85,435,302
0
0
null
null
null
null
UTF-8
C++
false
false
3,092
cpp
main.cpp
#include <iostream> #include <cstdlib> #include <ctime> using namespace std; struct lista{ int wartosc; lista *next; lista *prev; }; lista *l_head = NULL; lista *l_ost = NULL; void insertion_sort(int tab[], int rozmiar){ int tmp; for(int i = 1; i < rozmiar; i++){ while(i > 0 && tab[i - 1] > tab[i]){ tmp = tab[i]; tab[i] = tab[i - 1]; tab[i - 1] = tmp; i--; } } } void sortuj_l(){ } void l_tworz(int tab[], int rozmiar){ int i = 0; while(i < rozmiar){ if(l_head == NULL){ l_head = new lista; l_head->next = NULL; l_head->prev = NULL; l_head->wartosc = tab[i]; l_ost = l_head; i++; }else{ lista *l = new lista; l_ost->next = l; l->prev = l_ost; l->next = NULL; l->wartosc = tab[i]; l_ost = l; i++; } } } bool powt(int tab[], int wartosc, int rozmiar) { for(int i = 0; i < rozmiar; i++) { if(tab[i] == wartosc) return false; } return true; } void wyswietl_t(int tab[], int rozmiar){ for(int i = 0; i < rozmiar; i++){ cout << tab[i] << " "; } cout << endl; } void wyswietl_l(int rozmiar){ lista *tmp = l_head; cout << endl; if(tmp == NULL){ cout << "Brak elementow" << endl; }else{ while(tmp != NULL){ cout << tmp->wartosc << " "; tmp = tmp->next; } } delete tmp; } void t_tab(int *tab, int rozmiar){ int wartosc; for(int i = 0; i < rozmiar; i++){ wartosc = rand() % 100000; if(powt(tab, wartosc, rozmiar)) tab[i] = wartosc; } } void wyswietl_m(){ cout << "Stworz tablice - wcisnij 0" << endl; cout << "Stworz posortowana liste - wcisnij 1" << endl; cout << "Stworz drzewo BST - wcisnij 2" << endl; cout << "Stworz drzewo AVL - wcisnij 3" << endl; } int opcja(){ int wybor; while(1){ cout << endl << "Wybierz opcje " << endl; if(cin >> wybor){ cin.ignore(); break; } } return wybor; } int main(){ int *tab, rozmiar, menu; srand(time(NULL)); wyswietl_m(); while(1){ menu = opcja(); switch(menu){ case 0: cout << "Podaj rozmiar tablicy." << endl; cin >> rozmiar; tab = new int [rozmiar]; t_tab (tab, rozmiar); wyswietl_t(tab, rozmiar); break; case 1: //insertion_sort(tab, rozmiar); l_tworz(tab, rozmiar); sortuj_l(); wyswietl_l(rozmiar); break; } } return 0; }
ed167702f24b073ff6a09f2ceac4de0d388151aa
446a749d41af0008ba557dca6a62c0fbf8fed3ad
/URI/robot.cpp
f6ffe00b5c9cf11338443073b99f168cfcf3aa20
[]
no_license
Sirivasv/ProgrammingChallenges
b8910f869548491a81e5352f72295a6886cc150e
5d9039725b2947f392a179f75896b8a57b4537cb
refs/heads/master
2021-01-12T09:08:15.814557
2020-05-15T21:40:14
2020-05-15T21:40:14
76,768,160
0
0
null
2018-10-13T17:18:12
2016-12-18T07:02:21
C++
UTF-8
C++
false
false
1,612
cpp
robot.cpp
#include <bits/stdc++.h> using namespace std; const int MAXN = 105; char mtr[MAXN][MAXN]; char oris[] = {'N', 'L', 'S', 'O'}; int N, M, NS; bool Valid(int xi, int yi) { if (((xi >= 0 ) && (xi < M)) && ((yi >= 0 ) && (yi < N)) && (mtr[yi][xi] != '#')) return true; return false; } bool IsOr(char c) { for (int i = 0 ; i < 4; ++i) if (c == oris[i]) return true; return false; } int main() { while (cin >> N >> M >> NS) { if ((N + M + NS) == 0) break; int xi = 0, yi = 0, idori = 0; char curori; for (int i = 0; i < N; ++i) { for (int j = 0; j < M; ++j) { cin >> mtr[i][j]; if (IsOr(mtr[i][j])) { if (mtr[i][j] == 'N') idori = 0; else if (mtr[i][j] == 'L') idori = 1; else if (mtr[i][j] == 'S') idori = 2; else idori = 3; xi = j; yi = i; mtr[i][j] = '.'; } } } string s; cin >> s; int ans = 0; for (int i = 0; i < s.size(); ++i) { curori = oris[idori]; //cout << curori << ' ' << yi << ' ' << xi << '\n'; if (s[i] == 'D') { idori = (idori + 1) % 4; curori = oris[idori]; } else if (s[i] == 'F') { int nx = xi, ny = yi; if (curori == 'N') { ny = yi - 1; } else if(curori == 'S') { ny = yi + 1; } else if (curori == 'L') { nx = xi + 1; } else { nx = xi - 1; } if (!Valid(nx, ny)) continue; xi = nx; yi = ny; if (mtr[yi][xi] == '*') { ans++; mtr[yi][xi] = '.'; } } else { idori = (idori - 1 + 4) % 4; curori = oris[idori]; } } cout << ans << '\n'; } return 0; }
e02f8514f49c30aabfcf7eea8a03976a04a78e65
5613a9287a1cc6b460517f4368c9d15acb9f9c7e
/PH_Events.h
2a1cb3c569c64100213e7407452e8d829f4a501b
[ "MIT" ]
permissive
net234/ESPEEDOMUS
5d234ed64cd18fd69fda1eee93dff806dce36b4c
32ff94e79572f70836653731e60b426f042c28cf
refs/heads/master
2022-05-28T00:35:08.101587
2020-04-25T13:57:08
2020-04-25T13:57:08
258,780,686
0
0
null
2020-04-25T13:53:20
2020-04-25T13:20:18
C++
UTF-8
C++
false
false
4,690
h
PH_Events.h
/************************************************* ************************************************* PH_Events.h librairie pour les Events Pierre HENRY V1.3 P.henry 23/04/2020 Gestion d'evenement en boucle GetEvent HandleEvent V1.0 P.HENRY 24/02/2020 From scratch with arduino.cc totorial :) bug possible : si GetEvent n,est pas appelé au moins 1 fois durant 1 seconde on pert 1 seconde Ajout pulse LED de vie V1.1 P.HENRY 29/02/2020 passage du timestamp en read_only les events 100Hz et 10Hz sont non cumulatif & non prioritaire l'event 1HZ deviens cumulatif et prioritaire V1.2 P.Henry 09/03/2020 Version sans TimerOne Integration de freeram Integration de _stringComplete V1.2.1 P.Henry 10/03/2020 Ajout de pushEvent (un seul) todo: mettre plusieurs pushevent avec un delay V1.2.2 P.Henry 15/03/2020 Mise en public de timestamp time stamp (long) est destiné maintenir l'heure sur 24 Heures (0.. 86400L 0x15180) ajout du ev24H pour gerer les jours integration eventnill economie memoire pour inputString V1.3 P.Henry 14/04/2020 compatibilité avec les ESP ajout d'un buffer pour les push event avec un delay gestion du pushevent en 100' de seconde *************************************************/ #pragma once #include "Arduino.h" #define USE_SERIALEVENT // remove this if you need standard Serial.read //#define USE_TimerOne // remove this if you need TimerOne on your side (work only with AVR) //const int FrequenceTimer = 100; // frequence d'interuption en Hz #define MAX_WAITING_EVENT 10 // max event who can be pusshed at once #define MAX_WAITING_DELAYEVENT 10 // max delayed event // without timerone without Serial event // P:4836 R:305 N:225.500 // without timerone with Serial event // P:7866 R:383 N:136 400 // with timerone without Serial event // P:4760 R:300 N:288.500 // with timerone with serial event // P:7792 R:378 N:184 500 typedef enum { evNill = 0, // Rien (on sort d'un sleep) ev100Hz, // un tick 100HZ pas de cumul en cas de retard (le nombre de 100Hz passé est dans paramEvent) ev10Hz, // un tick 100Z pas de cumul en cas de retard (le nombre de 10Hz passé est dans paramEvent) ev1Hz, // un tick 1HZ il y aura un tick pour chaque seconde ev24H, // 24H depuis le boot (gerer le rolover de timestamp si necessaire) evDepassement1HZ, evInChar, evInString, evUser = 99 } typeEvent; struct delayEvent { long delay; typeEvent codeEvent; }; class Event { public: Event(const byte aPinNumber = LED_BUILTIN, const byte inputStringSizeMax = 30) { // constructeur _codeEvent = evNill; _waitingEventIndex = 0; // Event:Event(); _LedPulse = aPinNumber; #ifdef USE_SERIALEVENT _inputStringSizeMax = inputStringSizeMax; #endif } void begin(); typeEvent GetEvent(const bool sleep = true); void HandleEvent(); bool removeDelayEvent(const byte codeevent); bool pushEvent(const byte codeevent, const long delaySeconde = 0); bool pushEventMillisec(const byte codeevent, const long delayMillisec = 0); void SetPulsePercent(byte); // durée du pulse de 0 a 100% byte Second() const; byte Minute() const; byte Hour() const; // acces en R/O byte codeEvent() const { return (_codeEvent); }; int paramEvent() const { return (_paramEvent); }; #ifdef USE_SERIALEVENT char inChar = '\0'; String inputString = ""; #endif int freeRam(); unsigned long timestamp = 0; //timestamp en millisec (environ 49 jours) protected: long _nillEventCompteur = 0; byte _LedPulse; // Pin de la led de vie typeEvent _codeEvent = evNill; byte _pulse10Hz = 1; // 10% du temps par default int _paramEvent; // unsigned int _; // Evenement regroupés (pour ev100Hz et ev10Hz) byte _waitingEventIndex = 0; typeEvent _waitingEvent[MAX_WAITING_EVENT]; byte _waitingDelayEventIndex = 0; delayEvent _waitingDelayEvent[MAX_WAITING_DELAYEVENT]; #ifdef USE_SERIALEVENT byte _inputStringSizeMax = 1; bool _stringComplete = false; bool _stringErase = false; #endif }; class EventTrack : public Event { public: EventTrack(const byte aPinNumber = LED_BUILTIN) : Event(aPinNumber) {}; void HandleEvent(); protected: byte _trackTime = 0; int _ev100HzMissed = 0; int _ev10HzMissed = 0; };
1dbd390d23083f6e9cc6534884b086fbfbed9a2a
a4ed9eadba761d7eee9635499b23bf9f51c2353c
/Veiculo.h
1aa888ef0f1ae0e7c3b47582c0d3f1ff5a52cc4a
[]
no_license
arashisann/builder
d35a18103b6609455eff3501f01a016a76809aef
343c948425cd5f80097ed59b3fb803739a796698
refs/heads/master
2020-01-23T22:01:04.054615
2016-11-25T01:05:10
2016-11-25T01:05:10
74,713,516
0
0
null
null
null
null
UTF-8
C++
false
false
1,583
h
Veiculo.h
#include <iostream> #include <string> class Veiculo { public: class Builder; void setRodas(size_t num); void setCor(std::string cor); void setCavalos(size_t cavalos); Veiculo(size_t num, size_t cavalos, std::string cor); Veiculo() {} void imprimeDados(void); private: size_t _numero_rodas, _cavalo_vapor; std::string _cor; }; class Veiculo::Builder { public: Builder() : _numero_rodas { 0 }, _cavalo_vapor { 0 }, _cor { "Indefinido" } {} Builder& setRodas(size_t num) { _numero_rodas = num; return *this; } Builder& setCor(std::string cor) { _cor = cor; return *this; } Builder& setCavalos(size_t cavalos) { _cavalo_vapor = cavalos; return *this; } Builder& setCarroBranco() { _numero_rodas = 4; _cor = "Branco"; _cavalo_vapor = 150; return *this; } Veiculo build() { return Veiculo(_numero_rodas, _cavalo_vapor, _cor); } private: size_t _numero_rodas, _cavalo_vapor; std::string _cor; }; void Veiculo::setRodas(size_t num) { _numero_rodas = num; } void Veiculo::setCor(std::string cor) { _cor = cor; } void Veiculo::setCavalos(size_t cavalos) { _cavalo_vapor = cavalos; } Veiculo::Veiculo(size_t num, size_t cavalos, std::string cor) : _numero_rodas{num}, _cavalo_vapor{cavalos}, _cor{cor} {} void Veiculo::imprimeDados() { std::cout << "Cor: " << _cor << "\nNúmero de rodas: " << _numero_rodas << "\nPotência: " << _cavalo_vapor << " Cavalos" << std::endl; }
e458425483b72ab347d2ce4b463447380be371b7
88ae8695987ada722184307301e221e1ba3cc2fa
/third_party/blink/renderer/bindings/core/v8/custom/v8_html_plugin_element_custom.cc
55a3104db4e200cd890e1a7c99f34da76634f1b5
[ "LGPL-2.0-or-later", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-only", "GPL-1.0-or-later", "GPL-2.0-only", "LGPL-2.0-only", "BSD-2-Clause", "LicenseRef-scancode-other-copyleft", "BSD-3-Clause", "Apache-2.0", "MIT" ]
permissive
iridium-browser/iridium-browser
71d9c5ff76e014e6900b825f67389ab0ccd01329
5ee297f53dc7f8e70183031cff62f37b0f19d25f
refs/heads/master
2023-08-03T16:44:16.844552
2023-07-20T15:17:00
2023-07-23T16:09:30
220,016,632
341
40
BSD-3-Clause
2021-08-13T13:54:45
2019-11-06T14:32:31
null
UTF-8
C++
false
false
7,053
cc
v8_html_plugin_element_custom.cc
/* * Copyright (C) 2009 Google Inc. All rights reserved. * Copyright (C) 2014 Opera Software ASA. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <memory> #include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h" #include "third_party/blink/renderer/bindings/core/v8/v8_html_embed_element.h" #include "third_party/blink/renderer/bindings/core/v8/v8_html_object_element.h" #include "third_party/blink/renderer/core/execution_context/execution_context.h" #include "third_party/blink/renderer/core/frame/web_feature.h" #include "third_party/blink/renderer/core/html/html_embed_element.h" #include "third_party/blink/renderer/core/html/html_object_element.h" #include "third_party/blink/renderer/platform/bindings/dom_wrapper_world.h" #include "third_party/blink/renderer/platform/bindings/script_state.h" #include "third_party/blink/renderer/platform/instrumentation/use_counter.h" namespace blink { namespace { template <typename ElementType> void GetScriptableObjectProperty( const AtomicString& name, const v8::PropertyCallbackInfo<v8::Value>& info) { ScriptState* state = ScriptState::Current(info.GetIsolate()); if (!state->World().IsMainWorld()) { if (state->World().IsIsolatedWorld()) { UseCounter::Count(CurrentExecutionContext(info.GetIsolate()), WebFeature::kPluginInstanceAccessFromIsolatedWorld); } // The plugin system cannot deal with multiple worlds, so block any // non-main world access. return; } UseCounter::Count(CurrentExecutionContext(info.GetIsolate()), WebFeature::kPluginInstanceAccessFromMainWorld); HTMLPlugInElement* impl = ElementType::ToWrappableUnsafe(info.Holder()); v8::Local<v8::Object> instance = impl->PluginWrapper(); if (instance.IsEmpty()) return; v8::Local<v8::String> v8_name = V8AtomicString(info.GetIsolate(), name); bool has_own_property; v8::Local<v8::Value> value; if (!instance->HasOwnProperty(state->GetContext(), v8_name) .To(&has_own_property) || !has_own_property || !instance->Get(state->GetContext(), v8_name).ToLocal(&value)) { return; } UseCounter::Count(CurrentExecutionContext(info.GetIsolate()), WebFeature::kPluginInstanceAccessSuccessful); V8SetReturnValue(info, value); } template <typename ElementType> void SetScriptableObjectProperty( const AtomicString& name, v8::Local<v8::Value> value, const v8::PropertyCallbackInfo<v8::Value>& info) { DCHECK(!value.IsEmpty()); ScriptState* state = ScriptState::Current(info.GetIsolate()); if (!state->World().IsMainWorld()) { // The plugin system cannot deal with multiple worlds, so block any // non-main world access. return; } HTMLPlugInElement* impl = ElementType::ToWrappableUnsafe(info.Holder()); v8::Local<v8::Object> instance = impl->PluginWrapper(); if (instance.IsEmpty()) return; // Don't intercept any of the properties of the HTMLPluginElement. v8::Local<v8::String> v8_name = V8AtomicString(info.GetIsolate(), name); v8::Local<v8::Context> context = state->GetContext(); bool instance_has_property; bool holder_has_property; if (!instance->HasOwnProperty(context, v8_name).To(&instance_has_property) || !info.Holder()->Has(context, v8_name).To(&holder_has_property) || (!instance_has_property && holder_has_property)) { return; } // FIXME: The gTalk pepper plugin is the only plugin to make use of // SetProperty and that is being deprecated. This can be removed as soon as // it goes away. // Call SetProperty on a pepper plugin's scriptable object. Note that we // never set the return value here which would indicate that the plugin has // intercepted the SetProperty call, which means that the property on the // DOM element will also be set. For plugin's that don't intercept the call // (all except gTalk) this makes no difference at all. For gTalk the fact // that the property on the DOM element also gets set is inconsequential. bool created; if (!instance->CreateDataProperty(context, v8_name, value).To(&created)) return; V8SetReturnValue(info, value); } } // namespace void V8HTMLEmbedElement::NamedPropertyGetterCustom( const AtomicString& name, const v8::PropertyCallbackInfo<v8::Value>& info) { UseCounter::Count(CurrentExecutionContext(info.GetIsolate()), WebFeature::kHTMLEmbedElementGetter); GetScriptableObjectProperty<V8HTMLEmbedElement>(name, info); } void V8HTMLObjectElement::NamedPropertyGetterCustom( const AtomicString& name, const v8::PropertyCallbackInfo<v8::Value>& info) { UseCounter::Count(CurrentExecutionContext(info.GetIsolate()), WebFeature::kHTMLObjectElementGetter); GetScriptableObjectProperty<V8HTMLObjectElement>(name, info); } void V8HTMLEmbedElement::NamedPropertySetterCustom( const AtomicString& name, v8::Local<v8::Value> value, const v8::PropertyCallbackInfo<v8::Value>& info) { UseCounter::Count(CurrentExecutionContext(info.GetIsolate()), WebFeature::kHTMLEmbedElementSetter); SetScriptableObjectProperty<V8HTMLEmbedElement>(name, value, info); } void V8HTMLObjectElement::NamedPropertySetterCustom( const AtomicString& name, v8::Local<v8::Value> value, const v8::PropertyCallbackInfo<v8::Value>& info) { UseCounter::Count(CurrentExecutionContext(info.GetIsolate()), WebFeature::kHTMLObjectElementSetter); SetScriptableObjectProperty<V8HTMLObjectElement>(name, value, info); } } // namespace blink
d60a1630e9e6a96920cef4cb29d3a5b2d6cd1f78
aa13288ea83886535f85dc1561a5265b5f844c59
/Implementation/Source/Util/src/Exports/MatrixUtil.h
0d658a164cea7c0bd1df366b2216f5ad5d07b8af
[]
no_license
GarondEisenfaust/ImageBasedShaving
57fdf6afa8c179036afcb2f65a75e51173d34d06
b0c78f46670de1561055a3324adb585b14184ee6
refs/heads/master
2020-11-23T22:35:26.488579
2019-12-13T14:55:26
2019-12-13T14:55:26
227,848,870
0
0
null
null
null
null
UTF-8
C++
false
false
792
h
MatrixUtil.h
#pragma once namespace MatUtil { cv::Mat_<cv::Vec3d> ReadImageAndConvertTodouble(const std::filesystem::path& imageName); cv::Mat_<double> ReadMatrixFromFile(const std::filesystem::path& path); void WriteVectorizedImage(const std::string& name, const cv::Mat_<double>& vectorizedImage, int channels = 3, int rows = 95); void WriteImage(const std::string& name, const cv::Mat_<cv::Vec3d>& image); template <class T, class ChannelT> cv::Mat_<T> VectorizeImage(const cv::Mat_<ChannelT>& image) { return image.reshape(1, image.rows * image.cols * image.channels()); } template <class ChannelT, class T> cv::Mat_<ChannelT> DeVectorizeImage(const cv::Mat_<T>& image, int channels, int rows) { return image.reshape(channels, rows); } }
c4368dff447e0f9d5a73c619e8c1481d545b96a0
918fa7c719257b342f8eb931b088ac3a0641224d
/src/cpp/assembler/BinaryGenerator.h
35a1358179a68e4f5493b33f5a5e6f50a2eaee92
[]
no_license
hdhzero/Hivek
fa0aa0fc3dd5d045874ca32390f66eb8df91c615
9397e69f9010d07cfa991f594529adc81ea5b64b
refs/heads/master
2021-01-10T11:35:59.989298
2013-06-26T17:17:47
2013-06-26T17:17:47
8,507,347
1
1
null
null
null
null
UTF-8
C++
false
false
750
h
BinaryGenerator.h
#ifndef HIVEK_ASSEMBLER_BINARY_GENERATOR_H #define HIVEK_ASSEMBLER_BINARY_GENERATOR_H #include "HivekAssembler.h" namespace HivekAssembler { class BinaryGenerator { private: Table* table; std::ofstream file; private: uint32_t op2bin(Instruction& op); uint16_t op2bin14(Instruction& op); uint8_t get_byte(uint32_t v, int pos); void write32op(uint32_t inst); void write16op(uint16_t inst); void generate_data(); void generate_instructions(); public: void set_table(Table* table); void generate_binary(); void open(char* filename); void close(); }; } #endif
8bc09788528ab2dc73e6227c85782b915e5583e6
d99541989f4d75593d1882dec5081d8bc9dd7b16
/Zonas.ino
23c3dbe0e06ba4a00b17584dad0334957f056913
[]
no_license
EstebanPerez25/Proyecto-Candidates
b56c15cf87db7f3f13b4cb126d93cd492bd9fa04
c259a7f293d1eaad79dfd8fa1932d3ea35a71e4b
refs/heads/main
2023-09-02T13:46:59.054994
2021-11-04T21:21:50
2021-11-04T21:21:50
424,740,592
0
0
null
null
null
null
UTF-8
C++
false
false
6,920
ino
Zonas.ino
#include "Zonas.h" #include "Navegacion.h" #include "SensorColor.h" #include "SensorUltrasonico.h" float distancia; //Variable para distancia detectada por ultrasónicos byte ds = 15; // Distancia para considerar pared al frente //3 Sensores Ultrasónicos. (1 señal de Trig para los 3) #define trign 3 #define echo_I A0 #define echo_F A1 #define echo_D A2 //2 Sensores de color. (s0 y s1 están conectados a Vcc; s2 y s3 alimenta esos pines de ambos sensores) #define s2n 4 #define s3n 5 #define out_I A3 #define out_D A4 //Controlador Motorreductores #define in1n 6 #define in2n 7 #define in3n 8 #define in4n 9 //Servomotor #define servoM 10 //Led RGB Aquí llamaremos a la funión para endender el led, usando el dato recibido de la función getColor, o de la Zona C #define led_Rn 11 #define led_Gn 12 #define led_Bn 13 //Para el Sensor Acelerómetro/Giroscopio de usan lo pines 2, SCL y SDA de Arduino /////////////////////////////////////////////////////////////////OBJETOS o INSTANCIAS //Sensores Ultrasónicos sensorUltrasonico sensorUS_I(trign, echo_I); sensorUltrasonico sensorUS_F(trign, echo_F); sensorUltrasonico sensorUS_D(trign, echo_D); //Sensores de Color sensorColor sensorC_I(s2n, s3n, out_I, 0); sensorColor sensorC_D(s2n, s3n, out_D, 1); //Navegación del Robot navegacion navegar(in1n, in2n, in3n, in4n); //Para .accion : 0-> Apagar motores 1-> Giro a la izquierda. 2-> Giro a la derecha. 3-> Giro 180 4-> Avanzar //LedRGB //Aquí llamaremos a la funión para endender el led, usando el dato recibido de la función getColor, o de la Zona C ledRGB led_rgb(led_Rn, led_Gn, led_Bn); //Constructor zonas::zonas() { } /////////////////////////////////////////////////////////////////////////////////////////////////////// METODOS void zonas::test() { Serial.println(sensorC_I.getColor()); Serial.println(sensorC_D.getColor()); Serial.println("OK1"); delay(3000); Serial.println(sensorC_I.getColor()); Serial.println(sensorC_D.getColor()); Serial.println("OK2"); delay(3000); Serial.println(sensorC_I.getColor()); Serial.println(sensorC_D.getColor()); Serial.println("OK3"); } void zonas::calibrar() { //Los datos recopilados deben remplazarse en sus respectivas clases sensorC_I.valoresRGB(); Serial.println("*------------------------------------------------------------*"); //Obtener valores RGB para cada color sensorC_D.valoresRGB(); // Serial.println("Pon el robot en la posición para calibrar, tienes 5 egundos..."); delay(5000); // orientacionAyG.offsetsM(); //Obtener offsets a remplazar de Acelerómetro y Giroscopio } /////////////////////////////////////////////////////////////////////////////////////////// ZONA A void zonas::zonaA() { byte v = 350; while (true) { if ((sensorUS_F.distancia() > 25.0) && (sensorUS_I.distancia() > 30.0)) {//Toda libre delay(250); navegar.accion(0); navegar.accion(1); navegar.accion(4); delay(v); navegar.accion(0); } else if ((sensorUS_F.distancia() > 25.0) && (sensorUS_I.distancia() < 30.0)) { //Frente libre navegar.accion(4); delay(v); navegar.accion(0); } else if ((sensorUS_F.distancia() < 25) && (sensorUS_I.distancia() > 30)) {//Izquierda libre delay(250); navegar.accion(1); delay(v); navegar.accion(0); navegar.accion(4); } else { // Ninguna navegar.accion(2); } } } /////////////////////////////////////////////////////////////////////////////////////////// ZONA B void zonas::zonaB() { for (int n = 0; n < 6; n++) { while (sensorUS_F.distancia() > 25) { navegar.accion(1); } navegar.accion(0); navegar.accion(1); }//Llega hasta esquina inferior derecha while (sensorUS_D.distancia() < 30) { navegar.accion(4); } delay(350); navegar.accion(0); navegar.accion(2); navegar.accion(4); delay(450); navegar.accion(0); } /////////////////////////////////////////////////////////////////////////////////////////// ZONA C void zonas::zonaC() { byte left = 0; byte right = 0; byte sum = 0; byte binary_sum = 0; byte cI; //Color Inicial Izquierda byte cD; //Color Inicial Izquierda Serial.println("Preparación"); do { cI = sensorC_I.getColor(); cD = sensorC_D.getColor(); navegar.accion(4); //Avanza hasta detectar color Serial.println("Avanza"); if ((sensorUS_F.distancia() < 15) || (sensorC_I.getColor() != cI) || (sensorC_D.getColor() != cD) ) { Serial.println(sensorUS_F.distancia()); Serial.println(sensorC_D.getColor()); Serial.println(sensorC_I.getColor()); navegar.accion(0); Serial.println("Alto"); //Hacer sumas de color if (sensorC_I.getColor() == 1) { // yellow left += 1; } else if (sensorC_I.getColor() == 4) { // green left += 2; } else if (sensorC_I.getColor() == 6) { // black right = 0; } else if (sensorC_I.getColor() == 0) { // white left += 0; } if (sensorC_I.getColor() == 1) { // yellow right += 1; } else if (sensorC_I.getColor() == 4) { // green right += 2; } else if (sensorC_I.getColor() == 6) { // black left = 0; } else if (sensorC_I.getColor() == 0) { // white right += 0; sum = (left + right); binary_sum = dec_to_bin(sum); if ((sensorUS_F.distancia() < ds) && (binary_sum % 2 == 0)) { // pair navegar.accion(1); //Giro Izquierda } else if ((sensorUS_F.distancia()) < ds && (binary_sum % 2 != 0)) { // odd navegar.accion(2); //Giro Derecha } } }//End if sumatorias } while (sensorC_I.getColor() != 7);//Hace el algoritmo de la zona mientras no llegue al check point de la rampa color ROSA }//End Zona C void zonas::rampa() { navegar.accion(2); //Giro Derecha while ((sensorUS_F.distancia() < ds)) { navegar.accion(5); //Reversa } } //////////Funciones extra zona C int dec_to_bin(int dec) { int bin[8]; int lenght = sizeof(bin); for (int i = 0; i < 8; i++) { bin[i] = dec % 2; dec = dec / 2; } for (int i = 7; i >= 0; i--) { if (bin[i] == 0) { led_rgb.rojo(); } else if (bin[i] == 1) { led_rgb.verde(); } } led_rgb.azul(); //Encendido led azul para indicar fin de secuencia binario return bin[last_element(bin, lenght)]; } // Get Last Element int last_element(int aray[], int lenght) { int last = 0; last = (lenght / sizeof(aray[0]) - 8 ); return last; }
8516a60dee87bafe60c9d5ac1ea661b69caff9f7
37f03b7b8fae74c1106acdff0da0d5731c0f01c1
/src/gtest/test.cpp
501b92de0bdc39da70d98f85e893c460f1afa398
[]
no_license
jing1804/fake_obtlib
cc7b47a87af518c2899dd49e7047245aedfb4907
a16a8c2691d627527b2678f92ccaba7ffa000e8e
refs/heads/master
2023-01-24T03:49:27.385500
2020-12-11T00:43:39
2020-12-11T00:43:39
316,449,506
0
0
null
null
null
null
UTF-8
C++
false
false
1,102
cpp
test.cpp
#include "gtest/gtest.h" #include "RREService_api.h" #include "handler.h" class ClassTest : public testing::Test { public: virtual void SetUpTestCase() { } virtual void TearDownTestCase() { } virtual void SetUp() { } virtual void TearDown() { } private: }; TEST(Client, test) { ECUINFOSTR info; obt_log_callback_b cb; bool re = RREServiceInit(info, cb); EXPECT_EQ(re, true) << "init failure"; EXPECT_EQ(RREServiceTcpGetTcpStatus(), 1); RREServiceTcpConnect(); EXPECT_EQ(RREServiceTcpGetTcpStatus(), 3); EXPECT_EQ(RREServiceTcpGetDoipRaStatus(), 1); RREServiceTcpClose(); EXPECT_EQ(RREServiceTcpGetTcpStatus(), 1); } TEST(Server, test) { char strmesg[2056]; OBT_MSG stmesg; stmesg.len = 10; short stype = CLI_SEND_MSG; rres_serialization(&stmesg, &stype, strmesg); EXPECT_EQ(stype, *((short*)strmesg)); EXPECT_EQ(10, *((int*)&strmesg[6])); OBT_MSG stm; short st; rres_deserialization(strmesg, &stm, &st); EXPECT_EQ(stm.len, 10); EXPECT_EQ(st, CLI_SEND_MSG); } int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
7145ec1414e7ee9ca71c8e8eced9476dba258ef5
8bb7e4b0f6c47793c0f643dc7f2df8b7f5646ca6
/1201 - DCN Lab - Spring 2012/Lab09_TCP_Header_Analysis/TCP_Header_Analysis/src/PacketManip.cpp
977611f0bae8931de88c2f4c0fafc0b9a8aafb50
[]
no_license
inf-eth/i02-0491-courses
405cb0d534fed643434dd2126776cbe030af4d13
f7e2ea222aeb2b21bcc9d2793a8652cc7f5afe23
refs/heads/master
2021-01-10T09:47:16.518013
2015-07-23T17:09:14
2015-07-23T17:09:14
46,210,614
1
0
null
null
null
null
UTF-8
C++
false
false
6,068
cpp
PacketManip.cpp
#include <PacketManip.h> #include <cstdlib> // exit() #include <ctime> #include <iostream> #include <bitset> using std::cout; using std::cerr; using std::endl; using std::bitset; void packet_capture_callback(u_char *, const struct pcap_pkthdr*, const u_char*); CPacketManip::CPacketManip (const char *pdev, const char *pfilter) { // ask pcap for the network address and mask of the device if (pcap_lookupnet (pdev, &netp, &maskp, errbuf) == -1) { cerr << "ERROR pcap_lookupnet(): " << errbuf << endl; exit(-1); } // open device for reading this time lets set it in promiscuous mode so we can monitor traffic to another machine descr = pcap_open_live (pdev, BUFSIZ, 1, -1, errbuf); if(descr == NULL) { cerr << "ERROR pcap_open_live(): " << errbuf << endl; exit(-1); } // Lets try and compile the program.. non-optimized if (pcap_compile (descr, &fp, pfilter, 0, netp) == -1) { cerr << "ERROR calling pcap_compile()" << endl; exit(-1); } // set the compiled program as the filter if (pcap_setfilter (descr, &fp) == -1) { cerr << "ERROR setting filter" << endl; exit(1); } cout << "Device: " << pdev << endl; cout << "Filter: " << pfilter << endl; } void CPacketManip::Loop () { pcap_loop (descr, -1, packet_capture_callback, NULL); } // TODO: All the work needs to be done here. void packet_capture_callback(u_char *useless,const struct pcap_pkthdr* header,const u_char* packet) { // TODO: Comment this to stop some spam onscreen or set the appropriate filter program in main() if running on network. cout << " Recieved a packet at: " << ctime((const time_t*)&header->ts.tv_sec) << endl; // Header pointers. const struct sniff_ethernet *ethernet; /* The ethernet header */ const struct sniff_ip *ip; /* The IP header */ const struct sniff_tcp *tcp; /* The TCP header */ const u_char *payload; /* Packet payload */ u_int size_ip; // IP header length. u_int size_tcp; // TCP header legnth. // ************************** Pointer Initialization ********************************* // packet* is the starting address of captured packet stored in memory. ethernet = (struct sniff_ethernet*)(packet); // First thing in a packet is ethernet header. ip = (struct sniff_ip*)(packet + SIZE_ETHERNET); // IP header comes after ethernet header. size_ip = IP_HL(ip)*4; // IP_HL is a macro for ((ip)->ip_vhl) & 0x0f; // IP_HL(ip) gives length in 32bit words. Multiplication by 4 gives length in bytes. if (size_ip < 20) { cerr << "ERROR: Invalid IP header length: " << size_ip << " bytes." << endl; return; } tcp = (struct sniff_tcp*)(packet + SIZE_ETHERNET + size_ip); // TCP header follows ethernet and IP headers. size_tcp = TH_OFF(tcp)*4; // TH_OFF(tcp) is a macro for ((ip)->ip_vhl) >> 4; // TH_OFF(tcp) gives length of TCP header in 32bit words. Multiplication by 4 gives length in bytes. if (size_tcp < 20) { cerr << "ERROR: Invalid TCP header length: " << size_tcp << " bytes." << endl; return; } payload = (u_char *)(packet + SIZE_ETHERNET + size_ip + size_tcp); // Payload or data in packet. // ************************************************************************************* // TODO: Packet capturing condition. Only process packets with the specified protocol, and port numbers. // TODO: Process UDP packets and display their headers. // Default condition is to capture only packets with TCP protocol and source port = 6000 or 6001 // ntohs(tcp->th_sport) gives source port // ntohs(tcp->th_dport) gives destination port // Protocols are IPPROTO_IP, IPPROTO_UDP, IPPROTO_ICMP etc. if ( ip->ip_p == IPPROTO_TCP && (ntohs(tcp->th_sport) == 6000 || ntohs(tcp->th_sport) == 6001) ) { // TODO: Process the headers. Display IP header. cout << " Recieved a TCP packet at: " << ctime((const time_t*)&header->ts.tv_sec) << endl; /* define/compute tcp payload (segment) offset */ //payload = (packet + SIZE_ETHERNET + size_ip + size_tcp); /* compute tcp payload (segment) size */ u_int size_payload = ntohs(ip->ip_len) - (size_ip + size_tcp); u_int PacketSize = size_payload + size_ip + SIZE_ETHERNET + size_tcp; cout << "Payload size: " << size_payload << endl; cout << "Packet size: " << PacketSize << endl; // bitset is a C++ class for bit manipulation. It has overloaded [], << and >> operators for easy access to individual bits and input/output. // Using bitset of size 8 to display bits in a single character (byte). bitset<8> DataOffset; bitset<8> Flags; DataOffset = tcp->th_offx2; // tcp->th_offx2 points to offset character. Flags = tcp->th_flags; // tcp->th_flags character contain flag bits. cout << "******* TCP Header *******" << endl << "Source Port: " << ntohs(tcp->th_sport) << endl << "Destination Port: " << ntohs(tcp->th_dport) << endl << "Sequence No.: " << ntohl (tcp->th_seq) << endl << "Acknowledgement No.: " << ntohl(tcp->th_ack) << endl << "TCP header length: " << size_tcp << endl << "Data offset flags: " << DataOffset << endl << "Flags: " << endl << "\t\t" << "FIN: " << Flags[0] << endl << "\t\t" << "SYN: " << Flags[1] << endl << "\t\t" << "RESET: " << Flags[2] << endl << "\t\t" << "PUSH: " << Flags[3] << endl << "\t\t" << "ACK: " << Flags[4] << endl << "\t\t" << "URGENT: " << Flags[5] << endl << "\t\t" << "ECE: " << Flags[6] << endl << "\t\t" << "CWR: " << Flags[7] << endl << "Window size: " << ntohs(tcp->th_win) << endl << "Checksum: " << ntohs(tcp->th_sum) << endl << "Urgent Pointer: " << ntohs(tcp->th_urp) << endl; // TODO: Display payload data. if (size_payload != 0) { cout << "Payload: "; u_int Payload_Offset = SIZE_ETHERNET + size_ip + size_tcp; for (int i=0; i<size_payload; i++) { cout << packet[i + Payload_Offset]; } cout << endl; } cout << "*************************" << endl; } else return; // Not a packet of our interest. }
b6843078c08ea901b3060f772f32766850ef9e8d
347bea86f83d5e2475ca3a0ebf6de397f1a1fa4c
/Practical 4/main.cpp
2647602455bfef749f90e5e51115207053540488
[]
no_license
MarcosGaming/Physics_Practicals
fe93d31c12c32e53557ed9714f175eeea32d18e9
6f58ff9691d1f0a68377c0946ca71aa2ea108a1b
refs/heads/master
2018-12-21T08:20:42.739381
2018-12-06T16:50:29
2018-12-06T16:50:29
75,084,908
1
0
null
null
null
null
UTF-8
C++
false
false
4,378
cpp
main.cpp
#pragma once // Math constants #define _USE_MATH_DEFINES #include <cmath> #include <random> // Std. Includes #include <string> #include <time.h> // GLM #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/gtx/matrix_operation.hpp> #include "glm/ext.hpp" // Other Libs #include "SOIL2/SOIL2.h" // project includes #include "Application.h" #include "Shader.h" #include "Mesh.h" #include "Body.h" #include "Particle.h" // time GLfloat t = 0.0f; const GLfloat deltaTime = 0.01f; GLfloat currentTime = (GLfloat)glfwGetTime(); GLfloat accumulator = 0.0f; // main function int main() { // create application Application app = Application::Application(); app.initRender(); Application::camera.setCameraPosition(glm::vec3(0.0f, 5.0f, 20.0f)); // create ground plane Mesh plane = Mesh::Mesh(Mesh::QUAD); // scale it up x5 plane.scale(glm::vec3(5.0f, 5.0f, 5.0f)); Shader lambert = Shader("resources/shaders/physics.vert", "resources/shaders/physics.frag"); plane.setShader(lambert); // Gravity constant glm::vec3 g = glm::vec3(0.0f, -9.8f, 0.0f); // TASK 2.2 HOOKE'S LAW IMPLEMENTATION VARIABLES /*Particle particle2 = Particle::Particle(); particle2.translate(glm::vec3(0.0f, 5.0f, 0.0f)); particle2.getMesh().setShader(Shader("resources/shaders/solid.vert", "resources/shaders/solid_blue.frag")); Particle particle1 = Particle::Particle(); particle1.translate(glm::vec3(0.0f, 4.0f, 0.0f)); particle1.getMesh().setShader(Shader("resources/shaders/solid.vert", "resources/shaders/solid_blue.frag")); particle1.addForce(&Gravity::Gravity(glm::vec3(0.0f, -9.8f, 0.0f))); Hooke fsd = Hooke::Hooke(&particle1, &particle2, 10.0f, 0.1f, 1.0f); particle1.addForce(&fsd);*/ //TASK 2.3 CHAIN OF PARTICLES CONNECTED BY SPRINGS VARIABLES Particle particleStatic = Particle::Particle(); particleStatic.translate(glm::vec3(0.0f, 8.0f, 0.0f)); particleStatic.getMesh().setShader(Shader("resources/shaders/solid.vert", "resources/shaders/solid_blue.frag")); std::vector<Particle> particles; particles.push_back(particleStatic); int numberParticles = 5; for (int i = 1; i < numberParticles; i++) { Particle particle = Particle::Particle(); particle.translate(glm::vec3(0.0f, (particles[i-1].getPos().y-1.0f), 0.0f)); particle.getMesh().setShader(Shader("resources/shaders/solid.vert", "resources/shaders/solid_blue.frag")); particles.push_back(particle); } for (int i = 1; i < numberParticles; i++) { Gravity* fgravity = new Gravity(glm::vec3(0.0f, -9.8f, 0.0f)); particles[i].addForce(fgravity); Hooke* fsd = new Hooke(&particles[i], &particles[i - 1], 20.0f * i * i, 0.01f, 1.0f); particles[i].addForce(fsd); } // Game loop while (!glfwWindowShouldClose(app.getWindow())) { // Set frame time GLfloat newTime = (GLfloat)glfwGetTime(); GLfloat frameTime = newTime - currentTime; currentTime = newTime; accumulator += frameTime; /* ** INTERACTION */ // Manage interaction app.doMovement(deltaTime); /* ** SIMULATION */ while (accumulator >= deltaTime) { // TASK 2.2 HOOKE'S LAW IMPLEMENTATION // Calculate acceleration /*particle1.setAcc(particle1.applyForces(particle1.getPos(), particle1.getVel(), t, deltaTime)); // Integrate to calculate new velocity and position particle1.setVel(particle1.getVel() + particle1.getAcc() * deltaTime); particle1.translate(particle1.getVel() * deltaTime);*/ //TASK 2.3 CHAIN OF PARTICLES CONNECTED BY SPRINGS for (int i = 0; i < numberParticles; i++) { // Calculate acceleration particles[i].setAcc(particles[i].applyForces(particles[i].getPos(), particles[i].getVel(), t, deltaTime)); // Integrate to calculate new velocity and position particles[i].setVel(particles[i].getVel() + particles[i].getAcc() * deltaTime); particles[i].translate(particles[i].getVel() * deltaTime); } accumulator -= deltaTime; t += deltaTime; } /* ** RENDER */ // clear buffer app.clear(); // draw groud plane app.draw(plane); // TASK 2.2 HOOKE'S LAW IMPLEMENTATION DRAW /*app.draw(particle2.getMesh()); app.draw(particle1.getMesh());*/ //TASK 2.3 CHAIN OF PARTICLES CONNECTED BY SPRINGS DRAW for (int i = 0; i < numberParticles; i++) { app.draw(particles[i].getMesh()); } app.display(); } app.terminate(); return EXIT_SUCCESS; }
44fa727d3954c5e23b9b2e842e4e1e323105da30
a51e16ef75b288ddb9d596e91d48270f8dc6a30b
/Sorting/08- Shell Sort.cpp
31b3946c38b5beb9a6ab9738a18d6b7cd366b4f4
[]
no_license
A2andil/Algorithms
11678f947fbcb377fdb27de520da4fc64e498bf6
1b4ff0ee837870e58f2cdcd0a8867d364eedcaa0
refs/heads/master
2022-11-30T00:49:42.945295
2020-08-11T09:49:11
2020-08-11T09:49:11
61,442,916
0
0
null
null
null
null
UTF-8
C++
false
false
476
cpp
08- Shell Sort.cpp
// in the name of God #include <iostream> #include <set> #include <algorithm> #define ll long long using namespace std; vector<int> list; int shell_sort() { int n = list.size(), gap = n / 2; while (gap > 0) { for (int i = gap; i < n; i += 1) { for (int j = i; j >= gap && list[j - gap] > list[j]; j -= gap) swap(list[j], list[j - gap]); } gap /= 2; } } int main() { return 0; }
25bf8d8c0dfc20334a3b10734de202a0c0516289
dc5b4cad35298b7380ab81f1d2eb88a0c071d43e
/src/ecs/system/RenderSystemMeshFilter.cpp
e6a1fb603c0451d316dd80c209ec51d7b60e07e6
[]
no_license
tustvold/talon
1db86210b30acb86b936a4a6968ebed2c3a0110c
3639995646de9e9589b9ba97bac0aea85671acc0
refs/heads/master
2020-05-02T13:10:42.053891
2019-03-27T11:10:16
2019-03-27T11:10:16
177,977,449
0
0
null
null
null
null
UTF-8
C++
false
false
1,250
cpp
RenderSystemMeshFilter.cpp
#include "RenderSystemMeshFilter.hpp" #include "rendering/system/RenderPass.hpp" USING_TALON_NS; RenderSystemMeshFilter::RenderSystemMeshFilter() = default; RenderSystemMeshFilter::~RenderSystemMeshFilter() = default; void RenderSystemMeshFilter::update(const RenderSystemArgs &args) { commandBuffer.reset(); vk::CommandBufferBeginInfo beginInfo; beginInfo.flags |= vk::CommandBufferUsageFlagBits::eRenderPassContinue; beginInfo.setPInheritanceInfo(args.commandBufferInheritanceInfo); { auto recordHandle = commandBuffer.begin(beginInfo); args.world->for_each<ComponentModelMatrix, ComponentMeshFilter>(boost::hana::fuse( [this, &args](EntityID id, boost::hana::tuple<const ComponentModelMatrix *, const ComponentMeshFilter *> components) { //ComponentTransformTree* transform = components[0_c]; const ComponentMeshFilter *meshFilter = components[1_c]; args.renderPass->bindMaterial(args.swapChain, meshFilter->material, &commandBuffer); meshFilter->mesh->bind(&commandBuffer); meshFilter->mesh->draw(&commandBuffer); })); } args.primaryCommandBuffer->executeCommandBuffer(&commandBuffer); }
ba26c01924acbec70e66e19e44cbb2b723ef35fd
f2279faca9b56f013988a88f9ba01555f1134889
/Assign020.cpp
c219afc4898d547f687062a3dfa2a28544d21b67
[]
no_license
nish235/C-CppAssignments
c8f36ff83a06391799feb6eb7efab6cd4c8d52bf
5eb8bf3d2f91fcc7a8527ecf81efec3f5dda1dda
refs/heads/master
2022-12-27T03:19:41.868628
2020-10-09T11:52:29
2020-10-09T11:52:29
292,768,840
0
0
null
null
null
null
UTF-8
C++
false
false
285
cpp
Assign020.cpp
#include<iostream> using namespace std; int main() { int n,i; cout<<"\n Enter Number : "; cin>>n; cout<<"\n SQUARE OF NUMBERS BETWEEN 1 & "<<n<<endl; for(i=2;i<=n;i++) { if((i%2)==0) { cout<<"\n\t"<<i<<"\t"<<i*i; } } cout<<"\n\n"; return 0; }
f5cf2df36d2bb66094c46a3ae70ad1fa4a407d7f
201d7dcc07e667cccb512fb00bbe2274567209a0
/Proto_Shooting/GameOver.cpp
9b369ffe41cb493f15b33a371fd36d71b76718cf
[]
no_license
OnoMakito/Skill_Check
372048f28c500bf695f6645c270d48ea8ffef395
7aa61e1193cc320a0b19a7a65efadcb7df7adf5c
refs/heads/master
2022-02-20T00:57:34.137762
2019-10-01T10:20:35
2019-10-01T10:20:35
212,033,103
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
1,839
cpp
GameOver.cpp
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include "GameOver.h" #include "MyTex.h" #include "Sprite.h" #include "input.h" #include "common.h" #include "BG.h" #include "score.h" #include "Judgement.h" #include "PatternAnimation.h" #include "Enemy.h" static unsigned int GameOver_Tex; static int GameOver_WaitCount; static unsigned int Result_Score_Tex; static int Result_WaitCount; static bool NewScore_o; void GameOver_Init() { Result_Score_Tex = Texture_SetLoadFile("Asset\\Score_Result.png", 418, 81); GameOver_Tex = Texture_SetLoadFile("Asset\\GAMEOVER.png", 1270, 820); GameOver_WaitCount = 0; NewScore_o = false; FILE *fp; fp = fopen("Asset\\Score.txt", "r"); //ファイルの読み込み展開 int Score[5]; fread(&Score, sizeof(int), 5, fp); fclose(fp); int score = Get_Score(); bool Sort = false; for (int i = 0; i < 5 && !Sort; i++) { if (Score[i] <= score) { for (int j = 4; i < j; j--) { Score[j] = Score[j - 1]; } Score[i] = score; if (i == 0) { NewScore_o = true; } Sort = true; } } fp = fopen("Asset\\Score.txt", "w"); //ファイルの追加書き込み展開 if (fp == NULL) { PostQuitMessage(0); } fwrite(Score, sizeof(int), 5, fp); //セーブ fclose(fp); } void GameOver_Update() { GameOver_WaitCount ++ ; if (Keyboard_IsPress(DIK_SPACE) && GameOver_WaitCount > 30) { SetSecene(4); } Bg_Update(); Enemy_Update(); } void GameOver_Draw(void) { Bg_Draw(); Enemy_Draw(); Sprite_Draw(GameOver_Tex, 0, 0, 0, 0, 1270, 820, 0, 0, 0, 1); Sprite_Draw(Result_Score_Tex, 0, 0, 0, 0, 418, 81, 0, 0, 0, 1); Score_Draw(Get_Score(), 0, 50, 4, true, false); PatternAnimation_Draw_TitleEnter(150, 200, GetFrame()); if (NewScore_o) { PatternAnimation_NewScore(0, 70, GetFrame()); } } void GameOver_UnInit() { }
2d67c5535066df126dcd612a1260d70723fb6eff
6f100f69232c6597c3f9564acde9c303b2adf47d
/Kattis/Dyslectionary/main.cpp
0c591ab9435fced38c07d0476066213d18519c93
[]
no_license
douglasbravimbraga/programming-contests
43e1b6aaa5a3ef51f5815fed8cb9a607f4f334cc
75e444977cc3ff701b7390b8de70c88f6b40c52f
refs/heads/master
2023-07-20T07:58:53.145049
2021-08-01T12:48:23
2021-08-01T12:48:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
603
cpp
main.cpp
#include <bits/stdc++.h> using namespace std; int main() { string line; int tc = 0; while (getline(cin, line)) { vector<string> lines; lines.push_back(line); if (tc++) cout << endl; while(getline(cin, line) && line.length()) { lines.push_back(line); } size_t max_len = 0; for (string& l : lines) { max_len = max(max_len, l.length()); reverse(l.begin(), l.end()); } sort(lines.begin(), lines.end()); for (string& ll : lines) { reverse(ll.begin(), ll.end()); for (int i = ll.length(); i < max_len; i++) cout << ' '; cout << ll << endl; } } return 0; }
3cf6c011ebab1acde30ead4142eaa0e076580611
35de73d3cc956831c1ac45386dfd163e722c9db1
/TeamProject/Light.h
2bf8bf78d3d99c649d14ffa179879913c3bdf567
[]
no_license
ggraca/csc8506-teamproject
e39969978d19b6c1037b62d623fa2f0db25e2016
81ca8b1588a001f405575643574c8609d903605c
refs/heads/master
2020-04-19T13:38:57.529496
2019-03-29T12:40:19
2019-03-29T12:40:19
168,222,954
0
0
null
null
null
null
UTF-8
C++
false
false
884
h
Light.h
#pragma once #include "Component.h" #include "Transform.h" #include "../Common/Vector4.h" using namespace NCL::Maths; enum LightType { Directional, Point, Spot }; class Light : public Component { public: Light(LightType type, Vector4 colour, float radius, float brightness) { this->type = type; this->colour = colour; this->radius = radius; this->brightness = brightness; } Light() {}; ~Light(void) {}; LightType GetType() const { return type; } void SetType(LightType val) { type = val; } float GetRadius() const { return radius; } void SetRadius(float val) { radius = val; } Vector4 GetColour() const { return colour; } void SetColour(Vector4 val) { colour = val; } float GetBrightness() const { return brightness; } void SetBrightness(float val) { brightness = val; } protected: LightType type; Vector4 colour; float radius; float brightness; };
3253e026bc57b753922afa0edda4019c1aa2a17b
771db0f8fcf50822b199d3180d31584fb01cc929
/payroll.cpp
2d1a2d8ba2e5c55441d4e4dd747c3b9410b599b4
[]
no_license
curet/EmployeesPayroll
8da8bd8b4a0117177eab0f51b902f9889628b9f3
01e5be63879f476b66d32be9741d529a6786bb2e
refs/heads/main
2023-05-31T12:11:03.359363
2021-06-19T15:47:51
2021-06-19T15:47:51
378,446,735
0
0
null
null
null
null
UTF-8
C++
false
false
3,965
cpp
payroll.cpp
// JOSE C.S. CURET #include <iostream> #include <fstream> #include <iterator> #include <string> #include <list> using namespace std; class Employees{ private: string name; int idNumber; double hoursWorked; double hourlyPayRate; list <Employees> employeesInfo; public: Employees() : idNumber(0), name(), hourlyPayRate(0.00), hoursWorked(0.00) {} Employees(int id, string name, double rate, double hrsWorked) : idNumber(id), name(name), hourlyPayRate(rate), hoursWorked(hrsWorked) {} void readFile(); void readFileEmployeesInfo(); void readFileEmployeesHoursWorked(); void sortEmployeesPerIncome(); void displayPayrollInfo(); }; void Employees::readFile() { readFileEmployeesInfo(); readFileEmployeesHoursWorked(); } void Employees::readFileEmployeesInfo(){ cout << "Please enter the name of the file that contains employees Information" "\nPlease include the extension of the file you would like to analyze" << " (e.g. example.txt, example.dat)" << endl; ifstream inputFile; string nameOfFile; cin >> nameOfFile; inputFile.open(nameOfFile); while(!inputFile){ inputFile.clear(); cout << "Invalid Input!" << endl; cout << "Review your filename" << endl; cin >> nameOfFile; inputFile.open(nameOfFile); } while(!inputFile.eof()){ inputFile >> idNumber >> hourlyPayRate; inputFile.ignore(1); getline(inputFile, name); employeesInfo.push_back(Employees(idNumber, name, hourlyPayRate, 0.00)); } inputFile.close(); } void Employees::readFileEmployeesHoursWorked(){ cout << "Please enter the name of the file that contains employees hours worked" "\nPlease include the extension of the file you would like to analyze" << " (e.g. example.txt, example.dat)" << endl; ifstream inputFile; string nameOfFile; cin >> nameOfFile; inputFile.open(nameOfFile); while(!inputFile){ inputFile.clear(); cout << "Invalid Input!" << endl; cout << "Review your filename" << endl; cin >> nameOfFile; inputFile.open(nameOfFile); } list <Employees>::iterator iter; while(inputFile >> idNumber >> hoursWorked){ bool idFound = false; for(iter = employeesInfo.begin(); iter != employeesInfo.end(); ++iter){ if(iter->idNumber == idNumber){ iter->hoursWorked += hoursWorked; idFound = true; } } if(!idFound){ employeesInfo.push_back(Employees(idNumber, "Unregistered Employee", 0.00, hoursWorked)); } } inputFile.close(); sortEmployeesPerIncome(); } void Employees::sortEmployeesPerIncome(){ bool swapped; list <Employees>::iterator iter; do{ auto it = employeesInfo.begin(); auto next = std::next(it, 1); swapped = false; for(iter = employeesInfo.begin(); next != employeesInfo.end(); ++iter, ++next){ if(((iter->hoursWorked) * (iter->hourlyPayRate)) < ((next->hoursWorked) * (next->hourlyPayRate))){ swap(*iter, *next); swapped = true; } } }while(swapped); } void Employees::displayPayrollInfo() { list <Employees>::iterator iter; cout << "*********Payroll Information********" << endl; for(iter = employeesInfo.begin(); iter != employeesInfo.end(); ++iter){ if(iter->name == "Unregistered Employee"){ cout << iter->name << "(s) with " << iter->hoursWorked << " unassigned hours" << endl; } else{ cout << iter->name << ", $"; cout << (iter->hoursWorked * iter->hourlyPayRate) << endl; } } cout << "*********End payroll**************" << endl; } int main(){ Employees e; e.readFile(); e.displayPayrollInfo(); return 0; }
85e16725ec5770124f6d368f45007419c638721d
1605ae42bf1c7d0d487b60278d1c6d6cfeb3d52e
/tester/main.cpp
2d318453e005cc26f2f12b1165e431ad2e9d3b02
[ "MIT" ]
permissive
Buerner/ssrface
3ca622bba563c11a84db34e9ece90ff9df66a9af
226afe2badb432cfef21f40cbce05c2c026d3e19
refs/heads/master
2021-01-01T19:17:07.425879
2017-08-08T16:25:23
2017-08-08T16:25:23
98,553,751
0
0
null
null
null
null
UTF-8
C++
false
false
1,189
cpp
main.cpp
// // main.cpp // ssrface // // Created by Martin Bürner on 30.11.16. // Copyright © 2016 Martin Bürner. All rights reserved. // #include "SceneManager.hpp" void print_scene( ssrface::Scene* scene_ptr, void* ) { auto ids = scene_ptr->get_source_ids(); scene_ptr->print(); } int main() { ssrface::SceneManager manager; // Set address for SSR running on localhost. manager.set_ssr_address( "127.0.0.1", 4711 ); manager.set_new_source_callback( print_scene, NULL ); manager.connect(); sleep(1); // Performe some actions in case connection was successfull. if ( manager.is_connected() ) { manager.run(); manager.clear_scene(); manager.setup_new_source( "Alice", 1.f, 1.f, false ); sleep(1); manager.turn_reference(0); sleep(1); manager.turn_reference(180); manager.setup_new_source( "Bob", 0.f, -1.f, false ); sleep(1); manager.move_source(1, -1, 1); sleep(1); manager.clear_scene(); manager.disconnect(); } else { printf("Unable to connect to SSR.\n"); } return 0; }
39d1569e62a27bbd65e0e33993e7a5bf96689f57
b7aa96fbfc50da8ad00804ec63804932c902a0c8
/src/Flight.cpp
35707c90fb76397910c15ddc0f2be13f1f13c5d1
[]
no_license
dherraiz/atcsimv2
57108b6afe10c4e03f7fa249418126d58945a893
ee811723c41a3a482e468d9fbbc017f368b8a92d
refs/heads/master
2022-10-30T01:44:51.713149
2020-06-18T20:28:57
2020-06-18T20:28:57
271,759,035
0
0
null
null
null
null
UTF-8
C++
false
false
3,635
cpp
Flight.cpp
/* * Flight.cpp * * Created on: 15/07/2014 * Author: paco * * Copyright 2014 Francisco Martín * * This file is part of ATCSim. * * ATCSim is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ATCSim 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 ATCSim. If not, see <http://www.gnu.org/licenses/>. */ #include "std_msgs/String.h" #include "Flight.h" #ifdef __APPLE__ #include <OpenGL/gl.h> #include <OpenGL/glu.h> #else #include <GL/glu.h> #include <GL/gl.h> #endif #include "Common.h" #include <iostream> #include <string> #include <math.h> Flight::~Flight() { // TODO Auto-generated destructor stub } Flight::Flight(std::string _id, Position _pos, float _bearing, float _inclination, float _speed) { id = _id; pos = _pos; bearing = _bearing; init_bearing = _bearing; inclination = _inclination; //speed = _speed; setSpeed(_speed); // Through set in order to limit speeds route.clear(); inStorm = false; focused = false; points = INIT_FLIGHT_POINTS; w_speed = 0.0f; } void Flight::update(float delta_t) { float trans; Position CPpos; float distXY_CP = 1.0f; //[TODO] float reduc = 0.02; //REDUCTOR DE VELOCIDAD [ TODO ] if(routed()) { float goal_bearing, diff_bearing, new_w; CPpos = route.front().pos; if(CPpos.get_z() <= MAINTAIN_ALT){ // Maintain altitude float current_alt = (this->getPosition()).get_z(); CPpos.set_z(current_alt); route.front().pos.set_z(current_alt); } pos.angles(CPpos, goal_bearing, inclination); goal_bearing = normalizePi(goal_bearing + M_PI); diff_bearing = normalizePi(goal_bearing - bearing); new_w = diff_bearing; if(fabs(new_w)>MAX_FLIFGT_W) new_w = (fabs(new_w)/new_w) * MAX_FLIFGT_W; bearing = bearing + new_w*delta_t*50; //TODO Factor de aumento para que gire normal" float goal_speed, diff_speed, acc; //mantener la velocidad durante el giro if(fabs(new_w) < MAX_FLIFGT_W*0.9){ goal_speed = checkSpeedLimits(route.front().speed); }else{ goal_speed = speed; } acc = (goal_speed - speed); if(fabs(acc)>MAX_ACELERATION) acc = (acc/fabs(acc))*MAX_ACELERATION; speed = speed + acc*delta_t*50; //gire antes de llegar al CP /*if(route.size()>=2){ Position CPpos_next; std::list<Route>::iterator it = route.begin(); CPpos_next = (++it)->pos; float alpha; if(0.0 <= pos.distX_EjeBody(CPpos, CPpos_next)){ //saber si el CPpos_next esta adelante o atras del CPpos alpha = M_PI - pos.get_angle(CPpos, CPpos_next); }else{ alpha = pos.get_angle(CPpos, CPpos_next); } distXY_CP = fabs(speed / (MAX_FLIFGT_W * tan(alpha/2))); }*/ if(pos.distance(CPpos)<DIST_POINT*reduc*0.01 /*|| pos.distanceXY(CPpos)<=distXY_CP*/){ route.pop_front(); ROS_INFO_STREAM("POPPING "<< id); } }else{ inclination = 0.0; } last_pos = pos; trans = speed*reduc * delta_t; pos.set_x(pos.get_x() + trans * cos(bearing) * cos(inclination)); pos.set_y(pos.get_y() + trans * sin(bearing) * cos(inclination)); pos.set_z(pos.get_z() + ( trans * sin(inclination))); } float Flight::checkSpeedLimits(float tgt_speed){ return (tgt_speed > CRASH_SPEED_MAX ? CRASH_SPEED_MAX : tgt_speed); }
906113a93114b5fae52860420ed4e40d1d972f2c
e0258286b3345c7afc09cc0b31b28b981f1f3ac7
/Serveur_interaction_sans_contact-master/Serveur_isc/Serveur_isc/DataCalibrageHandler.cpp
a6ec76738c4a925ed05bbb0eed55e324d73c6394
[]
no_license
IHMISC2020/ISCServer
6e3423655ebb97815aaac149915af83d9f862a7f
f3861e81569b8932240e2dbea3a22d7fe2856432
refs/heads/main
2023-04-09T16:42:20.783647
2021-04-13T17:26:59
2021-04-13T17:26:59
357,605,967
0
0
null
null
null
null
UTF-8
C++
false
false
489
cpp
DataCalibrageHandler.cpp
#include "DataCalibrageHandler.h" /*static*/DataCalibrageHandler* DataCalibrageHandler::mInstance = nullptr; DataCalibrageHandler::DataCalibrageHandler() {} /*virtual*/DataCalibrageHandler::~DataCalibrageHandler() {} /*static*/ DataCalibrageHandler& DataCalibrageHandler::getInstance() { if (mInstance == nullptr) mInstance = new DataCalibrageHandler; return *mInstance; } const std::vector<DataCalibrage>& DataCalibrageHandler::getDataCalibrage() const { return mDataCalibrages; }
85d344fc0bd54dbe2387d440d4c0773fa83bd8bf
280e6ebe8bd55299e5a2b538a9cf2571a9f81352
/应用/经典面试100题/经典面试100题/70.cpp
3ac5dd257eac2a514d83af3afc1e61d1c6deb34b
[]
no_license
WadeZeak/C_and_Cpp
3a0996b6a44f7ee455250e5bbfa7b5541b133af7
da98ea0a14d158cba48c609fa474c46a1095e312
refs/heads/master
2021-01-25T14:11:40.514329
2018-03-03T10:17:14
2018-03-03T10:17:14
123,668,111
0
0
null
null
null
null
GB18030
C++
false
false
705
cpp
70.cpp
#include<iostream> using namespace std; struct CLS { int m_i; CLS(int i) : m_i(i) {} CLS() { /* 在默认构造函数内部再调用带参的构造函数属用户行为而非编译器行为,亦即仅执行函数调用, 而不会执行其后的初始化表达式。只有在生成对象时,初始化表达式才会随相应的构造函数一起调用。 */ CLS(0); } }; void run(int *sa, int sz);//如果在两个函数的参数表中只有缺省实参不同则第二个声明被视为第一个的重复声明 。 void run(int *, int = 10); void main() { CLS obj; cout << obj.m_i << endl; static int val;//静态变量自动初始化 cout << val << endl;//0 cin.get(); }
6e895bf0867c7fadb6617b66de7299baf12fbb96
c8fcc1acf73585045a5c7213cfb9f90e4c1e809e
/HDU/1671-性质.cpp
26e2f589a0c973054fe6cc3754f01e90aa543b33
[]
no_license
Jonariguez/ACM_Code
6db4396b20d0b0aeef30e4d47b51fb5e3ec48e03
465a11746d577197772f64aa11209eebd5bfcdd3
refs/heads/master
2020-03-24T07:09:53.482953
2018-11-19T09:21:33
2018-11-19T09:21:33
142,554,816
3
0
null
null
null
null
GB18030
C++
false
false
1,450
cpp
1671-性质.cpp
/*http://www.cnblogs.com/dolphin0520/archive/2011/10/15/2213752.html 存在前缀的序列的性质: 引用:存在若干个字符串序列,对于两个 字符串序列X[1....n],Y[1....m],如果X是Y的前缀, 则在对所有的字符串序列按字典顺序排序后, X[1..n]和Y[1....m]在位置上必然是直接相邻或者 间接相邻的。间接相邻指存在字符串序列Z[1....t], 使得X是Z的前缀(X和Z直接相邻),Z是Y的前缀(Z和Y 直接相邻),则X和Y也被认为是相邻的。 */ #include <stdio.h> #include <string.h> #include <algorithm> using namespace std; const int maxn=500000+10; struct Str{ int len; char ss[11]; }s[10005]; int cmp(const Str &x,const Str &y){ return strcmp(x.ss,y.ss)<0; } int Strcmp(char *a,char *b){ //查看a是否是b的前缀,如果是返回0 int i,n=strlen(a); for(i=0;i<n;i++) if(a[i]!=b[i]) return 1; return 0; } int main() { int i,n,t; char str[11]; scanf("%d",&t); while(t--){ scanf("%d",&n); for(i=0;i<n;i++){ scanf("%s",s[i].ss); s[i].len=strlen(s[i].ss); } sort(s,s+n,cmp); for(i=0;i<n-1;i++){ int len1=s[i].len,len2=s[i+1].len; if(len1<=len2 && Strcmp(s[i].ss,s[i+1].ss)==0) break; } if(i==n-1) printf("YES\n"); else printf("NO\n"); } return 0; }