blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 4
201
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
85
| license_type
stringclasses 2
values | repo_name
stringlengths 7
100
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 260
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 11.4k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 17
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 80
values | src_encoding
stringclasses 28
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 8
9.86M
| extension
stringclasses 52
values | content
stringlengths 8
9.86M
| authors
sequencelengths 1
1
| author
stringlengths 0
119
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
12f3c848c92f087d6d2a1c6284373bd1ff664d19 | 337f830cdc233ad239a5cc2f52c6562fbb671ea8 | /case5cells/6.6/polyMesh/pointZones | bc3a89f1e0b994f6b16c3c775ba0e6499adc04bf | [] | no_license | j-avdeev/laplacianFoamF | dba31d0941c061b2435532cdfbd5a5b337e6ffe9 | 6e1504dc84780dc86076145c18862f1882078da5 | refs/heads/master | 2021-06-25T23:52:36.435909 | 2017-02-05T17:28:45 | 2017-02-05T17:28:45 | 26,997,393 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 873 | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: 2.3.0 |
| \\ / A nd | Web: www.OpenFOAM.org |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class regIOobject;
location "6.6/polyMesh";
object pointZones;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
0
()
// ************************************************************************* //
| [
"[email protected]"
] | ||
d2eb986dd64833b946474fc1d72e0c8b5a759757 | df3e6c2f276ef80ea6dd260ea8ff1f6ff65246db | /MEXUM.cpp | 4f5bd413473e7417fd98aa21e06e44ea22a5def9 | [
"MIT"
] | permissive | sachanakshat/Competitive_Practice | a3e1a77894d5ca1811debdc4304fcbe5a80f3ff3 | 63170d87398bf5bd163febecdcfef8db21c632c7 | refs/heads/main | 2023-03-28T08:20:00.347713 | 2021-03-30T10:10:17 | 2021-03-30T10:10:17 | 352,952,307 | 0 | 0 | MIT | 2021-03-30T10:10:18 | 2021-03-30T09:57:34 | null | UTF-8 | C++ | false | false | 714 | cpp | #include <iostream>
#include <algorithm>
#include <vector>
#include<bits/stdc++.h>
using namespace std;
int* subsum(int a[], int index, int subindex, int sub[], int N)
{
if(index == N)
{
return sub;
}
int sub[subindex] = a[index] + subsum(a, index+1, subindex+1, sub, N);
int sum[subindex] = subsum(a, index+1, subindex, sub, N);
return sum1+sum2;
}
int main()
{
int T,N,i,j,k,l,power;
cin>>T;
for(i=0; i<T; i++)
{
cin>>N;
int a[N],sub[N];
for(j=0; j<N; j++)
{
cin>>a[j];
sub[j] = 0;
}
// power = pow(2,N);
// int ss[power];
sol = subsum(a,0,0,sub,N);
}
return 0;
} | [
"[email protected]"
] | |
307f7aca6d80cbb4c174debf0567a5be42016025 | 3181b69e42860996b019d71ff956cc1a69c00127 | /caleb.hpp | 2367723aaf1890778e4ac2c3e9c23522dfba7844 | [] | no_license | amcalhoun84/Group-Mu-The-Summerworth-Horror | 4737dc375f841b802cd6158a418999dd39bd9749 | a3e8b36f5d9719841f50f2f273518279bf78c592 | refs/heads/master | 2020-04-05T18:32:21.249738 | 2016-06-09T20:55:12 | 2016-06-09T20:55:12 | 55,563,848 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 295 | hpp | #ifndef _CALEB_HPP
#define _CALEB_HPP
#include "creature.hpp"
class Caleb : public Creature
{
private:
string insults;
string response;
public:
Caleb();
~Caleb();
std::string conversation(string cmd);
std::string randomInsult();
int attackPlayerHP();
};
#endif | [
"[email protected]"
] | |
96454b51922a36b5045c892e2a169f758cc457b5 | 1f7f599da6cbf91f4afd8abfb497c465f7663c8b | /emscripten-arch/hello.cpp | fb0de74fdceefb470c7f45c6c27c3a48b1ee5b54 | [] | no_license | cjxgm/emscripten-arch | 7853ecd6f66245743c0643ca02f0a8726997c56b | bd4c14ae295e4937d9971243d0f6f5832aa04408 | refs/heads/master | 2021-05-09T22:50:32.935849 | 2018-10-06T09:48:01 | 2018-10-06T09:48:01 | 118,765,651 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 179 | cpp | #include <iostream>
#include <stdexcept>
int main() try
{
throw std::runtime_error{"hello world"};
}
catch (std::exception const& ex) {
std::cerr << ex.what() << "\n";
}
| [
"[email protected]"
] | |
8da703989e02999fc1ec6ff6737b1e2776777f81 | 2b78e93ea6c85993bc66690319bea1112ef3e8f4 | /meinwidget.h | 5e8bd30db6360ce38b594243061a3f5ec02ead53 | [] | no_license | dsteige1/SteigerDavid_Cpp2 | b40df8c703744ff65dcd4bfa49b95854ce51ae4c | 1a8e19771ef5aa8f756c2cb8e77cdc43ea0d229b | refs/heads/master | 2020-03-23T09:52:53.657518 | 2018-09-15T14:57:30 | 2018-09-15T14:57:30 | 141,412,849 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 436 | h | #include <QWidget>
#include "spielfeld.h"
#include <QPushButton>
class meinWidget : public QWidget{
Q_OBJECT
public:
meinWidget(QWidget *parent = 0);
QPushButton *starter=new QPushButton(tr("Start")); //Button is initiated here, so that I can change the name via the Slots
private:
spielfeld *meinSpielfeld = new spielfeld;
int count=1;
private slots:
void start();
void load();
void save();
};
| [
"[email protected]"
] | |
09730ad175241ca2c15ca80fc62753167e9b0e4e | e1826894c8e2aca01f04829e0b797654ca72c38f | /cpp/Lynx3-patterns.cpp | 6b1c6b46b2dc9d9ed8f397b1395a38df41a601df | [] | no_license | maksverver/lynx | 01df0cdc3282972e020c330e164ba498b20469d4 | 4db3d375d8b1cbca6752ccc1461034b3d95fd938 | refs/heads/master | 2023-05-11T12:00:23.239704 | 2014-05-26T13:10:36 | 2014-05-26T13:10:36 | 20,185,503 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 37,566 | cpp | #include <vector>
// Patterns for the monte carlo simulation
// patterns[i] encodes the patterns that must be checked when the opponent has played position i in the previous simulation step
// The patterns for a position are encoded in an array, where one pattern consists of four long longs:
// 1 & 2: A bit mask encoding a set of positions that all must belong long to us
// 3 & 4: A bit mask encoding a set of positions of which none may belong long to the opponent
// The high 16 bits of the last long long encode the position that we must play if the pattern matches
// Currently there are two patterns encoded:
// Bridges: If the opponent plays in a bridge belong longing to us, we will defend that bridge by connecting it
// A primitive edge connection pattern: If a position of us is less than three steps away from the edge and the opponent plays below us (a neighbour of our position that is one step away from the edge),
// then we play next to the position of the opponent below our move, but only if the two positions below the move that we play do not belong long to the opponent
// Note that we have experimented with more 'correct' edge connection patterns, but we found that this only resulted in weaker play
extern const std::vector<unsigned long long> patterns[107] = {{},
{8ULL,0ULL,16ULL,1125899906842624ULL,8ULL,0ULL,4ULL,562949953421312ULL},
{64ULL,0ULL,32ULL,1407374883553280ULL,8ULL,0ULL,2ULL,281474976710656ULL},
{128ULL,0ULL,30ULL,844424930131968ULL,128ULL,0ULL,100ULL,1688849860263936ULL,128ULL,0ULL,784ULL,2251799813685248ULL,66ULL,0ULL,4ULL,562949953421312ULL,132ULL,0ULL,64ULL,1688849860263936ULL,320ULL,0ULL,128ULL,1970324836974592ULL,144ULL,0ULL,256ULL,2251799813685248ULL,258ULL,0ULL,16ULL,1125899906842624ULL,20ULL,0ULL,2ULL,281474976710656ULL},
{256ULL,0ULL,512ULL,2533274790395904ULL,8ULL,0ULL,2ULL,281474976710656ULL},
{2048ULL,0ULL,1024ULL,2814749767106560ULL,64ULL,0ULL,4ULL,562949953421312ULL},
{128ULL,0ULL,30ULL,844424930131968ULL,128ULL,0ULL,100ULL,1688849860263936ULL,128ULL,0ULL,784ULL,2251799813685248ULL,4096ULL,0ULL,100ULL,1688849860263936ULL,4096ULL,0ULL,3104ULL,3096224743817216ULL,132ULL,0ULL,8ULL,844424930131968ULL,4104ULL,0ULL,128ULL,1970324836974592ULL,2176ULL,0ULL,4096ULL,3377699720527872ULL,4128ULL,0ULL,2048ULL,3096224743817216ULL,2052ULL,0ULL,32ULL,1407374883553280ULL,40ULL,0ULL,4ULL,562949953421312ULL},
{8192ULL,0ULL,456ULL,1970324836974592ULL,8192ULL,0ULL,6208ULL,3377699720527872ULL,8192ULL,0ULL,49408ULL,3940649673949184ULL,4104ULL,0ULL,64ULL,1688849860263936ULL,8256ULL,0ULL,4096ULL,3377699720527872ULL,20480ULL,0ULL,8192ULL,3659174697238528ULL,8448ULL,0ULL,16384ULL,3940649673949184ULL,16392ULL,0ULL,256ULL,2251799813685248ULL,320ULL,0ULL,8ULL,844424930131968ULL},
{16384ULL,0ULL,784ULL,2251799813685248ULL,16384ULL,0ULL,98816ULL,4222124650659840ULL,128ULL,0ULL,30ULL,844424930131968ULL,128ULL,0ULL,100ULL,1688849860263936ULL,128ULL,0ULL,784ULL,2251799813685248ULL,520ULL,0ULL,16ULL,1125899906842624ULL,32784ULL,0ULL,512ULL,2533274790395904ULL,16896ULL,0ULL,32768ULL,4222124650659840ULL,32896ULL,0ULL,16384ULL,3940649673949184ULL,16392ULL,0ULL,128ULL,1970324836974592ULL,144ULL,0ULL,8ULL,844424930131968ULL},
{256ULL,0ULL,16ULL,1125899906842624ULL,32768ULL,0ULL,65536ULL,4503599627370496ULL},
{2048ULL,0ULL,32ULL,1407374883553280ULL,262144ULL,0ULL,131072ULL,4785074604081152ULL},
{524288ULL,0ULL,394240ULL,5066549580791808ULL,524288ULL,0ULL,3104ULL,3096224743817216ULL,4096ULL,0ULL,100ULL,1688849860263936ULL,4096ULL,0ULL,3104ULL,3096224743817216ULL,525312ULL,0ULL,262144ULL,5066549580791808ULL,262176ULL,0ULL,1024ULL,2814749767106560ULL,1088ULL,0ULL,32ULL,1407374883553280ULL,4128ULL,0ULL,64ULL,1688849860263936ULL,524352ULL,0ULL,4096ULL,3377699720527872ULL,266240ULL,0ULL,524288ULL,5348024557502464ULL},
{1048576ULL,0ULL,788480ULL,5348024557502464ULL,1048576ULL,0ULL,6208ULL,3377699720527872ULL,8192ULL,0ULL,456ULL,1970324836974592ULL,8192ULL,0ULL,6208ULL,3377699720527872ULL,8192ULL,0ULL,49408ULL,3940649673949184ULL,532480ULL,0ULL,1048576ULL,5629499534213120ULL,1048704ULL,0ULL,8192ULL,3659174697238528ULL,8256ULL,0ULL,128ULL,1970324836974592ULL,2176ULL,0ULL,64ULL,1688849860263936ULL,524352ULL,0ULL,2048ULL,3096224743817216ULL,1050624ULL,0ULL,524288ULL,5348024557502464ULL},
{2101248ULL,0ULL,1048576ULL,5629499534213120ULL,1048704ULL,0ULL,4096ULL,3377699720527872ULL,20480ULL,0ULL,128ULL,1970324836974592ULL,4194432ULL,0ULL,16384ULL,3940649673949184ULL,2113536ULL,0ULL,4194304ULL,6192449487634432ULL,5242880ULL,0ULL,2097152ULL,5910974510923776ULL},
{4194304ULL,0ULL,25198592ULL,6473924464345088ULL,4194304ULL,0ULL,49408ULL,3940649673949184ULL,8192ULL,0ULL,456ULL,1970324836974592ULL,8192ULL,0ULL,6208ULL,3377699720527872ULL,8192ULL,0ULL,49408ULL,3940649673949184ULL,8396800ULL,0ULL,4194304ULL,6192449487634432ULL,4194432ULL,0ULL,8192ULL,3659174697238528ULL,8448ULL,0ULL,128ULL,1970324836974592ULL,32896ULL,0ULL,256ULL,2251799813685248ULL,8388864ULL,0ULL,32768ULL,4222124650659840ULL,4227072ULL,0ULL,8388608ULL,6473924464345088ULL},
{8388608ULL,0ULL,50397184ULL,6755399441055744ULL,8388608ULL,0ULL,98816ULL,4222124650659840ULL,16384ULL,0ULL,784ULL,2251799813685248ULL,16384ULL,0ULL,98816ULL,4222124650659840ULL,8454144ULL,0ULL,16777216ULL,6755399441055744ULL,16793600ULL,0ULL,8388608ULL,6473924464345088ULL,8388864ULL,0ULL,16384ULL,3940649673949184ULL,16896ULL,0ULL,256ULL,2251799813685248ULL,65792ULL,0ULL,512ULL,2533274790395904ULL,16777728ULL,0ULL,65536ULL,4503599627370496ULL},
{32768ULL,0ULL,512ULL,2533274790395904ULL,16777216ULL,0ULL,33554432ULL,7036874417766400ULL},
{134217728ULL,0ULL,67108864ULL,7318349394477056ULL,262144ULL,0ULL,1024ULL,2814749767106560ULL},
{268435456ULL,0ULL,394240ULL,5066549580791808ULL,268435456ULL,0ULL,201457664ULL,7599824371187712ULL,524288ULL,0ULL,394240ULL,5066549580791808ULL,524288ULL,0ULL,3104ULL,3096224743817216ULL,268566528ULL,0ULL,134217728ULL,7599824371187712ULL,134742016ULL,0ULL,268435456ULL,7881299347898368ULL,268437504ULL,0ULL,524288ULL,5348024557502464ULL,525312ULL,0ULL,2048ULL,3096224743817216ULL,133120ULL,0ULL,1024ULL,2814749767106560ULL,134218752ULL,0ULL,131072ULL,4785074604081152ULL},
{1048576ULL,0ULL,788480ULL,5348024557502464ULL,1048576ULL,0ULL,6208ULL,3377699720527872ULL,536870912ULL,0ULL,788480ULL,5348024557502464ULL,536870912ULL,0ULL,402915328ULL,7881299347898368ULL,266240ULL,0ULL,2048ULL,3096224743817216ULL,1050624ULL,0ULL,4096ULL,3377699720527872ULL,536875008ULL,0ULL,1048576ULL,5629499534213120ULL,269484032ULL,0ULL,536870912ULL,8162774324609024ULL,537133056ULL,0ULL,268435456ULL,7881299347898368ULL,268437504ULL,0ULL,262144ULL,5066549580791808ULL},
{1074266112ULL,0ULL,536870912ULL,8162774324609024ULL,538968064ULL,0ULL,1073741824ULL,8444249301319680ULL,1073750016ULL,0ULL,2097152ULL,5910974510923776ULL,2101248ULL,0ULL,8192ULL,3659174697238528ULL,532480ULL,0ULL,4096ULL,3377699720527872ULL,536875008ULL,0ULL,524288ULL,5348024557502464ULL},
{4294975488ULL,0ULL,4194304ULL,6192449487634432ULL,5242880ULL,0ULL,8192ULL,3659174697238528ULL,1073750016ULL,0ULL,1048576ULL,5629499534213120ULL,2148532224ULL,0ULL,1073741824ULL,8444249301319680ULL,5368709120ULL,0ULL,2147483648ULL,8725724278030336ULL,2151677952ULL,0ULL,4294967296ULL,9007199254740992ULL},
{4303355904ULL,0ULL,8589934592ULL,9288674231451648ULL,8589950976ULL,0ULL,8388608ULL,6473924464345088ULL,8396800ULL,0ULL,16384ULL,3940649673949184ULL,2113536ULL,0ULL,8192ULL,3659174697238528ULL,4294975488ULL,0ULL,2097152ULL,5910974510923776ULL,8592031744ULL,0ULL,4294967296ULL,9007199254740992ULL},
{8589934592ULL,0ULL,51556384768ULL,9570149208162304ULL,8589934592ULL,0ULL,25198592ULL,6473924464345088ULL,4194304ULL,0ULL,25198592ULL,6473924464345088ULL,4194304ULL,0ULL,49408ULL,3940649673949184ULL,17184063488ULL,0ULL,8589934592ULL,9288674231451648ULL,8589950976ULL,0ULL,4194304ULL,6192449487634432ULL,4227072ULL,0ULL,16384ULL,3940649673949184ULL,16793600ULL,0ULL,32768ULL,4222124650659840ULL,17179901952ULL,0ULL,16777216ULL,6755399441055744ULL,8606711808ULL,0ULL,17179869184ULL,9570149208162304ULL},
{17179869184ULL,0ULL,103112769536ULL,9851624184872960ULL,17179869184ULL,0ULL,50397184ULL,6755399441055744ULL,8388608ULL,0ULL,50397184ULL,6755399441055744ULL,8388608ULL,0ULL,98816ULL,4222124650659840ULL,17213423616ULL,0ULL,34359738368ULL,9851624184872960ULL,34359803904ULL,0ULL,33554432ULL,7036874417766400ULL,33587200ULL,0ULL,65536ULL,4503599627370496ULL,8454144ULL,0ULL,32768ULL,4222124650659840ULL,17179901952ULL,0ULL,8388608ULL,6473924464345088ULL,34368126976ULL,0ULL,17179869184ULL,9570149208162304ULL},
{34359738368ULL,0ULL,68719476736ULL,10133099161583616ULL,16777216ULL,0ULL,65536ULL,4503599627370496ULL},
{274877906944ULL,0ULL,137438953472ULL,10414574138294272ULL,134217728ULL,0ULL,131072ULL,4785074604081152ULL},
{268435456ULL,0ULL,394240ULL,5066549580791808ULL,268435456ULL,0ULL,201457664ULL,7599824371187712ULL,549755813888ULL,0ULL,4615063718147915776ULL,14355223812243456ULL,549755813888ULL,0ULL,1126312290811904ULL,10696049115004928ULL,549755813888ULL,0ULL,201457664ULL,7599824371187712ULL,268566528ULL,0ULL,262144ULL,5066549580791808ULL,549756076032ULL,0ULL,268435456ULL,7881299347898368ULL,275146342400ULL,0ULL,549755813888ULL,10977524091715584ULL,549822922752ULL,0ULL,274877906944ULL,10696049115004928ULL,274878038016ULL,0ULL,67108864ULL,7318349394477056ULL,67371008ULL,0ULL,131072ULL,4785074604081152ULL},
{1099511627776ULL,0ULL,2252624581623808ULL,10977524091715584ULL,1099511627776ULL,0ULL,-9216616637413720064ULL,14636698788954112ULL,1099511627776ULL,0ULL,402915328ULL,7881299347898368ULL,536870912ULL,0ULL,788480ULL,5348024557502464ULL,536870912ULL,0ULL,402915328ULL,7881299347898368ULL,134742016ULL,0ULL,262144ULL,5066549580791808ULL,549756076032ULL,0ULL,134217728ULL,7599824371187712ULL,1099645845504ULL,0ULL,549755813888ULL,10977524091715584ULL,550292684800ULL,0ULL,1099511627776ULL,11258999068426240ULL,1099512152064ULL,0ULL,536870912ULL,8162774324609024ULL,537133056ULL,0ULL,524288ULL,5348024557502464ULL},
{1074266112ULL,0ULL,1048576ULL,5629499534213120ULL,2199024304128ULL,0ULL,1073741824ULL,8444249301319680ULL,1100585369600ULL,0ULL,2199023255552ULL,11540474045136896ULL,2199291691008ULL,0ULL,1099511627776ULL,11258999068426240ULL,1099512152064ULL,0ULL,268435456ULL,7881299347898368ULL,269484032ULL,0ULL,524288ULL,5348024557502464ULL},
{538968064ULL,0ULL,1048576ULL,5629499534213120ULL,2199024304128ULL,0ULL,536870912ULL,8162774324609024ULL,4398583382016ULL,0ULL,2199023255552ULL,11540474045136896ULL,2201170739200ULL,0ULL,4398046511104ULL,11821949021847552ULL,4398048608256ULL,0ULL,2147483648ULL,8725724278030336ULL,2148532224ULL,0ULL,2097152ULL,5910974510923776ULL},
{5368709120ULL,0ULL,2097152ULL,5910974510923776ULL,4398048608256ULL,0ULL,1073741824ULL,8444249301319680ULL,8797166764032ULL,0ULL,4398046511104ULL,11821949021847552ULL,21990232555520ULL,0ULL,8796093022208ULL,12103423998558208ULL,8800387989504ULL,0ULL,17592186044416ULL,12384898975268864ULL,17592188141568ULL,0ULL,4294967296ULL,9007199254740992ULL},
{8592031744ULL,0ULL,4194304ULL,6192449487634432ULL,2151677952ULL,0ULL,2097152ULL,5910974510923776ULL,17592188141568ULL,0ULL,2147483648ULL,8725724278030336ULL,35186519572480ULL,0ULL,17592186044416ULL,12384898975268864ULL,17600775979008ULL,0ULL,35184372088832ULL,12666373951979520ULL,35184376283136ULL,0ULL,8589934592ULL,9288674231451648ULL},
{17184063488ULL,0ULL,8388608ULL,6473924464345088ULL,4303355904ULL,0ULL,4194304ULL,6192449487634432ULL,35184376283136ULL,0ULL,4294967296ULL,9007199254740992ULL,70373039144960ULL,0ULL,35184372088832ULL,12666373951979520ULL,35201551958016ULL,0ULL,70368744177664ULL,12947848928690176ULL,70368752566272ULL,0ULL,17179869184ULL,9570149208162304ULL},
{8589934592ULL,0ULL,51556384768ULL,9570149208162304ULL,8589934592ULL,0ULL,25198592ULL,6473924464345088ULL,70368744177664ULL,0ULL,51556384768ULL,9570149208162304ULL,70368744177664ULL,0ULL,1729382256910270464ULL,16607023625928832ULL,70368744177664ULL,0ULL,1153343751431651328ULL,13229323905400832ULL,34368126976ULL,0ULL,16777216ULL,6755399441055744ULL,8606711808ULL,0ULL,8388608ULL,6473924464345088ULL,70368752566272ULL,0ULL,8589934592ULL,9288674231451648ULL,140746078289920ULL,0ULL,70368744177664ULL,12947848928690176ULL,70403103916032ULL,0ULL,140737488355328ULL,13229323905400832ULL,140737505132544ULL,0ULL,34359738368ULL,9851624184872960ULL},
{17179869184ULL,0ULL,103112769536ULL,9851624184872960ULL,17179869184ULL,0ULL,50397184ULL,6755399441055744ULL,140737488355328ULL,0ULL,103112769536ULL,9851624184872960ULL,140737488355328ULL,0ULL,2306687502863302656ULL,13510798882111488ULL,140737488355328ULL,0ULL,3458764513820540928ULL,16888498602639616ULL,17213423616ULL,0ULL,16777216ULL,6755399441055744ULL,68736253952ULL,0ULL,33554432ULL,7036874417766400ULL,281475010265088ULL,0ULL,68719476736ULL,10133099161583616ULL,140806207832064ULL,0ULL,281474976710656ULL,13510798882111488ULL,281492156579840ULL,0ULL,140737488355328ULL,13229323905400832ULL,140737505132544ULL,0ULL,17179869184ULL,9570149208162304ULL},
{34359738368ULL,0ULL,33554432ULL,7036874417766400ULL,281474976710656ULL,0ULL,562949953421312ULL,13792273858822144ULL},
{274877906944ULL,0ULL,67108864ULL,7318349394477056ULL,274877906944ULL,0ULL,1125899906842624ULL,14073748835532800ULL},
{549755813888ULL,0ULL,4615063718147915776ULL,14355223812243456ULL,549755813888ULL,0ULL,1126312290811904ULL,10696049115004928ULL,549755813888ULL,0ULL,201457664ULL,7599824371187712ULL,2251937252638720ULL,0ULL,1125899906842624ULL,14073748835532800ULL,1125899973951488ULL,0ULL,137438953472ULL,10414574138294272ULL,137573171200ULL,0ULL,67108864ULL,7318349394477056ULL,549822922752ULL,0ULL,134217728ULL,7599824371187712ULL,2251799947902976ULL,0ULL,549755813888ULL,10977524091715584ULL,1126449662656512ULL,0ULL,2251799813685248ULL,14355223812243456ULL},
{1099511627776ULL,0ULL,2252624581623808ULL,10977524091715584ULL,1099511627776ULL,0ULL,-9216616637413720064ULL,14636698788954112ULL,1099511627776ULL,0ULL,402915328ULL,7881299347898368ULL,2251799947902976ULL,0ULL,274877906944ULL,10696049115004928ULL,275146342400ULL,0ULL,134217728ULL,7599824371187712ULL,1099645845504ULL,0ULL,268435456ULL,7881299347898368ULL,4503599895805952ULL,0ULL,1099511627776ULL,11258999068426240ULL,2252899325313024ULL,0ULL,4503599627370496ULL,14636698788954112ULL,4503874505277440ULL,0ULL,2251799813685248ULL,14355223812243456ULL},
{9007749010554880ULL,0ULL,4503599627370496ULL,14636698788954112ULL,4505798650626048ULL,0ULL,9007199254740992ULL,14918173765664768ULL,9007199791611904ULL,0ULL,2199023255552ULL,11540474045136896ULL,2199291691008ULL,0ULL,536870912ULL,8162774324609024ULL,550292684800ULL,0ULL,268435456ULL,7881299347898368ULL,4503599895805952ULL,0ULL,549755813888ULL,10977524091715584ULL},
{18015498021109760ULL,0ULL,9007199254740992ULL,14918173765664768ULL,9007199791611904ULL,0ULL,1099511627776ULL,11258999068426240ULL,1100585369600ULL,0ULL,536870912ULL,8162774324609024ULL,4398583382016ULL,0ULL,1073741824ULL,8444249301319680ULL,18014399583223808ULL,0ULL,4398046511104ULL,11821949021847552ULL,9011597301252096ULL,0ULL,18014398509481984ULL,15199648742375424ULL},
{36030996042219520ULL,0ULL,18014398509481984ULL,15199648742375424ULL,18014399583223808ULL,0ULL,2199023255552ULL,11540474045136896ULL,2201170739200ULL,0ULL,1073741824ULL,8444249301319680ULL,8797166764032ULL,0ULL,2147483648ULL,8725724278030336ULL,36028799166447616ULL,0ULL,8796093022208ULL,12103423998558208ULL,18023194602504192ULL,0ULL,36028797018963968ULL,15481123719086080ULL},
{36028799166447616ULL,0ULL,4398046511104ULL,11821949021847552ULL,21990232555520ULL,0ULL,2147483648ULL,8725724278030336ULL,72057596185411584ULL,0ULL,17592186044416ULL,12384898975268864ULL,36046389205008384ULL,0ULL,72057594037927936ULL,15762598695796736ULL,72061992084439040ULL,0ULL,36028797018963968ULL,15481123719086080ULL},
{8800387989504ULL,0ULL,2147483648ULL,8725724278030336ULL,72057596185411584ULL,0ULL,8796093022208ULL,12103423998558208ULL,144123984168878080ULL,0ULL,72057594037927936ULL,15762598695796736ULL,72092778410016768ULL,0ULL,144115188075855872ULL,16044073672507392ULL,144115192370823168ULL,0ULL,35184372088832ULL,12666373951979520ULL,35186519572480ULL,0ULL,4294967296ULL,9007199254740992ULL},
{70373039144960ULL,0ULL,8589934592ULL,9288674231451648ULL,288230384741646336ULL,0ULL,70368744177664ULL,12947848928690176ULL,144185556820033536ULL,0ULL,288230376151711744ULL,16325548649218048ULL,288247968337756160ULL,0ULL,144115188075855872ULL,16044073672507392ULL,144115192370823168ULL,0ULL,17592186044416ULL,12384898975268864ULL,17600775979008ULL,0ULL,4294967296ULL,9007199254740992ULL},
{35201551958016ULL,0ULL,8589934592ULL,9288674231451648ULL,288230384741646336ULL,0ULL,35184372088832ULL,12666373951979520ULL,576495936675512320ULL,0ULL,288230376151711744ULL,16325548649218048ULL,288371113640067072ULL,0ULL,576460752303423488ULL,16607023625928704ULL,576460769483292672ULL,0ULL,140737488355328ULL,13229323905400832ULL,140746078289920ULL,0ULL,17179869184ULL,9570149208162304ULL},
{70368744177664ULL,0ULL,51556384768ULL,9570149208162304ULL,70368744177664ULL,0ULL,1729382256910270464ULL,16607023625928832ULL,70368744177664ULL,0ULL,1153343751431651328ULL,13229323905400832ULL,281492156579840ULL,0ULL,34359738368ULL,9851624184872960ULL,1152921538966585344ULL,0ULL,281474976710656ULL,13510798882111488ULL,576742227280134144ULL,0ULL,1152921504606846976ULL,16888498602639360ULL,1152991873351024640ULL,0ULL,576460752303423488ULL,16607023625928704ULL,576460769483292672ULL,0ULL,70368744177664ULL,12947848928690176ULL,70403103916032ULL,0ULL,17179869184ULL,9570149208162304ULL},
{140737488355328ULL,0ULL,103112769536ULL,9851624184872960ULL,140737488355328ULL,0ULL,2306687502863302656ULL,13510798882111488ULL,140737488355328ULL,0ULL,3458764513820540928ULL,16888498602639616ULL,562984313159680ULL,0ULL,68719476736ULL,10133099161583616ULL,2305843077933170688ULL,0ULL,562949953421312ULL,13792273858822144ULL,1153484454560268288ULL,0ULL,2305843009213693952ULL,17169973579350016ULL,2305983746702049280ULL,0ULL,1152921504606846976ULL,16888498602639360ULL,1152921538966585344ULL,0ULL,140737488355328ULL,13229323905400832ULL,140806207832064ULL,0ULL,34359738368ULL,9851624184872960ULL},
{281474976710656ULL,0ULL,2305843009213693952ULL,17169973579350016ULL,281474976710656ULL,0ULL,68719476736ULL,10133099161583616ULL},
{2251799813685248ULL,0ULL,4611686018427387904ULL,17451448556060672ULL,274877906944ULL,0ULL,137438953472ULL,10414574138294272ULL},
{549755813888ULL,0ULL,4615063718147915776ULL,14355223812243456ULL,549755813888ULL,0ULL,1126312290811904ULL,10696049115004928ULL,549755813888ULL,0ULL,201457664ULL,7599824371187712ULL,4503599627370496ULL,0ULL,4615063718147915776ULL,14355223812243456ULL,4503599627370496ULL,0ULL,-4611686018427387904ULL,17732923532771840ULL,1126449662656512ULL,0ULL,274877906944ULL,10696049115004928ULL,4503874505277440ULL,0ULL,549755813888ULL,10977524091715584ULL,-9223371487098961920ULL,0ULL,4503599627370496ULL,14636698788954112ULL,4616189618054758400ULL,0ULL,-9223372036854775808ULL,17732923532771328ULL,-9222246136947933184ULL,0ULL,4611686018427387904ULL,17451448556060672ULL,4611686293305294848ULL,0ULL,1125899906842624ULL,14073748835532800ULL},
{1099511627776ULL,0ULL,2252624581623808ULL,10977524091715584ULL,1099511627776ULL,0ULL,-9216616637413720064ULL,14636698788954112ULL,1099511627776ULL,0ULL,402915328ULL,7881299347898368ULL,9007199254740992ULL,0ULL,-9223372036854775808ULL,18014398509483009ULL,9007199254740992ULL,0ULL,-9216616637413720064ULL,14636698788954112ULL,2252899325313024ULL,0ULL,549755813888ULL,10977524091715584ULL,9007749010554880ULL,0ULL,1099511627776ULL,11258999068426240ULL,1099511627776ULL,1ULL,9007199254740992ULL,14918173765664768ULL,-9214364837600034816ULL,0ULL,0ULL,18014398509481985ULL,2251799813685248ULL,1ULL,-9223372036854775808ULL,17732923532771328ULL,-9223371487098961920ULL,0ULL,2251799813685248ULL,14355223812243456ULL},
{18014398509481984ULL,1ULL,0ULL,18295873486192642ULL,2199023255552ULL,2ULL,18014398509481984ULL,15199648742375424ULL,18015498021109760ULL,0ULL,2199023255552ULL,11540474045136896ULL,4505798650626048ULL,0ULL,1099511627776ULL,11258999068426240ULL,1099511627776ULL,1ULL,4503599627370496ULL,14636698788954112ULL,4503599627370496ULL,2ULL,0ULL,18014398509481985ULL},
{36028797018963968ULL,2ULL,0ULL,18577348462903300ULL,9007199254740992ULL,4ULL,0ULL,18295873486192642ULL,2199023255552ULL,2ULL,9007199254740992ULL,14918173765664768ULL,9011597301252096ULL,0ULL,2199023255552ULL,11540474045136896ULL,36030996042219520ULL,0ULL,4398046511104ULL,11821949021847552ULL,4398046511104ULL,4ULL,36028797018963968ULL,15481123719086080ULL},
{18014398509481984ULL,8ULL,0ULL,18577348462903300ULL,72057594037927936ULL,4ULL,0ULL,18858823439613960ULL,8796093022208ULL,8ULL,72057594037927936ULL,15762598695796736ULL,72061992084439040ULL,0ULL,8796093022208ULL,12103423998558208ULL,18023194602504192ULL,0ULL,4398046511104ULL,11821949021847552ULL,4398046511104ULL,4ULL,18014398509481984ULL,15199648742375424ULL},
{36028797018963968ULL,16ULL,0ULL,18858823439613960ULL,8796093022208ULL,8ULL,36028797018963968ULL,15481123719086080ULL,36046389205008384ULL,0ULL,8796093022208ULL,12103423998558208ULL,144123984168878080ULL,0ULL,17592186044416ULL,12384898975268864ULL,17592186044416ULL,16ULL,144115188075855872ULL,16044073672507392ULL,144115188075855872ULL,8ULL,0ULL,19140298416324624ULL},
{288230376151711744ULL,16ULL,0ULL,19421773393035296ULL,35184372088832ULL,32ULL,288230376151711744ULL,16325548649218048ULL,288247968337756160ULL,0ULL,35184372088832ULL,12666373951979520ULL,72092778410016768ULL,0ULL,17592186044416ULL,12384898975268864ULL,17592186044416ULL,16ULL,72057594037927936ULL,15762598695796736ULL,72057594037927936ULL,32ULL,0ULL,19140298416324624ULL},
{576460752303423488ULL,32ULL,0ULL,19703248369745984ULL,70368744177664ULL,64ULL,576460752303423488ULL,16607023625928704ULL,576495936675512320ULL,0ULL,70368744177664ULL,12947848928690176ULL,144185556820033536ULL,0ULL,35184372088832ULL,12666373951979520ULL,35184372088832ULL,32ULL,144115188075855872ULL,16044073672507392ULL,144115188075855872ULL,64ULL,0ULL,19421773393035296ULL},
{70368744177664ULL,0ULL,51556384768ULL,9570149208162304ULL,70368744177664ULL,0ULL,1729382256910270464ULL,16607023625928832ULL,70368744177664ULL,0ULL,1153343751431651328ULL,13229323905400832ULL,288230376151711744ULL,0ULL,0ULL,19703248369877184ULL,288230376151711744ULL,0ULL,1729382256910270464ULL,16607023625928832ULL,1152921504606846976ULL,64ULL,0ULL,19984723346456704ULL,140737488355328ULL,128ULL,1152921504606846976ULL,16888498602639360ULL,1152991873351024640ULL,0ULL,140737488355328ULL,13229323905400832ULL,288371113640067072ULL,0ULL,70368744177664ULL,12947848928690176ULL,70368744177664ULL,64ULL,288230376151711744ULL,16325548649218048ULL,288230376151711744ULL,128ULL,0ULL,19703248369745984ULL},
{576460752303423488ULL,0ULL,0ULL,19984723346719104ULL,576460752303423488ULL,0ULL,3458764513820540928ULL,16888498602639616ULL,140737488355328ULL,0ULL,103112769536ULL,9851624184872960ULL,140737488355328ULL,0ULL,2306687502863302656ULL,13510798882111488ULL,140737488355328ULL,0ULL,3458764513820540928ULL,16888498602639616ULL,140737488355328ULL,128ULL,576460752303423488ULL,16607023625928704ULL,576742227280134144ULL,0ULL,140737488355328ULL,13229323905400832ULL,2305983746702049280ULL,0ULL,281474976710656ULL,13510798882111488ULL,281474976710656ULL,256ULL,2305843009213693952ULL,17169973579350016ULL,2305843009213693952ULL,128ULL,0ULL,20266198323167488ULL,576460752303423488ULL,256ULL,0ULL,19984723346456704ULL},
{1152921504606846976ULL,0ULL,0ULL,20266198323167488ULL,281474976710656ULL,0ULL,562949953421312ULL,13792273858822144ULL},
{-9223372036854775808ULL,0ULL,0ULL,20547673299878400ULL,2251799813685248ULL,0ULL,1125899906842624ULL,14073748835532800ULL},
{4503599627370496ULL,0ULL,4615063718147915776ULL,14355223812243456ULL,4503599627370496ULL,0ULL,-4611686018427387904ULL,17732923532771840ULL,0ULL,1ULL,-4611686018427387904ULL,17732923532771840ULL,0ULL,1ULL,0ULL,20829148277114368ULL,2251799813685248ULL,1ULL,4503599627370496ULL,14636698788954112ULL,4503599627370496ULL,1024ULL,0ULL,18014398509481985ULL,0ULL,513ULL,0ULL,20829148276589568ULL,4611686018427387904ULL,1024ULL,0ULL,20547673299878400ULL,2251799813685248ULL,512ULL,4611686018427387904ULL,17451448556060672ULL,4616189618054758400ULL,0ULL,2251799813685248ULL,14355223812243456ULL},
{0ULL,2ULL,-9223372036854775808ULL,18014398509483009ULL,0ULL,2ULL,0ULL,21110623254350848ULL,9007199254740992ULL,0ULL,-9223372036854775808ULL,18014398509483009ULL,9007199254740992ULL,0ULL,-9216616637413720064ULL,14636698788954112ULL,4503599627370496ULL,2ULL,9007199254740992ULL,14918173765664768ULL,-9214364837600034816ULL,0ULL,4503599627370496ULL,14636698788954112ULL,4503599627370496ULL,1024ULL,-9223372036854775808ULL,17732923532771328ULL,-9223372036854775808ULL,2048ULL,0ULL,20829148276589568ULL,0ULL,1026ULL,0ULL,21110623253301248ULL,9007199254740992ULL,2048ULL,0ULL,18295873486192642ULL},
{18014398509481984ULL,1ULL,9007199254740992ULL,14918173765664768ULL,9007199254740992ULL,4ULL,18014398509481984ULL,15199648742375424ULL,18014398509481984ULL,4096ULL,0ULL,18577348462903300ULL,0ULL,2052ULL,0ULL,21392098230013952ULL,0ULL,4097ULL,0ULL,21110623253301248ULL,9007199254740992ULL,2048ULL,0ULL,18014398509481985ULL},
{36028797018963968ULL,2ULL,18014398509481984ULL,15199648742375424ULL,18014398509481984ULL,4096ULL,0ULL,18295873486192642ULL,0ULL,8194ULL,0ULL,21392098230013952ULL,0ULL,4104ULL,0ULL,21673573206728704ULL,36028797018963968ULL,8192ULL,0ULL,18858823439613960ULL,18014398509481984ULL,8ULL,36028797018963968ULL,15481123719086080ULL},
{0ULL,8208ULL,0ULL,21955048183447552ULL,0ULL,16388ULL,0ULL,21673573206728704ULL,36028797018963968ULL,8192ULL,0ULL,18577348462903300ULL,72057594037927936ULL,4ULL,36028797018963968ULL,15481123719086080ULL,36028797018963968ULL,16ULL,72057594037927936ULL,15762598695796736ULL,72057594037927936ULL,16384ULL,0ULL,19140298416324624ULL},
{72057594037927936ULL,32ULL,144115188075855872ULL,16044073672507392ULL,144115188075855872ULL,8ULL,72057594037927936ULL,15762598695796736ULL,72057594037927936ULL,16384ULL,0ULL,18858823439613960ULL,0ULL,32776ULL,0ULL,21955048183447552ULL,0ULL,16416ULL,0ULL,22236523160174592ULL,144115188075855872ULL,32768ULL,0ULL,19421773393035296ULL},
{288230376151711744ULL,16ULL,144115188075855872ULL,16044073672507392ULL,144115188075855872ULL,64ULL,288230376151711744ULL,16325548649218048ULL,288230376151711744ULL,65536ULL,0ULL,19703248369745984ULL,0ULL,32832ULL,0ULL,22517998136918016ULL,0ULL,65552ULL,0ULL,22236523160174592ULL,144115188075855872ULL,32768ULL,0ULL,19140298416324624ULL},
{0ULL,32ULL,0ULL,19703248369877184ULL,0ULL,32ULL,0ULL,22517998204157952ULL,288230376151711744ULL,0ULL,0ULL,19703248369877184ULL,288230376151711744ULL,0ULL,1729382256910270464ULL,16607023625928832ULL,0ULL,131104ULL,0ULL,22517998136918016ULL,0ULL,65664ULL,0ULL,22799473113694208ULL,576460752303423488ULL,131072ULL,0ULL,19984723346456704ULL,288230376151711744ULL,128ULL,576460752303423488ULL,16607023625928704ULL,576460752303423488ULL,32ULL,288230376151711744ULL,16325548649218048ULL,288230376151711744ULL,65536ULL,0ULL,19421773393035296ULL},
{0ULL,64ULL,0ULL,19984723346719104ULL,0ULL,64ULL,0ULL,22799473248174080ULL,576460752303423488ULL,0ULL,0ULL,19984723346719104ULL,576460752303423488ULL,0ULL,3458764513820540928ULL,16888498602639616ULL,0ULL,262208ULL,0ULL,22799473113694208ULL,0ULL,131328ULL,0ULL,23080948090535936ULL,1152921504606846976ULL,262144ULL,0ULL,20266198323167488ULL,576460752303423488ULL,256ULL,1152921504606846976ULL,16888498602639360ULL,1152921504606846976ULL,64ULL,576460752303423488ULL,16607023625928704ULL,576460752303423488ULL,131072ULL,0ULL,19703248369745984ULL},
{1152921504606846976ULL,0ULL,2305843009213693952ULL,17169973579350016ULL,0ULL,128ULL,0ULL,23080948090535936ULL},
{-9223372036854775808ULL,0ULL,4611686018427387904ULL,17451448556060672ULL,0ULL,1024ULL,0ULL,23362423067508736ULL},
{0ULL,1ULL,-4611686018427387904ULL,17732923532771840ULL,0ULL,1ULL,0ULL,20829148277114368ULL,0ULL,2048ULL,0ULL,23643898313703424ULL,0ULL,2048ULL,0ULL,20829148277114368ULL,0ULL,1049088ULL,0ULL,23362423067508736ULL,-9223372036854775808ULL,524288ULL,0ULL,20547673299878400ULL,0ULL,513ULL,-9223372036854775808ULL,17732923532771328ULL,-9223372036854775808ULL,2048ULL,0ULL,18014398509481985ULL,0ULL,1048577ULL,0ULL,21110623253301248ULL,0ULL,526336ULL,0ULL,23643898044743680ULL},
{0ULL,2ULL,-9223372036854775808ULL,18014398509483009ULL,0ULL,2ULL,0ULL,21110623254350848ULL,0ULL,4096ULL,0ULL,23925374634164224ULL,0ULL,4096ULL,0ULL,24206851222536192ULL,0ULL,4096ULL,0ULL,21110623254350848ULL,0ULL,2098176ULL,0ULL,23643898044743680ULL,0ULL,1048577ULL,0ULL,20829148276589568ULL,0ULL,1026ULL,0ULL,18014398509481985ULL,0ULL,4097ULL,0ULL,18295873486192642ULL,0ULL,2097154ULL,0ULL,21392098230013952ULL,0ULL,1052672ULL,0ULL,23925373022502912ULL},
{0ULL,2105344ULL,0ULL,24206848001310720ULL,0ULL,4194308ULL,0ULL,21673573206728704ULL,0ULL,8194ULL,0ULL,18577348462903300ULL,0ULL,2052ULL,0ULL,18295873486192642ULL,0ULL,2097154ULL,0ULL,21110623253301248ULL,0ULL,4196352ULL,0ULL,23925373022502912ULL},
{0ULL,8392704ULL,0ULL,24206848001310720ULL,0ULL,4194308ULL,0ULL,21392098230013952ULL,0ULL,4104ULL,0ULL,18577348462903300ULL,0ULL,16388ULL,0ULL,18858823439613960ULL,0ULL,8388616ULL,0ULL,21955048183447552ULL,0ULL,4210688ULL,0ULL,24488322982215680ULL},
{0ULL,8208ULL,0ULL,18858823439613960ULL,0ULL,8388616ULL,0ULL,21673573206728704ULL,0ULL,16785408ULL,0ULL,24488322982215680ULL,0ULL,8421376ULL,0ULL,24769797967314944ULL,0ULL,16777232ULL,0ULL,22236523160174592ULL,0ULL,32776ULL,0ULL,19140298416324624ULL},
{0ULL,65552ULL,0ULL,19421773393035296ULL,0ULL,33554464ULL,0ULL,22517998136918016ULL,0ULL,16842752ULL,0ULL,25051272960802816ULL,0ULL,33570816ULL,0ULL,24769797967314944ULL,0ULL,16777232ULL,0ULL,21955048183447552ULL,0ULL,16416ULL,0ULL,19140298416324624ULL},
{0ULL,32ULL,0ULL,19703248369877184ULL,0ULL,32ULL,0ULL,22517998204157952ULL,0ULL,32768ULL,0ULL,22517998204157952ULL,0ULL,32768ULL,0ULL,25051298797715456ULL,0ULL,32768ULL,0ULL,24769810852216832ULL,0ULL,131104ULL,0ULL,19703248369745984ULL,0ULL,67108928ULL,0ULL,22799473113694208ULL,0ULL,33685504ULL,0ULL,25332747971067904ULL,0ULL,67141632ULL,0ULL,25051272960802816ULL,0ULL,33554464ULL,0ULL,22236523160174592ULL,0ULL,32832ULL,0ULL,19421773393035296ULL},
{0ULL,64ULL,0ULL,19984723346719104ULL,0ULL,64ULL,0ULL,22799473248174080ULL,0ULL,65536ULL,0ULL,22799473248174080ULL,0ULL,65536ULL,0ULL,25332782465024000ULL,0ULL,262208ULL,0ULL,19984723346456704ULL,0ULL,134217856ULL,0ULL,23080948090535936ULL,0ULL,67371008ULL,0ULL,25614223014887424ULL,0ULL,134283264ULL,0ULL,25332747971067904ULL,0ULL,67108928ULL,0ULL,22517998136918016ULL,0ULL,65664ULL,0ULL,19703248369745984ULL},
{0ULL,131072ULL,0ULL,25614223014887424ULL,0ULL,128ULL,0ULL,20266198323167488ULL},
{0ULL,1024ULL,0ULL,20547673299878400ULL,0ULL,1048576ULL,0ULL,25895698125815808ULL},
{0ULL,2097152ULL,0ULL,23643898313703424ULL,0ULL,2097152ULL,0ULL,26177379797827584ULL,0ULL,2097152ULL,0ULL,26459061201403904ULL,0ULL,2048ULL,0ULL,23643898313703424ULL,0ULL,2048ULL,0ULL,20829148277114368ULL,0ULL,270532608ULL,0ULL,26177173370961920ULL,0ULL,537395200ULL,0ULL,25895698125815808ULL,0ULL,268436480ULL,0ULL,23362423067508736ULL,0ULL,526336ULL,0ULL,20829148276589568ULL,0ULL,2098176ULL,0ULL,21110623253301248ULL,0ULL,536872960ULL,0ULL,23925373022502912ULL},
{0ULL,4096ULL,0ULL,23925374634164224ULL,0ULL,4096ULL,0ULL,24206851222536192ULL,0ULL,4096ULL,0ULL,21110623254350848ULL,0ULL,1074790400ULL,0ULL,26177173370961920ULL,0ULL,541065216ULL,0ULL,26458648884543488ULL,0ULL,1073745920ULL,0ULL,24206848001310720ULL,0ULL,4196352ULL,0ULL,21392098230013952ULL,0ULL,1052672ULL,0ULL,21110623253301248ULL,0ULL,536872960ULL,0ULL,23643898044743680ULL},
{0ULL,4096ULL,0ULL,23925374634164224ULL,0ULL,4096ULL,0ULL,24206851222536192ULL,0ULL,4096ULL,0ULL,21110623254350848ULL,0ULL,8192ULL,0ULL,24488329424666624ULL,0ULL,8192ULL,0ULL,24206851222536192ULL,0ULL,2105344ULL,0ULL,21392098230013952ULL,0ULL,8392704ULL,0ULL,21673573206728704ULL,0ULL,2147491840ULL,0ULL,24488322982215680ULL,0ULL,1082130432ULL,0ULL,26740124934995968ULL,0ULL,2149580800ULL,0ULL,26458648884543488ULL,0ULL,1073745920ULL,0ULL,23925373022502912ULL},
{0ULL,8192ULL,0ULL,24488329424666624ULL,0ULL,8192ULL,0ULL,24206851222536192ULL,0ULL,16384ULL,0ULL,24488329424666624ULL,0ULL,16384ULL,0ULL,24769810852216832ULL,0ULL,4210688ULL,0ULL,21673573206728704ULL,0ULL,16785408ULL,0ULL,21955048183447552ULL,0ULL,4294983680ULL,0ULL,24769797967314944ULL,0ULL,2164260864ULL,0ULL,27021602059190272ULL,0ULL,4299161600ULL,0ULL,26740124934995968ULL,0ULL,2147491840ULL,0ULL,24206848001310720ULL},
{0ULL,32768ULL,0ULL,22517998204157952ULL,0ULL,32768ULL,0ULL,25051298797715456ULL,0ULL,32768ULL,0ULL,24769810852216832ULL,0ULL,16384ULL,0ULL,24488329424666624ULL,0ULL,16384ULL,0ULL,24769810852216832ULL,0ULL,8598323200ULL,0ULL,27021602059190272ULL,0ULL,4328521728ULL,0ULL,27303081330868224ULL,0ULL,8589967360ULL,0ULL,25051272960802816ULL,0ULL,33570816ULL,0ULL,22236523160174592ULL,0ULL,8421376ULL,0ULL,21955048183447552ULL,0ULL,4294983680ULL,0ULL,24488322982215680ULL},
{0ULL,32768ULL,0ULL,22517998204157952ULL,0ULL,32768ULL,0ULL,25051298797715456ULL,0ULL,32768ULL,0ULL,24769810852216832ULL,0ULL,17196646400ULL,0ULL,27303081330868224ULL,0ULL,8589967360ULL,0ULL,24769797967314944ULL,0ULL,16842752ULL,0ULL,22236523160174592ULL,0ULL,67141632ULL,0ULL,22517998136918016ULL,0ULL,17179934720ULL,0ULL,25332747971067904ULL,0ULL,8657043456ULL,0ULL,27584564897513472ULL},
{0ULL,65536ULL,0ULL,22799473248174080ULL,0ULL,65536ULL,0ULL,25332782465024000ULL,0ULL,33554432ULL,0ULL,27591196327018496ULL,0ULL,33554432ULL,0ULL,27306379865751552ULL,0ULL,33554432ULL,0ULL,25332782465024000ULL,0ULL,17314086912ULL,0ULL,27866057054093312ULL,0ULL,34359869440ULL,0ULL,25614223014887424ULL,0ULL,134283264ULL,0ULL,22799473113694208ULL,0ULL,33685504ULL,0ULL,22517998136918016ULL,0ULL,17179934720ULL,0ULL,25051272960802816ULL,0ULL,34393292800ULL,0ULL,27584564897513472ULL},
{0ULL,131072ULL,0ULL,23080948090535936ULL,0ULL,67108864ULL,0ULL,27866057054093312ULL},
{0ULL,1048576ULL,0ULL,23362423067508736ULL,0ULL,536870912ULL,0ULL,28147566390542336ULL},
{0ULL,2097152ULL,0ULL,23643898313703424ULL,0ULL,2097152ULL,0ULL,26177379797827584ULL,0ULL,2097152ULL,0ULL,26459061201403904ULL,0ULL,270532608ULL,0ULL,23643898044743680ULL,0ULL,68720525312ULL,0ULL,25895698125815808ULL,0ULL,137707388928ULL,0ULL,28147566390542336ULL,0ULL,69793218560ULL,0ULL,28429110086729728ULL,0ULL,137441050624ULL,0ULL,26458648884543488ULL,0ULL,1074790400ULL,0ULL,23925373022502912ULL},
{0ULL,2097152ULL,0ULL,23643898313703424ULL,0ULL,2097152ULL,0ULL,26177379797827584ULL,0ULL,2097152ULL,0ULL,26459061201403904ULL,0ULL,4194304ULL,0ULL,26740949568716800ULL,0ULL,4194304ULL,0ULL,26459061201403904ULL,0ULL,2149580800ULL,0ULL,24206848001310720ULL,0ULL,274882101248ULL,0ULL,26740124934995968ULL,0ULL,139586437120ULL,0ULL,28710722502393856ULL,0ULL,275414777856ULL,0ULL,28429110086729728ULL,0ULL,137441050624ULL,0ULL,26177173370961920ULL,0ULL,541065216ULL,0ULL,23925373022502912ULL},
{0ULL,8388608ULL,0ULL,27023251326631936ULL,0ULL,8388608ULL,0ULL,26740949568716800ULL,0ULL,4194304ULL,0ULL,26740949568716800ULL,0ULL,4194304ULL,0ULL,26459061201403904ULL,0ULL,279172874240ULL,0ULL,28992472357011456ULL,0ULL,549764202496ULL,0ULL,27021602059190272ULL,0ULL,4299161600ULL,0ULL,24488322982215680ULL,0ULL,1082130432ULL,0ULL,24206848001310720ULL,0ULL,274882101248ULL,0ULL,26458648884543488ULL,0ULL,550829555712ULL,0ULL,28710722502393856ULL},
{0ULL,8388608ULL,0ULL,27023251326631936ULL,0ULL,8388608ULL,0ULL,26740949568716800ULL,0ULL,16777216ULL,0ULL,27023251326631936ULL,0ULL,16777216ULL,0ULL,27306379865751552ULL,0ULL,549764202496ULL,0ULL,26740124934995968ULL,0ULL,2164260864ULL,0ULL,24488322982215680ULL,0ULL,8598323200ULL,0ULL,24769797967314944ULL,0ULL,1099528404992ULL,0ULL,27303081330868224ULL,0ULL,558345748480ULL,0ULL,29274497089536000ULL,0ULL,1101659111424ULL,0ULL,28992472357011456ULL},
{0ULL,33554432ULL,0ULL,27591196327018496ULL,0ULL,33554432ULL,0ULL,27306379865751552ULL,0ULL,33554432ULL,0ULL,25332782465024000ULL,0ULL,16777216ULL,0ULL,27023251326631936ULL,0ULL,16777216ULL,0ULL,27306379865751552ULL,0ULL,17196646400ULL,0ULL,25051272960802816ULL,0ULL,4328521728ULL,0ULL,24769797967314944ULL,0ULL,1099528404992ULL,0ULL,27021602059190272ULL,0ULL,2203318222848ULL,0ULL,29274497089536000ULL,0ULL,1116691496960ULL,0ULL,29557071577874432ULL,0ULL,2199056809984ULL,0ULL,27584564897513472ULL},
{0ULL,33554432ULL,0ULL,27591196327018496ULL,0ULL,33554432ULL,0ULL,27306379865751552ULL,0ULL,33554432ULL,0ULL,25332782465024000ULL,0ULL,2233382993920ULL,0ULL,29840745577840640ULL,0ULL,4406636445696ULL,0ULL,29557071577874432ULL,0ULL,2199056809984ULL,0ULL,27303081330868224ULL,0ULL,8657043456ULL,0ULL,25051272960802816ULL,0ULL,34393292800ULL,0ULL,25332747971067904ULL,0ULL,4398113619968ULL,0ULL,27866057054093312ULL},
{0ULL,67108864ULL,0ULL,25614223014887424ULL,0ULL,17179869184ULL,0ULL,29840745577840640ULL},
{0ULL,536870912ULL,0ULL,25895698125815808ULL,0ULL,536870912ULL,0ULL,28429110086729728ULL},
{0ULL,536870912ULL,0ULL,28147566390542336ULL,0ULL,1073741824ULL,0ULL,28710722502393856ULL},
{0ULL,1073741824ULL,0ULL,28429110086729728ULL,0ULL,2147483648ULL,0ULL,28992472357011456ULL},
{0ULL,4294967296ULL,0ULL,29274497089536000ULL,0ULL,2147483648ULL,0ULL,28710722502393856ULL},
{0ULL,8589934592ULL,0ULL,29557071577874432ULL,0ULL,4294967296ULL,0ULL,28992472357011456ULL},
{0ULL,8589934592ULL,0ULL,29274497089536000ULL,0ULL,17179869184ULL,0ULL,29840745577840640ULL},
{0ULL,17179869184ULL,0ULL,29557071577874432ULL,0ULL,17179869184ULL,0ULL,27866057054093312ULL}};
| [
"[email protected]"
] | |
8706e867bbf866ca372015be551852844ef99ce2 | 915c7ea66fc5d6ea3f38c4f84296a285fd95ae5f | /src/stats.cpp | 59a76bd48d51c78e5685d994aafd57515add6354 | [
"MIT",
"LicenseRef-scancode-llnl",
"BSD-3-Clause",
"LicenseRef-scancode-hdf5",
"BSL-1.0",
"BSD-2-Clause"
] | permissive | matq007/kEDM | ba602306d3454329465e960c629d10fe28ef24a2 | e7f08b6488d76d06b52bbc60fa34a79469349c30 | refs/heads/master | 2023-09-05T06:32:33.860993 | 2021-11-16T07:24:06 | 2021-11-16T07:24:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,887 | cpp | #include "stats.hpp"
namespace edm
{
float corrcoef(TimeSeries x, TimeSeries y)
{
#ifndef KOKKOS_ENABLE_CUDA
using std::min;
using std::sqrt;
#endif
CorrcoefState state;
Kokkos::parallel_reduce(
"EDM::stats::corrcef", min(x.size(), y.size()),
KOKKOS_LAMBDA(int i, CorrcoefState &upd) {
upd += CorrcoefState(x(i), y(i));
},
Kokkos::Sum<CorrcoefState>(state));
return state.rho();
}
void corrcoef(CrossMap rho, Dataset ds, TimeSeries x)
{
#ifndef KOKKOS_ENABLE_CUDA
using std::min;
using std::sqrt;
#endif
Kokkos::parallel_for(
"EDM::stats::corrcef", Kokkos::TeamPolicy<>(ds.extent(1), Kokkos::AUTO),
KOKKOS_LAMBDA(const Kokkos::TeamPolicy<>::member_type &member) {
const int j = member.league_rank();
CorrcoefState state;
Kokkos::parallel_reduce(
Kokkos::TeamThreadRange(member, min(x.extent(0), ds.extent(0))),
[=](int i, CorrcoefState &upd) {
upd += CorrcoefState(x(i), ds(i, j));
},
Kokkos::Sum<CorrcoefState>(state));
rho(j) = state.rho();
});
}
float mae(TimeSeries x, TimeSeries y)
{
#ifndef KOKKOS_ENABLE_CUDA
using std::abs;
using std::min;
#endif
int n = min(x.size(), y.size());
float sum;
Kokkos::parallel_reduce(
"EDM::stats::mae", n,
KOKKOS_LAMBDA(int i, float &upd) { upd += abs(x(i) - y(i)); }, sum);
return sum / n;
}
float mse(TimeSeries x, TimeSeries y)
{
#ifndef KOKKOS_ENABLE_CUDA
using std::min;
#endif
int n = min(x.size(), y.size());
float sum;
Kokkos::parallel_reduce(
"EDM::stats::mse", n,
KOKKOS_LAMBDA(int i, float &upd) {
upd += (x(i) - y(i)) * (x(i) - y(i));
},
sum);
return sum / n;
}
} // namespace edm
| [
"[email protected]"
] | |
851decc822a0bed1058a1b10a685929b45775be3 | 800184441b1bc983e851a5b19ada981916379d32 | /libraries/chain/include/graphene/chain/transaction_object.hpp | 06ed0e743e477055c2fe642f67c5bd824a0a236f | [] | no_license | 0xae/graphene | 83d441382b3df331a35da9407522d586f997ecc0 | 49fb41c440339121a066a33dc97069a5144bdf93 | refs/heads/master | 2020-12-02T23:01:07.614739 | 2015-07-08T03:47:27 | 2015-07-08T03:47:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,287 | hpp | /*
* Copyright (c) 2015, Cryptonomex, Inc.
* All rights reserved.
*
* This source code is provided for evaluation in private test networks only, until September 8, 2015. After this date, this license expires and
* the code may not be used, modified or distributed for any purpose. Redistribution and use in source and binary forms, with or without modification,
* are permitted until September 8, 2015, provided that the following conditions are met:
*
* 1. The code and/or derivative works are used only for private test networks consisting of no more than 10 P2P nodes.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
#include <fc/io/raw.hpp>
#include <graphene/chain/transaction.hpp>
#include <graphene/db/index.hpp>
#include <graphene/db/generic_index.hpp>
#include <fc/uint128.hpp>
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/hashed_index.hpp>
#include <boost/multi_index/mem_fun.hpp>
namespace graphene { namespace chain {
using namespace graphene::db;
using boost::multi_index_container;
using namespace boost::multi_index;
/**
* The purpose of this object is to enable the detection of duplicate transactions. When a transaction is included
* in a block a transaction_object is added. At the end of block processing all transaction_objects that have
* expired can be removed from the index.
*/
class transaction_object : public abstract_object<transaction_object>
{
public:
static const uint8_t space_id = implementation_ids;
static const uint8_t type_id = impl_transaction_object_type;
signed_transaction trx;
time_point_sec expiration;
transaction_id_type trx_id;
};
struct by_expiration;
struct by_id;
struct by_trx_id;
typedef multi_index_container<
transaction_object,
indexed_by<
hashed_unique< tag<by_id>, member< object, object_id_type, &object::id > >,
hashed_unique< tag<by_trx_id>, BOOST_MULTI_INDEX_MEMBER(transaction_object, transaction_id_type, trx_id), std::hash<transaction_id_type> >,
ordered_non_unique< tag<by_expiration>, BOOST_MULTI_INDEX_MEMBER(transaction_object, time_point_sec, expiration)>
>
> transaction_multi_index_type;
typedef generic_index<transaction_object, transaction_multi_index_type> transaction_index;
} }
FC_REFLECT_DERIVED( graphene::chain::transaction_object, (graphene::db::object), (trx)(expiration) )
| [
"[email protected]"
] | |
ce88bec82a0fc311bdd2b2a190c19e42da0e18be | 0a64bfcfd943372df11eb47c7a037db606d06da0 | /cs12/Assignment 4/intvector.cpp | c7f86889bf22c395b0edb517109edf2d0cb71f51 | [] | no_license | zacharysells/school | 9e09c00e4a3e87cd798ca21813edc11ac4eeb4b7 | e59270018cb3d4752c618d410d7f2af8f921aac8 | refs/heads/master | 2021-01-10T19:31:01.721574 | 2015-06-05T18:57:29 | 2015-06-05T18:57:29 | 27,702,632 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 5,366 | cpp | // Course: CS 12 <Winter 2012r>
//
// First Name: Zachary
// Last Name: Sells
// Course username: zsell001
// email address: [email protected]
//
// Lecture Section: 001
// Lab Section: 025
// TA: Mirebrahim, Seyed Hamid
//
// Assignment: assn4
//
// I hereby certify that the code in this file
// is ENTIRELY my own original work.
//
// =================================================================
#include <iostream>
#include "intvector.h"
#include <cstdlib>
using namespace std;
//Constructors/Destructors
IntVector::IntVector()
:vsize(0),vcapacity(0),data(NULL)//Default constructor.
{}
IntVector::IntVector(unsigned s)
:vsize(s),vcapacity(s),data(NULL)
{
data = new int[s];
for(unsigned i = 0; i < vcapacity; i++)
{
data[i] = 0;//Set all elements to zero.
}
}
IntVector::IntVector(unsigned s, int value)
:vsize(s),vcapacity(s),data(NULL)
{
data = new int[s];
for(unsigned i = 0; i < vsize; i++)
{
data[i] = value;//Set elements according to 'value' parameter
}
}
IntVector::~IntVector()
{
delete[] data;//Deconstructor
}
void IntVector::expand()
{
int * temp = new int[vcapacity * 2];//Double vector's capacity
for(unsigned i = 0; i < vsize; i++)
{
temp[i] = data[i];
}
vcapacity = vcapacity * 2;
delete[] data;
data = temp;
}
void IntVector::expand(unsigned amount)//Expand vector's capacity by 'amount' parameter
{
int * temp = new int[vcapacity + amount];
for(unsigned i = 0; i < vsize; i++)
{
temp[i] = data[i];
}
vcapacity = vcapacity + amount;
delete[] data;
data = temp;
}
unsigned IntVector::size() const
{
return vsize;//Return size of vector.
}
unsigned IntVector::capacity() const
{
return vcapacity;//Return capacity of vector.
}
bool IntVector::empty() const
{
return (vsize == 0);//Check if vector's size is zero.
}
const int & IntVector::operator[](unsigned index)const
{
return data[index];
}
const int& IntVector::front() const
{
return data[0];// Return value of last element.
}
const int& IntVector::back() const
{
return *(data + (vsize - 1));//Return value of last element.
}
const int & IntVector::at(unsigned index) const
{
if(index > vsize)
exit(0);//Exit program if index is out of range of vector
return data[index];//Return by value as R-value.
}
int & IntVector::at(unsigned index)
{
if(index > vsize)
exit(0);// Exit program if index is out of range of vector
return data[index];//Return by reference as L-value.
}
void IntVector::insert(unsigned index, int data)
{
if(index > vsize)//Make sure index isnt bigger than size.
{
exit(1);
}
if(vcapacity == 0)
{
expand(1);
}
if(vsize == vcapacity)//Increase capacity if size is equal to capacity.
{
expand();
}
for(unsigned i = vsize; i > index ; i--)
{
this->data[i] = this->data[i-1];//Shift all values up one.
}
this->data[index] = data;//Input 'data' parameter into new element.
vsize++;//Increase size by one.
}
void IntVector::erase(unsigned index)
{
if(index > vsize)//Make sure index isnt bigger than size.
{
exit(0);
}
for(unsigned i = index; i < vsize; i++)
{
data[i] = data[i+1];//Move all elements down one position.
}
vsize--;//Decrease size by one.
}
void IntVector::push_back(int data)
{
if(vcapacity == 0)
{
expand(1);//If vector is empty, set capacity to 1.
}
else if (vsize == vcapacity)
{
expand();//Increase capacity if size is equal to capacity.
}
this->data[vsize] = data;//Input 'data' parameter into new element.
vsize++;//Increase size by one.
}
void IntVector::pop_back()
{
if(vsize == 0)
exit(0);//Exit program if size is zero
vsize--;//Decrease size by one.
}
void IntVector::clear()
{
vsize = 0;//Reduce size to zero.
}
void IntVector::resize(unsigned sz)
{
if(sz < vsize)
{
vsize = sz;//Just reduce size to 'sz' parameter
}
else
{
if(sz > vcapacity)
{
if(vcapacity * 2 > sz)//Increase capacity by the bigger of the two.
{
expand();
}
else
{
expand(sz - vcapacity);
}
}
vsize = sz;//Set new size.
}
}
void IntVector::resize(unsigned sz, int value)
{
if(sz < vsize)
{
vsize = sz;//Just change size to 'sz' parameter
}
else
{
if(sz > vcapacity)
{
if(vcapacity * 2 > sz)//Set capacity to greater of the two.
{
expand();
}
else
{
expand(sz - vcapacity);
}
}
for(unsigned i = vsize; i < vcapacity; i++)
{
data[i] = value;//Assign elements to 'value' parameter
}
vsize = sz;//Set new size.
}
}
void IntVector::reserve(unsigned n)
{
if(n < vcapacity)
return;
if(vcapacity * 2 > n)//Change capacity to greater of the two.
expand();
else
expand(n-vcapacity);
}
void IntVector::assign(unsigned n, int value)
{
if(n > vcapacity)
{
if(vcapacity * 2 > n)//Change capacity to greater of two.
expand();
else
expand(n-vcapacity);
vsize = n;
//Set all values in newly assigned size to 'value' paramater.
for(unsigned i = 0; i < vsize; i++)
{
data[i] = value;
}
}
else
{
vsize = n;//set new size and assign new values according to parameter 'value'
for(unsigned i = 0; i <vsize; i++)
{
data[i] = value;
}
}
}
int & IntVector::front()//L-value
{
return data[0];
}
int & IntVector::back()//L-value
{
return data[vsize - 1];
}
int & IntVector::operator[](unsigned index)//L-value
{
return data[index];
}
| [
"[email protected]"
] | |
366e0a2f67f1e2364182102ec7ff1b575e15a59c | 034d8e28730a6d8b8fb9cb403791f8693c8fd619 | /Hashing/Hashing/Main.cpp | 0af633ef41e61f9f7e4884ea5239f692ac0880b4 | [] | no_license | MisterMew/4-CodeDesignandDataStructures | 7173db768e24d15db950cbe5866494e79e2e623f | ca1878658b9cb5e372c6c3ac28bdf0fe5450f387 | refs/heads/main | 2023-09-02T18:33:15.197430 | 2021-10-09T04:54:04 | 2021-10-09T04:54:04 | 378,316,284 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,551 | cpp | #include "MainCore.h"
bool FileExists(string filepath) {
struct stat buffer;
return (stat(filepath.c_str(), &buffer) == 0);
}
#pragma region [ MENU Functions ]
/// HASH MENU: View Menu
/* View menu options for hashtable */
void HashMenuOptions() {
cout <<
"\n HASHING OPTIONS"
"\n [1] Check List"
"\n [2] Insert Item"
"\n [3] Remove Item"
"\n [4] Print Table"
"\n [0] EXIT"
<< endl;
}
/// HASH MENU: Validat Input
/* Validate user input for insert/remove */
void ValidateKey() {
/// INSERT Item
// Validate user input when inserting an item to the table
if (optSelected == OptSelect::InsertItem) {
cout << "\n [2]TIP!> If nothing happenes, the input was illegal.";
cout << "\n [2]INSERT> Please enter a key. (EG: Alpha, Bravo2, CH4RL13)" << "\n /: ";
cin >> gKey;
cout << "\n [2]INSERT> Please enter some data. (EG: 905, 247, 390)" << "\n /: ";
cin >> gData;
while (!cin) { //Validate for integer input
cin.clear();
cin.ignore();
cout << "\n /: ";
cin >> gData;
}
return;
}
/// REMOVE Item
// Validate user input when removing an item from the table
if (optSelected == OptSelect::RemoveItem) {
cout << "\n [3]DELETE> Please enter a key. (EG: Alpha, Bravo2, CH4RL13)" << "\n /: ";
getline(cin, gKey);
return;
}
}
/// HASH MENU: Validate Menu Input
/* Validate user input for selecting a menu option */
void MenuValidation() {
bool flag = true;
while (flag) {
cout << "\n //: ";
cin >> userInput;
switch (userInput) {
///CHECK TABLE
// Check if the hashtable is empty or not
case OptSelect::CheckTable:
flag = false;
HT.isEmpty();
continue;
///INSERT ITEM
// Insert an item to the hashtable
case OptSelect::InsertItem:
optSelected = OptSelect::InsertItem;
flag = false;
ValidateKey();
HT.InsertItem(gKey, gData);
continue;
///REMOVE ITEM
// Remove an item from the hashtable
case OptSelect::RemoveItem:
optSelected = OptSelect::RemoveItem;
flag = false;
ValidateKey();
HT.RemoveItem(gKey);
continue;
///PRINT TABLE
// Prints the hash table to the console
case OptSelect::PrintTable:
flag = false;
HT.PrintTable();
continue;
///EXIT CONSOLE
// Ends the program
case OptSelect::Exit:
flag = false;
exitConsole = true;
exit(0);
continue;
default: cout << "[]> Invalid.\n"; continue; //Loops until a valid input is recieved.
}
}
}
#pragma endregion
int main() {
HashTable hashTable;
HashMenuOptions();
while (!exitConsole) {
MenuValidation();
}
return 0;
} | [
"[email protected]"
] | |
06d7d449c82012931a285549002f14e25dc247d5 | f5b593692f3b54f051cd23397d09eac69e38ee9a | /powerplay 7/Object.cpp | fa58585398bfb51487d333673245fada02fb1114 | [] | no_license | AustinJesse/Power-Play-7 | 5520256c89e52dcf2cbc801ee0f38507c03f0be9 | e66267d6bbc75e378a37f6b17be0b36c84ff01a6 | refs/heads/master | 2022-11-06T10:42:09.211783 | 2020-06-24T04:35:17 | 2020-06-24T04:35:17 | 274,575,498 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,195 | cpp | #include <random>
#include <iostream>
#include "Monster.h"
#include "Object.h"
std::random_device Object::seed;
std::default_random_engine Object::engine(seed());
Object::Object(Type name, int strength, int health, int level) : name{ name }, strength{ strength }, health{ health }, level{ level }
{
}
bool Object::isDead()
{
if (health <= 0) {return true;}
else {return false;}
}
Object::Type Object::getName() const
{
return name;
}
int Object::getLevel() const
{
return level;
}
int Object::getHealth() const
{
return health;
}
std::ostream& operator<<(std::ostream& o, const Object& src)
{
o << "L:" << src.getLevel() << " ";
switch (src.getName())
{
case Object::Type::player:
std::cout << "Player";
break;
case Object::Type::slime:
std::cout << "Slime";
break;
case Object::Type::orc:
std::cout << "Orc";
break;
case Object::Type::sprite:
std::cout << "Sprite";
break;
case Object::Type::dragon:
std::cout << "Dragon";
break;
}
o << " h:" << src.getHealth();
return o;
}
//int Object::damageDone(int modification) const
//{
// int potentialDamage{ strength + modification };
// std::normal_distribution<double> damageDealt(potentialDamage, 2.0);
// std::cout << *this << " deals ";
// return std::max(1, (int)damageDealt(engine));
//}
int Object::damageDone(int modification) const
{
int potentialDamage{ strength + modification };
std::normal_distribution<double> damageDealt(potentialDamage, 2.0);
int damage = std::max(1, (int)damageDealt(engine));
//std::cout << *this << " deals " << damage << " damage!" << std::endl;
return damage;
}
//int Object::damageTaken(int damageDone, int AC)
//{
// return this->health -= (damageDone + AC);
//}
int Object::damageTaken(int damageDone, int AC)
{
//std::normal_distribution<double> defense(AC, 1.0 / level);
//damageDone = std::max(0, damageDone - (int)defense(engine));
//damageDone = 1; // damage is always 1...
//std::cout << damageDone << " damage to ";
//std::cout << *this << "!!!" << std::endl;
//health -= (damageDone + AC);
//return health;
std::cout << *this << " takes " << damageDone + AC << " damage!" << std::endl;
return this->health -= (damageDone + AC);
} | [
"[email protected]"
] | |
6ddad8dd5b2465130cd16fc1469dc4cbb61cbaaf | 35a0f73a51d65b24470876f51353b18a8a7937ff | /source/game/entity/Blood.cpp | 10dac799fe0f9c520b44b95438a01be052a4d591 | [
"MIT"
] | permissive | edeksumo/carpg | a7c3f90a31649b056bc18dda45448791d51739d7 | 7801960e05358c797ec968fda3cc0722d7421f6b | refs/heads/master | 2021-01-21T03:37:42.802907 | 2015-05-17T09:40:01 | 2015-05-17T09:40:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 559 | cpp | #include "Pch.h"
#include "Base.h"
#include "Blood.h"
#include "SaveState.h"
//=================================================================================================
void Blood::Save(File& f) const
{
f.Write<byte>(type);
f << pos;
f << normal;
f << size;
f << rot;
}
//=================================================================================================
void Blood::Load(File& f)
{
if(LOAD_VERSION >= V_0_3)
type = (BLOOD)f.Read<byte>();
else
type = (BLOOD)f.Read<int>();
f >> pos;
f >> normal;
f >> size;
f >> rot;
}
| [
"[email protected]"
] | |
cd78a6433df1ef18a97db3b39d9441638ccf2e4a | 912224938987d2dd68abd1acab48b09e57c5caea | /offerJZ36.cpp | 3997d084d7b1fbcfd2c3aa890c27784ab0c9b81e | [] | no_license | LavenSun/NiuKe-Practice | edb17eece5165f8297e7887668e549935d0e4f8e | c3c73789fae7c14b66d2a35af6e9509873483303 | refs/heads/master | 2022-11-17T03:33:09.165459 | 2020-07-17T10:14:02 | 2020-07-17T10:14:02 | 183,882,529 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 504 | cpp | //输入两个链表,找出它们的第一个公共结点。
//(注意因为传入数据是链表,所以错误测试数据的提示是用其他方式显示的,保证传入数据是正确的)
class Solution {
public:
ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
ListNode *ta = pHead1, *tb = pHead2;
while (ta != tb) {
ta = ta ? ta->next : pHead2;
tb = tb ? tb->next : pHead1;
}
return ta;
}
};
| [
"[email protected]"
] | |
d7b8df404510d4d94de12d6ccacd12cd41bfaa1a | 7595abb601d1f75749ceec4013ce440f5f035ff2 | /defaulted.h | 4f57ca0c2bb6031180c640c36d7af199853852b9 | [] | no_license | sv1990/Defaulted | d5bb426a0d8fc9cd0616d1c0d27088def54e6a82 | b7bfafee74a4557259bf39f814f08f95a6a7b280 | refs/heads/master | 2021-05-05T09:55:11.070922 | 2017-09-17T20:54:01 | 2017-09-17T20:54:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 816 | h | #ifndef defaulted_h
#define defaulted_h
namespace fluent
{
struct DefaultValue{};
static const DefaultValue defaultValue;
template<typename T, T... DefaultedParameters>
class Defaulted
{
public:
Defaulted(T t) : value_(std::move(t)){}
Defaulted(DefaultValue) : value_(DefaultedParameters...) {}
T const& get() const { return value_; }
T & get() { return value_; }
private:
T value_;
};
template<typename T, typename GetValue>
class DefaultedF
{
public:
DefaultedF(T t) : value_(std::move(t)){}
DefaultedF(DefaultValue) : value_(GetValue::get()) {}
T const& get() const { return value_; }
T & get() { return value_; }
private:
T value_;
};
}
#endif /* defaulted_h */
| [
"[email protected]"
] | |
7d29492616733c839f6b96c5999f642c4148712f | edfc92a7df8d8ce526324f8e21d603450bec6c23 | /editors/ComponentEditor/general/desceditor.h | 19187634f3736859befbd3f68cb068a3362c635b | [] | no_license | shrimpdede/kactus2 | 97be5f47918c99c7a3b3c4e17cf89f1cba267588 | 401b9dc80c2f4f3d081a639e498b08a50c89de71 | refs/heads/master | 2021-01-21T20:30:09.864195 | 2015-09-14T12:42:14 | 2015-09-14T12:42:14 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 1,756 | h | //-----------------------------------------------------------------------------
// File: desceditor.h
//-----------------------------------------------------------------------------
// Project: Kactus 2
// Author: Joni-Matti Määttä
// Date: 7.2.2011
//
// Description:
// Description editor for the component editor.
//-----------------------------------------------------------------------------
#ifndef DESCEDITOR_H
#define DESCEDITOR_H
#include <QGroupBox>
#include <QPlainTextEdit>
//-----------------------------------------------------------------------------
//! DescEditor class.
//-----------------------------------------------------------------------------
class DescEditor : public QGroupBox
{
Q_OBJECT
public:
/*!
* Constructor.
*
* @param [in] parent The parent widget.
*/
DescEditor(QWidget* parent = 0);
/*!
* Destructor.
*/
virtual ~DescEditor();
/*!
* Sets the description to the widget.
*
* @param [in] The description string.
*/
void setDescription(QString const& desc);
/*!
* Returns the description string.
*/
QString getDescription() const;
signals:
//! Emitted when the contents of the editor have changed.
void contentChanged();
private:
// Disable copying.
DescEditor(DescEditor const& rhs);
DescEditor& operator=(DescEditor const& rhs);
//-----------------------------------------------------------------------------
// Data.
//-----------------------------------------------------------------------------
//! The text edit for the description.
QPlainTextEdit* m_descEdit;
};
#endif // DESCEDITOR_H | [
"jonim@f0aa6db5-7f46-43cc-a8a5-a31efdaafa67"
] | jonim@f0aa6db5-7f46-43cc-a8a5-a31efdaafa67 |
bb3b6cac7f830704292ed73897e3ed478bc7df6d | 6b7bc255186b607345f6267facd61a1440e56119 | /libredex/VirtualScope.cpp | fefcb783c87be24d47fe88df6a479ef2a030cc6f | [
"MIT"
] | permissive | tectas/redex | 8c56ae776df1df17df055fe131a38a40314a7d0c | 67885df47c1cd6d05e9d8620adf024b77c78194b | refs/heads/master | 2022-11-30T20:27:42.210836 | 2022-11-22T08:26:20 | 2022-11-22T08:26:20 | 56,158,480 | 0 | 0 | NOASSERTION | 2022-11-22T08:26:23 | 2016-04-13T14:22:52 | C++ | UTF-8 | C++ | false | false | 33,707 | cpp | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "VirtualScope.h"
#include "Creators.h"
#include "DexAccess.h"
#include "DexUtil.h"
#include "ReachableClasses.h"
#include "Show.h"
#include "Timer.h"
#include "Trace.h"
#include <map>
#include <set>
namespace {
/**
* Create a DexClass for Object, which may be missing if no
* jar files were specified on the command line
*/
void create_object_class() {
std::vector<DexMethod*> object_methods;
auto type = type::java_lang_Object();
// create the following methods:
// protected java.lang.Object.clone()Ljava/lang/Object;
// public java.lang.Object.equals(Ljava/lang/Object;)Z
// protected java.lang.Object.finalize()V
// public final native java.lang.Object.getClass()Ljava/lang/Class;
// public native java.lang.Object.hashCode()I
// public final native java.lang.Object.notify()V
// public final native java.lang.Object.notifyAll()V
// public java.lang.Object.toString()Ljava/lang/String;
// public final java.lang.Object.wait()V
// public final java.lang.Object.wait(J)V
// public final native java.lang.Object.wait(JI)V
// required sigs
auto void_args = DexTypeList::make_type_list({});
auto void_object = DexProto::make_proto(type::java_lang_Object(), void_args);
auto object_bool = DexProto::make_proto(
type::_boolean(),
DexTypeList::make_type_list({type::java_lang_Object()}));
auto void_void = DexProto::make_proto(type::_void(), void_args);
auto void_class = DexProto::make_proto(type::java_lang_Class(), void_args);
auto void_int = DexProto::make_proto(type::_int(), void_args);
auto void_string = DexProto::make_proto(type::java_lang_String(), void_args);
auto long_void = DexProto::make_proto(
type::_void(), DexTypeList::make_type_list({type::_int()}));
auto long_int_void = DexProto::make_proto(
type::_void(),
DexTypeList::make_type_list({type::_long(), type::_int()}));
// required names
auto clone = DexString::make_string("clone");
auto equals = DexString::make_string("equals");
auto finalize = DexString::make_string("finalize");
auto getClass = DexString::make_string("getClass");
auto hashCode = DexString::make_string("hashCode");
auto notify = DexString::make_string("notify");
auto notifyAll = DexString::make_string("notifyAll");
auto toString = DexString::make_string("toString");
auto wait = DexString::make_string("wait");
// create methods and add to the list of object methods
// All the checks to see if the methods exist are because we cannot set
// access/virtual for external methods, so if the method exists (i.e. if this
// function is called multiple times with type::java_lang_Object()), we
// will fail an assertion. This only happens in tests when no external jars
// are available protected java.lang.Object.clone()Ljava/lang/Object;
auto method =
static_cast<DexMethod*>(DexMethod::make_method(type, clone, void_object));
method->set_access(ACC_PROTECTED);
method->set_virtual(true);
method->set_external();
object_methods.push_back(method);
// public java.lang.Object.equals(Ljava/lang/Object;)Z
method = static_cast<DexMethod*>(
DexMethod::make_method(type, equals, object_bool));
method->set_access(ACC_PUBLIC);
method->set_virtual(true);
method->set_external();
object_methods.push_back(method);
// protected java.lang.Object.finalize()V
method = static_cast<DexMethod*>(
DexMethod::make_method(type, finalize, void_void));
method->set_access(ACC_PROTECTED);
method->set_virtual(true);
method->set_external();
object_methods.push_back(method);
// public final native java.lang.Object.getClass()Ljava/lang/Class;
method = static_cast<DexMethod*>(
DexMethod::make_method(type, getClass, void_class));
method->set_access(ACC_PUBLIC | ACC_FINAL | ACC_NATIVE);
method->set_virtual(true);
method->set_external();
object_methods.push_back(method);
// public native java.lang.Object.hashCode()I
method =
static_cast<DexMethod*>(DexMethod::make_method(type, hashCode, void_int));
method->set_access(ACC_PUBLIC | ACC_NATIVE);
method->set_virtual(true);
method->set_external();
object_methods.push_back(method);
method =
static_cast<DexMethod*>(DexMethod::make_method(type, notify, void_void));
method->set_access(ACC_PUBLIC | ACC_FINAL | ACC_NATIVE);
method->set_virtual(true);
method->set_external();
object_methods.push_back(method);
// public final native java.lang.Object.notifyAll()V
method = static_cast<DexMethod*>(
DexMethod::make_method(type, notifyAll, void_void));
method->set_access(ACC_PUBLIC | ACC_FINAL | ACC_NATIVE);
method->set_virtual(true);
method->set_external();
object_methods.push_back(method);
// public java.lang.Object.toString()Ljava/lang/String;
method = static_cast<DexMethod*>(
DexMethod::make_method(type, toString, void_string));
method->set_access(ACC_PUBLIC);
method->set_virtual(true);
method->set_external();
object_methods.push_back(method);
// public final java.lang.Object.wait()V
method =
static_cast<DexMethod*>(DexMethod::make_method(type, wait, void_void));
method->set_access(ACC_PUBLIC | ACC_FINAL);
method->set_virtual(true);
method->set_external();
object_methods.push_back(method);
// public final java.lang.Object.wait(J)V
method =
static_cast<DexMethod*>(DexMethod::make_method(type, wait, long_void));
method->set_access(ACC_PUBLIC | ACC_FINAL);
method->set_virtual(true);
method->set_external();
object_methods.push_back(method);
// public final native java.lang.Object.wait(JI)V
method = static_cast<DexMethod*>(
DexMethod::make_method(type, wait, long_int_void));
method->set_access(ACC_PUBLIC | ACC_FINAL | ACC_NATIVE);
method->set_virtual(true);
method->set_external();
object_methods.push_back(method);
// Now make sure Object itself exists.
if (type_class(type) == nullptr) {
ClassCreator cc(type);
cc.set_access(ACC_PUBLIC);
auto object_class = cc.create();
for (auto const& m : object_methods) {
object_class->add_method(m);
}
}
}
// map from a proto to the set of interface implementing that sig
using IntfProtoMap = std::map<const DexProto*, TypeSet, dexprotos_comparator>;
// a map from name to signatures for a set of interfaces
using BaseIntfSigs =
std::map<const DexString*, IntfProtoMap, dexstrings_comparator>;
// map to track signatures as (name, sig)
using BaseSigs = std::map<const DexString*,
std::set<const DexProto*, dexprotos_comparator>,
dexstrings_comparator>;
/**
* Create a BaseSig which is the set of method definitions in a type.
*/
BaseSigs load_base_sigs(SignatureMap& sig_map) {
BaseSigs base_sigs;
for (const auto& proto_it : sig_map) {
for (const auto& scope : proto_it.second) {
base_sigs[proto_it.first].insert(scope.first);
}
}
return base_sigs;
}
/**
* VirtualScope merge functions.
*/
void merge(VirtualScope& scope, const VirtualScope& another) {
TRACE(VIRT,
4,
"merge scopes %s, %s - %s, %s",
SHOW(scope.type),
SHOW(scope.methods[0].first),
SHOW(another.type),
SHOW(another.methods[0].first));
for (const auto& meth : another.methods) {
scope.methods.push_back(meth);
}
scope.interfaces.insert(another.interfaces.begin(), another.interfaces.end());
}
/**
* Deal with the tragic escape story...
* if an interface down the hierarchy is marked ESCAPED
* everything defined in base escapes as well.
*/
void escape_all(VirtualScopes& scopes) {
for (auto& scope : scopes) {
for (auto& vmeth : scope.methods) {
TRACE(VIRT, 6, "ESCAPED %s", SHOW(vmeth.first));
vmeth.second |= ESCAPED;
}
}
}
/**
* Deal with the tragic escape story...
* if an interface at the class level is marked ESCAPED
* everything defined in base and children escapes as well.
*/
void escape_all(SignatureMap& sig_map) {
for (auto& protos_it : sig_map) {
for (auto& scopes_it : protos_it.second) {
escape_all(scopes_it.second);
}
}
}
/**
* Mark VirtualFlags at each level walking up the hierarchy.
* Walk through all the method definitions in base.
*/
void mark_methods(const DexType* type,
SignatureMap& sig_map,
const BaseSigs& base_sigs,
bool escape) {
for (const auto& protos_it : base_sigs) {
const auto name = protos_it.first;
for (const auto& proto : protos_it.second) {
auto& scopes = sig_map[name][proto];
always_assert(!scopes.empty());
always_assert(scopes[0].type == type);
// mark final and override accordingly
auto& first_scope = scopes[0];
if (first_scope.methods.size() == 1) {
TRACE(VIRT, 6, "FINAL %s", SHOW(first_scope.methods[0].first));
first_scope.methods[0].second |= FINAL;
} else {
for (auto meth = first_scope.methods.begin() + 1;
meth != first_scope.methods.end();
meth++) {
TRACE(VIRT, 6, "OVERRIDE %s", SHOW((*meth).first));
(*meth).second |= OVERRIDE;
}
}
// all others must be interfaces but we have a definition
// in base so they must all be override
if (scopes.size() > 1) {
for (auto scope = scopes.begin() + 1; scope != scopes.end(); scope++) {
always_assert(!(*scope).methods.empty());
TRACE(VIRT, 6, "OVERRIDE %s", SHOW((*scope).methods[0].first));
(*scope).methods[0].second |= OVERRIDE;
}
}
if (escape) {
escape_all(scopes);
}
}
}
}
/**
* Once the sig map is complete for a type, build the interface scopes
* for that type. So in
* interface I { void m(); }
* class A implements I { void m() {} }
* this step would build the entry for I.m() adding all the methods
* in the VirtualScope for A.m().
*/
void build_interface_scope(const DexType* type,
SignatureMap& sig_map,
const BaseIntfSigs& intf_sig_map) {
for (const auto& proto_it : intf_sig_map) {
for (const auto& intfs_it : proto_it.second) {
auto& scopes = sig_map[proto_it.first][intfs_it.first];
// first virtual scope must be that in type, it's the first we built
always_assert(scopes[0].type == type);
// mark impl all the class virtual scope
for (auto& meth : scopes[0].methods) {
TRACE(VIRT, 6, "IMPL %s", SHOW(meth.first));
meth.second |= IMPL;
}
// remaining scopes must be for interfaces so they are
// marked IMPL already.
// Scope for interfaces in base are not there yet so
// make a copy of the class virtual scope for every
// interface scope
const auto& intfs = intfs_it.second;
for (const auto& intf : intfs) {
VirtualScope vg;
vg.type = intf;
vg.methods = scopes[0].methods;
scopes.push_back(vg);
}
}
}
}
/**
* Merge 2 signatures map. The map from derived_sig_map is copied in
* base_sig_map.
* Interface methods in base don't have an entry yet, that will be build later
* because it's a straight copy of the class virtual scope.
*/
void merge(const BaseSigs& base_sigs,
const BaseIntfSigs& base_intf_sig_map,
SignatureMap& base_sig_map,
const SignatureMap& derived_sig_map) {
// Helpers
// is_base_sig(name, proto) - is the (name, proto) a definition in base
const auto is_base_sig = [&](const DexString* name, const DexProto* proto) {
TRACE(VIRT, 5, "/check base sigs for %s:%s", SHOW(name), SHOW(proto));
const auto sigs = base_sigs.find(name);
if (sigs == base_sigs.end()) return false;
return sigs->second.count(proto) > 0;
};
// is_base_intf_sig(name, proto) - is the (name, proto) an interface in base
const auto is_base_intf_sig =
[&](const DexString* name, const DexProto* proto, const DexType* intf) {
TRACE(VIRT,
5,
"/check base intf (%s) sigs for %s:%s",
SHOW(intf),
SHOW(name),
SHOW(proto));
const auto& sigs = base_intf_sig_map.find(name);
if (sigs == base_intf_sig_map.end()) return false;
const auto& intfs_it = sigs->second.find(proto);
if (intfs_it == sigs->second.end()) return false;
return intfs_it->second.count(intf) > 0;
};
// walk all derived signatures
for (const auto& derived_sig_entry : derived_sig_map) {
const auto name = derived_sig_entry.first;
auto& name_map = base_sig_map[name];
auto& derived_protos_map = derived_sig_entry.second;
for (const auto& derived_scopes_it : derived_protos_map) {
const auto proto = derived_scopes_it.first;
auto& virt_scopes = name_map[proto];
// the signature in derived does not exists in base
if (!is_base_sig(name, proto)) {
TRACE(VIRT,
4,
"- no scope (%s:%s) in base, copy over",
SHOW(name),
SHOW(proto));
// not a known signature in original base, copy over
const auto& scopes = derived_scopes_it.second;
virt_scopes.insert(virt_scopes.end(), scopes.begin(), scopes.end());
if (traceEnabled(VIRT, 4)) {
for (const auto& scope : scopes) {
TRACE(VIRT,
4,
"- copy %s (%s:%s): (%ld) %s",
SHOW(scope.type),
SHOW(name),
SHOW(proto),
scope.methods.size(),
SHOW(scope.methods[0].first));
}
}
continue;
}
// it's a sig (name, proto) in original base, the derived entry
// needs to merge
// first scope in base_sig_map must be that of the type under
// analysis because we built it first and added to the empty vector
always_assert(!virt_scopes.empty());
TRACE(VIRT,
4,
"- found existing scopes for %s:%s (%ld) - first: %s, %ld, %ld",
SHOW(name),
SHOW(proto),
virt_scopes.size(),
SHOW(virt_scopes[0].type),
virt_scopes[0].methods.size(),
virt_scopes[0].interfaces.size());
always_assert(virt_scopes[0].type == type::java_lang_Object() ||
!is_interface(type_class(virt_scopes[0].type)));
// walk every scope in derived that we have to merge
TRACE(VIRT, 4, "-- walking scopes");
for (const auto& scope : derived_scopes_it.second) {
// if the scope was for a class (!interface) we merge
// with that of base which is now the top definition
TRACE(VIRT,
4,
"-- checking scope type %s(%ld)",
SHOW(scope.type),
scope.methods.size());
TRACE(VIRT,
4,
"-- is interface 0x%p %d",
scope.type,
scope.type != type::java_lang_Object() &&
is_interface(type_class(scope.type)));
if (scope.type == type::java_lang_Object() ||
!is_interface(type_class(scope.type))) {
TRACE(VIRT,
4,
"-- merging with base scopes %s(%ld) : %s",
SHOW(virt_scopes[0].type),
virt_scopes[0].methods.size(),
SHOW(virt_scopes[0].methods[0].first));
merge(virt_scopes[0], scope);
continue;
}
// interface case. If derived was for an interface in base
// do nothing because we will create those entries later
if (!is_base_intf_sig(name, proto, scope.type)) {
TRACE(VIRT,
4,
"-- unimplemented interface %s:%s - %s, %s",
SHOW(name),
SHOW(proto),
SHOW(scope.type),
SHOW(scope.methods[0].first));
virt_scopes.push_back(scope);
continue;
}
TRACE(VIRT,
4,
"-- implemented interface %s:%s - %s",
SHOW(name),
SHOW(proto),
SHOW(scope.type));
}
}
}
}
//
// Helpers to load interface methods in a MethodMap.
//
/**
* Make an entry for a Miranda method.
* The ref may not exist yet and we will create it with make_method.
* That is not causing issues because we are not changing that ref ever.
*/
DexMethod* make_miranda(const DexType* type,
const DexString* name,
const DexProto* proto) {
auto miranda = DexMethod::make_method(
const_cast<DexType*>(type), name, const_cast<DexProto*>(proto));
// The next assert may fire because we don't delete DexMethod from the
// cache and we may find one we have deleted and it was a def.
// Come up with a better assert story
// always_assert(!miranda->is_def());
return static_cast<DexMethod*>(miranda);
}
bool load_interfaces_methods(const DexTypeList*, BaseIntfSigs&);
/**
* Load methods for a given interface and its super interfaces.
* Return true if any interface escapes (no DexClass*).
*/
bool load_interface_methods(const DexClass* intf_cls,
BaseIntfSigs& intf_methods) {
bool escaped = false;
const auto* interfaces = intf_cls->get_interfaces();
if (!interfaces->empty()) {
if (load_interfaces_methods(interfaces, intf_methods)) {
escaped = true;
}
}
for (const auto& meth : intf_cls->get_vmethods()) {
intf_methods[meth->get_name()][meth->get_proto()].insert(
intf_cls->get_type());
}
return escaped;
}
/**
* Load methods for a list of interfaces.
* If any interface escapes (no DexClass*) return true.
*/
bool load_interfaces_methods(const DexTypeList* interfaces,
BaseIntfSigs& intf_methods) {
bool escaped = false;
for (const auto& intf : *interfaces) {
auto intf_cls = type_class(intf);
if (intf_cls == nullptr) {
TRACE(VIRT, 5, "[Unknown interface: %s]", SHOW(intf));
escaped = true;
continue;
}
if (load_interface_methods(intf_cls, intf_methods)) {
escaped = true;
}
}
return escaped;
}
/**
* Get all interface methods for a given type.
*/
bool get_interface_methods(const DexType* type, BaseIntfSigs& intf_methods) {
always_assert_log(intf_methods.empty(), "intf_methods is an out param");
// REVIEW: should we always have a DexClass for java.lang.Object?
if (type == type::java_lang_Object()) return false;
auto cls = type_class(type);
always_assert_log(
cls != nullptr, "DexClass must exist for type %s\n", SHOW(type));
bool escaped = false;
const auto* interfaces = cls->get_interfaces();
if (!interfaces->empty()) {
if (load_interfaces_methods(interfaces, intf_methods)) escaped = true;
}
return escaped;
}
/**
* Make sure all the intereface methods are added to the SignatureMap.
* SignatureMap in input contains only scopes for virtual in the class.
* After this step a type is fully specified with all its virtual methods
* and all interface methods that did not have an implementation created
* (as "pure miranda" methods).
* interface I { void m(); }
* abstract class A implements I {}
* in this case we create an entry for A.m() and mark it miranda
* even though the method did not exist. It will not be a def (!is_def()).
*/
bool load_interfaces(const DexType* type,
SignatureMap& sig_map,
BaseIntfSigs& intf_sig_map) {
bool escaped = get_interface_methods(type, intf_sig_map);
const auto intf_flags = MIRANDA | IMPL;
// sig_map contains only the virtual methods in the class and
// intf_sig_map only the methods in the interface.
// For any missing methods in the class we create a new (miranda) method.
// If the method is there already we mark it miranda.
for (const auto& sig_it : intf_sig_map) {
for (const auto& proto_it : sig_it.second) {
const auto& name = sig_it.first;
const auto& proto = proto_it.first;
always_assert(sig_map[name][proto].size() <= 1);
if (sig_map[name][proto].empty()) {
// the method interface is not implemented in current
// type. The class is abstract or a definition up the
// hierarchy is present.
// Make a pure miranda entry
auto mir_meth = make_miranda(type, name, proto);
VirtualScope scope;
scope.type = type;
scope.methods.emplace_back(mir_meth, intf_flags);
sig_map[name][proto].push_back(scope);
} else {
// the method interface is implemented in the current
// type, mark it miranda
auto& scope = sig_map[name][proto][0];
always_assert(scope.methods.size() == 1);
scope.methods[0].second |= intf_flags;
}
// add the implemented interfaces to the class
// virtual scope
sig_map[name][proto][0].interfaces.insert(proto_it.second.begin(),
proto_it.second.end());
}
}
return escaped;
}
/**
* Load all virtual methods in the given type and build an entry
* in the signature map.
* Those should be the only entries in the SignatureMap in input.
* They are all TOP_DEF until a parent proves otherwise.
*/
void load_methods(const DexType* type, SignatureMap& sig_map) {
auto const& vmethods = get_vmethods(type);
// add each virtual method to the SignatureMap
for (auto& vmeth : vmethods) {
auto& proto_map = sig_map[vmeth->get_name()];
auto& scopes = proto_map[vmeth->get_proto()];
always_assert(scopes.empty());
VirtualScope scope;
scope.type = type;
scope.methods.emplace_back(vmeth, TOP_DEF);
scopes.emplace_back(scope);
}
}
/**
* Compute VirtualScopes and virtual method flags.
* Starting from java.lang.Object recursively walk the type hierarchy down
* and while unwinding compare each method in the class being traversed with
* all methods coming from the children.
* Then perform the following:
* 1- if a method in the parent does not exist in any children mark it FINAL
* 2- if a method in the parent matches a list of methods in the children
* mark all children OVERRIDE
* 3- if a method is an implementation of an interface method mark it IMPL
* 4- if any escape occurs (unknown interface) mark all method in the branch
* (up to object as ESCAPED).
* 5- mark MIRANDA any method that implements an interface at the
* 'implements' point
*
* At the end top methods (where the method is introduced) are the only
* non OVERRIDE and possibly non IMPL.
* Any method that is FINAL and not OVERRIDE or IMPL is effectively a
* non virtual.
* Interfaces add a painful spin to this, best expressed by examples:
* class A { void m() {} }
* interface I { void m(); }
* class B extends A implements I {}
* in this case A.m() must be marked IMPL even though is up in the hierarchy
* chain. If not, it would be a FINAL non OVERRIDE and could be inlined and
* deleted breaking the interface contract. So we mark all methods that
* match interface down the hierarchy as IMPL.
* If an interface is not known (escapes) we mark all children methods
* and all methods up the hierarchy chain ESCAPED.
* Consider this example and assume interface I is unknown
* class A { public m() {} public g() {} public f() {} }
* class B extends A implements I {}
* class C extends B { public void k() {} }
* class D extends A { public void k() {} }
* in this case, not knowing interface I, we mark all methods in A, B and C
* ESCAPED but methods in D are not, so in this case they are just FINAL and
* effectively D.k() would be non virtual as opposed to C.k() which is ESCAPED.
*/
bool build_signature_map(const ClassHierarchy& hierarchy,
const DexType* type,
SignatureMap& sig_map) {
always_assert_log(sig_map.empty(),
"intf_methods and children_methods are out params");
const TypeSet& children = hierarchy.at(type);
TRACE(VIRT, 3, "* Visit %s", SHOW(type));
load_methods(type, sig_map);
// will hold all the signature introduced by interfaces in type
BaseIntfSigs intf_sig_map;
bool escape_down = load_interfaces(type, sig_map, intf_sig_map);
BaseSigs base_sigs = load_base_sigs(sig_map);
TRACE(VIRT, 3, "* Sig map computed for %s", SHOW(type));
// recurse through every child to collect all methods
// and interface methods under type
bool escape_up = false;
for (const auto& child : children) {
SignatureMap child_sig_map;
escape_up =
build_signature_map(hierarchy, child, child_sig_map) || escape_up;
TRACE(VIRT,
3,
"* Merging sig map of %s with child %s",
SHOW(type),
SHOW(child));
merge(base_sigs, intf_sig_map, sig_map, child_sig_map);
}
TRACE(VIRT, 3, "* Marking methods at %s", SHOW(type));
mark_methods(type, sig_map, base_sigs, escape_up);
build_interface_scope(type, sig_map, intf_sig_map);
if (escape_down) {
escape_all(sig_map);
}
TRACE(VIRT, 3, "* Visited %s(%d, %d)", SHOW(type), escape_up, escape_down);
return escape_up | escape_down;
}
const VirtualScope* find_rooted_scope(const SignatureMap& sig_map,
const DexType* type,
const DexMethod* meth) {
const auto& protos = sig_map.find(meth->get_name());
always_assert(protos != sig_map.end());
const auto& scopes = protos->second.find(meth->get_proto());
always_assert(scopes != protos->second.end());
for (const auto& scope : scopes->second) {
if (scope.type == type &&
method::signatures_match(scope.methods[0].first, meth)) {
return &scope;
}
}
return nullptr;
}
/**
* Find all interface scopes rooted at the class provided.
* Those are the scope rooted at a MIRANDA method as in
* interface I { void m(); }
* abstract class A imlements I {}
* class B entends A { public void m() {} }
* Class A will have a virtual scope for m().
*/
void get_rooted_interface_scope(const SignatureMap& sig_map,
const DexType* type,
const DexClass* cls,
Scopes& cls_scopes) {
for (const auto& intf : *cls->get_interfaces()) {
const DexClass* intf_cls = type_class(intf);
if (intf_cls == nullptr) continue;
for (const auto& meth : intf_cls->get_vmethods()) {
const auto scope = find_rooted_scope(sig_map, type, meth);
if (scope != nullptr && scope->type == type &&
!scope->methods[0].first->is_def()) {
const auto& existing_scopes = cls_scopes.find(type);
if (existing_scopes != cls_scopes.end()) {
bool already_found = false;
for (const auto& existing_scope : existing_scopes->second) {
if (existing_scope == scope) {
already_found = true;
}
}
if (already_found) continue;
}
TRACE(VIRT,
9,
"add rooted interface scope for %s (%s) on %s",
show_deobfuscated(meth).c_str(),
SHOW(meth->get_name()),
SHOW(type));
cls_scopes[type].emplace_back(scope);
}
}
get_rooted_interface_scope(sig_map, type, intf_cls, cls_scopes);
}
}
/**
* Find all scopes rooted to a given type and adds it to
* ClassScope for the given type.
*/
void get_root_scopes(const SignatureMap& sig_map,
const DexType* type,
Scopes& cls_scopes) {
const std::vector<DexMethod*>& methods = get_vmethods(type);
TRACE(VIRT, 9, "found %ld vmethods for %s", methods.size(), SHOW(type));
for (const auto meth : methods) {
const auto& protos = sig_map.find(meth->get_name());
always_assert(protos != sig_map.end());
const auto& scopes = protos->second.find(meth->get_proto());
always_assert(scopes != protos->second.end());
for (const auto& scope : scopes->second) {
if (scope.type == type) {
TRACE(VIRT, 9, "add virtual scope for %s", SHOW(type));
always_assert(scope.methods[0].first == meth);
cls_scopes[type].emplace_back(&scope);
}
}
}
get_rooted_interface_scope(sig_map, type, type_class(type), cls_scopes);
}
} // namespace
SignatureMap build_signature_map(const ClassHierarchy& class_hierarchy) {
SignatureMap signature_map;
build_signature_map(class_hierarchy, type::java_lang_Object(), signature_map);
return signature_map;
}
const std::vector<DexMethod*>& get_vmethods(const DexType* type) {
const DexClass* cls = type_class(type);
if (cls == nullptr) {
always_assert_log(
type == type::java_lang_Object(), "Unknown type %s\n", SHOW(type));
create_object_class();
cls = type_class(type);
}
return cls->get_vmethods();
}
const VirtualScope& find_virtual_scope(const SignatureMap& sig_map,
const DexMethod* meth) {
const auto& protos = sig_map.find(meth->get_name());
always_assert(protos != sig_map.end());
const auto& scopes = protos->second.find(meth->get_proto());
always_assert(scopes != protos->second.end());
const auto meth_type = meth->get_class();
for (const auto& scope : scopes->second) {
if (scope.type == type::java_lang_Object()) return scope;
if (type::is_subclass(scope.type, meth_type)) return scope;
}
not_reached_log("unreachable. Scope not found for %s\n", SHOW(meth));
}
bool can_rename_scope(const VirtualScope* scope) {
for (const auto& vmeth : scope->methods) {
if (!can_rename(vmeth.first) || (vmeth.second & ESCAPED) != 0) {
return false;
}
}
return true;
}
std::vector<const DexMethod*> select_from(const VirtualScope* scope,
const DexType* type) {
std::vector<const DexMethod*> refined_scope;
std::unordered_map<const DexType*, DexMethod*> non_child_methods;
bool found_root_method = false;
for (const auto& method : scope->methods) {
if (type::check_cast(method.first->get_class(), type)) {
found_root_method =
found_root_method || type == method.first->get_class();
refined_scope.emplace_back(method.first);
} else {
non_child_methods[method.first->get_class()] = method.first;
}
}
if (!found_root_method) {
auto cls = type_class(type);
while (cls != nullptr) {
const auto super = cls->get_super_class();
const auto& meth = non_child_methods.find(super);
if (meth != non_child_methods.end()) {
refined_scope.emplace_back(meth->second);
return refined_scope;
}
cls = type_class(super);
}
}
return refined_scope;
}
const std::vector<const VirtualScope*> ClassScopes::empty_scope =
std::vector<const VirtualScope*>();
const std::vector<std::vector<const VirtualScope*>>
ClassScopes::empty_interface_scope =
std::vector<std::vector<const VirtualScope*>>();
ClassScopes::ClassScopes(const Scope& scope) {
m_hierarchy = build_type_hierarchy(scope);
m_interface_map = build_interface_map(m_hierarchy);
m_sig_map = build_signature_map(m_hierarchy);
build_class_scopes(type::java_lang_Object());
build_interface_scopes();
}
const ClassHierarchy& ClassScopes::get_parent_to_children() const {
return m_hierarchy;
}
/**
* Builds the ClassScope for type and children.
* Calling with type::java_lang_Object() builds the ClassScope
* for the entire system as redex knows it.
*/
void ClassScopes::build_class_scopes(const DexType* type) {
auto cls = type_class(type);
always_assert(cls != nullptr || type == type::java_lang_Object());
get_root_scopes(m_sig_map, type, m_scopes);
const auto& children_it = m_hierarchy.find(type);
if (children_it != m_hierarchy.end()) {
for (const auto& child : children_it->second) {
build_class_scopes(child);
}
}
}
void ClassScopes::build_interface_scopes() {
for (const auto& intf_it : m_interface_map) {
const DexClass* intf_cls = type_class(intf_it.first);
if (intf_cls == nullptr) {
TRACE_NO_LINE(VIRT, 9, "missing DexClass for %s", SHOW(intf_it.first));
continue;
}
for (const auto& meth : intf_cls->get_vmethods()) {
const auto& scopes = m_sig_map[meth->get_name()][meth->get_proto()];
// at least the method itself
always_assert_log(!scopes.empty(), "Scope empty for %s", SHOW(meth));
auto& intf_scope = m_interface_scopes[intf_it.first];
intf_scope.push_back({});
for (const auto& scope : scopes) {
if (scope.interfaces.count(intf_it.first) == 0) continue;
TRACE(VIRT, 9, "add interface scope for %s", SHOW(intf_it.first));
intf_scope.back().push_back(&scope);
}
}
}
}
InterfaceScope ClassScopes::find_interface_scope(const DexMethod* meth) const {
InterfaceScope intf_scope;
DexType* intf = meth->get_class();
if (m_sig_map.count(meth->get_name()) == 0 ||
m_sig_map.at(meth->get_name()).count(meth->get_proto()) == 0) {
return intf_scope;
}
const auto& scopes = m_sig_map.at(meth->get_name()).at(meth->get_proto());
always_assert(!scopes.empty()); // at least the method itself
for (const auto& scope : scopes) {
if (scope.interfaces.count(intf) == 0) continue;
TRACE_NO_LINE(VIRT, 9, "add interface scope for %s", SHOW(intf));
intf_scope.push_back(&scope);
}
return intf_scope;
}
std::string ClassScopes::show_type(const DexType* type) { return show(type); }
| [
"[email protected]"
] | |
b66cc8ebb6f2f590f221cda99ecc387edf6e9294 | fa4a1fd904955489d9e44969bdc968df917f7fa9 | /Test2/상속.cpp | 604dc8c1b79ac33de43409607cfd226d3cd357e4 | [] | no_license | WhiteHair-H/Study-C-PLUS | 9b4461a050b082c940b1e29c79b96dd7d312a9d7 | b45e17e2030b442aa3e54176759cc394936ad71b | refs/heads/main | 2023-05-22T18:47:16.051846 | 2021-06-10T07:47:20 | 2021-06-10T07:47:20 | 372,756,097 | 1 | 0 | null | null | null | null | UHC | C++ | false | false | 1,101 | cpp | //#include <stdio.h>
//#include <iostream>
//using namespace std;
//
//class Human
//{
//private:
// char* name;
//public:
// Human(const char* aname)
// {
// int len = strlen(aname) + 1;
// name = new char[len];
// //strcpy(name, aname);
// strcpy_s(name, len, aname); // strcpy 보단 안정적
// }
// ~Human() { delete[] name; }
// void printName()
// {
// cout << "My name is " << name << endl;
// }
// const char* getName() { return name; }
//};
//
//class Student : public Human
//{
//private:
// char* major;
//public:
// Student(const char* aname, const char* amajor) : Human(aname)
// {
// int len = strlen(amajor) + 1;
// major = new char[len];
// strcpy_s(major, len, amajor);
// /*int len1 = strlen(aname) + 1;
// aname = new char[len1];
// strcpy_s(major, len1, aname);*/
// }
//
// void printMajor()
// {
// cout << "My name is " << getName() << " End My major is " << major << "입니다." << endl;
// }
// ~Student() { delete[] major; }
//};
//
//int main()
//{
// Human h("jinwoo");
// h.printName();
//
// Student s("jinwoo", "Iot");
// s.printMajor();
// return 0;
//} | [
"https://github.com/WhiteHair-H/BasicSetting.git"
] | https://github.com/WhiteHair-H/BasicSetting.git |
cf9db6b3e46b96cf4f3caa364512ed73127181f6 | bb842de9543d666b66ca8f7b292a43174ac1c76c | /Teensy/teensy_drive_Flex_MA/Timer0.hpp | bcbc3b364a5d329582055fc6052111e10ac3f239 | [] | no_license | jensdehoog95/MAP2017 | fa4bc686a357cffa514893c617e2aebe1dbfdc8d | 85be1b162f67a78a5d5373cbc4ba9aac018ad82d | refs/heads/master | 2021-03-19T05:57:46.629773 | 2017-06-26T13:47:14 | 2017-06-26T13:47:14 | 88,791,020 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,418 | hpp | /*
* Interrupt and PWM utilities for 16 bit Timer0 on ATmega168/328
* Original code by Jesse Tane for http://labs.ideo.com August 2008
* Modified March 2009 by Jérôme Despatis and Jesse Tane for ATmega328 support
* Modified June 2009 by Michael Polli and Jesse Tane to fix a bug in setPeriod() which caused the timer to stop
* Modified April 2012 by Paul Stoffregen - portable to other AVR chips, use inline functions
* Modified again, June 2014 by Paul Stoffregen - support Teensy 3.x & even more AVR chips
*
*
* This is free software. You can redistribute it and/or modify it under
* the terms of Creative Commons Attribution 3.0 United States License.
* To view a copy of this license, visit http://creativecommons.org/licenses/by/3.0/us/
* or send a letter to Creative Commons, 171 Second Street, Suite 300, San Francisco, California, 94105, USA.
*
*/
#ifndef TimerZero_h_
#define TimerZero_h_
#if defined(ARDUINO) && ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif
#include "config/known_16bit_timers.h"
#define TIMER1_RESOLUTION 65536UL // Timer0 is 16 bit
// Placing nearly all the code in this .h file allows the functions to be
// inlined by the compiler. In the very common case with constant values
// the compiler will perform all calculations and simply write constants
// to the hardware registers (for example, setPeriod).
class TimerZero
{
#if defined(__AVR__)
public:
//****************************
// Configuration
//****************************
void initialize(unsigned long microseconds=1000000) __attribute__((always_inline)) {
TCCR1B = _BV(WGM13); // set mode as phase and frequency correct pwm, stop the timer
TCCR1A = 0; // clear control register A
setPeriod(microseconds);
}
void setPeriod(unsigned long microseconds) __attribute__((always_inline)) {
const unsigned long cycles = (F_CPU / 2000000) * microseconds;
if (cycles < TIMER1_RESOLUTION) {
clockSelectBits = _BV(CS10);
pwmPeriod = cycles;
} else
if (cycles < TIMER1_RESOLUTION * 8) {
clockSelectBits = _BV(CS11);
pwmPeriod = cycles / 8;
} else
if (cycles < TIMER1_RESOLUTION * 64) {
clockSelectBits = _BV(CS11) | _BV(CS10);
pwmPeriod = cycles / 64;
} else
if (cycles < TIMER1_RESOLUTION * 256) {
clockSelectBits = _BV(CS12);
pwmPeriod = cycles / 256;
} else
if (cycles < TIMER1_RESOLUTION * 1024) {
clockSelectBits = _BV(CS12) | _BV(CS10);
pwmPeriod = cycles / 1024;
} else {
clockSelectBits = _BV(CS12) | _BV(CS10);
pwmPeriod = TIMER1_RESOLUTION - 1;
}
ICR1 = pwmPeriod;
TCCR1B = _BV(WGM13) | clockSelectBits;
}
//****************************
// Run Control
//****************************
void start() __attribute__((always_inline)) {
TCCR1B = 0;
TCNT1 = 0; // TODO: does this cause an undesired interrupt?
resume();
}
void stop() __attribute__((always_inline)) {
TCCR1B = _BV(WGM13);
}
void restart() __attribute__((always_inline)) {
start();
}
void resume() __attribute__((always_inline)) {
TCCR1B = _BV(WGM13) | clockSelectBits;
}
//****************************
// PWM outputs
//****************************
void setPwmDuty(char pin, unsigned int duty) __attribute__((always_inline)) {
unsigned long dutyCycle = pwmPeriod;
dutyCycle *= duty;
dutyCycle >>= 10;
if (pin == TIMER1_A_PIN) OCR1A = dutyCycle;
#ifdef TIMER1_B_PIN
else if (pin == TIMER1_B_PIN) OCR1B = dutyCycle;
#endif
#ifdef TIMER1_C_PIN
else if (pin == TIMER1_C_PIN) OCR1C = dutyCycle;
#endif
}
void pwm(char pin, unsigned int duty) __attribute__((always_inline)) {
if (pin == TIMER1_A_PIN) { pinMode(TIMER1_A_PIN, OUTPUT); TCCR1A |= _BV(COM1A1); }
#ifdef TIMER1_B_PIN
else if (pin == TIMER1_B_PIN) { pinMode(TIMER1_B_PIN, OUTPUT); TCCR1A |= _BV(COM1B1); }
#endif
#ifdef TIMER1_C_PIN
else if (pin == TIMER1_C_PIN) { pinMode(TIMER1_C_PIN, OUTPUT); TCCR1A |= _BV(COM1C1); }
#endif
setPwmDuty(pin, duty);
TCCR1B = _BV(WGM13) | clockSelectBits;
}
void pwm(char pin, unsigned int duty, unsigned long microseconds) __attribute__((always_inline)) {
if (microseconds > 0) setPeriod(microseconds);
pwm(pin, duty);
}
void disablePwm(char pin) __attribute__((always_inline)) {
if (pin == TIMER1_A_PIN) TCCR1A &= ~_BV(COM1A1);
#ifdef TIMER1_B_PIN
else if (pin == TIMER1_B_PIN) TCCR1A &= ~_BV(COM1B1);
#endif
#ifdef TIMER1_C_PIN
else if (pin == TIMER1_C_PIN) TCCR1A &= ~_BV(COM1C1);
#endif
}
//****************************
// Interrupt Function
//****************************
void attachInterrupt(void (*isr)()) __attribute__((always_inline)) {
isrCallback = isr;
TIMSK1 = _BV(TOIE1);
}
void attachInterrupt(void (*isr)(), unsigned long microseconds) __attribute__((always_inline)) {
if(microseconds > 0) setPeriod(microseconds);
attachInterrupt(isr);
}
void detachInterrupt() __attribute__((always_inline)) {
TIMSK1 = 0;
}
static void (*isrCallback)();
static void isrDefaultUnused();
private:
// properties
static unsigned short pwmPeriod;
static unsigned char clockSelectBits;
#elif defined(__arm__) && defined(CORE_TEENSY)
#if defined(KINETISK)
#define F_TIMER F_BUS
#elif defined(KINETISL)
#define F_TIMER (F_PLL/2)
#endif
public:
//****************************
// Configuration
//****************************
void initialize(unsigned long microseconds=1000000) __attribute__((always_inline)) {
setPeriod(microseconds);
}
void setPeriod(unsigned long microseconds) __attribute__((always_inline)) {
const unsigned long cycles = (F_TIMER / 2000000) * microseconds;
// A much faster if-else
// This is like a binary serch tree and no more than 3 conditions are evaluated.
// I haven't checked if this becomes significantly longer ASM than the simple ladder.
// It looks very similar to the ladder tho: same # of if's and else's
/*
// This code does not work properly in all cases :(
// https://github.com/PaulStoffregen/TimerOne/issues/17
if (cycles < TIMER0_RESOLUTION * 16) {
if (cycles < TIMER0_RESOLUTION * 4) {
if (cycles < TIMER0_RESOLUTION) {
clockSelectBits = 0;
pwmPeriod = cycles;
}else{
clockSelectBits = 1;
pwmPeriod = cycles >> 1;
}
}else{
if (cycles < TIMER1_RESOLUTION * 8) {
clockSelectBits = 3;
pwmPeriod = cycles >> 3;
}else{
clockSelectBits = 4;
pwmPeriod = cycles >> 4;
}
}
}else{
if (cycles > TIMER1_RESOLUTION * 64) {
if (cycles > TIMER1_RESOLUTION * 128) {
clockSelectBits = 7;
pwmPeriod = TIMER1_RESOLUTION - 1;
}else{
clockSelectBits = 7;
pwmPeriod = cycles >> 7;
}
}
else{
if (cycles > TIMER1_RESOLUTION * 32) {
clockSelectBits = 6;
pwmPeriod = cycles >> 6;
}else{
clockSelectBits = 5;
pwmPeriod = cycles >> 5;
}
}
}
*/
if (cycles < TIMER1_RESOLUTION) {
clockSelectBits = 0;
pwmPeriod = cycles;
} else
if (cycles < TIMER1_RESOLUTION * 2) {
clockSelectBits = 1;
pwmPeriod = cycles >> 1;
} else
if (cycles < TIMER1_RESOLUTION * 4) {
clockSelectBits = 2;
pwmPeriod = cycles >> 2;
} else
if (cycles < TIMER1_RESOLUTION * 8) {
clockSelectBits = 3;
pwmPeriod = cycles >> 3;
} else
if (cycles < TIMER1_RESOLUTION * 16) {
clockSelectBits = 4;
pwmPeriod = cycles >> 4;
} else
if (cycles < TIMER1_RESOLUTION * 32) {
clockSelectBits = 5;
pwmPeriod = cycles >> 5;
} else
if (cycles < TIMER1_RESOLUTION * 64) {
clockSelectBits = 6;
pwmPeriod = cycles >> 6;
} else
if (cycles < TIMER1_RESOLUTION * 128) {
clockSelectBits = 7;
pwmPeriod = cycles >> 7;
} else {
clockSelectBits = 7;
pwmPeriod = TIMER1_RESOLUTION - 1;
}
uint32_t sc = FTM0_SC;
FTM0_SC = 0;
FTM0_MOD = pwmPeriod;
FTM0_SC = FTM_SC_CLKS(1) | FTM_SC_CPWMS | clockSelectBits | (sc & FTM_SC_TOIE);
}
//****************************
// Run Control
//****************************
void start() __attribute__((always_inline)) {
stop();
FTM0_CNT = 0;
resume();
}
void stop() __attribute__((always_inline)) {
FTM0_SC = FTM0_SC & (FTM_SC_TOIE | FTM_SC_CPWMS | FTM_SC_PS(7));
}
void restart() __attribute__((always_inline)) {
start();
}
void resume() __attribute__((always_inline)) {
FTM0_SC = (FTM0_SC & (FTM_SC_TOIE | FTM_SC_PS(7))) | FTM_SC_CPWMS | FTM_SC_CLKS(1);
}
//****************************
// PWM outputs
//****************************
void setPwmDuty(char pin, unsigned int duty) __attribute__((always_inline)) {
unsigned long dutyCycle = pwmPeriod;
dutyCycle *= duty;
dutyCycle >>= 10;
if (pin == TIMER1_A_PIN) {
FTM0_C0V = dutyCycle;
} else if (pin == TIMER1_B_PIN) {
FTM0_C1V = dutyCycle;
}
}
void pwm(char pin, unsigned int duty) __attribute__((always_inline)) {
setPwmDuty(pin, duty);
if (pin == TIMER1_A_PIN) {
*portConfigRegister(TIMER1_A_PIN) = PORT_PCR_MUX(3) | PORT_PCR_DSE | PORT_PCR_SRE;
} else if (pin == TIMER1_B_PIN) {
*portConfigRegister(TIMER1_B_PIN) = PORT_PCR_MUX(3) | PORT_PCR_DSE | PORT_PCR_SRE;
}
}
void pwm(char pin, unsigned int duty, unsigned long microseconds) __attribute__((always_inline)) {
if (microseconds > 0) setPeriod(microseconds);
pwm(pin, duty);
}
void disablePwm(char pin) __attribute__((always_inline)) {
if (pin == TIMER1_A_PIN) {
*portConfigRegister(TIMER1_A_PIN) = 0;
} else if (pin == TIMER1_B_PIN) {
*portConfigRegister(TIMER1_B_PIN) = 0;
}
}
//****************************
// Interrupt Function
//****************************
void attachInterrupt(void (*isr)()) __attribute__((always_inline)) {
isrCallback = isr;
FTM0_SC |= FTM_SC_TOIE;
NVIC_ENABLE_IRQ(IRQ_FTM0);
}
void attachInterrupt(void (*isr)(), unsigned long microseconds) __attribute__((always_inline)) {
if(microseconds > 0) setPeriod(microseconds);
attachInterrupt(isr);
}
void detachInterrupt() __attribute__((always_inline)) {
FTM0_SC &= ~FTM_SC_TOIE;
NVIC_DISABLE_IRQ(IRQ_FTM0);
}
static void (*isrCallback)();
static void isrDefaultUnused();
private:
// properties
static unsigned short pwmPeriod;
static unsigned char clockSelectBits;
#undef F_TIMER
#endif
};
extern TimerZero Timer0;
#endif
| [
"[email protected]"
] | |
a7a11f15efab15c8d4481ab898d8d8a622bbb699 | 44313c3267c1b694970a7cffd50a486930fea285 | /OgreNewt 2/src/OgreNewt_Joint.cpp | 559070516191b169dc3e9a6fc54a77132eac34eb | [] | no_license | ehei1/maze-client | 3bd08b40d8a02c760e0da631c9680a8375b514d8 | 3ca195e0cf21d2cf0c9c75b1374ffdaae3f88245 | refs/heads/master | 2022-10-28T13:38:27.971161 | 2020-06-15T12:33:24 | 2020-06-15T12:33:24 | 272,433,103 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,094 | cpp | #include "OgreNewt_Joint.h"
#include "OgreNewt_Body.h"
#include "OgreNewt_World.h"
namespace OgreNewt
{
Joint::Joint()
{
// nothing here
}
Joint::~Joint()
{
if(m_joint)
{
if (NewtonJointGetUserData(m_joint))
{
NewtonJointSetDestructor( m_joint, NULL );
NewtonDestroyJoint( m_world->getNewtonWorld(), m_joint );
}
}
}
void _CDECL Joint::destructor( const NewtonJoint* me )
{
Joint* jnt;
jnt = (Joint*)NewtonJointGetUserData( me );
NewtonJointSetDestructor( me, NULL );
NewtonJointSetUserData( me, NULL );
delete jnt;
}
CustomJoint::CustomJoint( unsigned int maxDOF, const Body* body0, const Body* body1 ) : Joint()
{
m_maxDOF = maxDOF;
m_body0 = body0;
m_body1 = body1;
m_world = m_body0->getWorld();
if (body1)
m_joint = NewtonConstraintCreateUserJoint( m_world->getNewtonWorld(), m_maxDOF,
CustomJoint::newtonSubmitConstraint, CustomJoint::newtonGetInfo,
m_body0->getNewtonBody(), m_body1->getNewtonBody() );
else
m_joint = NewtonConstraintCreateUserJoint( m_world->getNewtonWorld(), m_maxDOF,
CustomJoint::newtonSubmitConstraint, CustomJoint::newtonGetInfo,
m_body0->getNewtonBody(), NULL );
NewtonJointSetUserData (m_joint, this);
NewtonJointSetDestructor (m_joint, destructor);
NewtonUserJointSetFeedbackCollectorCallback( m_joint, CustomJoint::newtonFeedbackCollector );
}
CustomJoint::~CustomJoint()
{
}
void CustomJoint::pinAndDirToLocal( const Ogre::Vector3& pinpt, const Ogre::Vector3& pindir,
Ogre::Quaternion& localOrient0, Ogre::Vector3& localPos0, Ogre::Quaternion& localOrient1, Ogre::Vector3& localPos1 ) const
{
localOrient0 = localOrient1 = Ogre::Quaternion::IDENTITY;
localPos0 = localPos1 = Ogre::Vector3::ZERO;
Ogre::Quaternion bodyOrient0 = Ogre::Quaternion::IDENTITY;
Ogre::Quaternion bodyOrient1 = Ogre::Quaternion::IDENTITY;
Ogre::Vector3 bodyPos0 = Ogre::Vector3::ZERO;
Ogre::Vector3 bodyPos1 = Ogre::Vector3::ZERO;
Ogre::Quaternion pinOrient = grammSchmidt(pindir);
m_body0->getPositionOrientation( bodyPos0, bodyOrient0 );
if (m_body1)
m_body1->getPositionOrientation( bodyPos1, bodyOrient1 );
localPos0 = bodyOrient0.Inverse() * (pinpt - bodyPos0);
localOrient0 = pinOrient * bodyOrient0.Inverse();
localPos1 = bodyOrient1.Inverse() * (pinpt - bodyPos1);
localOrient1 = pinOrient * bodyOrient1.Inverse();
}
void CustomJoint::localToGlobal( const Ogre::Quaternion& localOrient, const Ogre::Vector3& localPos, Ogre::Quaternion& globalOrient, Ogre::Vector3& globalPos, int bodyIndex ) const
{
globalOrient = Ogre::Quaternion::IDENTITY;
globalPos= Ogre::Vector3::ZERO;
const Body* bdy = NULL;
if (bodyIndex == 0)
bdy = m_body0;
else if (m_body1)
bdy = m_body1;
Ogre::Quaternion bodyOrient = Ogre::Quaternion::IDENTITY;
Ogre::Vector3 bodyPos = Ogre::Vector3::ZERO;
if (bdy)
bdy->getPositionOrientation( bodyPos, bodyOrient );
globalPos = (bodyOrient * localPos) + bodyPos;
globalOrient = bodyOrient * localOrient;
}
void CustomJoint::globalToLocal( const Ogre::Quaternion& globalOrient, const Ogre::Vector3& globalPos, Ogre::Quaternion& localOrient, Ogre::Vector3& localPos, int bodyIndex ) const
{
localOrient = Ogre::Quaternion::IDENTITY;
localPos= Ogre::Vector3::ZERO;
const Body* bdy = NULL;
if (bodyIndex == 0)
bdy = m_body0;
else if (m_body1)
bdy = m_body1;
Ogre::Quaternion bodyOrient = Ogre::Quaternion::IDENTITY;
Ogre::Vector3 bodyPos = Ogre::Vector3::ZERO;
if (bdy)
bdy->getPositionOrientation( bodyPos, bodyOrient );
Ogre::Quaternion bodyOrientInv = bodyOrient.Inverse();
localOrient = bodyOrientInv * globalOrient;
localPos = bodyOrientInv * (globalPos - bodyPos);
}
void CustomJoint::addLinearRow( const Ogre::Vector3& pt0, const Ogre::Vector3& pt1, const Ogre::Vector3& dir ) const
{
NewtonUserJointAddLinearRow( m_joint, &pt0.x, &pt1.x, &dir.x );
}
void CustomJoint::addAngularRow( Ogre::Radian relativeAngleError, const Ogre::Vector3& dir ) const
{
NewtonUserJointAddAngularRow( m_joint, relativeAngleError.valueRadians(), &dir.x );
}
void CustomJoint::addGeneralRow(const Ogre::Vector3& linear0, const Ogre::Vector3& angular0, const Ogre::Vector3& linear1, const Ogre::Vector3& angular1) const
{
float jacobian0[6], jacobian1[6];
jacobian0[0] = linear0.x;
jacobian0[1] = linear0.y;
jacobian0[2] = linear0.z;
jacobian0[3] = angular0.x;
jacobian0[4] = angular0.y;
jacobian0[5] = angular0.z;
jacobian1[0] = linear1.x;
jacobian1[1] = linear1.y;
jacobian1[2] = linear1.z;
jacobian1[3] = angular1.x;
jacobian1[4] = angular1.y;
jacobian1[5] = angular1.z;
NewtonUserJointAddGeneralRow( m_joint, jacobian0, jacobian1 );
}
void CustomJoint::setRowMinimumFriction( Ogre::Real friction ) const
{
NewtonUserJointSetRowMinimumFriction( m_joint, friction );
}
void CustomJoint::setRowMaximumFriction( Ogre::Real friction ) const
{
NewtonUserJointSetRowMaximumFriction( m_joint, friction );
}
void CustomJoint::setRowAcceleration( Ogre::Real accel ) const
{
NewtonUserJointSetRowAcceleration( m_joint, accel );
}
void CustomJoint::setRowStiffness( Ogre::Real stiffness ) const
{
NewtonUserJointSetRowStiffness( m_joint, stiffness );
}
void CustomJoint::setRowSpringDamper(Ogre::Real springK, Ogre::Real springD) const
{
NewtonUserJointSetRowSpringDamperAcceleration( m_joint, springK, springD );
}
void _CDECL CustomJoint::newtonSubmitConstraint( const NewtonJoint* me, float timeStep, int threadIndex )
{
CustomJoint* j = (CustomJoint*)NewtonJointGetUserData( me );
j->submitConstraint( (Ogre::Real)timeStep, threadIndex );
}
void _CDECL CustomJoint::newtonFeedbackCollector( const NewtonJoint* me, float timeStep, int threadIndex )
{
CustomJoint* j = (CustomJoint*)NewtonJointGetUserData( me );
j->feedbackCollector( (Ogre::Real)timeStep, threadIndex );
}
void _CDECL CustomJoint::newtonGetInfo(const NewtonJoint *me, NewtonJointRecord *info)
{
CustomJoint* j = (CustomJoint*)NewtonJointGetUserData( me );
}
Ogre::Quaternion CustomJoint::grammSchmidt( const Ogre::Vector3& pin ) const
{
Ogre::Vector3 front, up, right;
front = pin;
front.normalise();
if (Ogre::Math::Abs( front.z ) > 0.577f)
right = front.crossProduct( Ogre::Vector3(-front.y, front.z, 0.0f) );
else
right = front.crossProduct( Ogre::Vector3(-front.y, front.x, 0.0f) );
right.normalise();
up = right.crossProduct( front );
Ogre::Matrix3 ret;
ret.FromAxes( front, up, right );
Ogre::Quaternion quat;
quat.FromRotationMatrix( ret );
return quat;
}
} // end NAMESPACE OgreNewt
| [
"[email protected]"
] | |
8109ae58145d455808935722a19c545d390c51a0 | bf5ce4d5c5996d8e9cfa340811140bd193c55d3d | /set_stl.h | 364102a4e0542bae4170fd835afa3c7e46bb5e24 | [] | no_license | zhaofeng-shu33/set | 6b24cb4b2f9d646eda5d781122220710251d16f7 | 100b6fefd8b22e4e681e328e29451b6e1ee8a742 | refs/heads/master | 2022-11-16T15:47:03.598954 | 2022-10-20T02:39:45 | 2022-10-20T02:39:45 | 194,417,898 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,127 | h | # pragma once
#include <set>
#include <string>
#include <algorithm>
#include <iterator>
#include <iostream>
namespace stl{
template <class T>
class Set {
public:
using element_type = T;
using value_type = element_type;
typedef typename std::set<element_type>::iterator iterator;
typedef typename std::set<element_type>::reverse_iterator reverse_iterator;
typedef typename std::set<element_type>::const_iterator const_iterator;
//! empty set
Set() {}
std::size_t Cardinality() const {
return s.size();
}
bool HasElement(element_type i) const {
return static_cast<bool>(s.count(i));
}
bool IsSubSet(const Set& X) const {
for (element_type i : s) {
if (!X.HasElement(i))
return false;
}
return true;
}
void AddElement(element_type i) {
s.insert(i);
}
void push_back(element_type i) {
s.insert(i);
}
iterator insert(iterator position, const element_type& val) {
return s.insert(position, val);
}
void clear() {
s.clear();
}
iterator begin() {
return s.begin();
}
reverse_iterator rbegin() {
return s.rbegin();
}
iterator end() {
return s.end();
}
const_iterator begin() const {
return s.begin();
}
const_iterator end() const {
return s.end();
}
bool IsEmpty() { return s.size() == 0; }
friend std::ostream& operator << (std::ostream& stream, const Set& X) {
stream << "{";
std::size_t cnt = 0, limiter = X.Cardinality();
for (Set::iterator i = X.begin(); i != X.end(); i++) {
stream << *i;
cnt++;
if (cnt != limiter) {
stream << ", ";
}
}
stream << "}";
return stream;
}
friend bool operator==(const Set& a, const Set& b) {
return a.s == b.s;
}
friend bool operator!=(const Set& a, const Set& b) {
return a.s != b.s;
}
Set Union(const Set& X) const {
Set a;
std::set_union(X.begin(), X.end(), begin(), end(), std::inserter(a, a.begin()));
return a;
}
Set Intersection(const Set& X) const {
Set a;
std::set_intersection(X.begin(), X.end(), begin(), end(), std::inserter(a, a.begin()));
return a;
}
private:
std::set<element_type> s;
};
//! a thin wrapper around std::set
class CSet : public Set<std::size_t> {
public:
CSet(){}
CSet(const std::string& str);
//! construct a CSet from bitmask of val, for example if val = 14(0b1110), the set is {1,1,1,0}
//! n is the maximal size of the set
CSet(std::size_t n, unsigned long val);
//! generate a set $\{0, 1, \dots, n-1\}$
static CSet MakeDense(element_type n);
//! generate an empty set, the parameter is not used, reserved for compatibility consideration
static CSet MakeEmpty(element_type n);
// return self
CSet GetMembers() const;
CSet Complement(std::size_t n) const;
CSet Union(const CSet& X) const {
CSet a;
std::set_union(X.begin(), X.end(), begin(), end(), std::inserter(a, a.begin()));
return a;
}
CSet Intersection(const CSet& X) const {
CSet a;
std::set_intersection(X.begin(), X.end(), begin(), end(), std::inserter(a, a.begin()));
return a;
}
CSet Difference(const CSet& X) const {
CSet a;
std::set_difference(begin(), end(), X.begin(), X.end(), std::inserter(a, a.begin()));
return a;
}
friend bool operator<(const CSet& X, const CSet& Y) {
//alphabetical order
iterator it_x = X.begin(), it_y = Y.begin();
while (it_x != X.end() && it_y != Y.end()) {
if (*it_x > *it_y)
return false;
else if (*it_x < *it_y)
return true;
it_x++;
it_y++;
}
return false;
}
};
class Partition : public stl::Set<stl::CSet> {
public:
static Partition makeFine(int size);
static Partition makeDense(int size);
Partition() {}
Partition expand(const stl::CSet& A);
};
} | [
"[email protected]"
] | |
80896c34c0bdc6e5c84950aece842f54c4a23e36 | b01889a9d9c438bd5f7e1a56707027cf67644fdf | /include/hermes/VM/HermesValueTraits.h | 8d0410037caded1d7bed888b243b3733856f7d7c | [
"MIT"
] | permissive | Dhruvdd/hermes | f71eede552b02458a5717e1611c55ab09784c06b | dec2d951b8d20cf7fc30e324c3d2bafa0e6b12a8 | refs/heads/master | 2022-11-20T23:25:11.980557 | 2020-07-25T07:00:34 | 2020-07-25T07:00:34 | 282,389,948 | 0 | 0 | MIT | 2020-07-25T07:00:35 | 2020-07-25T06:59:41 | null | UTF-8 | C++ | false | false | 7,616 | h | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#ifndef HERMES_VM_HERMESVALUETRAITS_H
#define HERMES_VM_HERMESVALUETRAITS_H
#include "hermes/VM/CellKind.h"
#include "hermes/VM/HermesValue.h"
#include "hermes/VM/SymbolID.h"
#include <cassert>
#include <type_traits>
namespace hermes {
namespace vm {
/// White-list classes than can be managed by a HermesValue.
template <class T>
struct IsGCObject : public std::false_type {};
#define HERMES_VM_GCOBJECT(name) \
class name; \
template <> \
struct IsGCObject<name> : public std::true_type {}
// White-list objects that can be managed by HermesValue.
HERMES_VM_GCOBJECT(StringPrimitive);
HERMES_VM_GCOBJECT(JSObject);
HERMES_VM_GCOBJECT(Callable);
HERMES_VM_GCOBJECT(BoundFunction);
HERMES_VM_GCOBJECT(NativeFunction);
HERMES_VM_GCOBJECT(FinalizableNativeFunction);
HERMES_VM_GCOBJECT(NativeConstructor);
HERMES_VM_GCOBJECT(JSFunction);
HERMES_VM_GCOBJECT(JSGeneratorFunction);
HERMES_VM_GCOBJECT(GeneratorInnerFunction);
HERMES_VM_GCOBJECT(ArrayImpl);
HERMES_VM_GCOBJECT(Arguments);
HERMES_VM_GCOBJECT(Environment);
HERMES_VM_GCOBJECT(DictPropertyMap);
HERMES_VM_GCOBJECT(HiddenClass);
HERMES_VM_GCOBJECT(PropertyAccessor);
HERMES_VM_GCOBJECT(ArrayStorage);
HERMES_VM_GCOBJECT(JSArray);
HERMES_VM_GCOBJECT(PrimitiveBox);
HERMES_VM_GCOBJECT(JSArrayBuffer);
HERMES_VM_GCOBJECT(JSDataView);
HERMES_VM_GCOBJECT(JSTypedArrayBase);
HERMES_VM_GCOBJECT(JSString);
HERMES_VM_GCOBJECT(JSNumber);
HERMES_VM_GCOBJECT(JSBoolean);
HERMES_VM_GCOBJECT(JSSymbol);
HERMES_VM_GCOBJECT(JSRegExp);
HERMES_VM_GCOBJECT(JSDate);
HERMES_VM_GCOBJECT(JSError);
HERMES_VM_GCOBJECT(JSGenerator);
HERMES_VM_GCOBJECT(Domain);
HERMES_VM_GCOBJECT(RequireContext);
HERMES_VM_GCOBJECT(HashMapEntry);
HERMES_VM_GCOBJECT(OrderedHashMap);
HERMES_VM_GCOBJECT(JSWeakMapImplBase);
HERMES_VM_GCOBJECT(JSArrayIterator);
HERMES_VM_GCOBJECT(JSStringIterator);
HERMES_VM_GCOBJECT(JSProxy);
HERMES_VM_GCOBJECT(JSCallableProxy);
HERMES_VM_GCOBJECT(DecoratedObject);
HERMES_VM_GCOBJECT(HostObject);
#ifdef UNIT_TEST
HERMES_VM_GCOBJECT(TestCell);
#endif
// Typed arrays use templates and cannot use the macro above
template <typename T, CellKind C>
class JSTypedArray;
template <typename T, CellKind C>
struct IsGCObject<JSTypedArray<T, C>> : public std::true_type {};
template <CellKind C>
class JSMapImpl;
template <CellKind C>
struct IsGCObject<JSMapImpl<C>> : public std::true_type {};
template <CellKind C>
class JSMapIteratorImpl;
template <CellKind C>
struct IsGCObject<JSMapIteratorImpl<C>> : public std::true_type {};
template <CellKind C>
class JSWeakMapImpl;
template <CellKind C>
struct IsGCObject<JSWeakMapImpl<C>> : public std::true_type {};
template <typename T, bool Uniqued>
class DynamicStringPrimitive;
template <typename T, bool Uniqued>
struct IsGCObject<DynamicStringPrimitive<T, Uniqued>> : public std::true_type {
};
template <typename T>
class ExternalStringPrimitive;
template <typename T>
struct IsGCObject<ExternalStringPrimitive<T>> : public std::true_type {};
template <typename T>
class BufferedStringPrimitive;
template <typename T>
struct IsGCObject<BufferedStringPrimitive<T>> : public std::true_type {};
template <typename T, bool isGCObject = IsGCObject<T>::value>
struct HermesValueTraits;
class SegmentedArray;
template <>
struct IsGCObject<SegmentedArray> : public std::true_type {};
template <>
struct HermesValueTraits<HermesValue> {
/// The type to be returned by Handle<T>::get().
using value_type = HermesValue;
/// The type to be returned by Handle<T>::operator->().
using arrow_type = const HermesValue *;
/// Whether this type is a GCCell
static constexpr bool is_cell = false;
/// The default initialization value of this type.
static constexpr value_type defaultValue() {
return HermesValue::encodeUndefinedValue();
};
/// Encode a \c HermesValue into the type.
static value_type encode(HermesValue value) {
return value;
}
/// Decode a \c HermesValue from the type.
static HermesValue decode(value_type value) {
return value;
}
static const HermesValue *arrow(const HermesValue &value) {
return &value;
}
private:
// arrow() must be called with a reference to a non-temporary object, as it
// returns the address of its parameter. Forbid calls to arrow() with a
// temporary object through this unimplemented overload.
static void arrow(HermesValue &&value);
};
template <>
struct HermesValueTraits<SymbolID> {
/// The type to be returned by Handle<T>::get().
using value_type = SymbolID;
/// The type to be returned by Handle<T>::operator->().
using arrow_type = const SymbolID *;
/// Whether this type is a GCCell
static constexpr bool is_cell = false;
/// The default initialization value of this type.
static value_type defaultValue() {
return SymbolID{};
};
static HermesValue encode(SymbolID value) {
return HermesValue::encodeSymbolValue(value);
}
static value_type decode(HermesValue value) {
return value.getSymbol();
}
};
template <class T>
struct StringTraitsImpl {
using value_type = T *;
using arrow_type = value_type;
static constexpr bool is_cell = true;
static constexpr value_type defaultValue() {
return value_type{};
}
static HermesValue encode(T *value) {
return HermesValue::encodeStringValue(value);
}
static T *decode(HermesValue value) {
return (T *)value.getString();
}
static arrow_type arrow(const HermesValue &value) {
auto *res = decode(value);
assert(res && "dereferencing null handle");
return res;
}
static arrow_type arrow(value_type ptr) {
assert(ptr && "dereferencing null handle");
return ptr;
}
};
template <>
struct HermesValueTraits<StringPrimitive, true>
: public StringTraitsImpl<StringPrimitive> {};
template <>
struct HermesValueTraits<BufferedStringPrimitive<char>, true>
: public StringTraitsImpl<BufferedStringPrimitive<char>> {};
template <>
struct HermesValueTraits<BufferedStringPrimitive<char16_t>, true>
: public StringTraitsImpl<BufferedStringPrimitive<char16_t>> {};
template <class T>
struct HermesValueTraits<T, true> {
using value_type = T *;
using arrow_type = value_type;
static constexpr bool is_cell = true;
static constexpr value_type defaultValue() {
return value_type{};
}
static HermesValue encode(T *value) {
return HermesValue::encodeObjectValue(value);
}
static T *decode(HermesValue value) {
return static_cast<T *>(value.getObject());
}
static arrow_type arrow(const HermesValue &value) {
auto *res = decode(value);
assert(res && "dereferencing null handle");
return res;
}
static arrow_type arrow(value_type ptr) {
assert(ptr && "dereferencing null handle");
return ptr;
}
};
/// A helper class to deduce whether it is safe to assign Handle<From> into
/// Handle<To>.
template <class From, class To>
struct IsHermesValueConvertible {
using FromTraits = HermesValueTraits<From>;
using ToTraits = HermesValueTraits<To>;
static constexpr bool value =
// Anything is convertable to HermesValue.
std::is_same<To, HermesValue>::value ||
// A type is convertable to itself.
std::is_same<From, To>::value ||
// An object can be converted to its base class.
(FromTraits::is_cell && ToTraits::is_cell &&
std::is_base_of<To, From>::value);
};
} // namespace vm
} // namespace hermes
#endif // HERMES_VM_HERMESVALUETRAITS_H
| [
"[email protected]"
] | |
3d576e267fd66e9d496b500d6ea38aa407d3982d | f2598ff3ddeee3686360567682bf5eddd8ba1ab5 | /src/crypto/hmac_sha512.h | ec5f2213ceb838aba44c3a3faa62f55601974f5c | [
"MIT"
] | permissive | MyProductsKft/Vitalcoin | c4566dca1b9a60cbb39de25faa7251e3a3786735 | 492306908ee457362f2ba777cbd235d417f6d3b5 | refs/heads/master | 2020-03-21T02:15:27.776360 | 2018-10-31T17:32:15 | 2018-10-31T19:14:54 | 137,989,832 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 757 | h | // Copyright (c) 2014 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef VITALCOIN_CRYPTO_HMAC_SHA512_H
#define VITALCOIN_CRYPTO_HMAC_SHA512_H
#include "crypto/sha512.h"
#include <stdint.h>
#include <stdlib.h>
/** A hasher class for HMAC-SHA-512. */
class CHMAC_SHA512 {
private:
CSHA512 outer;
CSHA512 inner;
public:
static const size_t OUTPUT_SIZE = 64;
CHMAC_SHA512(const unsigned char *key, size_t keylen);
CHMAC_SHA512 &Write(const unsigned char *data, size_t len) {
inner.Write(data, len);
return *this;
}
void Finalize(unsigned char hash[OUTPUT_SIZE]);
};
#endif // VITALCOIN_CRYPTO_HMAC_SHA512_H
| [
"[email protected]"
] | |
ec31a517ee7116aff97a5790e3c77ca5103a2133 | 9d364070c646239b2efad7abbab58f4ad602ef7b | /platform/external/chromium_org/ui/events/linux/text_edit_key_bindings_delegate_auralinux.h | 9344bcb6c50d2a4465ed0f7c9ddf54f34661065c | [
"BSD-3-Clause"
] | permissive | denix123/a32_ul | 4ffe304b13c1266b6c7409d790979eb8e3b0379c | b2fd25640704f37d5248da9cc147ed267d4771c2 | refs/heads/master | 2021-01-17T20:21:17.196296 | 2016-08-16T04:30:53 | 2016-08-16T04:30:53 | 65,786,970 | 0 | 2 | null | 2020-03-06T22:00:52 | 2016-08-16T04:15:54 | null | UTF-8 | C++ | false | false | 892 | h | // Copyright 2014 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 UI_EVENTS_X_TEXT_EDIT_KEY_BINDINGS_DELEGATE_X11_H_
#define UI_EVENTS_X_TEXT_EDIT_KEY_BINDINGS_DELEGATE_X11_H_
#include <vector>
#include "ui/events/events_export.h"
namespace ui {
class Event;
class TextEditCommandAuraLinux;
class EVENTS_EXPORT TextEditKeyBindingsDelegateAuraLinux {
public:
virtual bool MatchEvent(const ui::Event& event,
std::vector<TextEditCommandAuraLinux>* commands) = 0;
protected:
virtual ~TextEditKeyBindingsDelegateAuraLinux() {}
};
EVENTS_EXPORT void SetTextEditKeyBindingsDelegate(
TextEditKeyBindingsDelegateAuraLinux* delegate);
EVENTS_EXPORT TextEditKeyBindingsDelegateAuraLinux*
GetTextEditKeyBindingsDelegate();
}
#endif
| [
"[email protected]"
] | |
ff608a81e09795f297539e02ffbab184e030da15 | 2e02f4a1333b593cd45ea6e8aadb21e1fb4b3e2f | /CodeForces/C/1530 C.cpp | b5764a2967a99f71fcf4192b5c3b591b16bb8cd8 | [] | no_license | rahul-goel/CompetitiveProgramming | 33c42145a5807ce1e1b94334faeeb960ad381edb | 7c042b81dd9208137bbbd34e397baa55c85ff793 | refs/heads/master | 2022-09-25T04:26:16.173096 | 2022-09-05T18:26:23 | 2022-09-05T18:26:23 | 231,899,837 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,119 | cpp | /*
Created by Rahul Goel.
*/
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
/*******************************************************************************/
using namespace std;
using namespace __gnu_pbds;
template < typename T >
using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
/*******************************************************************************/
using ll = long long;
using ld = long double;
const ll MOD = 1000000007;
// const ll MOD = 998244353;
const int INF = 1e9;
const ll LINF = 1e18;
/*******************************************************************************/
ll mod_sum() { return 0LL; }
template < typename T, typename... Args >
T mod_sum(T a, Args... args) { return ((a + mod_sum(args...))%MOD + MOD)%MOD; }
/*******************************************************************************/
ll mod_prod() { return 1LL; }
template< typename T, typename... Args >
T mod_prod(T a, Args... args) { return (a * mod_prod(args...))%MOD; }
/*******************************************************************************/
#ifdef ONLINE_JUDGE
#define endl '\n'
#endif
#define fastio ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)
#define all(c) (c).begin(), (c).end()
#define present(c,x) ((c).find(x) != (c).end())
#define cpresent(c,x) (find(all(c),x) != (c).end())
#define uniq(c) (c).resize(distance((c).begin(), unique(all(c))))
#define min_pq(t) priority_queue < t, vector < t >, greater < t > >
#define max_pq(t) priority_queue < t >
#define pb push_back
#define ff first
#define ss second
/*******************************************************************************/
using pii = pair < ll, ll >;
using vi = vector < ll >;
using vb = vector < bool >;
using vvi = vector < vector < ll > >;
using vvb = vector < vector < bool > >;
using vpii = vector < pii >;
using vvpii = vector < vector < pii > >;
/*******************************************************************************/
//.-.. . -. -.- .- .. ... .-.. --- ...- .
/*
Code begins after this.
*/
ll solve() {
ll n;
cin >> n;
vector<ll> a(n), b(n);
for (ll &x : a) cin >> x;
for (ll &x : b) cin >> x;
sort(all(a));
reverse(all(a));
sort(all(b));
reverse(all(b));
ll x = 0, y = 0;
for (ll i = 0; i < n; i++) x += a[i], y += b[i];
for (ll i = 1; i < n; i++) a[i] += a[i - 1], b[i] += b[i - 1];
ll left = 0, right = INF, mid;
ll ans = -1;
while (left <= right) {
mid = (left + right) >> 1;
ll takex = (n + mid) - (n + mid) / 4;
ll takey = (n + mid) - (n + mid) / 4;
ll xx = 0, yy = 0;
// x
ll tx = min(mid, takex);
xx += tx * 100;
takex -= tx;
if (takex - 1 >= 0) xx += a[takex - 1];
// y
ll ty = min(n, takey);
yy += b[ty - 1];
takey -= ty;
yy += takey * 0;
if (xx >= yy) {
ans = mid;
right = mid - 1;
} else {
left = mid + 1;
}
}
cout << ans << endl;
return 0;
}
signed main() {
fastio;
ll t = 1;
cin >> t;
while (t--) {
solve();
}
return 0;
}
| [
"[email protected]"
] | |
4aca813edf1373beaabaa3b9dd6781ff41384a76 | 513f3261ff64159df147cc2c03d13268bcfdda1c | /samples/opening_window/main.cpp | e3f3f5bb058e185383bc699873042aba4e1df6bc | [
"MIT"
] | permissive | sutirthaghosh/gentlemanly_engine | b29b858e498b6638b59618d3ce2e16505b033d1e | b9481628fdcf0f92d367f9d3afddd501462667fc | refs/heads/master | 2020-12-25T05:35:57.908639 | 2016-05-31T07:50:43 | 2016-05-31T07:50:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,400 | cpp | #include <ge/model_system.hpp>
#include <ge/qt_application.hpp>
#include <ge/asset_manager.hpp>
#include <ge/camera_component.hpp>
#include <ge/material_asset.hpp>
#include <ge/mesh_asset.hpp>
#include <ge/transform_component.hpp>
#include <ge/world.hpp>
#include <iostream>
#include <memory>
using namespace ge;
int main(int argc, char** argv)
{
try
{
qt_application app(argc, argv);
auto window = app.make_window(
"gentlemanly_engine_example_opening_window", {}, {1280, 720}, false, true);
auto viewport = app.make_viewport(*window);
ge::world world;
asset_manager asset_man;
asset_man.add_asset_path("data/");
entityx::Entity camera;
app.signal_init.connect([&] {
viewport->set_background_color({1.f, 0.f, 0.f, 1.f});
auto meshasset = asset_man.get_asset<mesh_asset>("square");
auto wallMesh = asset_man.get_asset<mesh_asset>("ground");
// wall
auto wall = world.entities.create();
wall.assign<model_component>(wallMesh.data);
wall.assign<transform_component>(transform{{4.f, 0.f}, 3.f});
// init camera
camera = world.entities.create();
auto trans = camera.assign<transform_component>(transform{{-0.f, 0.f}, 0.f});
camera.assign<camera_component>(20.f);
});
app.signal_update.connect([&](float dt) { world.update(dt); });
app.execute(*window);
}
catch (std::exception& e)
{
std::cout << e.what();
return 232;
}
}
| [
"[email protected]"
] | |
985f447c11bc2a917c256822ffa5621cf7054c0f | 905b2f9a603058acce7c0f498a3d077a16dad4c1 | /src/sqlite/backup.cpp | a730581c1c485d3e592788540468d7bbd5a8e958 | [
"BSD-3-Clause"
] | permissive | vinzenz/vsqlite-- | eae5585df125f81e05eea44a15a73cd108c33d89 | ea77afd29f5112663353f63c725c3c8bf29c00e4 | refs/heads/master | 2021-01-22T03:05:39.314441 | 2020-11-11T10:09:46 | 2020-11-12T20:51:26 | 5,426,635 | 21 | 18 | NOASSERTION | 2020-11-12T20:51:27 | 2012-08-15T13:56:03 | C++ | UTF-8 | C++ | false | false | 1,642 | cpp | #include <sqlite/backup.hpp>
#include <sqlite/connection.hpp>
#include <sqlite/private/private_accessor.hpp>
#include <sqlite/database_exception.hpp>
#include <sqlite3.h>
namespace sqlite {
backup::backup(connection& conn_to, connection& conn_from)
: m_pBackup(NULL), m_conn_to(conn_to) {
private_accessor::acccess_check(conn_to);
private_accessor::acccess_check(conn_from);
m_pBackup = sqlite3_backup_init(get_to_handle(), "main",
private_accessor::get_handle(conn_from), "main");
if(!m_pBackup) {
throw database_exception_code(sqlite3_errmsg(get_to_handle()),
sqlite3_errcode(get_to_handle()));
}
}
backup::~backup() {
try {
finish();
} catch(...) {
}
}
bool backup::step(int nPage) {
if(!m_pBackup) {
throw database_exception("Backup object is already destroyed");
}
int err = sqlite3_backup_step(m_pBackup, nPage);
switch(err) {
case SQLITE_OK:
return true;
case SQLITE_DONE:
return false;
default:
throw database_exception_code(sqlite3_errmsg(get_to_handle()), err);
}
}
void backup::finish() {
if(!m_pBackup) {
return;
}
int err = sqlite3_backup_finish(m_pBackup);
if(err != SQLITE_OK) {
throw database_exception_code(sqlite3_errmsg(get_to_handle()), err);
}
m_pBackup = NULL;
}
sqlite3* backup::get_to_handle() const {
return private_accessor::get_handle(m_conn_to);
}
}
| [
"[email protected]"
] | |
0e0f8e4afdc60ca0fcb33231153dd5673ac477dd | f982e7cb8c3a80cc5f460a91dbf95b52ff71170f | /CommandString/appendcommand.h | 9c7499f5b1ddccbc0c62311bcf1594d0cc7e3b7e | [] | no_license | EliakinCosta/CommandPattern | 096a2abcf63508e671c5865ae06476576e635da6 | e5db8aa13137ccc77aa6ff6859a80d47f5b5ce11 | refs/heads/master | 2021-01-19T04:48:05.487617 | 2016-09-24T14:31:35 | 2016-09-24T14:31:35 | 69,101,710 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 355 | h | #ifndef APPENDCOMMAND_H
#define APPENDCOMMAND_H
#include "icommand.h"
#include <QString>
class AppendCommand : public ICommand
{
public:
AppendCommand(QString *document, QString text);
virtual ~AppendCommand();
virtual void redo();
virtual void undo();
private:
QString *m_document;
QString m_text;
};
#endif // APPENDCOMMAND_H
| [
"[email protected]"
] | |
63a62bf193fb3b4e76ef4cb89708f887be01ead4 | fce87b7c9090716505a47a6317cd06ca08d5be5c | /lipan/lib/fun.cpp | 1b5c4b2ad8a2fe5e1f765b6c5e5a4005ccea0f81 | [] | no_license | lipan16/c | 85660bab45b2b7a1b6268b782e8f94cdea0f0bd3 | 44406610aeabfb27dade1af0127990fff6b66a49 | refs/heads/master | 2020-03-07T05:40:37.131071 | 2019-05-30T09:43:42 | 2019-05-30T09:43:42 | 127,302,560 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 207 | cpp | /*
* fun.cpp
*
* Created on: 2018Äê4ÔÂ24ÈÕ
* Author: asus
*/
unsigned long long fun(int i){
if(i==0)
return 1;
else
return i*fun(i-1);
}
int func(){
return 10;
}
| [
"[email protected]"
] | |
58da462fba2dafb8ab1ff3dc35cb3b4ed108d67d | 0d334a3e32652d9a624ca1eb4a1dfa77d6c8edc3 | /webDic/webDic/crawler.cpp | e6493cbf33ffb34e56634b7fb616feb199378b97 | [] | no_license | unbiarirang/web_dic | b0c52fd998b8c85516b800865addef8f123cd490 | ac3b11ffb328a49025f1c71c5ed705b63085ef06 | refs/heads/master | 2021-03-27T17:22:17.447901 | 2018-03-30T16:04:05 | 2018-03-30T16:04:05 | 114,513,801 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,813 | cpp | #include "crawler.h"
#include "charString.h"
#include "stack.h"
#include "curl\curl.h"
#include "avlTree.h"
#include "map.h"
#include "hash.h"
#include <pthread.h>
#include <thread>
#include <memory>
#include <vector>
#include <string>
#include <mutex>
AVLTree tree; // AVL tree inverse document
HashDoc hashDoc;// hash table inverse document
Map map; // word-wordID map
std::mutex m;
int g_key_index = 1; // word unique id index
// main algorithm
void analyze_html(int tid, std::vector<CharString>* urlStrs, std::ofstream &opStream, HashTable *dic, HashTable *dic_ex) {
std::vector<CharString>* words = new std::vector<CharString>; // split words result
std::vector<CharString> resultStr(4);
std::wstring wideData = L"";
for (int i = (URL_NUM / MAX_THREAD_NUM) * tid; i < (URL_NUM / MAX_THREAD_NUM) * (tid + 1); i++) {
DocID docID = i + 1;
resultStr.assign(4, "");
CharString urlStr = (*urlStrs)[i];
CharString dataStr = get_html_str(tid, urlStr);
bool exceptional_flag = false; // exceptional situation. in case of ansi string main contents
int index = 0;
resultStr[0] = urlStr;
// extract data trash1, trash2
index = extract_data_from_html(dataStr, "div class=\"z\"", 'a', index, &resultStr, &exceptional_flag, 3);
// no authority to visit this html page
if (index == -1) {
resultStr[0].concat("\n");
std::cout << resultStr[0];
opStream << ansi_to_utf8(&resultStr[0]);
resultStr.clear();
continue;
}
index = extract_data_from_html(dataStr, "a href=", 'a', index, &resultStr, &exceptional_flag, 3);
// extract data 1~3 (article big category, article small category, title)
index = extract_data_from_html(dataStr, "a href=", 'a', index, &resultStr, &exceptional_flag, 3);
index = extract_data_from_html(dataStr, "a href=", 'a', index, &resultStr, &exceptional_flag, 3);
index = extract_data_from_html(dataStr, "a href=", 'a', index, &resultStr, &exceptional_flag, 1);
// extract data 7 (article type)
index = extract_data_from_html(dataStr, "div class=\"ts z h1\"", 'a', index, &resultStr, &exceptional_flag, 3);
// extract data 5 (writer)
index = extract_data_from_html(dataStr, "div class=\"authi\"", 'a', index, &resultStr, &exceptional_flag, 3);
// extract data 6 (date)
index = extract_data_from_html(dataStr, "div class=\"authi\"", 'e', index, &resultStr, &exceptional_flag, 3);
//extract data 4 (main contents)
index = extract_data_from_html(dataStr, "div class=\"t_fsz\"", 'p', index, &resultStr, &exceptional_flag, 2);
if (exceptional_flag == true)
index = extract_data_from_html2(dataStr, "div class=\"t_fsz\"", 't', index, &resultStr);
filter_result_str(&resultStr, &wideData);
for (int k = 0; k < 3; k++) {
// handle main contents
if (k == 2) {
bool decimal_flag = false;
int j = 0;
// in case of decimal code main contents
while (true) {
if (j >= resultStr[k].getLen()) break;
if (resultStr[k].getStr()[j] == '&') {
decimal_flag = true; break;
}
if (resultStr[k].getStr()[j] < '0' || resultStr[k].getStr()[j] > '9') {
decimal_flag = false; break;
}
j++;
}
if (decimal_flag == true) {
CharString str = ansi_encode(wideData);
str.concat(",");
opStream << ansi_to_utf8(&str);
std::cout << str;
split_words(dic, dic_ex, words, &str, docID);
continue;
}
else {};
}
// print result string
resultStr[k].concat(",");
opStream << ansi_to_utf8(&resultStr[k]);
std::cout << resultStr[k];
// split words only from title and main contents
if (k == 1 || k == 2)
split_words(dic, dic_ex, words, &resultStr[k], docID);
}
// print split words result
for (auto word : *words) {
word.concat(" ");
std::cout << word;
opStream << ansi_to_utf8(&word);
}
std::cout << "\n";
opStream << std::endl;
words->clear();
resultStr.clear();
}
std::cout << "tid: " << tid << " ended" << std::endl;
}
// get url strings from input file
void get_url_str(std::vector<CharString>* urlStrs, CharString fileName)
{
char buffer[MAX_URL_LENGTH] = { 0 };
std::ifstream readFile(fileName.getStr());
try {
if (readFile.is_open() == true) {
std::cout << "read file: " << fileName << "\n";
// delete the first line of the file
readFile.getline(buffer, sizeof(char) * MAX_URL_LENGTH);
while (readFile.getline(buffer, sizeof(char) * MAX_URL_LENGTH)) {
CharString tempStr = buffer;
char* temp = tempStr.substring(tempStr.indexOf("\"") + 1, tempStr.getLen() - 2);
urlStrs->push_back(temp);
}
std::cout << "close file: " << fileName << "\n";
readFile.close();
}
}
catch (bool) {
std::cout << "fail to read file: " << fileName << "\n";
}
}
void get_search_str(std::vector<CharString>* searchStrs, CharString fileName)
{
std::vector<CharString> search_strs;
char buffer[1024] = { 0 };
std::ifstream readFile(fileName.getStr());
try {
if (readFile.is_open() == true) {
std::cout << "success read file " << fileName << std::endl;
while (readFile.getline(buffer, sizeof(char) * 1024))
searchStrs->push_back(buffer);
readFile.close();
}
}
catch (bool) {
std::cout << "fail to read file" << std::endl;
}
}
// curl write callback
std::string g_dataStr[MAX_THREAD_NUM];
size_t _write_callback(char* buf, size_t size, size_t nmemb, void* tid)
{
for (int c = 0; c<size*nmemb; c++)
g_dataStr[int(tid)].push_back(buf[c]);
return size*nmemb;
}
CharString get_html_str(int tid, CharString urlStr)
{
CURLcode res;
g_dataStr[tid] = std::string();
CURL* curl = curl_easy_init();
if (curl) {
curl_easy_setopt(curl, CURLOPT_URL, urlStr.getStr());
/* example.com is redirected, so we tell libcurl to follow redirection */
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &_write_callback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)tid);
/* Perform the request, res will get the return code */
m.lock();
res = curl_easy_perform(curl);
m.unlock();
/* Check for errors */
if (res != CURLE_OK)
fprintf(stderr, "curl_easy_perform() failed: %s\n",
curl_easy_strerror(res));
curl_easy_cleanup(curl);
}
return CharString(g_dataStr[tid]);
}
// return the end index of match string
int extract_data_from_html(CharString dataStr, CharString matchStr, char tag, int index_prev, std::vector<CharString>* resultStr, bool* exceptional_flag, int res_index)
{
int temp_index_prev = index_prev;
int index = get_index_of_match_str(dataStr, matchStr, index_prev);
if (index == -1) return -1;
bool get_tag_flag = false;
char c_before = 0;
Stack s = Stack();
Stack s2 = Stack();
char data[1024] = { 0 };
int data_index = 0;
while (true) {
char c = dataStr.getStr()[index];
if (c_before == '<' && c == tag) get_tag_flag = true;
if (get_tag_flag)
s.push(c);
// get data between <tag>...</tag>
if (c_before == '/' && c == tag) {
while (!s.empty()) {
s2.push(s.top());
s.pop();
}
bool get_content_flag = false;
char c;
while (!s2.empty()) {
c = s2.top();
if (c == '<' && get_content_flag == true) break;
if (get_content_flag) {
data[data_index] = s2.top();
data_index++;
}
if (c == '>') get_content_flag = true;
s2.pop();
}
// exceptional situation. for ansi string main contents
if (data[0] == '\n') {
*exceptional_flag = true;
return temp_index_prev;
}
(*resultStr)[res_index] = data;
return index;
}
c_before = c;
index++;
}
}
// exceptional situation. for ansi string main contents
int extract_data_from_html2(CharString dataStr, CharString matchStr, char tag, int index_prev, std::vector<CharString>* resultStr)
{
int temp_index_prev = index_prev;
int index = get_index_of_match_str(dataStr, matchStr, index_prev);
if (index == -1) return -1;
bool get_tag_flag = false;
char c_before = 0;
Stack s = Stack();
Stack s2 = Stack();
char data[1024] = { 0 };
int data_index = 0;
int count = 0;
while (true) {
char c = dataStr.getStr()[index];
if (count == 4) get_tag_flag = true;
if (c == '>') count++;
// replace " " with " "
if (c == '&') { index += 6; s.push(' '); continue; }
if (get_tag_flag && c != '\n' && c != ' ')
s.push(c);
// get data between <tag>...</tag>
if (get_tag_flag && c == '<') {
s.pop();
while (!s.empty()) {
s2.push(s.top());
s.pop();
}
while (!s2.empty()) {
if (s2.top() != ',' && s2.top() != '\n') {
data[data_index] = s2.top();
data_index++;
}
s2.pop();
}
(*resultStr)[2] = data;
return index;
}
c_before = c;
index++;
}
}
const int MAX_EXTRACT_STRING_LENGTH = 1024;
char extractStr[MAX_EXTRACT_STRING_LENGTH];
int get_index_of_match_str(CharString dataStr, CharString matchStr, int prev_index)
{
Stack s = Stack();
Stack s2 = Stack();
char c = 0;
int index = prev_index;
bool push_flag = false;
while (index < dataStr.getLen()) {
c = dataStr.getStr()[index];
// get data between the bracket <...>
if (c == '>' && push_flag == true) {
push_flag = false;
while (!s.empty()) {
s2.push(s.top());
s.pop();
}
int i = 0;
while (!s2.empty()) {
extractStr[i] = s2.top();
s2.pop();
i++;
}
extractStr[i] = '\0';
CharString tempStr = extractStr;
if (tempStr.indexOf(&matchStr) >= 0)
return index - tempStr.getLen() - 1;
for (int j = 0; j <= i; j++) {
extractStr[j] = 0;
}
}
if (push_flag)
s.push(c);
if (c == '<') push_flag = true;
index++;
}
return -1;
}
// use dic to split the source string
const int WORD_MAX_LEN = 8;
void split_words(HashTable* dic, HashTable* dic_ex, std::vector<CharString>* resultStr, CharString* srcStr, DocID docID)
{
CharString str = "";
int str_len = WORD_MAX_LEN;
int str_start_index = 0;
int str_end_index = WORD_MAX_LEN;
int index = 0;
while (true) {
str_len = WORD_MAX_LEN;
while (true) {
str_end_index = str_start_index + str_len;
if (str_end_index > srcStr->getLen()) str_end_index = srcStr->getLen();
index = str_start_index;
while (true) {
if (index == str_end_index) break;
str.concat(srcStr->getStr()[index]);
index++;
}
// get a series of number
if (str.getStr()[0] >= 48 && str.getStr()[0] <= 57) {
int num_count = 0;
int num_index = str_start_index;
while (true) {
if (srcStr->getStr()[num_index] < 48 || srcStr->getStr()[num_index] > 57) break;
num_count++;
num_index++;
}
int i = 8;
while (i < num_count) {
str.concat(&(srcStr->getStr()[str_start_index + i]));
i++;
}
str.getStr()[num_count] = '\0';
resultStr->push_back(str.substring(0, num_count-1));
str_start_index = str_start_index + num_count;
str = "";
break;
}
// remove all ascii characters except numbers
if ((str.getStr()[0] >= 32 && str.getStr()[0] < 48) || (str.getStr()[0] > 57 && str.getStr()[0] <= 148)) {
str_start_index = str_start_index + 1;
str = "";
break;
}
// filter exclusion words
if (dic_ex->isExist(str.getStr())) {
str_start_index = str_start_index + str_len;
str = "";
break;
}
// str remains a character
if (str_len == 2) {
resultStr->push_back(str); // save word
str_start_index = str_start_index + str_len;
str = "";
break;
}
// str is a word
if (dic->isExist(str)) {
resultStr->push_back(CharString(str)); // save word
// add a word to inverse document and map
if (docID) {
m.lock();
bool is_success = map.insert(str, g_key_index);
if (is_success) { // new word
WordNode* node = new WordNode(g_key_index, str);
node->add(docID);
tree.insert(g_key_index, node);
hashDoc.insert(g_key_index, node);
g_key_index++;
}
else { // the word already exist in inverse document and map
int wordID = map[str];
//WordNode* node = tree.search(wordID);
WordNode* node = hashDoc.search(wordID);
node->add(docID);
}
m.unlock();
}
str_start_index = str_start_index + str_len;
str = "";
break;
}
str_len--;
str = "";
}
if (str_start_index >= srcStr->getLen()) break;
}
}
void filter_result_str(std::vector<CharString>* resultStr, std::wstring* wideData)
{
bool is_decimal = false;
int j = 0;
// check if the main contents is decimal code
while (true) {
if ((*resultStr)[2].getStr()[j] == '&') {
is_decimal = true; break;
}
if ((*resultStr)[2].getStr()[j] < '0' || (*resultStr)[2].getStr()[j] > '9') {
is_decimal = false; break;
}
j++;
}
// convert decimal code to wide string
if (is_decimal == true) {
CharString contentStr = (*resultStr)[2];
std::wstring str = L"";
Stack s;
Stack s2;
bool end_flag = false;
bool push_flag = false;
bool non_decimal_flag = false;
long long code = 0;
for (int i = 0; i < contentStr.getLen(); i++) {
char c = contentStr.getStr()[i];
if (c == ' ' || c == ',') continue;
if (i == 0 && c != '&') end_flag = true;
if (c == ';') {
end_flag = true;
if (!s.empty()) {
while (!s.empty()) {
s2.push(s.top());
s.pop();
}
while (!s2.empty()) {
code = code * 10 + s2.top() - 48;
s2.pop();
}
}
if (code) {
wchar_t temp = wchar_t(code);
str += temp;
}
else //
str += L" ";
code = 0;
push_flag = false;
non_decimal_flag = false;
continue;
}
// non decimal code
if (end_flag == true && c != '&') {
non_decimal_flag = true;
if (c >= '0' && c <= '9')
str += std::to_wstring(c - 48);
else if (c == '\0') {}
else
str += c;
continue;
}
else
end_flag = false;
if (push_flag == true)
s.push(c);
if (c == '#')
push_flag = true;
}
*wideData = str;
}
} | [
"[email protected]"
] | |
d91d8dbaf61a1aa426444237090d2d83edee2ec6 | 9c1c77f33cc17042c09dde624f9f56a24b2a9094 | /Classes/PauseLayer.h | a7de73fa57c0ccbbfa160e01eb71d7b727f846a0 | [] | no_license | spocklin/spockTower | 9601fda1aa0df3b23176adffb505f99e1ba4ef1c | da20117b3615fd22fab73a9a00c587557c95399b | refs/heads/master | 2020-04-06T06:28:03.646344 | 2016-09-30T10:05:51 | 2016-09-30T10:05:51 | 69,004,890 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 730 | h | //
// PauseLayer.h
// CarrotFantasy
//
// Created by Yan on 14-9-21.
//
//
#ifndef __CarrotFantasy__PauseLayer__
#define __CarrotFantasy__PauseLayer__
#include "PublicDefine.h"
class PauseLayer:public Layer
{
public:
CREATE_FUNC(PauseLayer);
virtual void setFuncFlagPauseLayerIsClose(const std::function<void ()> & rFuncFlagPauseLayerIsClose);
protected:
virtual bool init();
virtual void onEnter()override;
virtual void onExit()override;
virtual void createMenu();
virtual void createSharedMenu();
virtual void closeTouchEvent();
std::function<void ()> _funcFlagPauseLayerIsClose;
};
#endif /* defined(__CarrotFantasy__PauseLayer__) */
| [
"[email protected]"
] | |
255d8edcaf92e958df0c53dddf0f75d253f44e37 | dd6147bf9433298a64bbceb7fdccaa4cc477fba6 | /Sinelnikov/lab4/code/Interaction.cpp | 11f3d742ad20df9781a2a2a302e7a9d84dc0ad42 | [] | no_license | moevm/oop | 64a89677879341a3e8e91ba6d719ab598dcabb49 | faffa7e14003b13c658ccf8853d6189b51ee30e6 | refs/heads/master | 2023-03-16T15:48:35.226647 | 2020-06-08T16:16:31 | 2020-06-08T16:16:31 | 85,785,460 | 42 | 304 | null | 2023-03-06T23:46:08 | 2017-03-22T04:37:01 | C++ | UTF-8 | C++ | false | false | 8,951 | cpp | //
// Created by max on 31.03.20.
//
#include "Interaction.h"
void Interaction::setBase(Field *f) {
int x,y;
while (1){
cout << "Введите координаты базы 1" << "\n";
cin >> x >> y;
if(x < f->getXsize() && y < f->getYsize() && x >= 0 && y>= 0 && !f->field[x][y].getIfOccupiedByBuilding()){
if(f->getLandscapeName(f->field[x][y].getLandscape()->getObjectId()) != "water" \
&& f->getLandscapeName(f->field[x][y].getLandscape()->getObjectId()) != "mountain") {
f->createBase(x, y);
f->getLog()->write("База установлена\n");
break;
} else{
f->getLog()->write("В данных природных условиях базу не поставить!!!\n");
}
} else
if(x < f->getXsize() && y < f->getYsize()) {
f->getLog()->write("На это место базу поставить нельзя! Поле занято ");
f->getLog()->write(f->getNeutralObjectName(f->field[x][y].getNeutralObject()->getObjectId()));
f->getLog()->write("\n");
}
else
f->getLog()->write("Выход за пределы поля!!!\n");
}
while (1){
cout << "Введите координаты базы 2" << "\n";
cin >> x >> y;
if(x < f->getXsize() && y < f->getYsize() && x >= 0 && y>= 0 && !f->field[x][y].getIfOccupiedByBuilding()){
if(f->getLandscapeName(f->field[x][y].getLandscape()->getObjectId()) != "water" \
&& f->getLandscapeName(f->field[x][y].getLandscape()->getObjectId()) != "mountain") {
f->createBase(x, y);
f->getLog()->write("База установлена\n");
break;
} else{
f->getLog()->write("В данных природных условиях базу не поставить!!!\n");
}
} else {
f->getLog()->write("На это место базу поставить нельзя! Поле занято ");
f->getLog()->write(f->getNeutralObjectName(f->field[x][y].getNeutralObject()->getObjectId()));
f->getLog()->write("\n");
}
}
}
void Interaction::services(Field* f,Unit *unit, NeutralObject *object, bool &check) {
object->operator+(unit);
f->getLog()->write("услуга оказана\n");
check = true;
}
void Interaction::repair(Field* f, Base* base, bool &check) {
base->increaseXp(2);
f->getLog()->write("Прочность базы улучшена\n");
check = true;
}
void Interaction::killUnit(Field* f, Unit *unit, int x, int y) {
f->field[f->getBaseXCoordinateById(f->field[x][y].getUnit()->getId())][f->getBaseYCoordinateById(f->field[x][y].getUnit()->getId())].getBase()->decreaseNumberOfUnits(1);
f->deleteUnit(x,y);
f->deleteUnitFromArray(unit->getNumberInArray());
}
void Interaction::battleWithUnit(Field* f,bool &check,Unit* unit1,Unit* unit2,int x1,int y1,int x2,int y2){
check = true;
if(unit1->getAttack() + unit1->getMoral() + unit1->getArmour() > unit2->getArmour() + unit2->getAttack() + unit2->getMoral()){
f->getLog()->write("Юнит с номером ");
f->getLog()->write(to_string(f->field[x2][y2].getUnit()->getNumberInArray()));
f->getLog()->write(" погиб \n");
this->killUnit(f,f->field[x2][y2].getUnit(),x2,y2);
f->move(x1,y1,x2,y2,check);
f->field[x1][y1].getUnit()->decreaseXp(f->field[x1][y1].getUnit()->getXp() / 2);
f->field[x1][y1].getUnit()->increaseMoral(2);
} else if(unit2->getAttack() + unit2->getMoral() + unit2->getArmour() > unit1->getArmour() + unit1->getAttack() + unit1->getMoral()){
this->killUnit(f,f->field[x1][y1].getUnit(),x1,y1);
f->field[x2][y2].getUnit()->decreaseXp(f->field[x2][y2].getUnit()->getXp() / 2);
f->field[x2][y2].getUnit()->increaseMoral(2);
} else{
f->field[x2][y2].getUnit()->decreaseXp(f->field[x2][y2].getUnit()->getXp() / 2 + 1);
f->field[x1][y1].getUnit()->decreaseXp(f->field[x1][y1].getUnit()->getXp() / 2 + 1);
if(f->field[x1][y1].getUnit()->getXp() <= 0){
f->getLog()->write("Юнит с номером ");
f->getLog()->write(to_string(f->field[x1][y1].getUnit()->getNumberInArray()));
f->getLog()->write(" погиб \n");
this->killUnit(f,f->field[x1][y1].getUnit(),x1,y1);
}
if(f->field[x2][y2].getUnit()->getXp() <= 0){
f->getLog()->write("Юнит с номером ");
f->getLog()->write(to_string(f->field[x2][y2].getUnit()->getNumberInArray()));
f->getLog()->write(" погиб \n");
this->killUnit(f,f->field[x2][y2].getUnit(),x2,y2);
}
}
}
void Interaction::attackBase(Field* f, bool &check,int x1,int y1,int x2,int y2) {
if(f->field[x1][y1].getUnit()->getAttack() / 2 + f->field[x1][y1].getUnit()->getMoral() / 5 >= f->field[x2][y2].getBase()->getBaseXp()){
f->destroyBase(f->field[x2][y2].getBase()->getObjectId());
} else{
f->field[x2][y2].getBase()->decreaseXp(f->field[x1][y1].getUnit()->getAttack() / 2 + f->field[x1][y1].getUnit()->getMoral() / 5);
}
check = true;
}
void Interaction::attack(Field* f,Unit* curr_unit,bool &check,int x,int y) {
bool check1,check2;
bool check_on_fit_to_field;
int player_move;
Unit* enemy_unit;
int x_new,y_new;
while (1) {
check_on_fit_to_field = false;
check1 = false;
check = false;
cout << "0 - вернуться на шаг назад\n";
cout << "1 - аттаковать направо\n";
cout << "2 - аттаковать налево\n";
cout << "3 - аттаковать наверх\n";
cout << "4 - аттаковать вниз\n";
int ch;
cin >> ch;
if(!ch)
break;
switch (ch) {
case 3:
x_new = x + 1;
y_new = y;
if(y_new >= f->getYsize()){
f->getLog()->write("Выход за пределы поля!!!\n");
break;
}
check_on_fit_to_field = true;
break;
case 4:
x_new = x - 1;
y_new = y;
if(y_new < 0){
f->getLog()->write("Выход за пределы поля!!!\n");
break;
}
check_on_fit_to_field = true;
break;
case 2:
x_new = x;
y_new = y - 1;
if(x_new < 0){
f->getLog()->write("Выход за пределы поля!!!\n");
break;
}
check_on_fit_to_field = true;
break;
case 1:
x_new = x;
y_new = y + 1;
if(x_new >= f->getXsize()){
f->getLog()->write("Выход за пределы поля!!!\n");
break;
}
check_on_fit_to_field = true;
break;
default:
break;
}
if(!check_on_fit_to_field)
continue;
while (1) {
cout << "0 - вернуться на шаг назад\n";
if (f->field[x_new][y_new].getIfOccupiedByUnit() &&
f->field[x_new][y_new].getUnit()->getId() != curr_unit->getId()) {
cout << "1 - Атаковать вражеского юнита\n";
check1 = true;
}
if (f->field[x_new][y_new].getBase() != nullptr && f->field[x_new][y_new].getBase()->getObjectId() != f->field[x][y].getUnit()->getId()) {
cout << "2 - Атаковать базу\n";
check2 = true;
}
if(!check1 && !check2){
f->getLog()->write("На этом поле нет объектов/юнитов для атаки\n");
break;
}
cin >> player_move;
if(!player_move)
break;
switch (player_move){
case 1:
enemy_unit = f->field[x_new][y_new].getUnit();
if(check1)
this->battleWithUnit(f,check,curr_unit,enemy_unit,x,y,x_new,y_new);
break;
case 2:
if(check2)
this->attackBase(f,check,x,y,x_new,y_new);
break;
default:
break;
}
if(check)
break;
}
if(check)
break;
}
}
| [
"[email protected]"
] | |
10705ac73a59b7068b0f460a7d8da3dfd7ea292c | 9a74de3dfe4288323ddb0d5b57a74aedc3ca63da | /ch14/14-38.cpp | 51d212fcf9e98a9033086e9bf65c643cb8c2d7fc | [] | no_license | ss-haze/cpp_primer | afd56dc810278f728c7d462ada009d1f179c36fa | 917b99845e80a36c4d82345864ceef3f8628fcac | refs/heads/main | 2023-06-05T14:00:38.343255 | 2021-06-28T15:22:27 | 2021-06-28T15:22:27 | 321,345,987 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,033 | cpp | #include <string>
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
using std::cout;
using std::ifstream;
using std::string;
class string_limit
{
public:
string_limit(size_t upper, size_t lower)
: bound_upper_(upper),
bound_lower_(lower) {}
bool operator()(string &str_length) const
{
return str_length.size() <= bound_upper_ &&
str_length.size() >= bound_lower_;
}
private:
size_t bound_lower_;
size_t bound_upper_;
};
int main()
{
ifstream ifs("input.txt");
if (!ifs)
{
std::cerr << "Error. Could not open file";
return 1;
}
std::vector<string> vs;
for (string s; ifs >> s; vs.push_back(s))
;
size_t bound_upper, bound_lower;
std::cout << "Input upper bound: ";
std::cin >> bound_upper;
std::cout << "Input lower bound: ";
std::cin >> bound_lower;
auto count = std::count_if(vs.begin(), vs.end(), string_limit(bound_upper, bound_lower));
std::cout << "Total words within specified bounds: " << count;
return 0;
} | [
"[email protected]"
] | |
6def73b8fc99a62deda8813e14d956b4556242f1 | 6881ae27fcdae1443da1f24eb73c7da452ecf5d8 | /reverse_linkelist.cpp | bf207b78a5f20143ca6d66b0acc822e95d3468e0 | [
"MIT"
] | permissive | navitiwari/OpenDS | 25b4fd85309a71eaa3d4a913ab2fdbc3dbd6a4a4 | 6666fccd580bc7a91cb3f4cd2a0a641fcdaf1f98 | refs/heads/master | 2020-04-01T01:14:23.694396 | 2018-10-12T10:08:28 | 2018-10-12T10:08:28 | 152,731,089 | 0 | 0 | MIT | 2018-10-12T10:08:29 | 2018-10-12T09:59:37 | C++ | UTF-8 | C++ | false | false | 677 | cpp | #include<iostream>
using namespace std;
struct node
{
int data;
node *next;
};
void createNode(node **head,int data)
{
node *temp=new node;
temp->data=data;
temp->next=*head;
*head=temp;
}
node *reverse(node *head)
{
node *current,*next,*prev;
prev=NULL;
current=head;
while(current!=NULL)
{
next=current->next;
current->next=prev;
prev=current;
current=next;
}
head=prev;
}
void display(node *head)
{
while(head!=NULL)
{
cout<<head->data<<" "<<endl;
head=head->next;
}
}
int main(int argc,char *argv[])
{
int i;
node *head=NULL;
node *tail=NULL;
for(i=0;i<argc-1;i++)
{
int k=(atoi)(argv[i+1]);
createNode(&head,k);
}
display(head);
}
| [
"[email protected]"
] | |
214593e855146e0eb5ea38c4a6ecc7eb519bebd1 | c7ef4e11ac87d3a65cceb5a631f7bd3aa27fc73c | /4.14/main.cpp | 7848f430bae1b5408e3a44cdad0b1b5ec7594774 | [] | no_license | Gracesr/song_rui | 544c6be7898af42cf5937cf1491306ee82ebe7c0 | 01e94b7ac87bc966615638e026c37e894c5d88cb | refs/heads/master | 2020-04-02T09:39:15.297807 | 2019-04-21T09:31:45 | 2019-04-21T09:31:45 | 154,302,833 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 769 | cpp | #include <iostream>
using namespace std;
int main{}
{
int account_number;
double a=0,b=0,c=0,d=0,e=0 ;
while{account_number!=-1}
{
cout<<"Enter account number{or -1 to quit}";
cin>>account;
if{account_number==-1}break;
cout<<"Enter beginning balance";
cin>>a;
cout<<"Enter total charges";
cin>>b;
cout<<"Enter total_credits";
cin>>c;
cout<<"Enter credit_limit";
cin>>d;
e=a+b-c;
if{e<=d}
{
cout<<"New balance is "<<e<<endl;
}
eles
{cout<<"New balance is"<<e<<endl;
cout<<"Account"<<account<<endl;
cout<<"Credit Limit"<<d<<endl;
cout<<"Balance"<<e<<endl;
cout << "Credit Limit Exceeded."<<endl;
}
return 0;
}
| [
"[email protected]"
] | |
e0a1f7925887d9f46be67b213d150e5ebf6347f1 | 46f118ad5fe5a4e47ce90b4350cf0d070271e16a | /src/clubman.h | f6facd61b635f2683756601d0f35ae2fad86a45f | [
"MIT"
] | permissive | lodyman93/taucoin | e8ddd76ddfed6ab0dc4482c625dcd1f82377703f | dbf0d2ca6a4c1a9c0a1d02538fdebb8b47a2aaa3 | refs/heads/master | 2020-03-29T11:02:33.111960 | 2018-09-20T07:50:55 | 2018-09-20T07:50:55 | 149,828,884 | 0 | 0 | MIT | 2018-09-21T23:31:20 | 2018-09-21T23:31:20 | null | UTF-8 | C++ | false | false | 914 | h | // Copyright (c) 2018- The taucoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef TAUCOIN_CLUB_MANAGER_H
#define TAUCOIN_CLUB_MANAGER_H
#include "amount.h"
#include "base58.h"
#include "consensus/params.h"
#include "main.h"
#include "script/script.h"
class ClubManager
{
public:
static const int DEFAULT_HARVEST_POWER = 0;
static ClubManager* GetInstance();
uint64_t GetHarvestPowerByAddress(std::string& addr, int nHeight);
bool IsAllowForge(const std::string& pubKey, int nHeight, uint64_t &harvestPower);
bool IsForgeScript(const CScript& script, CBitcoinAddress& addr, uint64_t& memCount, int nHeight = -1);
protected:
ClubManager();
private:
static ClubManager* pSingleton;
};
#endif // TAUCOIN_REWARD_MANAGER_H
| [
"[email protected]"
] | |
3db959887482b11c9f0adc9ea8ab8fb6d0cecd08 | 9ea624a093561c87e47b822008e35d40a136a953 | /src/OpcUaStackCore/Base/PoolBase.cpp | 121b800593b4dbab23dd09d079a421738e560304 | [
"Apache-2.0"
] | permissive | ASNeG/OpcUaStack | 399828371ed4c128360c710dcd831b41f192f27d | e7c365f006be878dcb588a83af9a0dde49bf2b5a | refs/heads/master | 2023-08-30T16:12:24.823685 | 2022-06-27T21:35:44 | 2022-06-27T21:35:44 | 149,216,768 | 141 | 41 | Apache-2.0 | 2023-08-22T09:10:17 | 2018-09-18T02:25:58 | C++ | UTF-8 | C++ | false | false | 6,924 | cpp | /*
Copyright 2015 Kai Huebl ([email protected])
Lizenziert gemäß Apache Licence Version 2.0 (die „Lizenz“); Nutzung dieser
Datei nur in Übereinstimmung mit der Lizenz erlaubt.
Eine Kopie der Lizenz erhalten Sie auf http://www.apache.org/licenses/LICENSE-2.0.
Sofern nicht gemäß geltendem Recht vorgeschrieben oder schriftlich vereinbart,
erfolgt die Bereitstellung der im Rahmen der Lizenz verbreiteten Software OHNE
GEWÄHR ODER VORBEHALTE – ganz gleich, ob ausdrücklich oder stillschweigend.
Informationen über die jeweiligen Bedingungen für Genehmigungen und Einschränkungen
im Rahmen der Lizenz finden Sie in der Lizenz.
Autor: Kai Huebl ([email protected])
*/
#include <iostream>
#include "OpcUaStackCore/Base/PoolBase.h"
namespace OpcUaStackCore
{
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
//
// PoolListEntry
//
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
PoolListEntry::PoolListEntry(void)
: next_(this)
, last_(this)
{
}
PoolListEntry::~PoolListEntry(void)
{
if (next_ == this && last_ == this) return;
next_->last_ = last_;
last_->next_ = next_;
next_ = this;
last_ = this;
}
char*
PoolListEntry::getMemory(void)
{
return ((char*)this) + sizeof(PoolListEntry);
}
PoolListEntry*
PoolListEntry::MemoryToPoolListEntry(char* memory)
{
return (PoolListEntry*)(memory - sizeof(PoolListEntry));
}
bool
PoolListEntry::empty(void)
{
return next_ == last_;
}
void
PoolListEntry::add(PoolListEntry* poolListEntry)
{
poolListEntry->next_ = next_;
poolListEntry->last_ = this;
next_->last_ = poolListEntry;
next_ = poolListEntry;
}
void
PoolListEntry::addAfter(PoolListEntry* poolListEntry)
{
add(poolListEntry);
}
void
PoolListEntry::addBefor(PoolListEntry* poolListEntry)
{
last_->addAfter(poolListEntry);
}
PoolListEntry*
PoolListEntry::del(void)
{
if (next_ == this && last_ == this) return this;
next_->last_ = last_;
last_->next_ = next_;
next_ = this;
last_ = this;
return this;
}
PoolListEntry*
PoolListEntry::delBefor(void)
{
return last_->del();
}
PoolListEntry*
PoolListEntry::delAfter(void)
{
return next_->del();
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
//
// PoolList
//
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
PoolList::PoolList(void)
: PoolListEntry()
, size_(0)
, garbageCollector_(this)
{
}
PoolList::~PoolList(void)
{
}
uint32_t
PoolList::size(void)
{
return size_;
}
bool
PoolList::empty(void)
{
return PoolListEntry::empty();
}
void
PoolList::addFirst(PoolListEntry* poolListEntry)
{
if (PoolListEntry::empty()) garbageCollector_ = poolListEntry;
size_++;
next_->add(poolListEntry);
}
void
PoolList::addLast(PoolListEntry* poolListEntry)
{
if (PoolListEntry::empty()) garbageCollector_ = poolListEntry;
size_++;
last_->add(poolListEntry);
}
PoolListEntry*
PoolList::del(PoolListEntry* poolListEntry)
{
if (garbageCollector_ == poolListEntry) garbageCollectorNext();
if (garbageCollector_ == poolListEntry) garbageCollector_ = this;
size_--;
return poolListEntry->del();
}
PoolListEntry*
PoolList::delFirst(void)
{
if (garbageCollector_ == next_) garbageCollectorNext();
if (garbageCollector_ == next_) garbageCollector_ = this;
size_--;
return next_->del();
}
PoolListEntry*
PoolList::delLast(void)
{
if (garbageCollector_ == last_) garbageCollectorNext();
if (garbageCollector_ == last_) garbageCollector_ = this;
size_--;
return last_->del();
}
PoolListEntry*
PoolList::garbageCollector(void)
{
if (PoolListEntry::empty()) return nullptr;
return garbageCollector_;
}
PoolListEntry*
PoolList::garbageCollectorNext(void)
{
if (PoolListEntry::empty()) return nullptr;
if (garbageCollector_->next_ == this) {
garbageCollector_ = garbageCollector_->next_->next_;
}
else {
garbageCollector_ = garbageCollector_->next_;
}
return garbageCollector_;
}
void
PoolList::log(std::ostream& os)
{
PoolListEntry* poolListEntry = this->next_;
while (poolListEntry != this) {
os << " " << poolListEntry;
poolListEntry = poolListEntry->next_;
}
os << std::endl;
}
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
//
// PoolBase
//
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
PoolBase::PoolBase(
uint32_t entrySize,
uint32_t startEntries,
uint32_t growEntries,
uint32_t maxUsedEntries,
uint32_t maxFreeEntries
)
: entrySize_(entrySize)
, startEntries_(startEntries)
, growEntries_(growEntries)
, maxUsedEntries_(maxUsedEntries)
, maxFreeEntries_(maxFreeEntries)
, usedEntries_(0)
, freeEntries_(0)
, freePoolList_()
{
if (startEntries_ == 0) startEntries_ = 1;
if (growEntries_ == 0) growEntries_ = 1;
if (maxFreeEntries_ != 0 && startEntries_ > maxFreeEntries_ ) maxFreeEntries_ = startEntries_;
entrySize_ += sizeof(PoolListEntry);
grow(startEntries_);
}
PoolBase::~PoolBase(void)
{
while (!freePoolList_.empty()) {
PoolListEntry* poolListEntry = freePoolList_.delFirst();
memoryDestructHandler(poolListEntry->getMemory());
delete (char*)poolListEntry;
}
freeEntries_ = 0;
}
uint32_t
PoolBase::freeEntries(void)
{
return freeEntries_;
}
uint32_t
PoolBase::usedEntries(void)
{
return usedEntries_;
}
PoolListEntry*
PoolBase::allocate(void)
{
if (freePoolList_.empty()) garbageCollector();
if (freePoolList_.empty() && !grow(growEntries_)) return nullptr;
freeEntries_++;
usedEntries_++;
return freePoolList_.delFirst();
}
void
PoolBase::free(PoolListEntry* poolListEntry)
{
usedEntries_--;
if (maxFreeEntries_ != 0 && freeEntries_ >= maxFreeEntries_) {
memoryDestructHandler(poolListEntry->getMemory());
delete (char*)poolListEntry;
return;
}
freePoolList_.addLast(new (poolListEntry) PoolListEntry);
freeEntries_++;
}
bool
PoolBase::grow(uint32_t growEntries)
{
if (maxUsedEntries_ != 0 && usedEntries_ >= maxUsedEntries_) return false;
for (uint32_t idx=0; idx<growEntries; idx++) {
char* memory = new char[entrySize_];
PoolListEntry* poolListEntry = new (memory) PoolListEntry();
memoryConstructHandler(poolListEntry->getMemory());
freePoolList_.addLast(poolListEntry);
}
freeEntries_ += growEntries;
return true;
}
}
| [
"[email protected]"
] | |
1c2f6d448b991a8a0cf92bbae82dc6d2b749c2b9 | 1224e8ce78eb40f8b92a8647f6e18625fb5caee7 | /http_message.cpp | 1a5cb284dcf952fdb43067f61facd057d504fa3e | [] | no_license | msg555/gnyproxy | 94e080e308af033fd0565389d03d54cd5b5b01ed | 50da686bd3aa3d4d84ce5dbc7fced18c7de1ead6 | refs/heads/master | 2021-01-15T13:44:57.728853 | 2012-01-26T02:44:21 | 2012-01-26T02:44:21 | 3,270,785 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 895 | cpp | #include "http_message.h"
#include <iostream>
using namespace std;
http_message::~http_message() {
}
void http_message::add_header(const string& key, const string& value) {
assert(state == HTTP_MESSAGE_HEADER);
headers.push_back(make_pair(key, value));
}
void http_message::append_entity(const string& entity_) {
assert(state == HTTP_MESSAGE_ENTITY);
entity.append(entity_);
}
void http_message::add_footer(const string& key, const string& value) {
assert(state == HTTP_MESSAGE_FOOTER);
footers.push_back(make_pair(key, value));
}
void http_message::end_header() {
assert(state <= HTTP_MESSAGE_HEADER);
state = HTTP_MESSAGE_ENTITY;
}
void http_message::end_entity() {
assert(state <= HTTP_MESSAGE_ENTITY);
state = HTTP_MESSAGE_FOOTER;
}
void http_message::end_footer() {
assert(state <= HTTP_MESSAGE_FOOTER);
state = HTTP_MESSAGE_DONE;
}
| [
"[email protected]"
] | |
1e0c45aafb3803facaf5574b7416e815bd34c440 | c51febc209233a9160f41913d895415704d2391f | /library/ATF/tagPAGERANGE.hpp | 9e24564de60ae573b492688d2ea6f5d3c9af85f7 | [
"MIT"
] | permissive | roussukke/Yorozuya | 81f81e5e759ecae02c793e65d6c3acc504091bc3 | d9a44592b0714da1aebf492b64fdcb3fa072afe5 | refs/heads/master | 2023-07-08T03:23:00.584855 | 2023-06-29T08:20:25 | 2023-06-29T08:20:25 | 463,330,454 | 0 | 0 | MIT | 2022-02-24T23:15:01 | 2022-02-24T23:15:00 | null | UTF-8 | C++ | false | false | 271 | hpp | // This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually
#pragma once
#include <common/common.h>
START_ATF_NAMESPACE
struct tagPAGERANGE
{
int nFromPage;
int nToPage;
};
END_ATF_NAMESPACE
| [
"[email protected]"
] | |
e4ed711e758348c29fedb462c5eb12babd1b7a3a | 297497957c531d81ba286bc91253fbbb78b4d8be | /gfx/skia/skia/src/codec/SkCodecImageGenerator.h | 54a79638e1e30e0c550b0c9e9108be8083f0bb46 | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | permissive | marco-c/gecko-dev-comments-removed | 7a9dd34045b07e6b22f0c636c0a836b9e639f9d3 | 61942784fb157763e65608e5a29b3729b0aa66fa | refs/heads/master | 2023-08-09T18:55:25.895853 | 2023-08-01T00:40:39 | 2023-08-01T00:40:39 | 211,297,481 | 0 | 0 | NOASSERTION | 2019-09-29T01:27:49 | 2019-09-27T10:44:24 | C++ | UTF-8 | C++ | false | false | 1,877 | h |
#ifndef SkCodecImageGenerator_DEFINED
#define SkCodecImageGenerator_DEFINED
#include "include/codec/SkCodec.h"
#include "include/core/SkData.h"
#include "include/core/SkImageGenerator.h"
#include "include/core/SkRefCnt.h"
#include "include/core/SkSize.h"
#include "include/core/SkYUVAPixmaps.h"
#include <cstddef>
#include <memory>
#include <optional>
enum SkAlphaType : int;
struct SkImageInfo;
class SkCodecImageGenerator : public SkImageGenerator {
public:
static std::unique_ptr<SkImageGenerator> MakeFromEncodedCodec(
sk_sp<SkData>, std::optional<SkAlphaType> = std::nullopt);
static std::unique_ptr<SkImageGenerator> MakeFromCodec(std::unique_ptr<SkCodec>);
SkISize getScaledDimensions(float desiredScale) const;
bool getPixels(const SkImageInfo& info, void* pixels, size_t rowBytes, const SkCodec::Options* options = nullptr);
int getFrameCount() { return fCodec->getFrameCount(); }
bool getFrameInfo(int index, SkCodec::FrameInfo* info) const {
return fCodec->getFrameInfo(index, info);
}
int getRepetitionCount() { return fCodec->getRepetitionCount(); }
protected:
sk_sp<SkData> onRefEncodedData() override;
bool onGetPixels(const SkImageInfo& info,
void* pixels,
size_t rowBytes,
const Options& opts) override;
bool onQueryYUVAInfo(const SkYUVAPixmapInfo::SupportedDataTypes&,
SkYUVAPixmapInfo*) const override;
bool onGetYUVAPlanes(const SkYUVAPixmaps& yuvaPixmaps) override;
private:
SkCodecImageGenerator(std::unique_ptr<SkCodec>, sk_sp<SkData>, std::optional<SkAlphaType>);
std::unique_ptr<SkCodec> fCodec;
sk_sp<SkData> fData;
using INHERITED = SkImageGenerator;
};
#endif
| [
"[email protected]"
] | |
3d7af267baf2c9a5ebb1c637f8187734415a3873 | 4a9e765bd2806cf6fcf94c635cdcccc483619119 | /disjoint_set/disjoint_set.h | 67f233b4b1714702c656ce14f7e3633d6c98b7b8 | [] | no_license | clangpp/codeset | 1c0aaf4c778ca96025f5ad4e6fcef7c9699d87a2 | 67bb303772b403c9946f262c3a10bf7342ce9072 | refs/heads/main | 2021-09-25T22:07:42.000609 | 2021-09-09T07:40:50 | 2021-09-09T07:40:50 | 13,406,758 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 4,192 | h | #ifndef DISJOINT_SET_H_
#define DISJOINT_SET_H_
#include <algorithm>
#include <cstddef>
#include <functional>
#include <stdexcept>
#include <vector>
// disjoint set algorithm
namespace disjoint_set {
typedef std::ptrdiff_t ssize_type;
// ************ notes **************
// concept RandomAccessIterator {
// std::iterator_traits<RandomAccessIterator>::value_type
// is compatible with ssize_type
// };
// ************ notes **************
// pre-condition: root1 and root2 are root node of disdinct subsets
template <typename RandomAccessIterator>
inline void union_sets_plain(RandomAccessIterator sets, ssize_type root1,
ssize_type root2) {
sets[root2] = root1;
}
template <typename RandomAccessIterator>
inline void union_sets_by_size(RandomAccessIterator sets, ssize_type root1,
ssize_type root2) {
if (sets[root1] <= sets[root2]) { // size(root1) >= size(root2)
sets[root1] += sets[root2]; // add root2's size to root1's
sets[root2] = root1; // attach tree root2 to tree root1
} else { // size(root1) < size(root2)
sets[root2] += sets[root1]; // add root1's size to root2's
sets[root1] = root2; // attach tree root1 to tree root2
}
}
template <typename RandomAccessIterator>
inline void union_sets_by_height(RandomAccessIterator sets, ssize_type root1,
ssize_type root2) {
if (sets[root1] <= sets[root2]) { // height(root1) >= height(root2)
if (sets[root1] == sets[root2]) {
--sets[root1]; // update height if same
}
sets[root2] = root1; // attach tree root2 to tree root1
} else { // height(root1) < height(root2)
sets[root1] = root2; // attach tree root1 to tree root2
}
}
// pre-condition: sets[s] is referencable
template <typename RandomAccessIterator>
ssize_type find_plain(RandomAccessIterator sets, ssize_type s) {
return sets[s] < 0 ? s : find_plain(sets, sets[s]);
}
template <typename RandomAccessIterator>
ssize_type find_compress_path(RandomAccessIterator sets, ssize_type s) {
if (sets[s] < 0) {
return s;
}
return sets[s] = find_compress_path(sets, sets[s]);
}
} // namespace disjoint_set
// disjoint set class
class DisjointSet {
public:
typedef std::size_t size_type;
typedef disjoint_set::ssize_type ssize_type;
typedef ssize_type setid_type;
public:
explicit DisjointSet(size_type n = 0) : sets_(n, -1) {}
// find root node of subset that s belongs to
setid_type find(setid_type s) const {
if (s < 0 || s >= ssize_type(sets_.size()))
throw std::invalid_argument("invalid setid");
return disjoint_set::find_plain(sets_.begin(), s);
}
// find root node of subset that s belongs to
setid_type find(setid_type s) {
if (s < 0 || s >= ssize_type(sets_.size()))
throw std::invalid_argument("invalid setid");
return disjoint_set::find_compress_path(sets_.begin(), s);
}
// union two subsets which s1 and s2 belongs to
// return true if union takes place, otherwise false.
bool union_sets(setid_type s1, setid_type s2) {
setid_type root1 = find(s1);
setid_type root2 = find(s2);
if (root1 == root2) return false;
disjoint_set::union_sets_by_size(sets_.begin(), root1, root2);
return true;
}
// get nodes amount in disjoint set
size_type size() const { return sets_.size(); }
// get subsets amount in disjoint set
size_type set_count() const {
return std::count_if(sets_.begin(), sets_.end(),
[](setid_type set) { return set < 0; });
}
// get nodes amount in subset that s belongs to
size_type set_size(setid_type s) const {
setid_type root = find(s);
return static_cast<size_type>(-sets_[root]);
}
// get nodes amount in subset that s belongs to
size_type set_size(setid_type s) {
setid_type root = find(s);
return static_cast<size_type>(-sets_[root]);
}
private:
std::vector<ssize_type> sets_;
};
#endif // DISJOINT_SET_H_
| [
"[email protected]"
] | |
3621461747e3c5dfdeeec15b8206a419e98200e6 | d17fbd6c677b1427452a298678e913d48b85a664 | /core/libs/jsi/src/jsc.cpp | 583e2b7ac8e26d0f167fddb702f0b9b3dcdfec10 | [] | no_license | sunflowerdeath/aardvark-old | 766e492978a329c9c7a529bc69ecda1493937133 | 131eb88ac4ef4c043c524403af5a0b0d62cadb49 | refs/heads/master | 2023-07-16T13:52:17.110611 | 2021-09-05T17:08:21 | 2021-09-05T17:08:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,360 | cpp | #include "jsc.hpp"
namespace aardvark::jsi {
class JscValue : public PointerData {
public:
JscValue(JSGlobalContextRef ctx, bool* ctx_invalid, JSValueRef ref)
: ctx(ctx), ctx_invalid(ctx_invalid), ref(ref) {
protect();
}
~JscValue() override {
if (!*ctx_invalid) JSValueUnprotect(ctx, ref);
}
void protect() {
if (!*ctx_invalid) JSValueProtect(ctx, ref);
}
PointerData* copy() override {
protect();
return new JscValue(*this);
}
bool* ctx_invalid;
JSGlobalContextRef ctx;
JSValueRef ref;
};
class JscString : public PointerData {
public:
JscString(JSStringRef ref) : ref(ref) {}
~JscString() override { JSStringRelease(ref); }
PointerData* copy() override {
JSStringRetain(ref);
return new JscString(*this);
}
JSStringRef ref;
};
// Classes are released on context destroy
class JscClass : public PointerData {
public:
JscClass(JSClassRef ref) : ref(ref) {}
PointerData* copy() override { return new JscClass(*this); }
JSClassRef ref;
};
std::shared_ptr<Jsc_Context> Jsc_Context::create() {
return std::make_shared<Jsc_Context>();
}
Jsc_Context* Jsc_Context::get(JSContextRef ctx) {
auto global_object = JSContextGetGlobalObject(ctx);
return static_cast<Jsc_Context*>(JSObjectGetPrivate(global_object));
}
Jsc_Context::Jsc_Context() {
// Create empty dummy class because default object class does not
// allocate storage for private data
auto global_class = JSClassCreate(&kJSClassDefinitionEmpty);
ctx = JSGlobalContextCreate(global_class);
auto global_object = JSContextGetGlobalObject(ctx);
JSObjectSetPrivate(global_object, (void*)this);
JSClassRelease(global_class);
error_constructor =
get_global_object().get_property("Error").value().to_object().value();
}
Jsc_Context::~Jsc_Context() {
ctx_invalid = true;
JSGlobalContextRelease(ctx);
for (auto& it : class_definitions) JSClassRelease(it.first);
}
// Helpers
String Jsc_Context::string_from_jsc(JSStringRef ref) {
return String(this, new JscString(ref));
}
Value Jsc_Context::value_from_jsc(JSValueRef ref) {
return Value(this, new JscValue(ctx, &ctx_invalid, ref));
}
Object Jsc_Context::object_from_jsc(JSObjectRef ref) {
return Object(this, new JscValue(ctx, &ctx_invalid, (JSValueRef)ref));
}
Class Jsc_Context::class_from_jsc(JSClassRef ref) {
return Class(this, new JscClass(ref));
}
JSValueRef Jsc_Context::value_to_jsc(const Value& value) {
return static_cast<JscValue*>(value.ptr)->ref;
}
JSObjectRef Jsc_Context::object_to_jsc(const Object& object) {
return (JSObjectRef) static_cast<JscValue*>(object.ptr)->ref;
}
JSStringRef Jsc_Context::string_to_jsc(const String& str) {
return static_cast<JscString*>(str.ptr)->ref;
}
JSClassRef Jsc_Context::class_to_jsc(const Class& cls) {
return static_cast<JscClass*>(cls.ptr)->ref;
}
tl::unexpected<Error> Jsc_Context::error_from_jsc(JSValueRef ref) {
auto value = value_from_jsc(ref);
return tl::make_unexpected(Error(this, &value));
}
void Jsc_Context::error_to_jsc(Error& error, JSValueRef* exception) {
*exception = value_to_jsc(error.value());
}
// Implementation
Result<Value> Jsc_Context::eval(
const std::string& source,
Object* this_obj,
const std::string& source_url) {
auto jsi_source = string_make_from_utf8(source);
auto jsc_this = this_obj == nullptr ? nullptr : object_to_jsc(*this_obj);
auto jsi_source_url = string_make_from_utf8(source_url);
auto exception = JSValueRef();
auto jsc_res = JSEvaluateScript(
ctx,
string_to_jsc(jsi_source),
jsc_this,
string_to_jsc(jsi_source_url),
0 /* starting_line_number */,
&exception);
if (exception != nullptr) return error_from_jsc(exception);
return value_from_jsc(jsc_res);
}
void Jsc_Context::garbage_collect() { JSGarbageCollect(ctx); }
Object Jsc_Context::get_global_object() {
return object_from_jsc(JSContextGetGlobalObject(ctx));
}
// String
std::string jsc_string_to_utf8(JSContextRef ctx, JSStringRef jsc_str) {
auto size = JSStringGetMaximumUTF8CStringSize(jsc_str);
auto buffer = new char[size];
JSStringGetUTF8CString(jsc_str, buffer, size);
auto str = std::string(buffer);
delete[] buffer;
return str;
}
String Jsc_Context::string_make_from_utf8(const std::string& str) {
auto jsc_str = JSStringCreateWithUTF8CString(str.c_str());
return string_from_jsc(jsc_str);
}
std::string Jsc_Context::string_to_utf8(const String& js_str) {
return jsc_string_to_utf8(ctx, string_to_jsc(js_str));
}
// Value
Value Jsc_Context::value_make_bool(bool value) {
return value_from_jsc(JSValueMakeBoolean(ctx, value));
}
Value Jsc_Context::value_make_number(double value) {
return value_from_jsc(JSValueMakeNumber(ctx, value));
}
Value Jsc_Context::value_make_null() {
return value_from_jsc(JSValueMakeNull(ctx));
}
Value Jsc_Context::value_make_undefined() {
return value_from_jsc(JSValueMakeUndefined(ctx));
}
Value Jsc_Context::value_make_string(const String& str) {
auto jsc_value = JSValueMakeString(ctx, string_to_jsc(str));
return value_from_jsc(jsc_value);
}
Value Jsc_Context::value_make_object(const Object& object) {
return value_from_jsc((JSValueRef)object_to_jsc(object));
}
WeakValue Jsc_Context::value_make_weak(const Value& value) {
// TODO
}
Value Jsc_Context::weak_value_lock(const WeakValue& value) {
// TODO
}
bool Jsc_Context::value_is_error(const Value& value) {
return JSValueIsInstanceOfConstructor(
ctx,
value_to_jsc(value),
object_to_jsc(error_constructor.value()),
nullptr);
}
Value Jsc_Context::value_make_error(const std::string& message) {
auto jsc_message =
JSValueMakeString(ctx, string_to_jsc(string_make_from_utf8(message)));
auto err = JSObjectMakeError(
ctx,
1, // arg_count
&jsc_message, // args
nullptr // exception
);
return value_from_jsc(err);
}
std::optional<ErrorLocation> Jsc_Context::value_get_error_location(
const Value& value) {
// TODO
return std::nullopt;
}
ValueType Jsc_Context::value_get_type(const Value& value) {
auto type = JSValueGetType(ctx, value_to_jsc(value));
switch (type) {
case kJSTypeUndefined:
return ValueType::undefined;
break;
case kJSTypeNull:
return ValueType::null;
break;
case kJSTypeBoolean:
return ValueType::boolean;
break;
case kJSTypeNumber:
return ValueType::number;
break;
case kJSTypeString:
return ValueType::string;
break;
case kJSTypeObject:
return ValueType::object;
break;
case kJSTypeSymbol:
return ValueType::symbol;
break;
}
}
Result<bool> Jsc_Context::value_to_bool(const Value& value) {
return JSValueToBoolean(ctx, value_to_jsc(value));
}
Result<double> Jsc_Context::value_to_number(const Value& value) {
auto exception = JSValueRef();
auto res = JSValueToNumber(ctx, value_to_jsc(value), &exception);
if (exception != nullptr) return error_from_jsc(exception);
return res;
}
Result<String> Jsc_Context::value_to_string(const Value& value) {
auto exception = JSValueRef();
auto jsc_string = JSValueToStringCopy(ctx, value_to_jsc(value), &exception);
if (exception != nullptr) return error_from_jsc(exception);
return string_from_jsc(jsc_string);
}
Result<Object> Jsc_Context::value_to_object(const Value& value) {
auto exception = JSValueRef();
auto jsc_object = JSValueToObject(ctx, value_to_jsc(value), &exception);
if (exception != nullptr) return error_from_jsc(exception);
return object_from_jsc(jsc_object);
}
bool Jsc_Context::value_strict_equal(const Value& a, const Value& b) {
return JSValueIsStrictEqual(ctx, value_to_jsc(a), value_to_jsc(b));
}
// Class
std::unordered_map<JSObjectRef, Jsc_Context::ClassInstanceRecord>
Jsc_Context::class_instances;
ClassDefinition* Jsc_Context::get_class_definition(JSObjectRef object) {
auto it = class_instances.find(object);
if (it == class_instances.end()) return nullptr;
return it->second.definition;
}
void Jsc_Context::finalize_class_instance(JSObjectRef object) {
auto it = Jsc_Context::class_instances.find(object);
if (it == Jsc_Context::class_instances.end()) return;
auto ctx = it->second.ctx;
auto definition = it->second.definition;
if (definition->finalizer) {
definition->finalizer(ctx->object_from_jsc(object));
}
Jsc_Context::class_instances.erase(it);
}
void class_finalize(JSObjectRef object) {
Jsc_Context::finalize_class_instance(object);
}
JSValueRef class_static_value_get(
JSContextRef ctx,
JSObjectRef object,
JSStringRef prop_name,
JSValueRef* exception) {
auto jsi_ctx = Jsc_Context::get(ctx);
auto jsi_object = jsi_ctx->object_from_jsc(object);
auto definition = Jsc_Context::get_class_definition(object);
auto name = jsc_string_to_utf8(ctx, prop_name);
auto jsi_res = definition->properties[name].get(jsi_object);
if (jsi_res.has_value()) {
return jsi_ctx->value_to_jsc(jsi_res.value());
} else {
jsi_ctx->error_to_jsc(jsi_res.error(), exception);
return nullptr;
}
}
bool class_static_value_set(
JSContextRef ctx,
JSObjectRef object,
JSStringRef prop_name,
JSValueRef value,
JSValueRef* exception) {
auto jsi_ctx = Jsc_Context::get(ctx);
auto jsi_object = jsi_ctx->object_from_jsc(object);
auto jsi_value = jsi_ctx->value_from_jsc(value);
auto definition = Jsc_Context::get_class_definition(object);
auto name = jsc_string_to_utf8(ctx, prop_name);
auto did_set_res = definition->properties[name].set(jsi_object, jsi_value);
if (did_set_res.has_value()) {
return did_set_res.value();
} else {
jsi_ctx->error_to_jsc(did_set_res.error(), exception);
return false;
}
}
Class Jsc_Context::class_make(const ClassDefinition& definition) {
auto jsc_definition = kJSClassDefinitionEmpty;
jsc_definition.className = definition.name.c_str();
jsc_definition.finalize = class_finalize;
// JSC C api has no Object.defineProperty so creating class relies on
// automatically generated class prototype
JSStaticValue static_values[definition.properties.size() + 1];
auto i = 0;
for (auto& it : definition.properties) {
static_values[i] = {it.first.c_str(),
class_static_value_get,
class_static_value_set,
kJSPropertyAttributeNone};
i++;
}
static_values[i] = {0, 0, 0};
jsc_definition.staticValues = static_values;
auto jsc_class = JSClassCreate(&jsc_definition);
auto jsi_class = class_from_jsc(jsc_class);
// Only way to get generated prototype is to create temporary object
auto instance = JSObjectMake(ctx, jsc_class, nullptr);
auto proto =
JSValueToObject(ctx, JSObjectGetPrototype(ctx, instance), nullptr);
// Add methods to the prototype as usual functions
if (!definition.methods.empty()) {
auto jsi_proto = object_from_jsc(proto);
for (auto& it : definition.methods) {
auto method_value = object_make_function(it.second).to_value();
jsi_proto.set_property(it.first, method_value);
}
}
class_definitions[jsc_class] = std::move(definition);
return jsi_class;
}
// Object
Object Jsc_Context::object_make(const Class* cls) {
auto exception = JSValueRef();
auto jsc_object = JSObjectMake(
ctx, cls == nullptr ? nullptr : class_to_jsc(*cls), &exception);
if (cls != nullptr) {
auto definition = &class_definitions.find(class_to_jsc(*cls))->second;
Jsc_Context::class_instances.emplace(
jsc_object, ClassInstanceRecord{this, definition});
}
return object_from_jsc(jsc_object);
}
JSValueRef native_function_call_as_function(
JSContextRef ctx,
JSObjectRef function,
JSObjectRef this_object,
size_t arg_count,
const JSValueRef args[],
JSValueRef* exception) {
auto jsi_ctx = Jsc_Context::get(ctx);
auto jsi_function = static_cast<Function*>(JSObjectGetPrivate(function));
auto jsi_this = this_object == nullptr
? jsi_ctx->value_make_null()
: jsi_ctx->value_from_jsc((JSValueRef)this_object);
auto jsi_args = std::vector<Value>();
jsi_args.reserve(arg_count);
for (auto i = 0; i < arg_count; i++) {
jsi_args.push_back(jsi_ctx->value_from_jsc(args[i]));
}
auto jsi_res = (*jsi_function)(jsi_this, jsi_args);
if (jsi_res.has_value()) {
return jsi_ctx->value_to_jsc(jsi_res.value());
} else {
jsi_ctx->error_to_jsc(jsi_res.error(), exception);
return nullptr;
}
}
void native_function_finalize(JSObjectRef object) {
delete static_cast<Function*>(JSObjectGetPrivate(object));
}
JSClassRef native_function_create_class() {
auto definition = kJSClassDefinitionEmpty;
definition.className = "NativeFunction";
definition.callAsFunction = native_function_call_as_function;
definition.finalize = native_function_finalize;
return JSClassCreate(&definition);
}
auto native_function_class = native_function_create_class();
Object Jsc_Context::object_make_function(const Function& function) {
auto function_ptr = new Function(function);
auto jsc_object = JSObjectMake(ctx, native_function_class, function_ptr);
return object_from_jsc(jsc_object);
}
Object Jsc_Context::object_make_constructor(const Class& cls) {
// TODO
}
Object Jsc_Context::object_make_constructor2(
const Class& cls, const Function& function) {
// TODO
}
Object Jsc_Context::object_make_array() {
auto jsc_array = JSObjectMakeArray(
ctx, // ctx
0, // args_count
nullptr, // args
nullptr // exception
);
return object_from_jsc(jsc_array);
}
Value Jsc_Context::object_to_value(const Object& object) {
return value_from_jsc((JSValueRef)object_to_jsc(object));
}
void Jsc_Context::object_set_private_data(const Object& object, void* data) {
JSObjectSetPrivate(object_to_jsc(object), data);
}
void* Jsc_Context::object_get_private_data(const Object& object) {
return JSObjectGetPrivate(object_to_jsc(object));
}
Result<Value> Jsc_Context::object_get_prototype(const Object& object) {
auto jsc_proto = JSObjectGetPrototype(ctx, object_to_jsc(object));
return value_from_jsc(jsc_proto);
}
VoidResult Jsc_Context::object_set_prototype(
const Object& object, const Value& proto) {
JSObjectSetPrototype(ctx, object_to_jsc(object), value_to_jsc(proto));
return VoidResult();
}
std::vector<std::string> Jsc_Context::object_get_property_names(
const Object& object) {
auto jsc_names = JSObjectCopyPropertyNames(ctx, object_to_jsc(object));
auto count = JSPropertyNameArrayGetCount(jsc_names);
auto names = std::vector<std::string>();
names.reserve(count);
for (auto i = 0; i < count; i++) {
auto name = JSPropertyNameArrayGetNameAtIndex(jsc_names, i);
names.push_back(jsc_string_to_utf8(ctx, name));
}
JSPropertyNameArrayRelease(jsc_names);
return names;
}
bool Jsc_Context::object_has_property(
const Object& object, const std::string& name) {
auto jsc_name = string_make_from_utf8(name);
return JSObjectHasProperty(
ctx, object_to_jsc(object), string_to_jsc(jsc_name));
}
Result<Value> Jsc_Context::object_get_property(
const Object& object, const std::string& name) {
auto jsc_name = string_make_from_utf8(name);
auto exception = JSValueRef();
auto jsc_value = JSObjectGetProperty(
ctx, object_to_jsc(object), string_to_jsc(jsc_name), &exception);
if (exception != nullptr) return error_from_jsc(exception);
return value_from_jsc(jsc_value);
}
VoidResult Jsc_Context::object_set_property(
const Object& object, const std::string& name, const Value& value) {
auto jsc_name = string_make_from_utf8(name);
auto exception = JSValueRef();
JSObjectSetProperty(
ctx,
object_to_jsc(object),
string_to_jsc(jsc_name),
value_to_jsc(value),
kJSPropertyAttributeNone,
&exception);
if (exception != nullptr) return error_from_jsc(exception);
return VoidResult();
}
VoidResult Jsc_Context::object_delete_property(
const Object& object, const std::string& name) {
auto jsc_name = string_make_from_utf8(name);
auto exception = JSValueRef();
JSObjectDeleteProperty(
ctx, object_to_jsc(object), string_to_jsc(jsc_name), &exception);
if (exception != nullptr) return error_from_jsc(exception);
return VoidResult();
}
bool Jsc_Context::object_is_function(const Object& object) {
return JSObjectIsFunction(ctx, object_to_jsc(object));
}
Result<Value> Jsc_Context::object_call_as_function(
const Object& object,
const Value* this_val,
const std::vector<Value>& args) {
auto jsc_obj = object_to_jsc(object);
auto jsc_this = this_val == nullptr
? nullptr
: (JSObjectRef)value_to_jsc(*this_val); // TODO
JSValueRef jsc_args[args.size()];
for (auto i = 0; i < args.size(); i++) {
jsc_args[i] = value_to_jsc(args[i]);
}
auto exception = JSValueRef();
auto jsc_res = JSObjectCallAsFunction(
ctx, jsc_obj, jsc_this, args.size(), jsc_args, &exception);
if (exception != nullptr) return error_from_jsc(exception);
return value_from_jsc(jsc_res);
}
bool Jsc_Context::object_is_constructor(const Object& object) {
// TODO
}
Result<Object> Jsc_Context::object_call_as_constructor(
const Object& object, const std::vector<Value>& args) {
auto jsc_obj = object_to_jsc(object);
JSValueRef jsc_args[args.size()];
for (auto i = 0; i < args.size(); i++) {
jsc_args[i] = value_to_jsc(args[i]);
}
auto exception = JSValueRef();
auto jsc_res = JSObjectCallAsConstructor(
ctx, jsc_obj, args.size(), jsc_args, &exception);
if (exception != nullptr) return error_from_jsc(exception);
return object_from_jsc(jsc_res);
}
bool Jsc_Context::object_is_array(const Object& object) {
return JSValueIsArray(ctx, object_to_jsc(object));
}
Result<Value> Jsc_Context::object_get_property_at_index(
const Object& object, size_t index) {
auto exception = JSValueRef();
auto res = JSObjectGetPropertyAtIndex(
ctx, object_to_jsc(object), index, &exception);
if (exception != nullptr) return error_from_jsc(exception);
return value_from_jsc(res);
}
VoidResult Jsc_Context::object_set_property_at_index(
const Object& object, size_t index, const Value& value) {
auto exception = JSValueRef();
JSObjectSetPropertyAtIndex(
ctx, object_to_jsc(object), index, value_to_jsc(value), &exception);
if (exception != nullptr) return error_from_jsc(exception);
return VoidResult();
}
} // namespace aardvark::jsi
| [
"[email protected]"
] | |
62b723b075914551f7ab46dec4eacd6ff9f8f211 | 4bd0543a3030e040e9ea60952a474b757ebf19e7 | /206. 反转链表.cpp | 5b03dc0c7e6c264a22f026c919262ea8db597400 | [] | no_license | tang2021/leetcode_test | f123a3c94aedb8a7876eba0ad92b98f26c4c4297 | b8a7127736f2f8214d464b1fb245a434cf205153 | refs/heads/main | 2023-04-01T13:54:08.297850 | 2021-04-03T11:14:05 | 2021-04-03T11:14:05 | 338,090,786 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 718 | cpp | // 206. 反转链表
// 反转一个单链表。
// 示例:
// 输入: 1->2->3->4->5->NULL
// 输出: 5->4->3->2->1->NULL
// 进阶:
// 你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
typedef struct ListNode{
int val;
ListNode* next;
ListNode(int x):val(x),next(nullptr){}
}ListNode;
ListNode* reverse(ListNode* head){
ListNode *newhead=nullptr,*h=head;
while(h!=nullptr){
ListNode* n=h->next;
h->next=newhead;
newhead=h;
h=n;
}
return newhead;
}
ListNode* reverse(ListNode* head){
if(head==nullptr)return head;
ListNode* p=reverse(head->next);
head->next->next=head;
head->next=nullptr;
return p;
} | [
"[email protected]"
] | |
d54f7b8732326b21ca11938b1ea258d6ed6eb51e | df5f44553b63f42f6e03242bd71a59f23a21a086 | /examples/pump-app/pump-common/gen/callback-stub.cpp | c8f1582be94f31e2cb8511688fb2e892ff1ac5ba | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | clapre/connectedhomeip | 2425f93fb7a53b60db4a6527d54afacb57753599 | 30732ad8f5a0e5f909a1b27f14946d355db89ec7 | refs/heads/master | 2023-05-24T02:46:05.898154 | 2021-06-11T13:41:46 | 2021-06-11T13:41:46 | 375,111,219 | 0 | 0 | Apache-2.0 | 2021-06-10T03:38:33 | 2021-06-08T18:43:48 | C++ | UTF-8 | C++ | false | false | 28,566 | cpp | /*
*
* Copyright (c) 2021 Project CHIP 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
*
* 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.
*/
// THIS FILE IS GENERATED BY ZAP
#include "callback.h"
#include <app/common/gen/cluster-id.h>
#include <lib/support/Span.h>
using namespace chip;
// Cluster Init Functions
void emberAfClusterInitCallback(EndpointId endpoint, ClusterId clusterId)
{
switch (clusterId)
{
case ZCL_BASIC_CLUSTER_ID:
emberAfBasicClusterInitCallback(endpoint);
break;
case ZCL_ETHERNET_NETWORK_DIAGNOSTICS_CLUSTER_ID:
emberAfEthernetNetworkDiagnosticsClusterInitCallback(endpoint);
break;
case ZCL_GENERAL_COMMISSIONING_CLUSTER_ID:
emberAfGeneralCommissioningClusterInitCallback(endpoint);
break;
case ZCL_GENERAL_DIAGNOSTICS_CLUSTER_ID:
emberAfGeneralDiagnosticsClusterInitCallback(endpoint);
break;
case ZCL_LEVEL_CONTROL_CLUSTER_ID:
emberAfLevelControlClusterInitCallback(endpoint);
break;
case ZCL_NETWORK_COMMISSIONING_CLUSTER_ID:
emberAfNetworkCommissioningClusterInitCallback(endpoint);
break;
case ZCL_ON_OFF_CLUSTER_ID:
emberAfOnOffClusterInitCallback(endpoint);
break;
case ZCL_OPERATIONAL_CREDENTIALS_CLUSTER_ID:
emberAfOperationalCredentialsClusterInitCallback(endpoint);
break;
case ZCL_PUMP_CONFIG_CONTROL_CLUSTER_ID:
emberAfPumpConfigurationAndControlClusterInitCallback(endpoint);
break;
case ZCL_SOFTWARE_DIAGNOSTICS_CLUSTER_ID:
emberAfSoftwareDiagnosticsClusterInitCallback(endpoint);
break;
case ZCL_TEMP_MEASUREMENT_CLUSTER_ID:
emberAfTemperatureMeasurementClusterInitCallback(endpoint);
break;
case ZCL_THREAD_NETWORK_DIAGNOSTICS_CLUSTER_ID:
emberAfThreadNetworkDiagnosticsClusterInitCallback(endpoint);
break;
case ZCL_WIFI_NETWORK_DIAGNOSTICS_CLUSTER_ID:
emberAfWiFiNetworkDiagnosticsClusterInitCallback(endpoint);
break;
default:
// Unrecognized cluster ID
break;
}
}
void __attribute__((weak)) emberAfBasicClusterInitCallback(EndpointId endpoint)
{
// To prevent warning
(void) endpoint;
}
void __attribute__((weak)) emberAfEthernetNetworkDiagnosticsClusterInitCallback(EndpointId endpoint)
{
// To prevent warning
(void) endpoint;
}
void __attribute__((weak)) emberAfGeneralCommissioningClusterInitCallback(EndpointId endpoint)
{
// To prevent warning
(void) endpoint;
}
void __attribute__((weak)) emberAfGeneralDiagnosticsClusterInitCallback(EndpointId endpoint)
{
// To prevent warning
(void) endpoint;
}
void __attribute__((weak)) emberAfLevelControlClusterInitCallback(EndpointId endpoint)
{
// To prevent warning
(void) endpoint;
}
void __attribute__((weak)) emberAfNetworkCommissioningClusterInitCallback(EndpointId endpoint)
{
// To prevent warning
(void) endpoint;
}
void __attribute__((weak)) emberAfOnOffClusterInitCallback(EndpointId endpoint)
{
// To prevent warning
(void) endpoint;
}
void __attribute__((weak)) emberAfOperationalCredentialsClusterInitCallback(EndpointId endpoint)
{
// To prevent warning
(void) endpoint;
}
void __attribute__((weak)) emberAfPumpConfigurationAndControlClusterInitCallback(EndpointId endpoint)
{
// To prevent warning
(void) endpoint;
}
void __attribute__((weak)) emberAfSoftwareDiagnosticsClusterInitCallback(EndpointId endpoint)
{
// To prevent warning
(void) endpoint;
}
void __attribute__((weak)) emberAfTemperatureMeasurementClusterInitCallback(EndpointId endpoint)
{
// To prevent warning
(void) endpoint;
}
void __attribute__((weak)) emberAfThreadNetworkDiagnosticsClusterInitCallback(EndpointId endpoint)
{
// To prevent warning
(void) endpoint;
}
void __attribute__((weak)) emberAfWiFiNetworkDiagnosticsClusterInitCallback(EndpointId endpoint)
{
// To prevent warning
(void) endpoint;
}
//
// Non-Cluster Related Callbacks
//
/** @brief Add To Current App Tasks
*
* This function is only useful to sleepy end devices. This function will note
* the passed item as part of a set of tasks the application has outstanding
* (e.g. message sent requiring APS acknwoledgement). This will affect how the
* application behaves with regard to sleeping and polling. Until the
* outstanding task is completed, the device may poll more frequently and sleep
* less often.
*
* @param tasks Ver.: always
*/
void __attribute__((weak)) emberAfAddToCurrentAppTasksCallback(EmberAfApplicationTask tasks) {}
/** @brief Remove From Current App Tasks
*
* This function is only useful to sleepy end devices. This function will
* remove the passed item from the set of tasks the application has outstanding
* (e.g. message sent requiring APS acknwoledgement). This will affect how the
* application behaves with regard to sleeping and polling. Removing the item
* from the list of outstanding tasks may allow the device to sleep longer and
* poll less frequently. If there are other outstanding tasks the system may
* still have to stay away and poll more often.
*
* @param tasks Ver.: always
*/
void __attribute__((weak)) emberAfRemoveFromCurrentAppTasksCallback(EmberAfApplicationTask tasks) {}
/** @brief Allow Network Write Attribute
*
* This function is called by the application framework before it writes an
* attribute in response to a write attribute request from an external device.
* The value passed into this callback is the value to which the attribute is to
* be set by the framework.
Example: In mirroring simple metering data
* on an Energy Services Interface (ESI) (formerly called Energy Service Portal
* (ESP) in SE 1.0).), a mirrored simple meter needs to write read-only
* attributes on its mirror. The-meter-mirror sample application, located in
* app/framework/sample-apps, uses this callback to allow the mirrored device to
* write simple metering attributes on the mirror regardless of the fact that
* most simple metering attributes are defined as read-only by the ZigBee
* specification.
Note: The ZCL specification does not (as of this
* writing) specify any permission-level security for writing writeable
* attributes. As far as the ZCL specification is concerned, if an attribute is
* writeable, any device that has a link key for the device should be able to
* write that attribute. Furthermore if an attribute is read only, it should not
* be written over the air. Thus, if you implement permissions for writing
* attributes as a feature, you MAY be operating outside the specification. This
* is unlikely to be a problem for writing read-only attributes, but it may be a
* problem for attributes that are writeable according to the specification but
* restricted by the application implementing this callback.
*
* @param endpoint Ver.: always
* @param clusterId Ver.: always
* @param attributeId Ver.: always
* @param mask Ver.: always
* @param manufacturerCode Ver.: always
* @param value Ver.: always
* @param type Ver.: always
*/
EmberAfAttributeWritePermission __attribute__((weak))
emberAfAllowNetworkWriteAttributeCallback(EndpointId endpoint, ClusterId clusterId, AttributeId attributeId, uint8_t mask,
uint16_t manufacturerCode, uint8_t * value, uint8_t type)
{
return EMBER_ZCL_ATTRIBUTE_WRITE_PERMISSION_ALLOW_WRITE_NORMAL; // Default
}
/** @brief Attribute Read Access
*
* This function is called whenever the Application Framework needs to check
* access permission for an attribute read.
*
* @param endpoint Ver.: always
* @param clusterId Ver.: always
* @param manufacturerCode Ver.: always
* @param attributeId Ver.: always
*/
bool __attribute__((weak))
emberAfAttributeReadAccessCallback(EndpointId endpoint, ClusterId clusterId, uint16_t manufacturerCode, AttributeId attributeId)
{
return true;
}
/** @brief Attribute Write Access
*
* This function is called whenever the Application Framework needs to check
* access permission for an attribute write.
*
* @param endpoint Ver.: always
* @param clusterId Ver.: always
* @param manufacturerCode Ver.: always
* @param attributeId Ver.: always
*/
bool __attribute__((weak))
emberAfAttributeWriteAccessCallback(EndpointId endpoint, ClusterId clusterId, uint16_t manufacturerCode, AttributeId attributeId)
{
return true;
}
/** @brief Default Response
*
* This function is called by the application framework when a Default Response
* command is received from an external device. The application should return
* true if the message was processed or false if it was not.
*
* @param clusterId The cluster identifier of this response. Ver.: always
* @param commandId The command identifier to which this is a response. Ver.:
* always
* @param status Specifies either SUCCESS or the nature of the error that was
* detected in the received command. Ver.: always
*/
bool __attribute__((weak)) emberAfDefaultResponseCallback(ClusterId clusterId, CommandId commandId, EmberAfStatus status)
{
return false;
}
/** @brief Configure Reporting Response
*
* This function is called by the application framework when a Configure
* Reporting Response command is received from an external device. The
* application should return true if the message was processed or false if it
* was not.
*
* @param clusterId The cluster identifier of this response. Ver.: always
* @param buffer Buffer containing the list of attribute status records. Ver.:
* always
* @param bufLen The length in bytes of the list. Ver.: always
*/
bool __attribute__((weak)) emberAfConfigureReportingResponseCallback(ClusterId clusterId, uint8_t * buffer, uint16_t bufLen)
{
return false;
}
/** @brief Read Reporting Configuration Response
*
* This function is called by the application framework when a Read Reporting
* Configuration Response command is received from an external device. The
* application should return true if the message was processed or false if it
* was not.
*
* @param clusterId The cluster identifier of this response. Ver.: always
* @param buffer Buffer containing the list of attribute reporting configuration
* records. Ver.: always
* @param bufLen The length in bytes of the list. Ver.: always
*/
bool __attribute__((weak)) emberAfReadReportingConfigurationResponseCallback(ClusterId clusterId, uint8_t * buffer, uint16_t bufLen)
{
return false;
}
/** @brief Discover Attributes Response
*
* This function is called by the application framework when a Discover
* Attributes Response or Discover Attributes Extended Response command is
* received from an external device. The Discover Attributes Response command
* contains a bool indicating if discovery is complete and a list of zero or
* more attribute identifier/type records. The final argument indicates whether
* the response is in the extended format or not. The application should return
* true if the message was processed or false if it was not.
*
* @param clusterId The cluster identifier of this response. Ver.: always
* @param discoveryComplete Indicates whether there are more attributes to be
* discovered. true if there are no more attributes to be discovered. Ver.:
* always
* @param buffer Buffer containing the list of attribute identifier/type
* records. Ver.: always
* @param bufLen The length in bytes of the list. Ver.: always
* @param extended Indicates whether the response is in the extended format or
* not. Ver.: always
*/
bool __attribute__((weak)) emberAfDiscoverAttributesResponseCallback(ClusterId clusterId, bool discoveryComplete, uint8_t * buffer,
uint16_t bufLen, bool extended)
{
return false;
}
/** @brief Discover Commands Generated Response
*
* This function is called by the framework when Discover Commands Generated
* Response is received.
*
* @param clusterId The cluster identifier of this response. Ver.: always
* @param manufacturerCode Manufacturer code Ver.: always
* @param discoveryComplete Indicates whether there are more commands to be
* discovered. Ver.: always
* @param commandIds Buffer containing the list of command identifiers. Ver.:
* always
* @param commandIdCount The length of bytes of the list, whish is the same as
* the number of identifiers. Ver.: always
*/
bool __attribute__((weak))
emberAfDiscoverCommandsGeneratedResponseCallback(ClusterId clusterId, uint16_t manufacturerCode, bool discoveryComplete,
CommandId * commandIds, uint16_t commandIdCount)
{
return false;
}
/** @brief Discover Commands Received Response
*
* This function is called by the framework when Discover Commands Received
* Response is received.
*
* @param clusterId The cluster identifier of this response. Ver.: always
* @param manufacturerCode Manufacturer code Ver.: always
* @param discoveryComplete Indicates whether there are more commands to be
* discovered. Ver.: always
* @param commandIds Buffer containing the list of command identifiers. Ver.:
* always
* @param commandIdCount The length of bytes of the list, whish is the same as
* the number of identifiers. Ver.: always
*/
bool __attribute__((weak))
emberAfDiscoverCommandsReceivedResponseCallback(ClusterId clusterId, uint16_t manufacturerCode, bool discoveryComplete,
CommandId * commandIds, uint16_t commandIdCount)
{
return false;
}
/** @brief Pre Command Received
*
* This callback is the second in the Application Framework's message processing
* chain. At this point in the processing of incoming over-the-air messages, the
* application has determined that the incoming message is a ZCL command. It
* parses enough of the message to populate an EmberAfClusterCommand struct. The
* Application Framework defines this struct value in a local scope to the
* command processing but also makes it available through a global pointer
* called emberAfCurrentCommand, in app/framework/util/util.c. When command
* processing is complete, this pointer is cleared.
*
* @param cmd Ver.: always
*/
bool __attribute__((weak)) emberAfPreCommandReceivedCallback(EmberAfClusterCommand * cmd)
{
return false;
}
/** @brief Pre Message Send
*
* This function is called by the framework when it is about to pass a message
* to the stack primitives for sending. This message may or may not be ZCL,
* ZDO, or some other protocol. This is called prior to
any ZigBee
* fragmentation that may be done. If the function returns true it is assumed
* the callback has consumed and processed the message. The callback must also
* set the EmberStatus status code to be passed back to the caller. The
* framework will do no further processing on the message.
If the
* function returns false then it is assumed that the callback has not processed
* the mesasge and the framework will continue to process accordingly.
*
* @param messageStruct The structure containing the parameters of the APS
* message to be sent. Ver.: always
* @param status A pointer to the status code value that will be returned to the
* caller. Ver.: always
*/
bool __attribute__((weak)) emberAfPreMessageSendCallback(EmberAfMessageStruct * messageStruct, EmberStatus * status)
{
return false;
}
/** @brief Message Sent
*
* This function is called by the application framework from the message sent
* handler, when it is informed by the stack regarding the message sent status.
* All of the values passed to the emberMessageSentHandler are passed on to this
* callback. This provides an opportunity for the application to verify that its
* message has been sent successfully and take the appropriate action. This
* callback should return a bool value of true or false. A value of true
* indicates that the message sent notification has been handled and should not
* be handled by the application framework.
*
* @param type Ver.: always
* @param destination Ver.: always
* @param apsFrame Ver.: always
* @param msgLen Ver.: always
* @param message Ver.: always
* @param status Ver.: always
*/
bool __attribute__((weak)) emberAfMessageSentCallback(const MessageSendDestination & destination, EmberApsFrame * apsFrame,
uint16_t msgLen, uint8_t * message, EmberStatus status)
{
return false;
}
/** @brief Pre Attribute Change
*
* This function is called by the application framework before it changes an
* attribute value. The value passed into this callback is the value to which
* the attribute is to be set by the framework. The application should return
* ::EMBER_ZCL_STATUS_SUCCESS to permit the change or any other ::EmberAfStatus
* to reject it.
*
* @param endpoint Ver.: always
* @param clusterId Ver.: always
* @param attributeId Ver.: always
* @param mask Ver.: always
* @param manufacturerCode Ver.: always
* @param type Ver.: always
* @param size Ver.: always
* @param value Ver.: always
*/
EmberAfStatus __attribute__((weak))
emberAfPreAttributeChangeCallback(EndpointId endpoint, ClusterId clusterId, AttributeId attributeId, uint8_t mask,
uint16_t manufacturerCode, uint8_t type, uint16_t size, uint8_t * value)
{
return EMBER_ZCL_STATUS_SUCCESS;
}
/** @brief Post Attribute Change
*
* This function is called by the application framework after it changes an
* attribute value. The value passed into this callback is the value to which
* the attribute was set by the framework.
*
* @param endpoint Ver.: always
* @param clusterId Ver.: always
* @param attributeId Ver.: always
* @param mask Ver.: always
* @param manufacturerCode Ver.: always
* @param type Ver.: always
* @param size Ver.: always
* @param value Ver.: always
*/
void __attribute__((weak))
emberAfPostAttributeChangeCallback(EndpointId endpoint, ClusterId clusterId, AttributeId attributeId, uint8_t mask,
uint16_t manufacturerCode, uint8_t type, uint16_t size, uint8_t * value)
{}
/** @brief Read Attributes Response
*
* This function is called by the application framework when a Read Attributes
* Response command is received from an external device. The application should
* return true if the message was processed or false if it was not.
*
* @param clusterId The cluster identifier of this response. Ver.: always
* @param buffer Buffer containing the list of read attribute status records.
* Ver.: always
* @param bufLen The length in bytes of the list. Ver.: always
*/
bool __attribute__((weak)) emberAfReadAttributesResponseCallback(ClusterId clusterId, uint8_t * buffer, uint16_t bufLen)
{
return false;
}
/** @brief External Attribute Read
*
* Like emberAfExternalAttributeWriteCallback above, this function is called
* when the framework needs to read an attribute that is not stored within the
* Application Framework's data structures.
All of the important
* information about the attribute itself is passed as a pointer to an
* EmberAfAttributeMetadata struct, which is stored within the application and
* used to manage the attribute. A complete description of the
* EmberAfAttributeMetadata struct is provided in
* app/framework/include/af-types.h
This function assumes that the
* application is able to read the attribute, write it into the passed buffer,
* and return immediately. Any attributes that require a state machine for
* reading and writing are not really candidates for externalization at the
* present time. The Application Framework does not currently include a state
* machine for reading or writing attributes that must take place across a
* series of application ticks. Attributes that cannot be read in a timely
* manner should be stored within the Application Framework and updated
* occasionally by the application code from within the
* emberAfMainTickCallback.
If the application was successfully able to
* read the attribute and write it into the passed buffer, it should return a
* value of EMBER_ZCL_STATUS_SUCCESS. Ensure that the size of the externally
* managed attribute value is smaller than what the buffer can hold. In the case
* of a buffer overflow throw an appropriate error such as
* EMBER_ZCL_STATUS_INSUFFICIENT_SPACE. Any other return value indicates the
* application was not able to read the attribute.
*
* @param endpoint Ver.: always
* @param clusterId Ver.: always
* @param attributeMetadata Ver.: always
* @param manufacturerCode Ver.: always
* @param buffer Ver.: always
* @param maxReadLength Ver.: always
* @param index Ver.: always
*/
EmberAfStatus __attribute__((weak))
emberAfExternalAttributeReadCallback(EndpointId endpoint, ClusterId clusterId, EmberAfAttributeMetadata * attributeMetadata,
uint16_t manufacturerCode, uint8_t * buffer, uint16_t maxReadLength, int32_t index)
{
return EMBER_ZCL_STATUS_FAILURE;
}
/** @brief Write Attributes Response
*
* This function is called by the application framework when a Write Attributes
* Response command is received from an external device. The application should
* return true if the message was processed or false if it was not.
*
* @param clusterId The cluster identifier of this response. Ver.: always
* @param buffer Buffer containing the list of write attribute status records.
* Ver.: always
* @param bufLen The length in bytes of the list. Ver.: always
*/
bool __attribute__((weak)) emberAfWriteAttributesResponseCallback(ClusterId clusterId, uint8_t * buffer, uint16_t bufLen)
{
return false;
}
/** @brief External Attribute Write
*
* This function is called whenever the Application Framework needs to write an
* attribute which is not stored within the data structures of the Application
* Framework itself. One of the new features in Version 2 is the ability to
* store attributes outside the Framework. This is particularly useful for
* attributes that do not need to be stored because they can be read off the
* hardware when they are needed, or are stored in some central location used by
* many modules within the system. In this case, you can indicate that the
* attribute is stored externally. When the framework needs to write an external
* attribute, it makes a call to this callback.
This callback is very
* useful for host micros which need to store attributes in persistent memory.
* Because each host micro (used with an Ember NCP) has its own type of
* persistent memory storage, the Application Framework does not include the
* ability to mark attributes as stored in flash the way that it does for Ember
* SoCs like the EM35x. On a host micro, any attributes that need to be stored
* in persistent memory should be marked as external and accessed through the
* external read and write callbacks. Any host code associated with the
* persistent storage should be implemented within this callback.
All of
* the important information about the attribute itself is passed as a pointer
* to an EmberAfAttributeMetadata struct, which is stored within the application
* and used to manage the attribute. A complete description of the
* EmberAfAttributeMetadata struct is provided in
* app/framework/include/af-types.h.
This function assumes that the
* application is able to write the attribute and return immediately. Any
* attributes that require a state machine for reading and writing are not
* candidates for externalization at the present time. The Application Framework
* does not currently include a state machine for reading or writing attributes
* that must take place across a series of application ticks. Attributes that
* cannot be written immediately should be stored within the Application
* Framework and updated occasionally by the application code from within the
* emberAfMainTickCallback.
If the application was successfully able to
* write the attribute, it returns a value of EMBER_ZCL_STATUS_SUCCESS. Any
* other return value indicates the application was not able to write the
* attribute.
*
* @param endpoint Ver.: always
* @param clusterId Ver.: always
* @param attributeMetadata Ver.: always
* @param manufacturerCode Ver.: always
* @param buffer Ver.: always
* @param index Ver.: always
*/
EmberAfStatus __attribute__((weak))
emberAfExternalAttributeWriteCallback(EndpointId endpoint, ClusterId clusterId, EmberAfAttributeMetadata * attributeMetadata,
uint16_t manufacturerCode, uint8_t * buffer, int32_t index)
{
return EMBER_ZCL_STATUS_FAILURE;
}
/** @brief Report Attributes
*
* This function is called by the application framework when a Report Attributes
* command is received from an external device. The application should return
* true if the message was processed or false if it was not.
*
* @param clusterId The cluster identifier of this command. Ver.: always
* @param buffer Buffer containing the list of attribute report records. Ver.:
* always
* @param bufLen The length in bytes of the list. Ver.: always
*/
bool __attribute__((weak)) emberAfReportAttributesCallback(ClusterId clusterId, uint8_t * buffer, uint16_t bufLen)
{
return false;
}
/** @brief Get Current Time
*
* This callback is called when device attempts to get current time from the
* hardware. If this device has means to retrieve exact time, then this method
* should implement it. If the callback can't provide the exact time it should
* return 0 to indicate failure. Default action is to return 0, which indicates
* that device does not have access to real time.
*
*/
uint32_t __attribute__((weak)) emberAfGetCurrentTimeCallback()
{
return 0;
}
/** @brief Get Endpoint Info
*
* This function is a callback to an application implemented endpoint that
* operates outside the normal application framework. When the framework wishes
* to perform operations with that endpoint it uses this callback to retrieve
* the endpoint's information. If the endpoint exists and the application can
* provide data then true shall be returned. Otherwise the callback must return
* false.
*
* @param endpoint The endpoint to retrieve data for. Ver.: always
* @param returnNetworkIndex The index corresponding to the ZigBee network the
* endpoint belongs to. If not using a multi-network device, 0 must be
* returned. Otherwise on a multi-network device the stack will switch to this
* network before sending the message. Ver.: always
* @param returnEndpointInfo A pointer to a data struct that will be written
* with information about the endpoint. Ver.: always
*/
bool __attribute__((weak))
emberAfGetEndpointInfoCallback(EndpointId endpoint, uint8_t * returnNetworkIndex, EmberAfEndpointInfoStruct * returnEndpointInfo)
{
return false;
}
/** @brief Registration Abort
*
* This callback is called when the device should abort the registration
* process.
*
*/
void __attribute__((weak)) emberAfRegistrationAbortCallback() {}
/** @brief Interpan Send Message
*
* This function will send a raw MAC message with interpan frame format using
* the passed parameters.
*
* @param header Interpan header info Ver.: always
* @param messageLength The length of the message received or to send Ver.:
* always
* @param message The message data received or to send. Ver.: always
*/
EmberStatus __attribute__((weak))
emberAfInterpanSendMessageCallback(EmberAfInterpanHeader * header, uint16_t messageLength, uint8_t * message)
{
return EMBER_LIBRARY_NOT_PRESENT;
}
/** @brief Start Move
*
* This function is called to initiate the process for a device to move (rejoin)
* to a new parent.
*
*/
bool __attribute__((weak)) emberAfStartMoveCallback()
{
return false;
}
| [
"[email protected]"
] | |
1207b6d2df26c88e639c80c64f883a1f0fade0b7 | 3f981d86067464fae3945e2c98e2e23912183afb | /Core/Scene/Primitive.h | e74ff35959978832df1f0d33c26b00a5d1ddb483 | [] | no_license | keithbugeja/illuminaPRT | 8b1a4664f202611412b8e7c720f1e309f05fe6a2 | faddb7d05a5ea71f8209dfa64d0c82b690347208 | refs/heads/master | 2021-03-27T19:50:03.104771 | 2014-05-20T11:12:49 | 2014-05-20T11:12:49 | 87,206,098 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,104 | h | //----------------------------------------------------------------------------------------------
// Filename: Primitive.h
// Author: Keith Bugeja
// Date: 27/02/2010
//----------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------
#pragma once
#include "System/IlluminaPRT.h"
//----------------------------------------------------------------------------------------------
namespace Illumina
{
namespace Core
{
class IPrimitive
{
public:
virtual bool IsBounded(void) const = 0;
virtual boost::shared_ptr<IBoundingVolume> GetWorldBounds(void) const = 0;
virtual Vector3 SamplePoint(float p_u, float p_v, Vector3 &p_normal) = 0;
virtual Vector3 SamplePoint(const Vector3 &p_viewPoint, float p_u, float p_v, Vector3 &p_normal) = 0;
virtual bool Intersects(const Ray &p_ray, Intersection &p_intersection) = 0;
virtual bool Intersects(const Ray &p_ray) = 0;
virtual std::string ToString(void) const = 0;
};
}
} | [
"[email protected]"
] | |
55c518396bd6a7830879ec746013237187c62d55 | 55a5062994ecdb8d3d2701161d79899176c3c5e5 | /google/cloud/pubsub/message.h | 790cd21d18e90ba26318e51da229e641dd780524 | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | whitemike889/google-cloud-cpp | 5a6e6ff4fde5ba2a0b6d3c031911c4b2b1001e8a | 128ffa910f61b7106a09877f6c9fa8ff9e83dc56 | refs/heads/master | 2023-05-11T08:03:02.596252 | 2020-08-05T23:57:46 | 2020-08-05T23:57:46 | 285,431,407 | 0 | 0 | Apache-2.0 | 2023-05-01T21:27:41 | 2020-08-06T00:08:58 | null | UTF-8 | C++ | false | false | 8,024 | h | // Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_PUBSUB_MESSAGE_H
#define GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_PUBSUB_MESSAGE_H
#include "google/cloud/pubsub/version.h"
#include <google/pubsub/v1/pubsub.pb.h>
#include <iosfwd>
#include <map>
#include <vector>
namespace google {
namespace cloud {
namespace pubsub {
inline namespace GOOGLE_CLOUD_CPP_PUBSUB_NS {
class Message;
} // namespace GOOGLE_CLOUD_CPP_PUBSUB_NS
} // namespace pubsub
namespace pubsub_internal {
inline namespace GOOGLE_CLOUD_CPP_PUBSUB_NS {
::google::pubsub::v1::PubsubMessage const& ToProto(pubsub::Message const&);
::google::pubsub::v1::PubsubMessage&& ToProto(pubsub::Message&&);
pubsub::Message FromProto(::google::pubsub::v1::PubsubMessage);
} // namespace GOOGLE_CLOUD_CPP_PUBSUB_NS
} // namespace pubsub_internal
namespace pubsub {
inline namespace GOOGLE_CLOUD_CPP_PUBSUB_NS {
class MessageBuilder;
/**
* Defines the type for message data.
*
* Inside Google some protobuf fields of type `bytes` are mapped to a different
* type than `std::string`. This is the case for message data. We use this
* type to automatically detect what is the representation for this field and
* use the correct mapping.
*
* External users of the Cloud Pubsub C++ client library should treat this as
* a complicated `typedef` for `std::string`. We have no plans to change the
* type in the external version of the C++ client library for the foreseeable
* future. In the eventuality that we do decide to change the type, this would
* be a reason update the library major version number, and we would give users
* time to migrate.
*
* In other words, external users of the Cloud Pubsub C++ client should simply
* write `std::string` where this type appears. For Google projects that must
* compile both inside and outside Google, this alias may be convenient.
*/
using PubsubMessageDataType = std::decay<decltype(
std::declval<google::pubsub::v1::PubsubMessage>().data())>::type;
/**
* The C++ representation for a Cloud Pub/Sub messages.
*
* Cloud Pub/Sub applications communicate to each other using messages. Note
* that messages must provide at least some data or some attributes. Use
* `MessageBuilder` to create instances of this class.
*/
class Message {
public:
/// @name accessors
//@{
PubsubMessageDataType const& data() const& { return proto_.data(); }
PubsubMessageDataType&& data() && {
return std::move(*proto_.mutable_data());
}
std::string const& message_id() const { return proto_.message_id(); }
std::string const& ordering_key() const { return proto_.ordering_key(); }
std::chrono::system_clock::time_point publish_time() const;
std::map<std::string, std::string> attributes() const {
std::map<std::string, std::string> r;
for (auto const& kv : proto_.attributes()) {
r.emplace(kv.first, kv.second);
}
return r;
}
//@}
/// @name Copy and move
//@{
Message(Message const&) = default;
Message& operator=(Message const&) = default;
Message(Message&&) = default;
Message& operator=(Message&&) = default;
//@}
/// @name Equality operators
//@{
friend bool operator==(Message const& a, Message const& b);
friend bool operator!=(Message const& a, Message const& b) {
return !(a == b);
}
//@}
/// Output in protobuf format, this is intended for debugging
friend std::ostream& operator<<(std::ostream& os, Message const& rhs);
private:
friend Message pubsub_internal::FromProto(
::google::pubsub::v1::PubsubMessage m);
friend ::google::pubsub::v1::PubsubMessage const& pubsub_internal::ToProto(
Message const& m);
friend ::google::pubsub::v1::PubsubMessage&& pubsub_internal::ToProto(
Message&& m);
friend class MessageBuilder;
Message() = default;
explicit Message(::google::pubsub::v1::PubsubMessage m)
: proto_(std::move(m)) {}
google::pubsub::v1::PubsubMessage proto_;
};
/**
* Constructs `Message` objects.
*/
class MessageBuilder {
public:
MessageBuilder() = default;
/// Create a new message.
Message Build() && { return Message(std::move(proto_)); }
/// Create a message with the data in @p data
MessageBuilder& SetData(std::string data) & {
proto_.set_data(std::move(data));
return *this;
}
/// Create a message with the data in @p data
MessageBuilder&& SetData(std::string data) && {
SetData(std::move(data));
return std::move(*this);
}
/// Create the message with ordering key @p key
MessageBuilder& SetOrderingKey(std::string key) & {
proto_.set_ordering_key(std::move(key));
return *this;
}
/// Create the message with ordering key @p key
MessageBuilder&& SetOrderingKey(std::string key) && {
return std::move(SetOrderingKey(std::move(key)));
}
/// Create a message with the attributes from the range [@p begin, @p end)
template <typename Iterator>
MessageBuilder& SetAttributes(Iterator begin, Iterator end) & {
google::protobuf::Map<std::string, std::string> tmp;
using value_type =
google::protobuf::Map<std::string, std::string>::value_type;
for (auto kv = begin; kv != end; ++kv) {
using std::get;
tmp.insert(value_type(get<0>(*kv), get<1>(*kv)));
}
proto_.mutable_attributes()->swap(tmp);
return *this;
}
/// Create a message with the attributes from the range [@p begin, @p end)
template <typename Iterator>
MessageBuilder&& SetAttributes(Iterator begin, Iterator end) && {
SetAttributes(std::move(begin), std::move(end));
return std::move(*this);
}
/// Create a message with the attributes in @p v
MessageBuilder& SetAttributes(
// NOLINTNEXTLINE(performance-unnecessary-value-param)
std::vector<std::pair<std::string, std::string>> v) & {
using value_type =
google::protobuf::Map<std::string, std::string>::value_type;
google::protobuf::Map<std::string, std::string> tmp;
for (auto& kv : v) {
tmp.insert(value_type(std::move(kv.first), std::move(kv.second)));
}
proto_.mutable_attributes()->swap(tmp);
return *this;
}
/// Create a message with the attributes in @p v
MessageBuilder&& SetAttributes(
// NOLINTNEXTLINE(performance-unnecessary-value-param)
std::vector<std::pair<std::string, std::string>> v) && {
SetAttributes(std::move(v));
return std::move(*this);
}
/// Create a message with the attributes in @p v
template <typename Pair>
MessageBuilder& SetAttributes(std::vector<Pair> v) & {
return SetAttributes(v.begin(), v.end());
}
/// Create a message with the attributes in @p v
template <typename Pair>
MessageBuilder&& SetAttributes(std::vector<Pair> v) && {
SetAttributes(std::move(v));
return std::move(*this);
}
private:
google::pubsub::v1::PubsubMessage proto_;
};
} // namespace GOOGLE_CLOUD_CPP_PUBSUB_NS
} // namespace pubsub
namespace pubsub_internal {
inline namespace GOOGLE_CLOUD_CPP_PUBSUB_NS {
inline ::google::pubsub::v1::PubsubMessage const& ToProto(
pubsub::Message const& m) {
return m.proto_;
}
inline ::google::pubsub::v1::PubsubMessage&& ToProto(pubsub::Message&& m) {
return std::move(m.proto_);
}
inline pubsub::Message FromProto(::google::pubsub::v1::PubsubMessage m) {
return pubsub::Message(std::move(m));
}
} // namespace GOOGLE_CLOUD_CPP_PUBSUB_NS
} // namespace pubsub_internal
} // namespace cloud
} // namespace google
#endif // GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_PUBSUB_MESSAGE_H
| [
"[email protected]"
] | |
e9e626600bfca4e5ce821dc6338d8ec3be2e3b8d | 08c8ca0dc8acc6063e0377c933b66ccfdc7b9db8 | /Source/WebKit/UIProcess/cairo/BackingStoreCairo.cpp | 55fbf33a89852505f49b04c4764826f83c119c6c | [
"BSD-3-Clause"
] | permissive | ijsf/DeniseEmbeddableWebKit | 5dab5d451a7c6a4c9a107bbcf1050e00ee7c01c8 | 57dfc6783d60f8f59b7129874e60f84d8c8556c9 | refs/heads/master | 2022-04-25T05:25:02.629593 | 2020-04-18T19:05:43 | 2020-04-18T19:06:26 | 256,827,831 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,005 | cpp | /*
* Copyright (C) 2011 Apple Inc. All rights reserved.
* Copyright (C) 2011,2014 Igalia S.L.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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 APPLE INC. AND ITS 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 APPLE INC. OR ITS 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 "config.h"
#include "BackingStore.h"
#include "ShareableBitmap.h"
#include "UpdateInfo.h"
#include "WebPageProxy.h"
#include <WebCore/BackingStoreBackendCairoImpl.h>
#include <WebCore/CairoUtilities.h>
#include <WebCore/GraphicsContext.h>
#include <WebCore/RefPtrCairo.h>
#include <cairo.h>
#if PLATFORM(GTK)
#include <gtk/gtk.h>
#endif
#if PLATFORM(GTK) && PLATFORM(X11) && defined(GDK_WINDOWING_X11)
#include <WebCore/BackingStoreBackendCairoX11.h>
#include <WebCore/PlatformDisplayX11.h>
#include <gdk/gdkx.h>
#endif
using namespace WebCore;
namespace WebKit {
std::unique_ptr<BackingStoreBackendCairo> BackingStore::createBackend()
{
#if PLATFORM(GTK) && PLATFORM(X11) && defined(GDK_WINDOWING_X11)
const auto& sharedDisplay = PlatformDisplay::sharedDisplay();
if (is<PlatformDisplayX11>(sharedDisplay)) {
GdkVisual* visual = gtk_widget_get_visual(m_webPageProxy.viewWidget());
GdkScreen* screen = gdk_visual_get_screen(visual);
ASSERT(downcast<PlatformDisplayX11>(sharedDisplay).native() == GDK_SCREEN_XDISPLAY(screen));
return std::make_unique<BackingStoreBackendCairoX11>(GDK_WINDOW_XID(gdk_screen_get_root_window(screen)),
GDK_VISUAL_XVISUAL(visual), gdk_visual_get_depth(visual), m_size, m_deviceScaleFactor);
}
#endif
return std::make_unique<BackingStoreBackendCairoImpl>(m_size, m_deviceScaleFactor);
}
void BackingStore::paint(cairo_t* context, const IntRect& rect)
{
ASSERT(m_backend);
cairo_save(context);
cairo_set_operator(context, CAIRO_OPERATOR_SOURCE);
cairo_set_source_surface(context, m_backend->surface(), 0, 0);
cairo_rectangle(context, rect.x(), rect.y(), rect.width(), rect.height());
cairo_fill(context);
cairo_restore(context);
}
void BackingStore::setPaintCallback(PaintCallback paintCallback)
{
m_paintCallback = paintCallback;
}
void BackingStore::incorporateUpdate(ShareableBitmap* bitmap, const UpdateInfo& updateInfo)
{
if (!m_backend)
m_backend = createBackend();
scroll(updateInfo.scrollRect, updateInfo.scrollOffset);
// Paint all update rects.
IntPoint updateRectLocation = updateInfo.updateRectBounds.location();
RefPtr<cairo_t> context = adoptRef(cairo_create(m_backend->surface()));
GraphicsContext graphicsContext(context.get());
for (const auto& updateRect : updateInfo.updateRects) {
IntRect srcRect = updateRect;
srcRect.move(-updateRectLocation.x(), -updateRectLocation.y());
#if PLATFORM(GTK)
if (!m_webPageProxy.drawsBackground()) {
const WebCore::Color color = m_webPageProxy.backgroundColor();
if (!color.isOpaque())
graphicsContext.clearRect(srcRect);
if (color.isVisible())
graphicsContext.fillRect(srcRect, color);
}
if(m_paintCallback) {
const GdkPoint dstPoint_ = { updateRect.location().x(), updateRect.location().y() };
const GdkRectangle srcRect_ = { srcRect.x(), srcRect.y(), srcRect.width(), srcRect.height() };
const GdkRectangle srcSize_ = { 0, 0, bitmap->size().width(), bitmap->size().height() };
m_paintCallback((uint8_t *)bitmap->data(), deviceScaleFactor(), dstPoint_, srcSize_, srcRect_);
}
#endif
bitmap->paint(graphicsContext, deviceScaleFactor(), updateRect.location(), srcRect);
}
}
void BackingStore::scroll(const IntRect& scrollRect, const IntSize& scrollOffset)
{
if (scrollOffset.isZero())
return;
ASSERT(m_backend);
m_backend->scroll(scrollRect, scrollOffset);
}
} // namespace WebKit
| [
"[email protected]"
] | |
e813dda94ab921072998364825e1f469d8818763 | 1160e42d7e740ccb58d7fac8dee66598226a205f | /sw/puzzle_main/loops2.ino | d2d4e773f55df257da6c963dc58e51e1a9140db7 | [] | no_license | byuccl/ICEBoard | 528d334b7509163b85d0063a3f9bac1e440ce7a3 | fd87b05e6c009b2e932abfab5c7d8dc7b913d017 | refs/heads/master | 2022-12-14T13:25:30.815069 | 2020-09-13T06:10:04 | 2020-09-13T06:10:04 | 228,904,194 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 913 | ino | #include "puzzles.h"
#include "iceBoard.h"
void loops2()
{
while (digitalRead(BC_PIN))
;
int x = 0;
leds.setPixelColor(LED1, GREEN);
leds.show();
while (x < 10)
{
while (!digitalRead(BC_PIN))
;
while (digitalRead(BC_PIN))
;
lcd.clear();
lcd.print("X is ");
lcd.print(x);
leds.setPixelColor(LED2, leds.getPixelColor(LED3));
leds.setPixelColor(LED3, leds.getPixelColor(LED4));
leds.setPixelColor(LED4, leds.getPixelColor(LED8));
leds.setPixelColor(LED8, leds.getPixelColor(LED7));
leds.setPixelColor(LED7, leds.getPixelColor(LED6));
leds.setPixelColor(LED6, leds.getPixelColor(LED5));
leds.setPixelColor(LED5, leds.getPixelColor(LED1));
leds.setPixelColor(LED1, leds.getPixelColor(LED2));
leds.show();
x++;
}
puzzle_done();
} | [
"[email protected]"
] | |
941bc382144536ff7435797ea4fc64e10dc7efae | 3649927ff70326ed8d2cd0872459c41dd34eb52f | /CD77_Halloween_Fun_2019/CD77_Halloween_Fun_2019.ino | b88453c536b74ab9b4ed08720e8cd04d79a6661a | [] | no_license | kkonstantin42/CD77_FastLED | aa1d78de8f13dcbc07bd523750ffc87dad4b837f | 152b582cc4eddacce1d817bd6bbbe7be2b83c03f | refs/heads/master | 2023-05-06T19:37:46.886755 | 2021-05-31T23:10:00 | 2021-05-31T23:10:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,212 | ino | /*
CD77_Halloween_Fun_2019 by Chemdoc77
Based by code from different sources.
See each tab for the sources.
*/
#include <FastLED.h>
#define LED_PIN 6
#define CHIPSET NEOPIXEL
#define NUM_LEDS 90
#define BRIGHTNESS 200
//Time Performance code
uint32_t gTimeCodeBase = 0;
uint32_t gTimeCode = 0;
uint32_t gLastTimeCodeDoneAt = 0;
uint32_t gLastTimeCodeDoneFrom = 0;
//=================
CRGB leds[NUM_LEDS];
//Fire2012withPalette stuff
CRGBPalette16 gPal;
#define FRAMES_PER_SECOND 60
bool gReverseDirection = false;
//========================
#include "Halloween_chase.h"
#include "Fire2012withPalette.h"
#include "Flicker.h"
#include "Time_performance.h"
void setup() {
delay(1000); // sanity delay
FastLED.addLeds<CHIPSET, LED_PIN>(leds, NUM_LEDS);
FastLED.setBrightness( BRIGHTNESS );
//Fire2012withPalette stuff
gPal = HeatColors_p;
FastLED.setMaxPowerInVoltsAndMilliamps(5,7500);
set_max_power_indicator_LED(13);
fill_solid(leds, NUM_LEDS, CRGB::Black);
FastLED.show();
//Time Performance code
RestartPerformance();
}
//============================================
void loop() {
//Time Performance code
gTimeCode = millis() - gTimeCodeBase;
Performance5();
}
| [
"[email protected]"
] | |
a3d15a791c68de6b31271918d502f397c5826116 | a1809f8abdb7d0d5bbf847b076df207400e7b08a | /Simpsons Hit&Run/game/libs/sim/simcollision/collisionanalysertranslator.hpp | f5c541ed4c6f1b4a82d56db6876dabe74a7777a2 | [] | no_license | RolphWoggom/shr.tar | 556cca3ff89fff3ff46a77b32a16bebca85acabf | 147796d55e69f490fb001f8cbdb9bf7de9e556ad | refs/heads/master | 2023-07-03T19:15:13.649803 | 2021-08-27T22:24:13 | 2021-08-27T22:24:13 | 400,380,551 | 8 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 977 | hpp | #ifndef _COLLISIONANALYSERTRANSLATOR_HPP_
#define _COLLISIONANALYSERTRANSLATOR_HPP_
#include "simcollision/collisionanalyserinfo.hpp"
#include "simcollision/collisionanalyserdata.hpp"
namespace sim
{
class CollisionAnalyserTranslator {
public:
static float GetCheapBounceSoundVolume(CollisionAnalyserData &data, CollisionAnalyserInfo &info);
static float GetBounceSoundVolume(CollisionAnalyserData &data, CollisionAnalyserInfo &info);
static float GetSlidingSoundVolume(CollisionAnalyserData &data, CollisionAnalyserInfo &info);
static float GetRollingASoundVolume(CollisionAnalyserData &data, CollisionAnalyserInfo &info);
static float GetRollingBSoundVolume(CollisionAnalyserData &data, CollisionAnalyserInfo &info);
static float GetSpinningASoundVolume(CollisionAnalyserData &data, CollisionAnalyserInfo &info);
static float GetSpinningBSoundVolume(CollisionAnalyserData &data, CollisionAnalyserInfo &info);
};
}
#endif | [
"[email protected]"
] | |
b639b268219c8d2644f4666794d8dfcb3509ce24 | fcc7a2d6914f839c56c20a5c26f3237847347c08 | /CApp/CInterfaceLoot.h | b0e6b49bfd4c2f5a210e97c04b559cbda55748bf | [] | no_license | SCRAPPYDOO/GameEngine | 2cbe376851847372be2bfe9fcac929d4e4711451 | 41eb8ed853888538890c9ef1de6bd989a4397345 | refs/heads/master | 2021-01-13T09:51:11.088984 | 2011-12-23T04:41:11 | 2011-12-23T04:41:11 | 1,931,783 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 614 | h | #ifndef _CINTERFACELOOT_H_
#define _CINTERFACELOOT_H_
#include "CInterface.h"
struct Loot
{
int nGuid; //Guid of unit
std::vector <int> UnitLootList;
};
class CInterfaceLoot : public CInterface
{
public:
CInterfaceLoot();
CInterfaceLoot(int nGuid, int nID);
~CInterfaceLoot() {}
public:
bool OnLoad();
void OnLoop();
void OnRender(SDL_Surface* Surf_Display);
void OnCleanup();
void OnButtonActivate(ButtonType Type);
void LoadLoot(int nGuid, int nID);
private:
std::vector <int> LootBoxList;
std::vector <Loot> LootListHandler;
};
#endif
| [
"[email protected]"
] | |
748793d127167a76a294c657294cd66921da7305 | 5896ed2b1fad13132057a76d17c95991c430c476 | /26 infinite continue fraction.cpp | 95556b08fb94a3906d25fc8a6b04ae7d122216d7 | [
"MIT"
] | permissive | adelacvg/PE | c1e51c11927299f5f86d55a12beb35eb38bca860 | 0345335a3f959342625be03ae36a21bbad45f273 | refs/heads/master | 2021-08-26T00:18:19.423054 | 2021-08-12T10:40:17 | 2021-08-12T10:40:17 | 156,980,203 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 605 | cpp | #include<bits/stdc++.h>
using namespace std;
string f(int num, int den)
{
string res;
map<int,int> m;
m.clear();
int rem = num%den;
while(rem&&m.find(rem) == m.end())
{
m[rem] = res.length();
rem *= 10;
res += to_string(rem / den);
rem %= den;
}
return (rem==0)?"":res.substr(m[rem]);
}
int main()
{
string ss;
int ans,mx=0;
for(int i=1;i<=1000;i++)
{
ss=f(1,i);
if(ss.length()>mx)
{
ans=i;
int len = ss.length();
mx=max(len,mx);
}
}
cout<<ans;
}
| [
"[email protected]"
] | |
a67d8c04398f8a84b9a6caa9d8fe96d431bf31cc | efda8165775d942b99ba42f65041474d602fe991 | /src/test_union_find.cpp | 371e7a0e6988756ab79ed550c95030e4f7c173fc | [] | no_license | surpass007/algorithm_collection | eab25a1ed41f63ebfd7ae70e18a86dfa5d260d9a | c9517f605858dfca782e9b0724e958b7ef77fdd5 | refs/heads/master | 2023-01-12T05:22:04.618498 | 2020-11-13T08:48:28 | 2020-11-13T08:53:43 | 312,514,944 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 54 | cpp |
#include "union_find.h"
int main() {
return 0;
} | [
"[email protected]"
] | |
6bcfd731b74f651444d02b1e3a7503ec2281af3a | b8499de1a793500b47f36e85828f997e3954e570 | /v2_3/build/Android/Debug/app/src/main/include/Fuse.Controls.Path.h | db7f888e11f82971b6edbb2b9a67c85145c2eaaa | [] | no_license | shrivaibhav/boysinbits | 37ccb707340a14f31bd57ea92b7b7ddc4859e989 | 04bb707691587b253abaac064317715adb9a9fe5 | refs/heads/master | 2020-03-24T05:22:21.998732 | 2018-07-26T20:06:00 | 2018-07-26T20:06:00 | 142,485,250 | 0 | 0 | null | 2018-07-26T20:03:22 | 2018-07-26T19:30:12 | C++ | UTF-8 | C++ | false | false | 3,084 | h | // This file was generated based on C:/Users/Vaibhav/AppData/Local/Fusetools/Packages/Fuse.Controls.Primitives/1.9.0/Shapes/Path.Surface.uno.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Fuse.Animations.IResize.h>
#include <Fuse.Binding.h>
#include <Fuse.Controls.SegmentedShape.h>
#include <Fuse.Drawing.IDrawObj-d34d045e.h>
#include <Fuse.Drawing.ISurfaceDrawable.h>
#include <Fuse.Drawing.LineSegment.h>
#include <Fuse.IActualPlacement.h>
#include <Fuse.INotifyUnrooted.h>
#include <Fuse.IProperties.h>
#include <Fuse.ISourceLocation.h>
#include <Fuse.ITemplateSource.h>
#include <Fuse.Node.h>
#include <Fuse.Scripting.IScriptObject.h>
#include <Fuse.Triggers.Actions.IHide.h>
#include <Fuse.Triggers.Actions.IShow.h>
#include <Fuse.Triggers.Actions-ea70af1f.h>
#include <Fuse.Visual.h>
#include <Uno.Collections.ICollection-1.h>
#include <Uno.Collections.IEnumerable-1.h>
#include <Uno.Collections.IList-1.h>
#include <Uno.Float4.h>
#include <Uno.UX.IPropertyListener.h>
namespace g{namespace Fuse{namespace Controls{struct Path;}}}
namespace g{namespace Fuse{namespace Controls{struct Path__Positioning;}}}
namespace g{namespace Fuse{namespace Internal{struct SizingContainer;}}}
namespace g{namespace Fuse{struct LayoutParams;}}
namespace g{namespace Uno{namespace Collections{struct List;}}}
namespace g{namespace Uno{struct Float2;}}
namespace g{namespace Uno{struct Rect;}}
namespace g{
namespace Fuse{
namespace Controls{
// public partial sealed class Path :8
// {
::g::Fuse::Controls::SegmentedShape_type* Path_typeof();
void Path__CalcNaturalExtents_fn(Path* __this, ::g::Uno::Rect* __retval);
void Path__CalcPositioning_fn(Path* __this, Path__Positioning* __retval);
void Path__CalcShapeExtents_fn(Path* __this, ::g::Uno::Rect* __retval);
void Path__get_Extents_fn(Path* __this, ::g::Uno::Float4* __retval);
void Path__set_Extents_fn(Path* __this, ::g::Uno::Float4* value);
void Path__get_FitMode_fn(Path* __this, int32_t* __retval);
void Path__set_FitMode_fn(Path* __this, int32_t* value);
void Path__GetContentSize_fn(Path* __this, ::g::Fuse::LayoutParams* lp, ::g::Uno::Float2* __retval);
void Path__GetDesiredContentSize_fn(Path* __this, ::g::Uno::Float2* __retval);
void Path__GetSegments_fn(Path* __this, uObject** __retval);
void Path__InvalidateSurfacePath_fn(Path* __this);
void Path__OnShapeLayoutChanged_fn(Path* __this);
void Path__get_Sizing_fn(Path* __this, ::g::Fuse::Internal::SizingContainer** __retval);
struct Path : ::g::Fuse::Controls::SegmentedShape
{
uStrong< ::g::Uno::Collections::List*> _segments1;
uStrong< ::g::Fuse::Internal::SizingContainer*> sizing;
int32_t _fitMode;
::g::Uno::Float4 _extents;
::g::Uno::Rect CalcNaturalExtents();
Path__Positioning CalcPositioning();
::g::Uno::Float4 Extents();
void Extents(::g::Uno::Float4 value);
int32_t FitMode();
void FitMode(int32_t value);
::g::Uno::Float2 GetDesiredContentSize();
void OnShapeLayoutChanged();
::g::Fuse::Internal::SizingContainer* Sizing();
};
// }
}}} // ::g::Fuse::Controls
| [
"[email protected]"
] | |
5969f57a59c2a56328a6d85947e941625435f8d7 | ea8ba7cfc4f4773ed516e094ded4bc36502f93b5 | /branch/old_angsys/angsys_beta3/source/angsys/angsys.desktop/pch.cpp | 300f290acaf9391bc795c5952dc48511665bda44 | [
"Apache-2.0"
] | permissive | ChuyX3/angsys | 15f896f0b4823b63a14aff8e35a30f344f2c30e8 | 89b2eaee866bcfd11e66efda49b38acc7468c780 | refs/heads/master | 2021-07-07T18:58:39.437477 | 2020-06-29T05:33:08 | 2020-06-29T05:33:08 | 92,321,439 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 290 | cpp | // stdafx.cpp : source file that includes just the standard includes
// angsys.desktop.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "pch.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| [
"[email protected]"
] | |
cfa2883b28715fc678268e1df2e82f2a02370e72 | 19c8acfcf3e01c638049ffebb92759b65ce8ab4a | /C语言/34.cpp | d4d3c343a0c243c15a995dbcd56c6663ee02c930 | [] | no_license | VestigesH/GH | c66a8fcf1a7fcfa2f76d6b0f4d22f8c4d0052d5d | 68f40a8bd545c262ce33f539658e6c3b5566ebeb | refs/heads/master | 2020-04-15T17:11:22.479870 | 2019-07-08T05:29:37 | 2019-07-08T05:29:37 | 164,864,719 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 916 | cpp | //题目:给一个不多于5位的正整数,要求:一、求它是几位数,二、逆序打印出各位数字。
#include <stdio.h>
int main()
{
int g,s,b,q,w;
long x;
printf("请输入不多于五位的正整数x:");
scanf("%ld",&x);
if (x<0||x>100000)
{
printf("输入错误\n");
return 0;
}
else if (0<x<=99999)
{
w=x/10000;
q=x/1000%10;
b=x/100%10;
s=x/10%10;
g=x%10;
if(w!=0)
{
printf("五位数\n");
printf("逆序打印:%d%d%d%d%d",g,s,b,q,w);
}
else if(w==0&&q!=0)
{
printf("四位数\n");
printf("逆序打印:%d%d%d%d",g,s,b,q);
}
else if(w==0&&q==0&&b!=0)
{
printf("三位数\n");
printf("逆序打印:%d%d%d",g,s,b);
}
else if(w==0&&q==0&&b==0&&s!=0)
{
printf("两位数\n");
printf("逆序打印:%d%d",g,s);
}
else if(w==0&&q==0&&b==0&&s==0&&g!=0)
{
printf("一位数\n");
printf("逆序打印:%d",x);
}
}
}
| [
"[email protected]"
] | |
d682d29c7241187bf2430acc2e5048229fa9c1c4 | 4d5f2cdc0b7120f74ba6f357b21dac063e71b606 | /star-ots/include/CosTransactionsPolicyType_skel.h | f03413c88054b08f768ebcaf4ef51a0bd4b6b172 | [
"BSD-2-Clause"
] | permissive | anjingbin/starccm | cf499238ceb1e4f0235421cb6f3cb823b932a2cd | 70db48004aa20bbb82cc24de80802b40c7024eff | refs/heads/master | 2021-01-11T19:49:04.306906 | 2017-01-19T02:02:50 | 2017-01-19T02:02:50 | 79,404,002 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 717 | h | // *************************************************************************
//
// This File Is Automatically Generated by the StarBusIDL-to-C++ Compiler !
//
// Copyright (c) 2003
// Network Information Security Institute,Computer College,NUDT.
// ChangSha,Hunan,PRC
//
// All Rights Reserved
//
// *************************************************************************
// Version: 5.0.0
#ifndef ___CosTransactionsPolicyType_skel_h__
#define ___CosTransactionsPolicyType_skel_h__
#include <CosTransactionsPolicyType.h>
#include <STAR/SkelForServerRequest.h>
#include <STAR/Policy.h>
//
// Module declare ::CosTransactions
//
namespace POA_CosTransactions
{
} // End of namespace POA_CosTransactions
#endif
| [
"[email protected]"
] | |
a419e26df65ca00a8627265b21ae8041582054f6 | 3d82ef9da7d1216c5ab14de2176f8b2c8340d610 | /src/cpp_share/util/def_mpir.h | 7b624faf331de8037f07eb6f668803e30ce8596e | [] | no_license | yeojinyeojin/e3 | 6d2d81fbbf3fcf1fe61e8ddc1deba1bb967f6058 | 0cf8fe9bdd853b9b2fc9bc6f24a96e7e25500c2f | refs/heads/master | 2022-02-16T06:39:21.936947 | 2019-09-02T12:32:16 | 2019-09-02T12:32:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,115 | h | #ifndef _E3_DEF_MPIR_H_
#define _E3_DEF_MPIR_H_
#include <string>
#include <memory>
#include <istream>
#include <ostream>
using std::string;
// FIXME add e3 namespace for all classes
int mpir_impl(); // 0 or 1
struct BigunNative;
class Bigun
{
std::shared_ptr<BigunNative> p;
using ull = unsigned long long;
public:
Bigun( ull = 0 );
Bigun(string x);
Bigun(const Bigun & a);
Bigun & operator=(const Bigun & a);
Bigun(Bigun && a);
Bigun & operator=(Bigun && a);
static int maxbitsz();
string str() const;
Bigun powmod(Bigun x, Bigun m) const;
Bigun addmod(Bigun x, Bigun m) const;
Bigun submod(Bigun x, Bigun m) const;
Bigun mulmod(Bigun x, Bigun m) const;
friend std::istream & operator>>(std::istream & is, Bigun & x);
friend std::ostream & operator<<(std::ostream & os, const Bigun & x) { return os << x.str(); }
Bigun & operator+=(const Bigun & a);
Bigun & operator-=(const Bigun & a);
Bigun & operator*=(const Bigun & a);
Bigun & operator/=(const Bigun & a);
Bigun & operator%=(const Bigun & a);
Bigun & operator&=(const Bigun & a);
Bigun & operator|=(const Bigun & a);
Bigun & operator^=(const Bigun & a);
Bigun & operator<<=(const Bigun & a);
Bigun & operator>>=(const Bigun & a);
Bigun operator++();
Bigun operator++(int);
Bigun operator--();
Bigun operator--(int);
Bigun operator+(const Bigun & a) const { Bigun r(*this); return r += a; }
Bigun operator-(const Bigun & a) const { Bigun r(*this); return r -= a; }
Bigun operator*(const Bigun & a) const { Bigun r(*this); return r *= a; }
Bigun operator/(const Bigun & a) const { Bigun r(*this); return r /= a; }
Bigun operator%(const Bigun & a) const { Bigun r(*this); return r %= a; }
Bigun operator&(const Bigun & a) const;
Bigun operator|(const Bigun & a) const { Bigun r(*this); return r |= a; }
Bigun operator^(const Bigun & a) const;
Bigun operator<<(const Bigun & a) const { Bigun r(*this); return r <<= a; }
Bigun operator>>(const Bigun & a) const { Bigun r(*this); return r >>= a; }
Bigun operator~() const;
bool operator!() const { return (*this == Bigun(0)); }
bool operator==(const Bigun & a) const;
bool operator!=(const Bigun & a) const { return !(*this == a); }
bool operator<(const Bigun & a) const;
bool operator<=(const Bigun & a) const { return !(*this > a); }
bool operator>(const Bigun & a) const { return !(a < *this); }
bool operator>=(const Bigun & a) const { return !(*this < a); }
bool operator&&(const Bigun & a) const;
bool operator||(const Bigun & a) const;
friend Bigun operator+(ull a, const Bigun & b) { return b + a; }
friend Bigun operator-(ull a, const Bigun & b) { return b - a; }
friend Bigun operator*(ull a, const Bigun & b) { return b * a; }
};
#endif // _E3_DEF_MPIR_H_
| [
"[email protected]"
] | |
e60757135841792a6d0d2000d933e7c53369d0a0 | 0e456e7610169365ad5d0304701a4939cbf230ef | /gfg/must do interview que/heap/MinimumCostOfRopes.cpp | b2248883a3c699780c5abe916535e1150ba36cda | [] | no_license | rverma870/DSA-practice | 8674e75225fdb4396560e5d8cfd9c4a3fc6a3356 | f714d4887888dd774fa1c10192c59767074425e9 | refs/heads/main | 2023-06-11T02:12:52.447346 | 2021-06-19T17:16:32 | 2021-06-19T17:16:32 | 369,564,546 | 0 | 0 | null | 2021-05-21T14:54:53 | 2021-05-21T14:39:21 | C++ | UTF-8 | C++ | false | false | 518 | cpp | #include<bits/stdc++.h>
using namespace std;
long long minCost(long long arr[], long long n)
{
priority_queue<long long, vector<long long>, greater<long long>>q;
for(long long i=0;i<n;i++)
q.push(arr[i]);
long long ans=0;
while(q.size()>1)
{
long long x,y;
x=q.top();
q.pop();
y=q.top();
q.pop();
ans+=x+y;
q.push(x+y);
}
return ans;
}
int main()
{
long long n;
cin>>n;
long long arr[n];
for(long long i=0;i<n;i++)
cin>>arr[i];
cout<<minCost(arr,n);
}
| [
"[email protected]"
] | |
621bbddc72f315cf42356563b6a22cd9ae1ac172 | ce2b2f58bd4cefb19768abf47a16920bd0923953 | /register_types.cpp | b755c0d77e5223960307f62ef74c3a7e1037dc5d | [
"MIT"
] | permissive | resultant-gamedev/godot-debugdraw | 288462d0ae04f2dae4028cb4f1bdf3668afe9642 | dfc6277c4746182b6a6b84c40eea0e0779967361 | refs/heads/master | 2021-01-19T02:15:09.632876 | 2017-01-24T20:26:57 | 2017-01-24T20:26:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 478 | cpp | /* register_types.cpp */
#include <object_type_db.h>
#include <globals.h>
#include <print_string.h>
#include "register_types.h"
#include "debugdraw.h"
void register_debugdraw_types()
{
// initialize singleton
memnew(DebugDraw);
// register singleton
Globals::get_singleton()->add_singleton(Globals::Singleton("DebugDraw", DebugDraw::get_singleton()));
}
void unregister_debugdraw_types()
{
// free singleton
memdelete(DebugDraw::get_singleton());
}
| [
"[email protected]"
] | |
371ce4a22d1adb9029b8f15e4d0b9d531c6b4cc0 | eed7b94f96fcff5e706c4ab726f12ee60647d272 | /linefollowing_jessa3/linefollowing_jessa3.ino | 97954075dcf4a8925914070cc4d07d33e1370e33 | [] | no_license | jessamarie21/AER201-v2 | d7713d11106b912eebbf3428c1ff2494dec2c48c | bf2f06d0f6b4ff00769c9893299f49259188e1ee | refs/heads/master | 2021-04-30T06:43:50.178574 | 2018-02-14T00:13:40 | 2018-02-14T00:13:40 | 121,451,715 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,099 | ino | #include <Event.h>
#include <Timer.h>
#include <Servo.h>
Timer t;
int pin = 13; //servo pin
int left_pins[] = {7, 4};
int right_pins[] = {3, 2};
const int enable_2 = 6; //left motor
const int enable_1 = 5; //right motor
const int one_pin = A4; //this is actually what you think two pin is
const int two_pin = A1; //this is actually what you think one_pin is
const int three_pin = A2;
const int four_pin = A3;
const int five_pin = A0;
const int encod_pin = A5;
int one_val;
int two_val;
int three_val;
int four_val;
int five_val;
int encod_val;
int one_exp = 595;
int two_exp = 595;
int one_black = 490;
int two_black = 480;
int three_black = 720;
int four_black = 600;
int five_black = 580;
int encod_black;
Servo myServo; //function connected to Servo
int angle = 0; //angle for servo to go to
int up = 10;
int down = 120;
unsigned long time;
long turn360 = 7540 + 200;
long turn180 = turn360 / 2 + 200; // 1/2
long turn90 = turn360 / 4; // 1/4
long turn270 = turn360 * 3 / 4; // 3/4
long one_sec = 1000;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(pin, OUTPUT);
t.every(7000, main_function);
for (int i = 0; i < 2; i++)
{
pinMode(left_pins[i], OUTPUT);
pinMode(right_pins[i], OUTPUT);
}
pick_up(up);
delay(1000);
}
void loop() {
// put your main code here, to run repeatedly:
t.update();
//gtest();
//align();
//Turn_left_off(75,75);
//Turn_left_off2(100,100);
//Turn_right_off(75,75);
//Turn_right_off2(75,75);
//Serial.println("straight");
}
void align()
{
one_val = analogRead(one_pin); //right
two_val = analogRead(two_pin); //left
//Serial.print(one_val);
//Serial.print(" ");
//Serial.println(two_val);
//these error values get larger the darker the sensor get because they get farther and farther from the expected value
//50 is just a number to scale down the errors so they can be added to the pwms
int r_error = (one_exp - one_val);
int l_error = (two_exp - two_val);
Serial.print(r_error);
Serial.print(" ");
Serial.println(l_error);
do
{
if (l_error > r_error)
{
Turn_left_off2(85, 85);
delay(500);
}
else
{
Turn_right_off2(85, 85);
delay(500);
}
one_val = analogRead(one_pin); //right
two_val = analogRead(two_pin); //left
r_error = abs(one_exp - one_val);
l_error = abs(two_exp - two_val);
Serial.print(r_error);
Serial.print(" ");
Serial.println(l_error);
} while (abs(l_error - r_error) >= 25);
}
void main_function()
{
/*plinetest(1);
chill(one_sec);
Turning_left();
chill(one_sec);*/
plinetest(1);
chill(one_sec);
Turning_right();
chill(one_sec);
plinetest(1);
chill(one_sec);
/*Turning_right();
chill(one_sec);
plinetest(1);
chill(one_sec);*/
//Turning_right_180();
//chill(one_sec);
STOPFOREVER(1);
}
void turn(int dir, long angle) //1 left, 0 right
{
time = millis();
bool one_hit_black = false;
bool two_hit_black = false;
Serial.println("Turning");
while(millis() - time < 500)
{
if(dir)
{
Turn_left_off2(100, 100);
}
else
{
Turn_right_off2(100, 100);
}
}
int time1 = millis();
while (millis() - time1 < angle)
{
if (dir)
{
Turn_left_off2(100, 100);
two_val = analogRead(two_pin);
one_val = analogRead(one_pin);
Serial.println(two_val);
if (two_val < two_black)
{
long time2 = millis();
if(angle == turn180)
{
while(millis() - time2 < 150)
{
angle = turn90;
Turn_left_off2(100, 100);
two_val = analogRead(two_pin);
one_val = analogRead(one_pin);
}
continue;
}
two_hit_black = true;
}
else if (one_val < one_exp && two_hit_black)
{
Serial.println("not timer two");
Serial.println(two_hit_black);
break;
}
}
else
{
Turn_right_off2(100, 100);
one_val = analogRead(one_pin);
two_val = analogRead(two_pin);
Serial.println(one_val);
if (one_val < one_black)
{
if(angle == turn180)
{
long time2 = millis();
while(millis() - time2 < 150)
{
angle = turn90;
Turn_right_off2(100, 100);
two_val = analogRead(two_pin);
one_val = analogRead(one_pin);
}
continue;
}
one_hit_black = true;
}
else if (two_val < two_exp && one_hit_black)
{
Serial.println("not timer one");
break;
}
}
}
two_val = analogRead(two_pin);
while(two_val < two_black)
{
Turn_right_off2(85,85);
one_val = analogRead(one_pin);
two_val = analogRead(two_pin);
if(one_val == one_exp && two_val == two_exp)
{
Serial.println("aligned two");
break;
}
}
one_val = analogRead(one_pin);
while(one_val < one_black)
{
Turn_left_off2(85,85);
one_val = analogRead(one_pin);
two_val = analogRead(two_pin);
if(one_val == one_exp && two_val == two_exp)
{
Serial.println("aligned one");
break;
}
}
Serial.println("Stopping");
}
void chill(long len)
{ time = millis();
while (millis() - time < len)
{
STOP();
}
}
void gtest() {
one_val = analogRead(one_pin);
two_val = analogRead(two_pin);
three_val = analogRead(three_pin);
four_val = analogRead(four_pin);
five_val = analogRead(five_pin);
encod_val = analogRead(encod_pin);
Serial.println("|ONE |TWO |THREE |FOUR |FIVE |ENC |");
Serial.print(" ");
Serial.print(one_val);
Serial.print(" ");
Serial.print(two_val);
Serial.print(" ");
Serial.print(three_val);
Serial.print(" ");
Serial.print(four_val);
Serial.print(" ");
Serial.print(five_val);
Serial.print(" ");
Serial.println(encod_val);
delay(5000);
}
//drives both motors forwards at different pwm
//lower number is the direction it will turn in
//rpwm = right motor
//lpwm = left motor
void Drive_fwd(int rpwm, int lpwm)
{
//Serial.println("Driving Forward");
analogWrite(enable_1, rpwm);
analogWrite(enable_2, lpwm);
digitalWrite(left_pins[0], LOW);
digitalWrite(left_pins[1], HIGH);
digitalWrite(right_pins[0], LOW);
digitalWrite(right_pins[1], HIGH);
}
void Drive_bwd(int rpwm, int lpwm)
{
//Serial.println("Driving Backward");
analogWrite(enable_1, rpwm);
analogWrite(enable_2, lpwm);
digitalWrite(left_pins[0], HIGH);
digitalWrite(left_pins[1], LOW);
digitalWrite(right_pins[0], HIGH);
digitalWrite(right_pins[1], LOW);
}
//turns robot left
//right wheel is off
void Turn_left_off(int rpwm, int lpwm)
{
//Serial.println("Driving Forward");
analogWrite(enable_1, rpwm);
analogWrite(enable_2, lpwm);
digitalWrite(left_pins[0], LOW);
digitalWrite(left_pins[1], LOW);
digitalWrite(right_pins[0], HIGH);
digitalWrite(right_pins[1], LOW);
}
//turns robot left
//both wheels on
void Turn_left_off2(int rpwm, int lpwm)
{
//Serial.println("Driving Forward");
analogWrite(enable_1, rpwm);
analogWrite(enable_2, lpwm);
digitalWrite(left_pins[0], LOW);
digitalWrite(left_pins[1], HIGH);
digitalWrite(right_pins[0], HIGH);
digitalWrite(right_pins[1], LOW);
}
//turns robot right
//left wheel is off
void Turn_right_off(int rpwm, int lpwm)
{
//Serial.println("Driving Forward");
analogWrite(enable_1, rpwm);
analogWrite(enable_2, lpwm);
digitalWrite(left_pins[0], HIGH);
digitalWrite(left_pins[1], LOW);
digitalWrite(right_pins[0], LOW);
digitalWrite(right_pins[1], LOW);
}
//turns robot right
//both wheels on
void Turn_right_off2(int rpwm, int lpwm)
{
//Serial.println("Driving Forward");
analogWrite(enable_1, rpwm);
analogWrite(enable_2, lpwm);
digitalWrite(left_pins[0], HIGH);
digitalWrite(left_pins[1], LOW);
digitalWrite(right_pins[0], LOW);
digitalWrite(right_pins[1], HIGH);
}
//stops both motors
void STOP()
{
//Serial.println("STOPPING!");
analogWrite(enable_1, 0);
analogWrite(enable_2, 0);
digitalWrite(left_pins[0], LOW);
digitalWrite(left_pins[1], LOW);
digitalWrite(right_pins[0], LOW);
digitalWrite(right_pins[1], LOW);
}
//stops both motors forever
void STOPFOREVER(int cond)
{
//infinite loop
while (cond)
STOP();
}
//new line following method
void plinetest(int lines)
{
int right_error[3] = {0,0,0};
int left_error[3] = {0,0,0};
int count = 0;
while (count < lines)
{
one_val = analogRead(one_pin); //right
two_val = analogRead(two_pin); //left
//Serial.print(one_val);
//Serial.print(" ");
//Serial.println(two_val);
//contasts that can be changed to increase the amount the robot tries to correct itself
int kpr = 2; //make this higher usually because for some reason this side never turns enough
int kpl = 1;
int ipr1 = 4;
int ipr2 = 4;
int ipl1 = 2;
int ipl2 = 2;
int rpwm = 100;
int lpwm = 100;
//these error values get larger the darker the sensor get because they get farther and farther from the expected value
//50 is just a number to scale down the errors so they can be added to the pwms
int r_error = (one_exp - one_val) / 50;
int l_error = (two_exp - two_val) / 50;
right_error[2] = right_error[1];
right_error[1] = right_error[0];
right_error[0] = r_error;
left_error[2] = left_error[1];
left_error[1] = left_error[0];
left_error[0] = l_error;
Serial.println("r_error || l_error");
Serial.print(r_error);
Serial.print(" ");
Serial.println(l_error);
//these are the corrected pwms
int r_corr = rpwm + kpr * r_error + right_error[1]*ipr1 + right_error[2]*ipr2;
int l_corr = lpwm + kpl * l_error + left_error[1]*ipl1 + left_error[2]*ipl2;
//Serial.print(l_corr);
//Serial.print(" ");
//Serial.println(r_corr);
Serial.println("r_corr");
Serial.println(r_corr);
Serial.println("l_corr");
Serial.println(l_corr);
Drive_fwd(l_corr, r_corr); //drives motors at the corrected pwm
//check if you cross line perpendicularly
three_val = analogRead(three_pin);
four_val = analogRead(four_pin);
if (four_val < four_black || three_val < three_black) //if either sensor four or three hit black (values from gtest)
{
Serial.print("Crossed line: ");
counting();
count++;
}
delay(100);
}
}
//method is used to count how many perpendicular lines we crossed
void counting()
{
int rlc = 0;
bool three_w = false; //set to true only when sensor three hits white again
bool four_w = false; //set to true only when sensor four hits black again
//you can only escape this while loop when both sensors hit white again
//this takes care of the lacalite hitting a perpendicular line at an angle
while (three_w == false || four_w == false)
{
three_val = analogRead(three_pin);
four_val = analogRead(four_pin);
//Serial.print(three_val);
//Serial.print(" ");
//Serial.println(four_val);
if (three_val > three_black)
{
three_w = true;
}
if (four_val > four_black)
{
four_w = true;
}
delay(50);
}
Serial.println("out of while");
//add 1 to line counter
rlc++;
//Serial.println(rlc);
}
void pick_up(int angle)
{
myServo.attach(9);
myServo.write(angle);
return;
}
void Turning_left()
{
four_val = analogRead(four_pin);
while(four_val > four_black)
{
Serial.println("four");
Turn_left_off2(100,100);
four_val = analogRead(four_pin);
}
three_val = analogRead(three_pin);
while(three_val > three_black)
{
Serial.println("three");
Turn_left_off2(100,100);
three_val = analogRead(three_pin);
two_val = analogRead(two_pin);
if(two_val < two_black)
{
Serial.println("break");
break;
}
}
one_val = analogRead(one_pin);
two_val = analogRead(two_pin);
while(two_val < two_black)
{
Turn_left_off2(100,100);
one_val = analogRead(one_pin);
two_val = analogRead(two_pin);
if(one_val == one_exp && two_val == two_exp)
{
Serial.println("align");
break;
}
}
}
void Turning_right()
{
three_val = analogRead(three_pin);
while(three_val > three_black)
{
Serial.println("three");
Turn_left_off2(100,100);
three_val = analogRead(three_pin);
}
four_val = analogRead(four_pin);
while(four_val > four_black)
{
Serial.println("four");
Turn_left_off2(100,100);
three_val = analogRead(three_pin);
one_val = analogRead(one_pin);
if(one_val < one_black)
{
Serial.println("break");
break;
}
}
one_val = analogRead(one_pin);
two_val = analogRead(two_pin);
while(one_val < one_black)
{
Turn_left_off2(100,100);
one_val = analogRead(one_pin);
two_val = analogRead(two_pin);
if(two_val == two_exp && one_val == one_exp)
{
Serial.println("align");
break;
}
}
}
void Turning_left_180()
{
four_val = analogRead(four_pin);
while(four_val > four_black)
{
Turn_left_off2(100,100);
four_val = analogRead(four_pin);
}
four_val = analogRead(four_pin);
while(four_val <= four_black)
{
Turn_left_off2(100,100);
four_val = analogRead(four_pin);
}
four_val = analogRead(four_pin);
while(four_val > four_black)
{
Turn_left_off2(100,100);
four_val = analogRead(four_pin);
}
four_val = analogRead(four_pin);
while(four_val <= four_black)
{
Turn_left_off2(100,100);
four_val = analogRead(four_pin);
}
while(four_val > four_black)
{
Turn_left_off2(100,100);
four_val = analogRead(four_pin);
two_val = analogRead(two_pin);
if(two_val < two_black)
{
break;
}
}
one_val = analogRead(one_pin);
two_val = analogRead(two_pin);
while(two_val < two_black)
{
Turn_left_off2(100,100);
one_val = analogRead(one_pin);
two_val = analogRead(two_pin);
if(one_val == one_exp && two_val == two_exp)
{
break;
}
}
}
void Turning_right_180()
{
three_val = analogRead(three_pin);
while(three_val > three_black)
{
Turn_right_off2(100,100);
three_val = analogRead(three_pin);
}
four_val = analogRead(four_pin);
while(four_val > four_black)
{
Turn_right_off2(100,100);
four_val = analogRead(four_pin);
}
three_val = analogRead(three_pin);
while(three_val > three_black)
{
Turn_right_off2(100,100);
three_val = analogRead(three_pin);
}
while(four_val > four_black)
{
Turn_right_off2(100,100);
four_val = analogRead(four_pin);
one_val = analogRead(one_pin);
if(one_val < one_black)
{
break;
}
}
one_val = analogRead(one_pin);
two_val = analogRead(two_pin);
while(one_val < one_black)
{
Turn_right_off2(100,100);
one_val = analogRead(one_pin);
two_val = analogRead(two_pin);
if(one_val == one_exp && two_val == two_exp)
{
break;
}
}
}
| [
"[email protected]"
] | |
9b0d7b9523fa4779567433a929f0cb1ffb177b57 | 2ae0b8d95d439ccfd55ea7933ad4a2994ad0f6c5 | /src/plugins/template/tests/functional/op_reference/avg_pool.cpp | ba97db25396a975a5c847f908b53a7302670792f | [
"Apache-2.0"
] | permissive | openvinotoolkit/openvino | 38ea745a247887a4e14580dbc9fc68005e2149f9 | e4bed7a31c9f00d8afbfcabee3f64f55496ae56a | refs/heads/master | 2023-08-18T03:47:44.572979 | 2023-08-17T21:24:59 | 2023-08-17T21:24:59 | 153,097,643 | 3,953 | 1,492 | Apache-2.0 | 2023-09-14T21:42:24 | 2018-10-15T10:54:40 | C++ | UTF-8 | C++ | false | false | 10,716 | cpp | // Copyright (C) 2018-2023 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include <gtest/gtest.h>
#include "base_reference_test.hpp"
#include "openvino/op/avg_pool.hpp"
using namespace ov;
using namespace reference_tests;
namespace {
struct AvgPoolParams {
template <class IT>
AvgPoolParams(const Shape& input_shape,
const Shape& output_shape,
const element::Type& input_type,
const element::Type& ouput_type,
const std::vector<IT>& input_values,
const std::vector<IT>& output_values,
const Strides& strides,
const Shape& pads_begin,
const Shape& pads_end,
const Shape& kernel,
const bool exclude_pad,
const op::RoundingType& rounding_type,
const op::PadType& pad_type)
: m_input_shape(input_shape),
m_output_shape(output_shape),
m_input_type(input_type),
m_output_type(ouput_type),
m_input_data(CreateTensor(input_type, input_values)),
m_expected_data(CreateTensor(ouput_type, output_values)),
m_strides(strides),
m_pads_begin(pads_begin),
m_pads_end(pads_end),
m_kernel(kernel),
m_exclude_pad(exclude_pad),
m_rounding_type(rounding_type),
m_pad_type(pad_type) {}
Shape m_input_shape;
Shape m_output_shape;
element::Type m_input_type;
element::Type m_output_type;
ov::Tensor m_input_data;
ov::Tensor m_expected_data;
Strides m_strides;
Shape m_pads_begin;
Shape m_pads_end;
Shape m_kernel;
bool m_exclude_pad;
op::RoundingType m_rounding_type;
op::PadType m_pad_type;
};
class ReferenceAvgPoolLayerTest : public testing::TestWithParam<AvgPoolParams>, public CommonReferenceTest {
public:
void SetUp() override {
auto params = GetParam();
function = CreateFunction(params.m_input_shape,
params.m_input_type,
params.m_strides,
params.m_pads_begin,
params.m_pads_end,
params.m_kernel,
params.m_exclude_pad,
params.m_rounding_type,
params.m_pad_type);
inputData = {params.m_input_data};
refOutData = {params.m_expected_data};
}
static std::string getTestCaseName(const testing::TestParamInfo<AvgPoolParams>& obj) {
auto params = obj.param;
std::ostringstream result;
result << "iShape=" << params.m_input_shape << "_";
result << "iType=" << params.m_input_type << "_";
result << "iShape=" << params.m_output_shape << "_";
result << "oType=" << params.m_output_type << "_";
result << "excludePad=" << params.m_exclude_pad << "_";
result << "roundingType=" << params.m_rounding_type << "_";
result << "padType=" << params.m_pad_type;
return result.str();
}
private:
static std::shared_ptr<Model> CreateFunction(const Shape& input_shape,
const element::Type& input_type,
const Strides& strides,
const Shape& pads_begin,
const Shape& pads_end,
const Shape& kernel,
const bool exclude_pad,
const op::RoundingType rounding_type,
const op::PadType pad_type) {
const auto in = std::make_shared<op::v0::Parameter>(input_type, input_shape);
const auto avgPool = std::make_shared<op::v1::AvgPool>(in,
strides,
pads_begin,
pads_end,
kernel,
exclude_pad,
rounding_type,
pad_type);
return std::make_shared<Model>(NodeVector{avgPool}, ParameterVector{in});
}
};
TEST_P(ReferenceAvgPoolLayerTest, AvgPoolWithHardcodedRefs) {
Exec();
}
template<typename T>
std::vector<T> getContinuousIncreasingValue(size_t elementSize, float step) {
std::vector<T> a(elementSize);
std::iota(std::begin(a), std::end(a), step);
return a;
}
template <element::Type_t IN_ET>
std::vector<AvgPoolParams> generateParamsForAvgPool() {
using T = typename element_type_traits<IN_ET>::value_type;
std::vector<AvgPoolParams> params{
AvgPoolParams(ov::Shape{1, 1, 3, 3},
ov::Shape{1, 1, 2, 2},
IN_ET,
IN_ET,
std::vector<T>{1, 2, 3, 4, 5, 6, 7, 8, 9},
std::vector<T>{3, 4, 6, 7},
Strides{1, 1},
Shape{0, 0},
Shape{0, 0},
Shape{2, 2},
true,
op::RoundingType::FLOOR,
op::PadType::NOTSET),
AvgPoolParams(ov::Shape{1, 1, 4, 4},
ov::Shape{1, 1, 2, 2},
IN_ET,
IN_ET,
std::vector<T>{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16},
std::vector<T>{6, 7, 10, 11},
Strides{1, 1},
Shape{0, 0},
Shape{0, 0},
Shape{3, 3},
true,
op::RoundingType::CEIL,
op::PadType::NOTSET),
AvgPoolParams(ov::Shape{1, 1, 2, 2},
ov::Shape{1, 1, 3, 3},
IN_ET,
IN_ET,
std::vector<T>{1, 2, 3, 4},
std::vector<T>{1, 1.5, 2, 2, 2.5, 3, 3, 3.5, 4},
Strides{1, 1},
Shape{1, 1},
Shape{1, 1},
Shape{2, 2},
true,
op::RoundingType::CEIL,
op::PadType::NOTSET),
AvgPoolParams(ov::Shape{1, 1, 1, 5},
ov::Shape{1, 1, 1, 3},
IN_ET,
IN_ET,
std::vector<T>{1, 2, 3, 4, 5},
std::vector<T>{1.5, 3, 4.5},
Strides{1, 2},
Shape{1, 1},
Shape{1, 1},
Shape{3, 3},
true,
op::RoundingType::CEIL,
op::PadType::EXPLICIT),
AvgPoolParams(ov::Shape{1, 1, 1, 5},
ov::Shape{1, 1, 1, 3},
IN_ET,
IN_ET,
std::vector<T>{2.5, 2, 12, 4, 5},
std::vector<T>{0.5, 2, 1},
Strides{1, 2},
Shape{1, 1},
Shape{1, 1},
Shape{3, 3},
false,
op::RoundingType::CEIL,
op::PadType::EXPLICIT),
AvgPoolParams(ov::Shape{1, 1, 3, 3},
ov::Shape{1, 1, 3, 3},
IN_ET,
IN_ET,
std::vector<T>{1, 2, 3, 4, 5, 6, 7, 8, 9},
std::vector<T>{3, 4, 2.25, 6, 7, 3.75, 3.75, 4.25, 2.25},
Strides{1, 1},
Shape{0, 0},
Shape{0, 0},
Shape{2, 2},
false,
op::RoundingType::CEIL,
op::PadType::SAME_UPPER),
AvgPoolParams(ov::Shape{1, 1, 3, 3},
ov::Shape{1, 1, 3, 3},
IN_ET,
IN_ET,
std::vector<T>{1, 2, 3, 4, 5, 6, 7, 8, 9},
std::vector<T>{0.25, 0.75, 1.25, 1.25, 3, 4, 2.75, 6, 7},
Strides{1, 1},
Shape{0, 0},
Shape{0, 0},
Shape{2, 2},
false,
op::RoundingType::CEIL,
op::PadType::SAME_LOWER),
AvgPoolParams(ov::Shape{1, 1, 2, 2, 2},
ov::Shape{1, 1, 2, 2, 1},
IN_ET,
IN_ET,
std::vector<T>{1, 2, 3, 4, 5, 6, 7, 8},
std::vector<T>{1.5, 3.5, 5.5, 7.5},
Strides{1, 1, 1},
Shape{0, 0, 0},
Shape{0, 0, 0},
Shape{1, 1, 2},
true,
op::RoundingType::CEIL,
op::PadType::VALID),
AvgPoolParams(ov::Shape{1, 1, 3, 3},
ov::Shape{1, 1, 3, 3},
IN_ET,
IN_ET,
getContinuousIncreasingValue<T>(1 * 1 * 3 * 3, 1),
std::vector<T>{1.0f, 2.5f, 0, 5.5f, 7.0f, 0, 0, 0, 0},
Strides{2, 2},
Shape{1, 1},
Shape{1, 1},
Shape{2, 2},
true,
op::RoundingType::CEIL,
op::PadType::NOTSET),
};
return params;
}
std::vector<AvgPoolParams> generateCombinedParamsForAvgPool() {
const std::vector<std::vector<AvgPoolParams>> allTypeParams{
generateParamsForAvgPool<element::Type_t::f32>(),
generateParamsForAvgPool<element::Type_t::f16>(),
generateParamsForAvgPool<element::Type_t::bf16>()
};
std::vector<AvgPoolParams> combinedParams;
for (const auto& params : allTypeParams) {
combinedParams.insert(combinedParams.end(), params.begin(), params.end());
}
return combinedParams;
}
INSTANTIATE_TEST_SUITE_P(
smoke_AvgPool_With_Hardcoded_Refs,
ReferenceAvgPoolLayerTest,
::testing::ValuesIn(generateCombinedParamsForAvgPool()),
ReferenceAvgPoolLayerTest::getTestCaseName);
} // namespace
| [
"[email protected]"
] | |
c017d136735df41fca07c9cf60f8b5ca9508e13d | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/CMake/CMake-gumtree/Kitware_CMake_repos_basic_block_block_15076.cpp | c57fc564c6913b99e9dfc08b2bd67bc9705eba89 | [] | 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 | 24 | cpp | (r != ERANGE)
break; | [
"[email protected]"
] | |
c2f33b10e58b37609a8c91d5f7e7cc3b0163ebbf | f9bf373f9f650c8f447c0abb58c89d6cc98e6d1a | /src/bm_sim/parser_error.cpp | f3b1c4df135a03f88cd6d4df04c0e2e38e8f84fe | [
"Apache-2.0"
] | permissive | riftadi/behavioral-model | 9af3ff02b0cba70215d5fd12bce1c24ffe25cf44 | 62c35021462a32de4ca479866ab63faeb2e28de3 | refs/heads/master | 2020-05-14T15:45:50.128759 | 2019-04-17T12:35:27 | 2019-04-17T12:35:27 | 160,981,407 | 1 | 0 | Apache-2.0 | 2019-04-05T20:36:15 | 2018-12-08T21:47:18 | C++ | UTF-8 | C++ | false | false | 3,431 | cpp | /* Copyright 2013-present Barefoot Networks, 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.
*/
/*
* Antonin Bas ([email protected])
*
*/
#include <bm/bm_sim/parser_error.h>
#include <algorithm> // for std::max_element
#include <cassert>
#include <string>
namespace bm {
constexpr ErrorCode::type_t ErrorCode::INVALID_V;
bool
ErrorCodeMap::add(const std::string &name, ErrorCode::type_t v) {
if (exists(name) || exists(v)) return false;
map_v_to_name[v] = name;
map_name_to_v[name] = v;
return true;
}
bool
ErrorCodeMap::exists(const std::string &name) const {
return map_name_to_v.find(name) != map_name_to_v.end();
}
bool
ErrorCodeMap::exists(ErrorCode::type_t v) const {
return map_v_to_name.find(v) != map_v_to_name.end();
}
void
ErrorCodeMap::add_core() {
using pair_type = decltype(map_v_to_name)::value_type;
auto max_p = std::max_element(
std::begin(map_v_to_name), std::end(map_v_to_name),
[] (const pair_type &p1, const pair_type &p2) {
return p1.first < p2.first;
});
auto max_v = (max_p == map_v_to_name.end()) ? 0 : (max_p->first + 1);
// TODO(antonin): write an iterator for Core enum class instead
for (const auto core : {Core::NoError, Core::PacketTooShort, Core::NoMatch,
Core::StackOutOfBounds, Core::HeaderTooShort,
Core::ParserTimeout}) {
auto name = core_to_name(core);
if (!exists(name)) add(name, max_v++);
}
}
ErrorCode
ErrorCodeMap::from_name(const std::string &name) const {
return ErrorCode(map_name_to_v.at(name));
}
ErrorCode
ErrorCodeMap::from_core(const Core &core) const {
return ErrorCode(map_name_to_v.at(core_to_name(core)));
}
const std::string &
ErrorCodeMap::to_name(const ErrorCode &code) const {
return map_v_to_name.at(code.v);
}
ErrorCodeMap
ErrorCodeMap::make_with_core() {
ErrorCodeMap error_codes;
error_codes.add_core();
return error_codes;
}
// could be constexpr in C++14
const char *
ErrorCodeMap::core_to_name(const Core &core) {
switch (core) {
case Core::NoError:
return "NoError";
case Core::PacketTooShort:
return "PacketTooShort";
case Core::NoMatch:
return "NoMatch";
case Core::StackOutOfBounds:
return "StackOutOfBounds";
case Core::HeaderTooShort:
return "HeaderTooShort";
case Core::ParserTimeout:
return "ParserTimeout";
}
// unreachable but gcc complains without it
assert(0);
return nullptr;
}
parser_exception_arch::parser_exception_arch(const ErrorCode &code)
: code(code) { }
ErrorCode
parser_exception_arch::get(const ErrorCodeMap &error_codes) const {
(void) error_codes;
return code;
}
parser_exception_core::parser_exception_core(ErrorCodeMap::Core core)
: core(core) { }
ErrorCode
parser_exception_core::get(const ErrorCodeMap &error_codes) const {
return error_codes.from_core(core);
}
} // namespace bm
| [
"[email protected]"
] | |
e4b07eebbec39e9abe39605e57c48eccd6fe6786 | 04b1803adb6653ecb7cb827c4f4aa616afacf629 | /chrome/browser/ui/android/infobars/near_oom_infobar.h | b647529044ff79d9d4da1a1b4b92d50a2b3b0ba0 | [
"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,494 | h | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_UI_ANDROID_INFOBARS_NEAR_OOM_INFOBAR_H_
#define CHROME_BROWSER_UI_ANDROID_INFOBARS_NEAR_OOM_INFOBAR_H_
#include "base/android/jni_android.h"
#include "base/android/scoped_java_ref.h"
#include "base/macros.h"
#include "chrome/browser/ui/android/infobars/infobar_android.h"
namespace content {
class WebContents;
}
class InterventionDelegate;
// Communicates to the user about the intervention performed by the browser to
// limit the page's memory usage. See NearOomInfoBar.java for UI specifics, and
// NearOomMessageDelegate for behavior specifics.
class NearOomInfoBar : public InfoBarAndroid {
public:
~NearOomInfoBar() override;
// |delegate| must remain alive while showing this info bar.
static void Show(content::WebContents* web_contents,
InterventionDelegate* delegate);
private:
explicit NearOomInfoBar(InterventionDelegate* delegate);
// InfoBarAndroid:
base::android::ScopedJavaLocalRef<jobject> CreateRenderInfoBar(
JNIEnv* env) override;
void OnLinkClicked(JNIEnv* env,
const base::android::JavaParamRef<jobject>& obj) override;
void ProcessButton(int action) override;
InterventionDelegate* delegate_;
DISALLOW_COPY_AND_ASSIGN(NearOomInfoBar);
};
#endif // CHROME_BROWSER_UI_ANDROID_INFOBARS_NEAR_OOM_INFOBAR_H_
| [
"[email protected]"
] | |
f3f80528e526dc1ecb376e31f46dd916812c6cdf | 216f5252a8df73f8547d6a6c831409c916bae3e5 | /windows_embedded_compact_2013_2015M09/WINCE800/private/test/BaseOS/Kernel/smp/depth/ksmpstress.cpp | c5468f1fa44f0af2527ea94abd100e7f8ac1b9d3 | [] | no_license | fanzcsoft/windows_embedded_compact_2013_2015M09 | 845fe834d84d3f0021047bc73d6cf9a75fabb74d | d04b71c517428ed2c73e94caf21a1582b34b18e3 | refs/heads/master | 2022-12-19T02:52:16.222712 | 2020-09-28T20:13:09 | 2020-09-28T20:13:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,409 | cpp | // Copyright (c) Microsoft Corporation. All rights reserved.
//
//
// Use of this source code is subject to the terms of the Microsoft
// premium shared source license agreement under which you licensed
// this source code. If you did not accept the terms of the license
// agreement, you are not authorized to use this source code.
// For the terms of the license, please see the license agreement
// signed by you and Microsoft.
// THE SOURCE CODE IS PROVIDED "AS IS", WITH NO WARRANTIES OR INDEMNITIES.
//
#include <windows.h>
#include <tchar.h>
#include "kharness.h"
#include "ksmplib.h"
//
// Returns 1 if no error. 0 otherwise
//
static DWORD Stress_Thread(LPVOID lpParam)
{
DWORD dwResult = WaitForSingleObject((HANDLE)lpParam, INFINITE);
return (WAIT_OBJECT_0 == dwResult)? 1: 0;
}
const DWORD MAX_NUM_OF_THREADS = 65536; //Max number of handles we can have in kernel
HANDLE hThread[MAX_NUM_OF_THREADS]={0}; //global, causes too many pages on the stack
const DWORD MAX_NUM_OF_PROCESSES = 65536; //Max number of handles we can have in kernel
HANDLE hProcess[MAX_NUM_OF_PROCESSES]={0}; //global, causes too many pages on the stack
//
// Returns the number of threads we created before CreateThread failed
//
static DWORD DoThreadStress1(PBOOL pfError)
{
DWORD dwCnt, dwNumOfThreadsCreated = 0;
HANDLE hEvt = CreateEvent(NULL, TRUE, FALSE, NULL); //Second parameter is true because we need to wake up all the waiters with 1 setevent
if(FALSE == IsValidHandle(hEvt)){
LogDetail(TEXT("CreateEvent() failed \r\n"));
*pfError = TRUE;
return 0;
}
for(dwCnt = 0; dwCnt < MAX_NUM_OF_THREADS; dwCnt++){
hThread[dwCnt] = CreateThread(NULL,
0,
(LPTHREAD_START_ROUTINE)Stress_Thread,
(LPVOID)hEvt,
0,
NULL);
if(NULL == hThread[dwCnt]){
//CreateThread() is going to fail eventually, so this is an expected error
LogDetail(TEXT("CreateThread() failed at iteration %d with error code: 0x%x\r\n"), dwCnt, GetLastError());
break;
}
else if(FALSE == CeSetThreadAffinity(hThread[dwCnt], GenerateAffinity(TRUE))){
LogDetail(TEXT("CeSetThreadAffinity() failed \r\n"));
*pfError = TRUE;
break;
}
}
dwNumOfThreadsCreated = dwCnt;
//Tell the threads to Exit
if(FALSE == SetEvent(hEvt) ||
FALSE == DoWaitForThread(&hThread[0], dwNumOfThreadsCreated, 1)){
*pfError = TRUE;
}
for(dwCnt = 0; dwCnt < dwNumOfThreadsCreated; dwCnt++){
CloseHandle(hThread[dwCnt]);
}
CloseHandle(hEvt);
Sleep(60*1000); //Sleep for 60 seconds to give the threads a chance to fully exit
return dwNumOfThreadsCreated;
}
//
// Stress test: CreateThread till we run out of memory while assigning affinities
//
TESTPROCAPI
SMP_DEPTH_STRESS_THREAD_1(
UINT uMsg,
TPPARAM tpParam,
LPFUNCTION_TABLE_ENTRY lpFTE
)
{
if (uMsg != TPM_EXECUTE){
return TPR_NOT_HANDLED;
}
HANDLE hTest=NULL, hStep=NULL;
const DWORD NUM_OF_ITERATIONS = 10;
DWORD dwNumOfThreads[NUM_OF_ITERATIONS]={0};
RestoreInitialCondition();
hTest = StartTest(NULL);
BEGINSTEP( hTest, hStep, TEXT("Begin stress test - thread"));
BOOL fError = FALSE;
for (DWORD dwCnt = 0; !fError && dwCnt < NUM_OF_ITERATIONS; dwCnt++){
dwNumOfThreads[dwCnt] = DoThreadStress1(&fError);
LogDetail(TEXT("Iteration %d: dwNumOfThreads[%d] = %d, fError = %s\r\n"),
dwCnt, dwCnt, dwNumOfThreads[dwCnt], fError?L"TRUE":L"FALSE");
}
CHECKTRUE(FALSE == fError);//Cannot use CHECKTRUE inside loop
ENDSTEP(hTest,hStep);
BEGINSTEP( hTest, hStep, TEXT("Checking result"));
const DWORD MIN_THREADS_EXPECTED = 1500;
BOOL bRC = TRUE;
for(DWORD dwCnt = 0; dwCnt < NUM_OF_ITERATIONS; dwCnt++){
if(0 == dwNumOfThreads[dwCnt]){
LogDetail(TEXT("ERROR: dwNumOfThreads[%d] = 0\r\n"),dwCnt);
bRC = FALSE;
}
else if(dwNumOfThreads[dwCnt] < MIN_THREADS_EXPECTED){
LogDetail(TEXT("WARNING: dwNumOfThreads[%d] = %d < MIN_THREADS_EXPECTED = %d\r\n"),dwCnt, dwNumOfThreads[dwCnt], MIN_THREADS_EXPECTED);
}
else{
LogDetail(TEXT("dwNumOfThreads[%d] = %d\r\n"),dwCnt, dwNumOfThreads[dwCnt]);
}
}
CHECKTRUE(bRC);
ENDSTEP(hTest,hStep);
RestoreInitialCondition();
if (!HasTheSystemRecovered(60) ) {
LogDetail(TEXT("WARNING: System has not recovered from the previous test\r\n") );
}
return FinishTest(hTest) ? TPR_PASS : TPR_FAIL;
}
//
// Worker function to do the actual work.
// Returns the number of processes we created before CreateProcess failed
//
static DWORD DoProcessStress1(PBOOL pfError)
{
DWORD dwCnt, dwNumOfProcessesCreated = 0;
HANDLE hEvt = CreateEvent(NULL, TRUE, FALSE, KSMP_P2_EVENT_NAME);
if(FALSE == IsValidHandle(hEvt)){
LogDetail(TEXT("CreateEvent() failed \r\n"));
*pfError = TRUE;
return 0;
}
for(dwCnt = 0; dwCnt < MAX_NUM_OF_PROCESSES; dwCnt++){
PROCESS_INFORMATION pi = {0};
if(FALSE == CreateProcess(KSMP_P2_EXE_NAME, NULL, NULL, NULL, FALSE, 0, NULL, NULL, NULL, &pi)){
LogDetail(TEXT("CreateProcess() failed at iteration %d with error code: 0x%x\r\n"), dwCnt, GetLastError());
break;
}
hProcess[dwCnt] = pi.hProcess;
CloseHandle(pi.hThread); //We don't need the thread handle of the primary thread
if(FALSE == CeSetProcessAffinity(hProcess[dwCnt], GenerateAffinity(TRUE))){
LogDetail(TEXT("CeSetProcessAffinity() failed \r\n"));
*pfError = TRUE;
break;
}
}
dwNumOfProcessesCreated = dwCnt;
//Tell the processes to Exit
if(FALSE == SetEvent(hEvt)){
*pfError = TRUE;
}
else{
//We are not going to use DoWaitForProcess() here since we do not want to check the return code
//Our child processes can fail if they run out of memory to CreateEvent (or OpenEvent) and return a different exit code
//Since both 0 and 1 are acceptable return code in this situation we'll just ignore the return code
for(dwCnt = 0; dwCnt < dwNumOfProcessesCreated; dwCnt++){
if(WAIT_OBJECT_0 != WaitForSingleObject(hProcess[dwCnt], INFINITE)){
LogDetail( TEXT("WaitForSingleObject() failed at line %ld (tid=0x%x, GLE=0x%x) at iteration = %d\r\n"),
__LINE__, GetCurrentThreadId(), GetLastError(), dwCnt);
*pfError = TRUE; //We should not return here, should at least try to wait for the rest of the processes
}
}
}
for(dwCnt = 0; dwCnt < dwNumOfProcessesCreated; dwCnt++){
CloseHandle(hProcess[dwCnt]);
}
CloseHandle(hEvt);
Sleep(60*1000); //Sleep for 60 seconds to give the threads a chance to fully exit
return dwNumOfProcessesCreated;
}
//
// Stress test: CreateProcess till we run out of memory while assigning affinities
//
TESTPROCAPI
SMP_DEPTH_STRESS_PROCESS_1(
UINT uMsg,
TPPARAM tpParam,
LPFUNCTION_TABLE_ENTRY lpFTE
)
{
if (uMsg != TPM_EXECUTE){
return TPR_NOT_HANDLED;
}
HANDLE hTest=NULL, hStep=NULL;
const DWORD NUM_OF_ITERATIONS = 10;
DWORD dwNumOfProcess[NUM_OF_ITERATIONS]={0};
RestoreInitialCondition();
hTest = StartTest(NULL);
BEGINSTEP( hTest, hStep, TEXT("Begin stress test - process"));
BOOL fError = FALSE;
for(DWORD dwCnt = 0; !fError && dwCnt < NUM_OF_ITERATIONS; dwCnt++){
dwNumOfProcess[dwCnt] = DoProcessStress1(&fError);
LogDetail(TEXT("Iteration %d: dwNumOfProcess[%d] = %d, fError = %s\r\n"),
dwCnt, dwCnt, dwNumOfProcess[dwCnt], fError?L"TRUE":L"FALSE");
}
CHECKTRUE(FALSE == fError);//Cannot use CHECKTRUE inside loop
ENDSTEP(hTest,hStep);
BEGINSTEP( hTest, hStep, TEXT("Checking result"));
const DWORD MIN_PROCESSES_EXPECTED = 200;
BOOL bRC = TRUE;
for(DWORD dwCnt = 0; dwCnt < NUM_OF_ITERATIONS; dwCnt++){
if(0 == dwNumOfProcess[dwCnt]){
LogDetail(TEXT("ERROR: dwNumOfProcess[%d] = 0 \r\n"),dwCnt);
bRC = FALSE;
}
else if(dwNumOfProcess[dwCnt] < MIN_PROCESSES_EXPECTED) {
LogDetail(TEXT("WARNING: dwNumOfProcess[%d] = %d < MIN_PROCESSES_EXPECTED = %d\r\n"),dwCnt, dwNumOfProcess[dwCnt], MIN_PROCESSES_EXPECTED);
}
else{
LogDetail(TEXT("dwNumOfProcess[%d] = %d\r\n"),dwCnt, dwNumOfProcess[dwCnt]);
}
}
CHECKTRUE(bRC);
ENDSTEP(hTest,hStep);
RestoreInitialCondition();
return FinishTest(hTest) ? TPR_PASS : TPR_FAIL;
} | [
"[email protected]"
] | |
972e3ed02b0bc54696f303a9f496fc8032290619 | 89ca99b517c10494f769cbda756bf0c8e00167fc | /src/grpc/server/AgentRestart.hpp | fa24d3e40036b03a68d7624aa3deac52f1504c95 | [] | no_license | nkumar43212/jvsim | fad56e25ae5eb8e8d0ad1272dacd8a25cb7e88ec | 7663c493cefcb7ffb04321226d0534be5711194e | refs/heads/master | 2021-01-17T11:49:10.052784 | 2016-07-28T22:32:56 | 2016-07-28T22:32:56 | 51,335,614 | 4 | 12 | null | 2018-08-07T02:11:14 | 2016-02-08T23:42:49 | C++ | UTF-8 | C++ | false | false | 382 | hpp | //
// AgentRestart.hpp
// Telemetry Agent
//
// Created: 6/9/16.
//
// Authors: ABBAS SAKARWALA
//
// Copyright © 2016 Juniper Networks. All rights reserved.
//
#ifndef AgentRestart_hpp
#define AgentRestart_hpp
#include "AgentServerLog.hpp"
#include "AgentSystemFactory.hpp"
bool on_startup (AgentServerLog *logger, AgentSystem *sys_handle);
#endif /* AgentRestart_hpp */
| [
"[email protected]"
] | |
b7572f3cf36ed2d93a4632096219f386660197d3 | 91a882547e393d4c4946a6c2c99186b5f72122dd | /Source/XPSP1/NT/com/rpc/runtime/charconv/convbvt.cxx | 59dde13983d589841bf6ffc03f7a00daa21289ed | [] | no_license | IAmAnubhavSaini/cryptoAlgorithm-nt5src | 94f9b46f101b983954ac6e453d0cf8d02aa76fc7 | d9e1cdeec650b9d6d3ce63f9f0abe50dabfaf9e2 | refs/heads/master | 2023-09-02T10:14:14.795579 | 2021-11-20T13:47:06 | 2021-11-20T13:47:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,037 | cxx | //+-------------------------------------------------------------------------
//
// Microsoft Windows
//
// Copyright (C) Microsoft Corporation, 1998 - 1999
//
// File: convbvt.cxx
//
//--------------------------------------------------------------------------
#include <precomp.hxx>
#include "CharConv.hxx"
int main()
{
WCHAR wt1[] = L"Hello world!";
WCHAR we[] = L"";
char at1[] = "Hello world!";
char ae[] = "";
char abuf[100];
WCHAR wbuf[100];
CHeapUnicode hu;
CHeapAnsi ha;
CNlUnicode nu;
CNlAnsi na;
CStackUnicode su;
CStackAnsi sa;
USES_CONVERSION;
// test heap conversions
ATTEMPT_HEAP_W2A(ha, wt1);
ASSERT(lstrcmpA(ha, at1) == 0);
ATTEMPT_HEAP_A2W(hu, at1);
ASSERT(lstrcmpW(hu, wt1) == 0);
// test Nl conversions
ATTEMPT_NL_W2A(na, wt1);
ASSERT(lstrcmpA(na, at1) == 0);
ATTEMPT_NL_A2W(nu, at1);
ASSERT(lstrcmpW(nu, wt1) == 0);
// test stack conversions
ATTEMPT_STACK_W2A(sa, wt1);
ASSERT(lstrcmpA(sa, at1) == 0);
ATTEMPT_STACK_A2W(su, at1);
ASSERT(lstrcmpW(su, wt1) == 0);
return 0;
} | [
"[email protected]"
] | |
7fa16ec54dcdd1aafea47fd284be7f005815cedb | b31a6e4962b25ef6d2959c1803e32f3e724bf041 | /gsoap/soapStub.h | 27f0426f64f2e0fa0ec2e93ad0a1b3fe183897fd | [] | no_license | nigefanshu/CppTest | 456ed3cab4cb5ab17dae2eee48ac7f5841b4c4ab | 9cc694738c602a7270309afe8710d58638a8f3f5 | refs/heads/master | 2021-09-02T14:44:08.109330 | 2018-01-03T08:27:46 | 2018-01-03T08:27:46 | 108,251,340 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,689 | h | /* soapStub.h
Generated by gSOAP 2.8.28 from add.h
gSOAP XML Web services tools
Copyright (C) 2000-2016, Robert van Engelen, Genivia Inc. All Rights Reserved.
The soapcpp2 tool and its generated software are released under the GPL.
This program is released under the GPL with the additional exemption that
compiling, linking, and/or using OpenSSL is allowed.
--------------------------------------------------------------------------------
A commercial use license is available from Genivia Inc., [email protected]
--------------------------------------------------------------------------------
*/
#ifndef soapStub_H
#define soapStub_H
#include "stdsoap2.h"
#if GSOAP_VERSION != 20828
# error "GSOAP VERSION 20828 MISMATCH IN GENERATED CODE VERSUS LIBRARY CODE: PLEASE REINSTALL PACKAGE"
#endif
/******************************************************************************\
* *
* Enumerations *
* *
\******************************************************************************/
/******************************************************************************\
* *
* Types with Custom Serializers *
* *
\******************************************************************************/
/******************************************************************************\
* *
* Classes, Structs, and Unions *
* *
\******************************************************************************/
struct ns__addResponse; /* add.h:14 */
struct ns__add; /* add.h:14 */
/* add.h:14 */
#ifndef SOAP_TYPE_ns__addResponse
#define SOAP_TYPE_ns__addResponse (9)
/* ns:addResponse complex type: */
struct ns__addResponse
{
public:
int *result; /* SOAP 1.2 RPC return element (when namespace qualified) */ /* optional element of XSD type xsd:int */
public:
int soap_type() const { return 9; } /* = unique type id SOAP_TYPE_ns__addResponse */
ns__addResponse();
friend SOAP_FMAC1 ns__addResponse * SOAP_FMAC2 soap_instantiate_ns__addResponse(struct soap*, int, const char*, const char*, size_t*);
};
#endif
/* add.h:14 */
#ifndef SOAP_TYPE_ns__add
#define SOAP_TYPE_ns__add (10)
/* ns:add complex type: */
struct ns__add
{
public:
int a; /* required element of XSD type xsd:int */
int b; /* required element of XSD type xsd:int */
public:
int soap_type() const { return 10; } /* = unique type id SOAP_TYPE_ns__add */
ns__add();
friend SOAP_FMAC1 ns__add * SOAP_FMAC2 soap_instantiate_ns__add(struct soap*, int, const char*, const char*, size_t*);
};
#endif
/* add.h:16 */
#ifndef WITH_NOGLOBAL
#ifndef SOAP_TYPE_SOAP_ENV__Header
#define SOAP_TYPE_SOAP_ENV__Header (11)
/* SOAP Header: */
struct SOAP_ENV__Header
{
public:
int soap_type() const { return 11; } /* = unique type id SOAP_TYPE_SOAP_ENV__Header */
SOAP_ENV__Header();
friend SOAP_FMAC1 SOAP_ENV__Header * SOAP_FMAC2 soap_instantiate_SOAP_ENV__Header(struct soap*, int, const char*, const char*, size_t*);
};
#endif
#endif
/* add.h:16 */
#ifndef WITH_NOGLOBAL
#ifndef SOAP_TYPE_SOAP_ENV__Code
#define SOAP_TYPE_SOAP_ENV__Code (12)
/* Type SOAP_ENV__Code is a recursive data type (in)directly referencing itself through its (base) class members */
/* SOAP Fault Code: */
struct SOAP_ENV__Code
{
public:
char *SOAP_ENV__Value; /* optional element of XSD type xsd:QName */
struct SOAP_ENV__Code *SOAP_ENV__Subcode; /* optional element of XSD type SOAP-ENV:Code */
public:
int soap_type() const { return 12; } /* = unique type id SOAP_TYPE_SOAP_ENV__Code */
SOAP_ENV__Code();
friend SOAP_FMAC1 SOAP_ENV__Code * SOAP_FMAC2 soap_instantiate_SOAP_ENV__Code(struct soap*, int, const char*, const char*, size_t*);
};
#endif
#endif
/* add.h:16 */
#ifndef WITH_NOGLOBAL
#ifndef SOAP_TYPE_SOAP_ENV__Detail
#define SOAP_TYPE_SOAP_ENV__Detail (14)
/* SOAP-ENV:Detail complex type: */
struct SOAP_ENV__Detail
{
public:
char *__any;
int __type; /* any type of element <fault> (defined below)
WARNING: do not create a cyclic data structure graph throught this element unless SOAP encoding or SOAP_XML_GRAPH are used for id-ref serialization */
void *fault; /* transient (not serialized) */
public:
int soap_type() const { return 14; } /* = unique type id SOAP_TYPE_SOAP_ENV__Detail */
SOAP_ENV__Detail();
friend SOAP_FMAC1 SOAP_ENV__Detail * SOAP_FMAC2 soap_instantiate_SOAP_ENV__Detail(struct soap*, int, const char*, const char*, size_t*);
};
#endif
#endif
/* add.h:16 */
#ifndef WITH_NOGLOBAL
#ifndef SOAP_TYPE_SOAP_ENV__Reason
#define SOAP_TYPE_SOAP_ENV__Reason (17)
/* SOAP-ENV:Reason complex type: */
struct SOAP_ENV__Reason
{
public:
char *SOAP_ENV__Text; /* optional element of XSD type xsd:string */
public:
int soap_type() const { return 17; } /* = unique type id SOAP_TYPE_SOAP_ENV__Reason */
SOAP_ENV__Reason();
friend SOAP_FMAC1 SOAP_ENV__Reason * SOAP_FMAC2 soap_instantiate_SOAP_ENV__Reason(struct soap*, int, const char*, const char*, size_t*);
};
#endif
#endif
/* add.h:16 */
#ifndef WITH_NOGLOBAL
#ifndef SOAP_TYPE_SOAP_ENV__Fault
#define SOAP_TYPE_SOAP_ENV__Fault (18)
/* SOAP Fault: */
struct SOAP_ENV__Fault
{
public:
char *faultcode; /* optional element of XSD type xsd:QName */
char *faultstring; /* optional element of XSD type xsd:string */
char *faultactor; /* optional element of XSD type xsd:string */
struct SOAP_ENV__Detail *detail; /* optional element of XSD type SOAP-ENV:Detail */
struct SOAP_ENV__Code *SOAP_ENV__Code; /* optional element of XSD type SOAP-ENV:Code */
struct SOAP_ENV__Reason *SOAP_ENV__Reason; /* optional element of XSD type SOAP-ENV:Reason */
char *SOAP_ENV__Node; /* optional element of XSD type xsd:string */
char *SOAP_ENV__Role; /* optional element of XSD type xsd:string */
struct SOAP_ENV__Detail *SOAP_ENV__Detail; /* optional element of XSD type SOAP-ENV:Detail */
public:
int soap_type() const { return 18; } /* = unique type id SOAP_TYPE_SOAP_ENV__Fault */
SOAP_ENV__Fault();
friend SOAP_FMAC1 SOAP_ENV__Fault * SOAP_FMAC2 soap_instantiate_SOAP_ENV__Fault(struct soap*, int, const char*, const char*, size_t*);
};
#endif
#endif
/******************************************************************************\
* *
* Typedefs *
* *
\******************************************************************************/
/* add.h:14 */
#ifndef SOAP_TYPE__QName
#define SOAP_TYPE__QName (5)
typedef char *_QName;
#endif
/* add.h:14 */
#ifndef SOAP_TYPE__XML
#define SOAP_TYPE__XML (6)
typedef char *_XML;
#endif
/******************************************************************************\
* *
* Externals *
* *
\******************************************************************************/
#endif
/* End of soapStub.h */
| [
"[email protected]"
] | |
72a8a36f7e13e94e74866fea1602ca0ebb708bdb | 4f7d03dc02c7e87e744490324b95445828e18358 | /SpeechRecog/SpeechRecog/timer.cpp | a54dacf23e1acac1007bd287fae53238728d4c18 | [] | no_license | mrpie95/Rehab-Robot | fe6cb79bdfdf1e76c4a6b52318d1028c57758a43 | 3c5a6a13bb1b8182508bde3c484f157803f8fabc | refs/heads/master | 2020-03-18T00:44:34.940056 | 2018-11-11T08:48:15 | 2018-11-11T08:48:15 | 134,110,324 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 721 | cpp | #include "timer.h"
using namespace std;
Timer::Timer()
{
resetTimer();
}
void Timer::resetTimer()
{
startTime = chrono::high_resolution_clock::now();
tick = true;
}
bool Timer::hasTickYet()
{
if (tick) {
tick = false;
return true;
} else {
if (chrono::duration_cast<chrono::seconds>(chrono::high_resolution_clock::now() - lastTick).count()>= 1) {
lastTick = chrono::high_resolution_clock::now();
tick = false;
return true;
} else return false;
}
}
double Timer::elapsedTimeSecond()
{
auto elapsed = chrono::duration_cast<chrono::seconds>(chrono::high_resolution_clock::now() - startTime);
return elapsed.count();
}
| [
"[email protected]"
] | |
4208b61b99f17c0065d6ed1d423bff2c5e0fcf0e | 77a08ec51aa16191986a739267fd9d4379bbb208 | /ybt/ybt1412.cpp | 393ee25a638e56e92f0fc86c70962ea1ae82d0c1 | [] | no_license | cenariusxz/ACM-Coding | 8f698203db802f79578921b311b38346950ef0ca | dc09ac9adfb4b80d463bdc93f52b479a957154e6 | refs/heads/master | 2023-06-24T13:12:13.279255 | 2021-07-26T01:24:36 | 2021-07-26T01:24:36 | 185,567,471 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 308 | cpp | #include <bits/stdc++.h>
using namespace std;
int main(){
int ans1 = 0, ans2 = 0;
for(int a = 1 ; a <= 1000 ; ++ a){
int tmp1 = 0, tmp0 = 0, tmp = a;
while(tmp){
if(tmp&1)tmp1++;
else tmp0++;
tmp>>=1;
}
if(tmp1>tmp0)ans1++;
else ans2++;
}
printf("%d %d\n",ans1,ans2);
return 0;
}
| [
"[email protected]"
] | |
848711263fac5aba78b7423e4ef1a27e60afa09b | e0ffcab91ae09bb4317033331f4ed2b52520da32 | /Terrain/include/PerlinNoise.h | 32bea303d6bb5e0c8cc360c87027e2dad6319a85 | [] | no_license | JamesDorling/ShadersCode | 2914dd9b57a61844ffff196b195e6bb1c06e0c48 | f8448be59db10606622062a7af38078be0c8b601 | refs/heads/master | 2023-09-04T12:35:45.200185 | 2023-08-25T16:49:26 | 2023-08-25T16:49:26 | 414,857,666 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,093 | h | #include <vector>
// THIS CLASS IS A TRANSLATION TO C++11 FROM THE REFERENCE
// JAVA IMPLEMENTATION OF THE IMPROVED PERLIN FUNCTION (see http://mrl.nyu.edu/~perlin/noise/)
// THE ORIGINAL JAVA IMPLEMENTATION IS COPYRIGHT 2002 KEN PERLIN
// I ADDED AN EXTRA METHOD THAT GENERATES A NEW PERMUTATION VECTOR (THIS IS NOT PRESENT IN THE ORIGINAL IMPLEMENTATION)
// ( CF : I took this from https://github.com/sol-prog/Perlin_Noise
// I added a function setSeed() - which can be called from Terrain class
#ifndef PERLINNOISE_H
#define PERLINNOISE_H
class PerlinNoise {
// The permutation vector
std::vector<int> p;
public:
// Initialize with the reference values for the permutation vector
PerlinNoise();
// Generate a new permutation vector based on the value of seed
PerlinNoise(unsigned int seed);
void setSeed(unsigned int seed);
// Get a noise value, for 2D images z can have any value
double noise(double x, double y, double z);
private:
double fade(double t);
double lerp(double t, double a, double b);
double grad(int hash, double x, double y, double z);
};
#endif
| [
"[email protected]"
] | |
6fdf21f769d01f19b4a50122466776ca41e6cbab | 58eee66e7025a0758c82ba10066f0676724f7e58 | /FinalProject_Aditi-Mehta_Anish-Narsian/Rasterizer.cpp | 6d0fe95686814c645a69f7dd34ac141439f10762 | [] | no_license | anarsian/OpenGL-project | 6241832e1e12ea0e8c3ec7344715639dbfc2b131 | 80878e9fe5e129cd5c6bb5b78869699acc875a1e | refs/heads/master | 2021-01-15T20:58:08.760753 | 2014-12-31T18:51:07 | 2014-12-31T18:51:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,163 | cpp | #ifdef _WIN32
#include <windows.h>
#endif
#include <iostream>
#include <math.h>
#include <cmath>
#include <GL/gl.h>
#include <GL/glut.h>
#include "Parser.h"
#include "cube.h"
#include "Camera.h"
#include "House.h"
using namespace std;
static int window_width = 512, window_height = 512;
float* pixels = new float[window_width * window_height * 3];
Parser bunny;
Parser dragon;
Cube bunnyMatrix;
Cube dragonMatrix;
int tag = 1;
Vector4 lightsource (8,60,10, 1);
double intensity = 305;
int lighton = 0;
int zbufferon = 0;
int psizeon = 0;
int sphereon = 0;
float* zbuffer = new float[window_width * window_height * 3];
struct Color // generic color class
{
float r,g,b; // red, green, blue
};
void loadData()
{
bunny = *new Parser("bunny.xyz", 2);
dragon = *new Parser("dragon.xyz", 1);
}
// Clear frame buffer
void clearBuffer()
{
Color clearColor = {0.0, 0.0, 0.0}; // clear color: black
for (int i=0; i<window_width*window_height; ++i)
{
pixels[i*3] = clearColor.r;
pixels[i*3+1] = clearColor.g;
pixels[i*3+2] = clearColor.b;
}
for(int i = 0; i < window_width * window_height * 3; i++)
zbuffer[i] = 1;
}
// Draw a point into the frame buffer
void drawPoint(int x, int y, float r, float g, float b, int size)
{
int t;
if(size % 2 == 0)
t = size/2;
else
t = (size/2) + 1;
if (sphereon == 0)
{
for(int i = x - size/2; i < x + t; i++)
{
for(int j = y - size/2; j < y + t; j++)
{
int offset = j*window_width*3 + i*3;
if ((offset + 2) < window_width * window_height * 3 && i < window_width - 2 && j < window_height -2 && offset >= 0)
{
pixels[offset] = r;
pixels[offset + 1] = g;
pixels[offset + 2] = b;
}
}
}
}
else
{
for(int i = x - size/2; i < x + t; i++)
{
for(int j = y - size/2; j < y + t; j++)
{
double dx = x - i;
double dy = y - j;
double distanceSquared = dx * dx + dy * dy;
if (distanceSquared <= size*size/4)
{
int offset = j*window_width*3 + i*3;
if ((offset + 2) < window_width * window_height * 3 && i < window_width - 2 && j < window_height -2 && offset >= 0)
{
pixels[offset] = r;
pixels[offset + 1] = g;
pixels[offset + 2] = b;
}
}
}
}
}
}
int getSize (double distance)
{
int d = floor(distance*10);
if (d == 8) return 4;
if (d == 9) return 7;
if (d > 9) return 9;
else return (int)(floor(d/2) - 1);
}
void transform(Vector4& tmp, Matrix4& model2world)
{
double fov = 60 / 180.0 * M_PI;
double aspect = double(window_width)/(double)window_height;
double n = 1, f = 1000.0;
Matrix4 projMatrix;
projMatrix.m[0][0] = 1.0/(aspect * tan(fov/2));
projMatrix.m[1][1] = 1.0/tan(fov/2);
projMatrix.m[2][2] = (n + f) / (n-f);
projMatrix.m[2][3] = (2.0*n*f)/(n-f);
projMatrix.m[3][2] = -1;
Matrix4 cameraMatrix;
cameraMatrix.makeTranslate(0,0,-20);
cameraMatrix * model2world;
projMatrix * cameraMatrix;
projMatrix * tmp;
tmp.dehomogenize();
}
void imageSpace(Vector4& tmp)
{
double x1 = window_width, x0 = 0;
double y1 = window_height, y0 = 0;
Matrix4 viewport;
viewport.identity();
viewport.m[0][0] = (x1 -x0)/2.0;
viewport.m[0][3] = (x1 + x0)/2.0;
viewport.m[1][1] = (y1-y0)/2.0;
viewport.m[1][3] = (y1+y0)/2.0;
viewport.m[2][2] = 0.5;
viewport.m[2][3] = 0.5;
viewport * tmp;
}
void light(Vector3 pos, Vector3 source, Vector3 normal, Color mc, Color& rc)
{
Vector3 ld = source - pos;
double d = ld.length();
Color li = {1.0*intensity, 1.0*intensity, 1.0*intensity};
Color lc = {li.r / (d*d), li.g / (d*d), li.b / (d*d) };
rc.r = 1.0/M_PI * mc.r * lc.r * ld.dot(ld, normal);
rc.g = 1.0/M_PI * mc.g * lc.g * ld.dot(ld, normal);
rc.b = 1.0/M_PI * mc.b * lc.b * ld.dot(ld, normal);
}
void rasterize()
{
if(tag == 1)
{
Vector4 tmp3 = lightsource;
bunnyMatrix.getMatrix() * tmp3;
Vector3 src (tmp3.x, tmp3.y, tmp3.z);
for (unsigned int i = 0; i < bunny.vertices.size(); i++)
{
Vector4 tmp(bunny.vertices[i].x, bunny.vertices[i].y, bunny.vertices[i].z, 1);
Vector4 tmp2(bunny.normals[i].x, bunny.normals[i].y, bunny.normals[i].z, 0);
transform(tmp, bunnyMatrix.getMatrix());
imageSpace(tmp);
float zvalue = tmp.z;
bunnyMatrix.getMatrix() * tmp2;
if(tmp.x < window_width && tmp.y < window_height && tmp.x > 0 && tmp.y > 0)
{
Vector3 pos(tmp.x, tmp.y, tmp.z);
Vector3 normals(tmp2.x, tmp2.y, tmp2.z);
Color m = {0.8, 0.1, 1.0};
Color finalcolor = m;
if (zbufferon == 1)
{
if(zvalue < zbuffer[(int)(floor(tmp.y)*window_width*3 + floor(tmp.x)*3)])
{
light(pos, src, normals, m, finalcolor);
if(psizeon == 1) drawPoint(floor(tmp.x), floor(tmp.y), finalcolor.r, finalcolor.g, finalcolor.b, getSize(zvalue));
else drawPoint(floor(tmp.x), floor(tmp.y), finalcolor.r, finalcolor.g, finalcolor.b, 1);
zbuffer[(int)(floor(tmp.y)*window_width*3 + floor(tmp.x)*3)]= zvalue;
}
}
else
{
if(lighton == 1) light(pos, src, normals, m, finalcolor);
drawPoint(floor(tmp.x), floor(tmp.y), finalcolor.r, finalcolor.g, finalcolor.b, 1);
}
}
}
}
else
{
Vector4 tmp3 = lightsource;
dragonMatrix.getMatrix() * tmp3;
Vector3 src (tmp3.x, tmp3.y, tmp3.z);
for (unsigned int i = 0; i < dragon.vertices.size(); i++)
{
Vector4 tmp(dragon.vertices[i].x, dragon.vertices[i].y, dragon.vertices[i].z, 1);
Vector4 tmp2(dragon.normals[i].x, dragon.normals[i].y, dragon.normals[i].z, 1);
transform(tmp, dragonMatrix.getMatrix());
imageSpace(tmp);
dragonMatrix.getMatrix() * tmp2;
float zvalue = tmp.z;
if(tmp.x < window_width && tmp.y < window_height && tmp.x > 0 && tmp.y > 0)
{
Vector3 pos(tmp.x, tmp.y, tmp.z);
Vector3 normals(tmp2.x, tmp2.y, tmp2.z);
Color m = {0.8, 0.1, 1};
Color finalcolor = m;
if (zbufferon == 1)
{
if(zvalue < zbuffer[(int)(floor(tmp.y)*window_width*3 + floor(tmp.x)*3)])
{
light(pos, src, normals, m, finalcolor);
if(psizeon == 1) drawPoint(floor(tmp.x), floor(tmp.y), finalcolor.r, finalcolor.g, finalcolor.b, getSize(zvalue));
else drawPoint(floor(tmp.x), floor(tmp.y), finalcolor.r, finalcolor.g, finalcolor.b, 1);
zbuffer[(int)(floor(tmp.y)*window_width*3 + floor(tmp.x)*3)]= zvalue;
}
}
else
{
if(lighton == 1) light(pos, src, normals, m, finalcolor);
drawPoint(floor(tmp.x), floor(tmp.y), finalcolor.r, finalcolor.g, finalcolor.b,1);
}
}
}
}
}
void displayCallback()
{
clearBuffer();
rasterize();
// glDrawPixels writes a block of pixels to the framebuffer
glDrawPixels(window_width, window_height, GL_RGB, GL_FLOAT, pixels);
glutSwapBuffers();
}
// Called whenever the window size changes
void reshapeCallback(int new_width, int new_height)
{
cerr << "Window::reshapeCallback called" << endl;
window_width = new_width;
window_height = new_height;
delete[] pixels;
pixels = new float[window_width * window_height * 3];
delete[] zbuffer;
zbuffer = new float[window_width * window_height * 3];
bunnyMatrix.reset();
bunny.findMaxMin();
bunnyMatrix.moveToCenter(bunny.findCenter());
bunnyMatrix.makeWindowSize(window_width, bunny.findScaleFactor());
bunnyMatrix.scale(0.8);
dragonMatrix.reset();
dragon.findMaxMin();
dragonMatrix.moveToCenter(dragon.findCenter());
dragonMatrix.makeWindowSize(window_width, dragon.findScaleFactor());
rasterize();
displayCallback();
}
void keyboardCallback(unsigned char key, int, int)
{
if(key == 49)
{
psizeon = 0;
zbufferon = 0;
lighton = 0;
sphereon = 0;
}
if(key == 50)
{
psizeon = 0;
zbufferon = 0;
lighton = 1;
sphereon = 0;
}
if(key == 51)
{
psizeon = 0;
lighton = 1;
zbufferon = 1;
sphereon = 0;
}
if(key == 52)
{
lighton = 1;
zbufferon = 1;
psizeon = 1;
sphereon = 0;
}
if (key == 53)
{
lighton = 1;
zbufferon = 1;
psizeon = 1;
sphereon = 1;
}
//if x is pressed, move cube left
if (key == 120)
{
if(tag == 1) bunnyMatrix.translate(-0.9,0,0);
if(tag == 2) dragonMatrix.translate(-0.9,0,0);
displayCallback();
}
//if X is pressed, move cube right
if (key == 88)
{
if(tag == 1) bunnyMatrix.translate(0.9,0,0);
if(tag == 2) dragonMatrix.translate(0.9,0,0);
displayCallback();
}
//if y is pressed, move cube down
if (key == 121)
{
if(tag == 1) bunnyMatrix.translate(0,-0.9,0);
if(tag == 2) dragonMatrix.translate(0,-0.9,0);
displayCallback();
}
//if Y is pressed, move cube up
if (key == 89)
{
if(tag == 1) bunnyMatrix.translate(0,0.9,0);
if(tag == 2) dragonMatrix.translate(0,0.9,0);
displayCallback();
}
//move cube into the screen by a small amount
if (key == 122)
{
if(tag == 1) bunnyMatrix.translate(0,0,-0.9);
if(tag == 2) dragonMatrix.translate(0,0,-0.9);
displayCallback();
}
//move cube out of the screen by a small amount
if (key == 90)
{
if(tag == 1) bunnyMatrix.translate(0,0,0.9);
if(tag == 2) dragonMatrix.translate(0,0,0.9);
displayCallback();
}
//reset
if(key == 114)
{
if(tag == 1) bunnyMatrix.reset();
if(tag == 2) dragonMatrix.reset();
displayCallback();
}
//scale down
if(key == 115)
{
if(tag == 1) bunnyMatrix.scale(0.95);
if(tag == 2) dragonMatrix.scale(0.95);
displayCallback();
}
//scale up
if(key == 83)
{
if(tag == 1) bunnyMatrix.scale(1.05);
if(tag == 2) dragonMatrix.scale(1.05);
displayCallback();
}
//rotate right and left
if(key == 113)
{
if(tag == 1) bunnyMatrix.spin(15);
if(tag == 2) dragonMatrix.spin(15);
displayCallback();
}
if(key == 81)
{
if(tag == 1) bunnyMatrix.spin(-15);
if(tag == 2) dragonMatrix.spin(-15);
displayCallback();
}
}
void specialKeyCallback(int key, int, int)
{
if(key == GLUT_KEY_F1)
{
bunnyMatrix.reset();
bunny.findMaxMin();
bunnyMatrix.moveToCenter(bunny.findCenter());
bunnyMatrix.makeWindowSize(window_width, bunny.findScaleFactor());
bunnyMatrix.scale(0.8);
bunnyMatrix.translate(0.8,0,0);
tag = 1;
displayCallback();
}
if(key == GLUT_KEY_F2)
{
dragonMatrix.reset();
dragon.findMaxMin();
dragonMatrix.moveToCenter(dragon.findCenter());
dragonMatrix.makeWindowSize(window_width, dragon.findScaleFactor());
tag = 2;
displayCallback();
}
}
void idleCallback()
{
displayCallback();
}
int main_tp(int argc, char** argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE);
glutInitWindowSize(window_width, window_height);
glutCreateWindow("Rasterizer");
loadData();
glutReshapeFunc(reshapeCallback);
glutDisplayFunc(displayCallback);
glutIdleFunc(idleCallback);
glutKeyboardFunc(keyboardCallback);
glutSpecialFunc(specialKeyCallback);
bunnyMatrix.getMatrix().identity();
dragonMatrix.getMatrix().identity();
glutMainLoop();
return 0;
}
| [
"[email protected]"
] | |
f0ccbc857c54e0a85321ebee55141a26a527f626 | 6c4965d8c08423648f64e6cdaae5c1171d5ffa0e | /ev_fitness.cpp | a8cd382ddfd74fb62c5f570126bb24d5144fbe11 | [] | no_license | pablopaolus/MiRepositorio | 69bd2185c47053480712389dfa255d956666ae0b | f4f9dc9700649b4deb375f78cbd27c935693b3f8 | refs/heads/master | 2021-01-17T11:17:37.965423 | 2014-04-29T14:47:01 | 2014-04-29T14:47:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,497 | cpp | #include <vector>
#include <sys/time.h>
#include <ctime>
#include <cstdio>
#include <cstdlib>
using namespace std;
int main(int argc, char *argv[]) {
// Compruebo el numero de argumentos
if(argc < 3) {
printf("Uso: %s <Tamaño de población> <Número de cromosomas>\n", argv[0]);
exit(-1);
}
srand(time(NULL));
int tamPob = atoi(argv[1]);
int numCro = atoi(argv[2]);
struct timeval timPOB;
// --------------Implementacion con unsigned char---------------
vector< vector<unsigned char> > POB1(tamPob, vector<unsigned char>(numCro));
vector< vector<unsigned char> >::iterator itPOB1;
vector<unsigned char>::iterator itGEN1;
// Voy rellenando aleatoriamente con 0 o 1 el vector de unsigned char
for(itPOB1 = POB1.begin(); itPOB1 != POB1.end(); ++itPOB1)
for(itGEN1 = (*itPOB1).begin(); itGEN1 != (*itPOB1).end(); ++itGEN1)
*itGEN1 = rand() % 2;
gettimeofday(&timPOB, NULL);
double dTime1 = timPOB.tv_sec+(timPOB.tv_usec/1000000.0);
// Voy comprobando si esta a 1 y lo sumo al contador
// Eficiencia: O(n)
// Ejecuciones: 2*n
int cont = 0;
for(itPOB1 = POB1.begin(); itPOB1 != POB1.end(); ++itPOB1)
for(itGEN1 = (*itPOB1).begin(); itGEN1 != (*itPOB1).end(); ++itGEN1)
if(*itGEN1 == 1)
++cont;
gettimeofday(&timPOB, NULL);
double dTime2 = timPOB.tv_sec+(timPOB.tv_usec/1000000.0);
printf("\nUnsigned char: %.6lf Segundos\n", dTime2 - dTime1);
// ----------Implementacion con bits y unsigned char------------
int numCro8 = numCro / 8;
int rest8 = numCro % 8;
bool exacto = (rest8 == 0) ? true : false;
if(!exacto)
++numCro8;
vector< vector<unsigned char> > POB2(tamPob, vector<unsigned char>(numCro8));
vector< vector<unsigned char> >::iterator itPOB2;
vector<unsigned char>::iterator itGEN2;
// Voy rellenando aleatoriamente con numeros entre 0 y 255 el vector de unsigned char
for(itPOB2 = POB2.begin(); itPOB2 != POB2.end(); ++itPOB2)
for(itGEN2 = (*itPOB2).begin(); itGEN2 != (*itPOB2).end(); ++itGEN2)
*itGEN2 = rand() % 256;
gettimeofday(&timPOB, NULL);
dTime1 = timPOB.tv_sec+(timPOB.tv_usec/1000000.0);
// Voy comprobando cada bit de cada unsigned char si está a 1 y lo sumo al contador (Brian Kernighan)
// Eficiencia: O(n*log2(num)) -->>> OJO!! n/8 operaciones básicas + log2(num)
// Ejecuciones: (n/8) + (n/8)*(log2(num)*3) -->>> de media n/2
cont = 0;
for(itPOB2 = POB2.begin(); itPOB2 != POB2.end(); ++itPOB2)
for(itGEN2 = (*itPOB2).begin(); itGEN2 != (*itPOB2).end(); ++itGEN2) {
unsigned char num = *itGEN2;
while (num) {
num &= (num-1);
++cont;
}
}
gettimeofday(&timPOB, NULL);
dTime2 = timPOB.tv_sec+(timPOB.tv_usec/1000000.0);
printf("Unsigned char (bits) Brian Kernighan: %.6lf Segundos\n", dTime2 - dTime1);
gettimeofday(&timPOB, NULL);
dTime1 = timPOB.tv_sec+(timPOB.tv_usec/1000000.0);
// Creacion de la tabla precomputada
unsigned char BitsSetTable[256];
BitsSetTable[0] = 0;
for(int i = 0; i < 256; ++i)
BitsSetTable[i] = (i & 1) + BitsSetTable[i / 2];
// Voy comprobando en la tabla cuantos unos tiene cada unsigned char y lo sumo al contador (Lookup Table)
// Eficiencia: O(n)
// Ejecuciones: 2*(n/8) = n/4
cont = 0;
for(itPOB2 = POB2.begin(); itPOB2 != POB2.end(); ++itPOB2)
for(itGEN2 = (*itPOB2).begin(); itGEN2 != (*itPOB2).end(); ++itGEN2)
cont += BitsSetTable[*itGEN2];
gettimeofday(&timPOB, NULL);
dTime2 = timPOB.tv_sec+(timPOB.tv_usec/1000000.0);
printf("Unsigned char (bits) Lookup Table: %.6lf Segundos\n\n", dTime2 - dTime1);
}
| [
"[email protected]"
] | |
766b4a07d4c10139adaac4ba5f9a98f8dd2c9a67 | 30773b649ebd89ffadd16d30fd62740b77ca7865 | /SDK/EmissaryActivated_AF_PromptAccessKey_classes.h | 74bcc76d3c02f9c25f9c2323abeb4736adab5430 | [] | no_license | The-Jani/Sot-SDK | 7f2772fb5df421e02b8fec237248af407cb2540b | 2a158a461c697cca8db67aa28ffe3e43677dcf11 | refs/heads/main | 2023-07-09T07:17:56.972569 | 2021-08-18T23:45:06 | 2021-08-18T23:45:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 830 | h | #pragma once
// Name: S, Version: 2.2.1
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass EmissaryActivated_AF_PromptAccessKey.EmissaryActivated_AF_PromptAccessKey_C
// 0x0000 (FullSize[0x0038] - InheritedSize[0x0038])
class UEmissaryActivated_AF_PromptAccessKey_C : public UPromptCounterAccessKey
{
public:
static UClass* StaticClass()
{
static UClass* ptr = UObject::FindClass("BlueprintGeneratedClass EmissaryActivated_AF_PromptAccessKey.EmissaryActivated_AF_PromptAccessKey_C");
return ptr;
}
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"[email protected]"
] | |
f740e6923c0ed0d9a2d2262e4c7138847b3bd2cf | 7c7edef030b3c831bfcabe408d8abc2fa3ba040a | /ConquestTD/src/GameScene/GameScene.h | cd9acbf02b4f84a0f53ad4c996a7ff791c1013dd | [] | no_license | SelenianRanger/ConquestTD | 985d4e9b56fd9c14f87ed1b8b6c01140680dbef7 | 7ed61bcb17bf5f243d86638eb5c28a4df12aa363 | refs/heads/master | 2022-08-10T17:45:03.270701 | 2018-02-27T23:56:24 | 2018-02-27T23:56:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 389 | h | #pragma once
#include <QGraphicsScene>
class QGraphicsView;
class GameController;
class ResourceManager;
class GameScene : public QGraphicsScene
{
Q_OBJECT
public:
GameScene(QObject *parent = 0);
~GameScene();
QGraphicsView* view();
private:
GameController *_game_controller;
ResourceManager *_resources;
QGraphicsView *_view;
public slots:
void setPaused(bool value);
};
| [
"[email protected]"
] | |
a87d0d3246300b38d55300c141092d25db6f6444 | c0c50db7407541abb9de5df82fe83a96a2992f3d | /practice_sketch_40_video__cross_sections/ofApp.h | d84f85659489f30b011bb2ae1ed454d67c8d941f | [] | no_license | kcarollee/openFrameWorks-Personal-Projects | a081a838704238ef0f9f10a3204cce6bd94f447e | f50ef64e431693ddf20f17f5a30b496efadf9de2 | refs/heads/master | 2023-08-20T08:17:09.554074 | 2023-08-16T02:35:25 | 2023-08-16T02:35:25 | 172,909,668 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,146 | h | #pragma once
#include "ofMain.h"
#include "ofxHapPlayer.h"
class ofApp : public ofBaseApp{
public:
void setup();
void update();
void draw();
void keyPressed(int key);
void keyReleased(int key);
void mouseMoved(int x, int y );
void mouseDragged(int x, int y, int button);
void mousePressed(int x, int y, int button);
void mouseReleased(int x, int y, int button);
void mouseEntered(int x, int y);
void mouseExited(int x, int y);
void windowResized(int w, int h);
void dragEvent(ofDragInfo dragInfo);
void gotMessage(ofMessage msg);
void videoShaderSetupAndDraw(int frameIndex, int mode, glm::vec2 pos, float radius, float divWidth, float divHeight);
public:
ofVideoGrabber webcam;
ofxHapPlayer movie;
deque<ofImage*> webcamFrameDeque;
deque<ofFbo*> videoFboDeque;
int dequeSize;
int viewMode, dispMode, randomMode;
int smallFrameSize;
ofShader SketchShader, VideoShader;
ofFbo sketchFbo;
ofMesh sketchMesh;
string modeString, dispModeString, randString, loadingString;
bool loadingFrames, automateModes, webcamMode, videoMode;
float randomSelectionRange;
ofMesh videoMesh;
ofSoundPlayer track;
};
| [
"[email protected]"
] | |
fac5c730481d7f6dd1d8cf8b77744ad686b233cb | 910ea874eb5c6cddc9945e5ae870ac64569e96c7 | /include/Utils.h | 94565786bc735712d36d0f2fe57e86329c18b45e | [] | no_license | Mihafin/edu_ext_sort | 07c1179ee7b10d3a91784da2c3f8caa951661a0c | d2cdb35fa36bd6024e14cb9ce083f429ec963277 | refs/heads/master | 2020-04-06T18:49:25.983111 | 2018-11-15T13:17:01 | 2018-11-15T13:17:01 | 157,714,115 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,144 | h | #pragma once
#include <cstdlib>
#include <string>
#include <fstream>
#include <random>
#include <iostream>
#include "Exception.h"
namespace ExtSorter
{
struct Utils
{
static const size_t get_file_size(const char* file_path);
template <typename T>
static void fill(const std::string& file_path, size_t file_size, bool fill_test_data = false);
template<typename T>
static void check_result(const std::string& file_path);
static void copy(std::shared_ptr<std::fstream>& from_file, std::shared_ptr<std::fstream>& to_file, size_t m_memory_limit, size_t file_size);
};
}
template<typename T>
void ExtSorter::Utils::fill(const std::string& file_path, size_t file_size, bool fill_test_data)
{
size_t type_size = sizeof(T);
std::fstream file(file_path, std::ios::out | std::ios::binary | std::ios::trunc);
if(!file)
{
throw ExtSorter::Exception("file to fill does't exist");
}
if (fill_test_data)
{
// T arr[] = {1, 1, 2, 2, 1, 1, 1, 2, 1, 2, 3, 4, 5, 6, 8, 1, 1, 9, 0};
T arr[] = {1, 1, 2, 2, 1, 1, 1, 2, 1, 2, 3, 4, 5, 6, 8, 1};
file_size = sizeof(arr);
size_t arr_size = file_size / type_size;
for(int i = 0; i < arr_size; ++i)
{
std::cout << arr[i];
if(i < arr_size - 1) std::cout << ", ";
if(!file.write((char*) &arr[i], type_size)) throw ExtSorter::Exception("can't write to filled file!");
}
std::cout << std::endl;
}
else
{
int trace_cnt = 5;
size_t arr_size = file_size / type_size;
std::default_random_engine generator;
std::uniform_int_distribution<T> num(std::numeric_limits<T>::min(), std::numeric_limits<T>::max());
generator.seed(static_cast<unsigned int>(std::chrono::system_clock::now().time_since_epoch().count()));
for (size_t i = 0; i < arr_size; ++i) {
T a = num(generator);
if(i < trace_cnt || i > arr_size - trace_cnt)
std::cout << i << ": " << a << std::endl;
if(i==trace_cnt) std::cout << "..." << std::endl;
if(!file.write((char *) &a, type_size)) throw ExtSorter::Exception("can't write to filled file!");
}
}
file.close();
}
template<typename T>
void ExtSorter::Utils::check_result(const std::string& file_path)
{
size_t file_size = get_file_size(file_path.c_str());
if(file_size == 0) throw ExtSorter::Exception("checked file size == 0!");
std::fstream file(file_path, std::ios::in | std::ios::binary);
if(!file) throw ExtSorter::Exception("checked file does't exist!");
file.seekg(0);
size_t type_size = sizeof(T);
size_t el_cnt = file_size / type_size;
size_t cnt = 0;
T val, prev;
for (size_t j = 0; j < el_cnt; ++j)
{
if(!file.read((char*) &val, type_size)) throw ExtSorter::Exception("can't reed checked file!");
if(j==0)
{
prev = val;
continue;
}
if(val < prev)
{
throw ExtSorter::Exception("check result error!");
}
++cnt;
prev = val;
}
}
| [
"[email protected]"
] | |
788a5df493a5f46e86f7758ba974e4bdada17cc9 | 2906e4e12a2ce33b5216a3e38b7f1ccb9d1d45ce | /device.h | a921b0506807158b98274131e8104d84fbb10f40 | [] | no_license | KolesnikAndrew/oldMT01 | c242f329be99e68eb4a65ef46a0f4a480975d1e8 | 6909f28472973665288fc9bc849ac770121bf3f8 | refs/heads/master | 2020-04-27T23:53:30.238401 | 2019-03-10T09:04:58 | 2019-03-10T09:04:58 | 174,794,748 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,469 | h | /**
* @file device.h
* @brief Заголовочный файл класса устройства на порту
* @details
* @note
* @author Инженер-программист Пясецкий Владимир
* @copyright © TRIOLCORP, 2014
*/
#ifndef DEVICE_H_
#define DEVICE_H_
#include <vector>
#include <libxml++/libxml++.h>
#include "server.h"
#include "parametermodbusfile.h"
using namespace std;
class V7Parameter;
class V7Port;
class ParameterModbusFile;
/**
* @brief класс устройства на порту
*/
class V7Device
{
public:
V7Device();
virtual ~V7Device();
/**
* @fn Init
* @brief Инициализация перед использованием
* @details
* @param pXMLNode - указатель на XML-элемент из конфигурационного файла
* @param pPort - указатель на порт устройства
* @return true - удачно, false - действие не удалось
*/
virtual bool Init(const xmlpp::Node* pXMLNode, V7Port* pPort);
/**
* @fn GetPort
* @brief Получить указатель на порт
* @details
* @param
* @return указатель или NULL
*/
V7Port* getPort();
/**
* @fn Session
* @brief Сеанс связи с устройством
* @details
* @param
* @return
*/
virtual void Session() = 0;
bool setDataToDevice(inputData_type* inputData);
bool setDataToDevice(umkaFile_type* inputData);
unsigned int mSessionNumber; /**< Номер сессии опроса параметра (служебный параметр для внутренних механизмов) */
unsigned int getUmkaConfigFileIdAndSetConfigBuffer() const;
//validState_type cvrtErrToValidState(int errCode) const;
// int getTypeId() const;
protected:
std::vector<V7Parameter*> mvpParameters; /**< Список указателей на параметры устройства */
std::vector<V7Parameter*> mvpUmkaFiles; /**< Список указателей на параметры устройства */
std::vector<V7Parameter*> mvpStatusWords; /**< Список указателей на параметры устройства */
std::vector<V7Parameter*> mvpByteSingleArrays; /**< Список указателей на параметры устройства */
std::vector<V7Parameter*> mvpSingleMatrix;
unsigned int mNumber; /**< Номер устройства в рамках модема */
int mBaud; /**< Скорость обмена */
char mParity; /**< Четность ('N' -none, 'E' - четный, 'O' - нечетный) */
int mDataBit; /**< Количество бит данных 5, 6, 7 или 8 */
int mStopBit; /**< Количество стоп-бит 1 или 2 */
string mSerialNumber; /**< Серийный номер */
string mName; /**< Наименование (строка до 250 символов) */
V7Port* mpPort; /**< Указатель на порт устройства */
std::string mConfigAT27Buffer;
int mTypeID; //! тип устройства.
//! 1001 - DinDout_v1
//! 1002 - DinDout_v2
public:
validState_type cvrtErrToValidState(int errCode) const;
inDataState_type cvrtErrToInputDataSTate(int16_t err);
};
#endif /* DEVICE_H_ */
| [
"[email protected]"
] | |
980d240a6d613a904c0e84abd0ca6170435b9ae4 | ff2365298ad897c75b987a336e68ca2bed92c9a8 | /code/cp/CP/rayata.cpp | b2f09d67ac3f78e12544b2f1261625b04ab5da16 | [] | no_license | ajaymalik2592/practice_cpp_code | ec6e85c74614d1a3bf409c09d0e80fb927238e21 | d48ff131384cb10d8dab9d9388ea62c8a7d47726 | refs/heads/master | 2023-03-22T13:06:57.560400 | 2021-03-24T14:02:24 | 2021-03-24T14:02:24 | 350,808,987 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 492 | cpp | #include<bits/stdc++.h>
using namespace std;
int main(){
int T; cin>>T;
while(T--){
string s; cin>>s;
int count = 0;
for(int i=0;i<s.size()-1;i++){
if(s[i] == 'C'){
if(s[i+1] == 'E' || s[i+1] == 'S' || s[i+1] == 'C')
count++;
}
else if(s[i] == 'E'){
if(s[i+1] == 'S' || s[i+1] == 'E')
count++;
}
else if(s[i] == 'S'){
if(s[i+1] == 'S')
count++;
}
}
if(count == s.size()-1)
cout<< "yes" <<endl;
else
cout<< "no" <<endl;
}
}
| [
"[email protected]"
] | |
6d27e1f57050bc0816accb2687bec1f4c9c9f663 | c276d4c4934fde84b78aed4ef2bce3745af5c21f | /2019SkillContest_DaeGuP/2019SkillContest_DaeGu.cpp | 6b5ec1db1bc7c433664874537b1cbf93de1c7879 | [] | no_license | wisemin01/2019SkillContest_DaeGu | 4c33fe13fbd208a55a13923213711e256b690cc7 | ade201e9e3d728c73f474cb755b8380b5173134a | refs/heads/master | 2020-06-27T00:23:26.251392 | 2019-08-26T01:23:31 | 2019-08-26T01:23:31 | 199,797,705 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,863 | cpp | //--------------------------------------------------------------------------------------
// File: 2019SkillContest_DaeGu.cpp
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//--------------------------------------------------------------------------------------
#include "DXUT.h"
#include "resource.h"
#include "MainGame.h"
#include "Engine/BaseLayer/Timer.h"
MainGame* g_pMainGame = nullptr;
//--------------------------------------------------------------------------------------
// Rejects any D3D9 devices that aren't acceptable to the app by returning false
//--------------------------------------------------------------------------------------
bool CALLBACK IsD3D9DeviceAcceptable( D3DCAPS9* pCaps, D3DFORMAT AdapterFormat, D3DFORMAT BackBufferFormat,
bool bWindowed, void* pUserContext )
{
// Typically want to skip back buffer formats that don't support alpha blending
IDirect3D9* pD3D = DXUTGetD3D9Object();
if( FAILED( pD3D->CheckDeviceFormat( pCaps->AdapterOrdinal, pCaps->DeviceType,
AdapterFormat, D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING,
D3DRTYPE_TEXTURE, BackBufferFormat ) ) )
return false;
return true;
}
//--------------------------------------------------------------------------------------
// Before a device is created, modify the device settings as needed
//--------------------------------------------------------------------------------------
bool CALLBACK ModifyDeviceSettings( DXUTDeviceSettings* pDeviceSettings, void* pUserContext )
{
return true;
}
//--------------------------------------------------------------------------------------
// Create any D3D9 resources that will live through a device reset (D3DPOOL_MANAGED)
// and aren't tied to the back buffer size
//--------------------------------------------------------------------------------------
HRESULT CALLBACK OnD3D9CreateDevice( IDirect3DDevice9* pd3dDevice, const D3DSURFACE_DESC* pBackBufferSurfaceDesc,
void* pUserContext )
{
g_pMainGame->Initialize();
return S_OK;
}
//--------------------------------------------------------------------------------------
// Create any D3D9 resources that won't live through a device reset (D3DPOOL_DEFAULT)
// or that are tied to the back buffer size
//--------------------------------------------------------------------------------------
HRESULT CALLBACK OnD3D9ResetDevice( IDirect3DDevice9* pd3dDevice, const D3DSURFACE_DESC* pBackBufferSurfaceDesc,
void* pUserContext )
{
g_pMainGame->OnResetDevice();
return S_OK;
}
//--------------------------------------------------------------------------------------
// Handle updates to the scene. This is called regardless of which D3D API is used
//--------------------------------------------------------------------------------------
void CALLBACK OnFrameMove( double fTime, float fElapsedTime, void* pUserContext )
{
g_pMainGame->Update();
}
//--------------------------------------------------------------------------------------
// Render the scene using the D3D9 device
//--------------------------------------------------------------------------------------
void CALLBACK OnD3D9FrameRender( IDirect3DDevice9* pd3dDevice, double fTime, float fElapsedTime, void* pUserContext )
{
HRESULT hr;
const Color color = Color(0.176f, 0.196f, 0.667f, 0.0f);
// Clear the render target and the zbuffer
V( pd3dDevice->Clear( 0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, color, 1.0f, 0 ) );
// Render the scene
if( SUCCEEDED( pd3dDevice->BeginScene() ) )
{
g_pMainGame->Render();
V( pd3dDevice->EndScene() );
}
}
//--------------------------------------------------------------------------------------
// Handle messages to the application
//--------------------------------------------------------------------------------------
LRESULT CALLBACK MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam,
bool* pbNoFurtherProcessing, void* pUserContext )
{
return 0;
}
//--------------------------------------------------------------------------------------
// Release D3D9 resources created in the OnD3D9ResetDevice callback
//--------------------------------------------------------------------------------------
void CALLBACK OnD3D9LostDevice( void* pUserContext )
{
g_pMainGame->OnLostDevice();
}
//--------------------------------------------------------------------------------------
// Release D3D9 resources created in the OnD3D9CreateDevice callback
//--------------------------------------------------------------------------------------
void CALLBACK OnD3D9DestroyDevice( void* pUserContext )
{
g_pMainGame->Release();
}
//--------------------------------------------------------------------------------------
// Initialize everything and go into a render loop
//--------------------------------------------------------------------------------------
INT WINAPI wWinMain( HINSTANCE, HINSTANCE, LPWSTR, int )
{
// Enable run-time memory check for debug builds.
#if defined(DEBUG) | defined(_DEBUG)
AllocConsole();
(void)(freopen("CONOUT$", "a", stdout));
(void)(freopen("CONOUT$", "a", stdout));
(void)(freopen("CONIN$", "r", stdin));
_CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
/// _CrtSetBreakAlloc(452);
#endif
// Set the callback functions
DXUTSetCallbackD3D9DeviceAcceptable( IsD3D9DeviceAcceptable );
DXUTSetCallbackD3D9DeviceCreated( OnD3D9CreateDevice );
DXUTSetCallbackD3D9DeviceReset( OnD3D9ResetDevice );
DXUTSetCallbackD3D9FrameRender( OnD3D9FrameRender );
DXUTSetCallbackD3D9DeviceLost( OnD3D9LostDevice );
DXUTSetCallbackD3D9DeviceDestroyed( OnD3D9DestroyDevice );
DXUTSetCallbackDeviceChanging( ModifyDeviceSettings );
DXUTSetCallbackMsgProc( MsgProc );
DXUTSetCallbackFrameMove( OnFrameMove );
// TODO: Perform any application-level initialization here
// DXUT_ERR_MSGBOX(L"CREATE WINDOW", 0L);
g_pMainGame = new MainGame();
// Initialize DXUT and create the desired Win32 window and Direct3D device for the application
DXUTInit( true, true ); // Parse the command line and show msgboxes
DXUTSetHotkeyHandling( true, true, true ); // handle the default hotkeys
DXUTSetCursorSettings( true, true ); // Show the cursor and clip it when in full screen
DXUTCreateWindow( L"WINDOW" );
DXUTCreateDevice( Window::IsWindowed, Window::Width, Window::Height );
// Start the render loop
DXUTMainLoop();
// TODO: Perform any application-level cleanup here
SAFE_DELETE(g_pMainGame);
#if defined(DEBUG) | defined(_DEBUG)
FreeConsole();
#endif
Timer::RemoveAll();
return DXUTGetExitCode();
}
| [
"[email protected]"
] | |
a903d35fc8f1be24af89b6950438c14932d82bea | f7b789e7311ebf20fa88b71f50acccfd9191aaec | /UiCtrls/UiCtrls/Tracker.cpp | d050fffc4e1cf0c8ee07553af00aa78e93e74ef5 | [] | no_license | 15831944/xc_code | 95b906cfd50ad0d5cc9abf9d341c2ea6278aee3e | 6b4556ced2aab4be1ca25e03052927953cb9d8ed | refs/heads/master | 2020-09-11T11:48:41.610232 | 2019-03-20T01:24:08 | 2019-03-20T01:24:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,115 | cpp | #include "stdafx.h"
#include "Tracker.h"
bool TrackDragAndDrop(CTracker& tracker, HWND hWnd)
{
bool bResult=true;
tracker.BeginDrag();
::SetCapture(hWnd);
MSG msg;
while((::GetCapture()==hWnd)&&
(GetMessage(&msg, NULL, 0, 0)))
{
if(!tracker.ProcessWindowMessage(&msg))
{
switch(msg.message)
{
case WM_MOUSEMOVE:
tracker.OnMove(GET_X_LPARAM( msg.lParam), GET_Y_LPARAM(msg.lParam));
break;
case WM_RBUTTONUP:
::ReleaseCapture();
bResult=tracker.OnDropRightButton(GET_X_LPARAM( msg.lParam), GET_Y_LPARAM(msg.lParam));
break;
case WM_LBUTTONUP:
::ReleaseCapture();
bResult=tracker.OnDropLeftButton(GET_X_LPARAM( msg.lParam), GET_Y_LPARAM(msg.lParam));
break;
case WM_KEYDOWN:
if(msg.wParam!=VK_ESCAPE)
break;
case WM_RBUTTONDOWN:
case WM_LBUTTONDOWN:
::ReleaseCapture();
tracker.OnCancelDrag(GET_X_LPARAM( msg.lParam), GET_Y_LPARAM(msg.lParam));
bResult=false;
break;
case WM_SYSKEYDOWN:
::ReleaseCapture();
tracker.OnCancelDrag(GET_X_LPARAM( msg.lParam), GET_Y_LPARAM(msg.lParam));
bResult=false;
default:
DispatchMessage(&msg);
}
}
}
tracker.EndDrag(!bResult);
ASSERT(::GetCapture()!=hWnd);
return bResult;
}
void TrackDragAndDrop(CCallBackListener&listener, HWND hWnd, POINT startPoint, bool lockWindowUpdate/* = false*/, HWND clientViewWnd/* = NULL*/)
{
ASSERT(::IsWindow( hWnd));
if (!::DragDetect( hWnd, startPoint))
return;
// tracker drawing conflicts with dock pane drawing
// disable drawing in the window during drag and drop operations.
if ( lockWindowUpdate)
::LockWindowUpdate( hWnd);
MSG msg;
bool dragging = false;
::SetCapture( hWnd);
while((::GetCapture()==hWnd) && (::GetMessage( &msg, NULL, 0, 0)))
{
CPoint hitPoint = CPoint( GET_X_LPARAM( msg.lParam), GET_Y_LPARAM( msg.lParam));
::ClientToScreen( hWnd, &hitPoint);
switch( msg.message) {
case WM_MOUSEMOVE:
{
if (!dragging)
{
dragging = true;
listener.DragStart( hWnd, clientViewWnd, hitPoint.x, hitPoint.y, static_cast<DWORD>(msg.wParam));
}
bool cancelDrag = false;
listener.DragOver( hWnd, clientViewWnd, hitPoint.x, hitPoint.y, static_cast<DWORD>(msg.wParam), cancelDrag );
if (cancelDrag)
{
dragging = false;
listener.DragCancel(hWnd, NULL);
::ReleaseCapture();
}
}
break;
case WM_LBUTTONUP:
if (dragging)
{
dragging = false;
listener.DragDrop( hWnd, clientViewWnd, hitPoint.x, hitPoint.y, static_cast<DWORD>(msg.wParam));
}
::ReleaseCapture();
break;
case WM_KEYDOWN:
case WM_SYSKEYDOWN:
switch (msg.wParam)
{
case VK_CONTROL:
case VK_SHIFT:
break;
default:
if (dragging)
{
dragging = false;
listener.DragCancel(hWnd, NULL);
}
::ReleaseCapture();
}
default:
::TranslateMessage(&msg);
::DispatchMessage(&msg);
}
}
// tidy up
if (dragging)
listener.DragCancel( hWnd, clientViewWnd);
if (lockWindowUpdate)
::LockWindowUpdate( NULL);
} | [
"[email protected]"
] | |
e46ec023d1065743e3234ecb06be4e65656d1da9 | 34f25fab358b91100ee0069b4e10784dd6db5e0b | /static-genetic-algorithm/include/host.h | f28aec9b41456cf3ef3fd4696d8d66dcd6db1fb1 | [] | no_license | qizzpzlz/simulator | ca8feafdda26b1f396041f1dd865069b6314e387 | 00e937ab1ade87b8a48a715466507310ff7e8a05 | refs/heads/master | 2021-07-11T20:23:56.896762 | 2020-06-28T15:29:55 | 2020-06-28T15:29:55 | 168,270,204 | 3 | 6 | null | 2020-05-15T07:05:19 | 2019-01-30T03:06:06 | C++ | UTF-8 | C++ | false | false | 1,233 | h | #pragma once
#include <vector>
#include "job.h"
#include <set>
#include <algorithm>
namespace genetic
{
struct HostInfo
{
float cpu_factor;
unsigned char max_slots;
bool write(std::streambuf& buf) const
{
const auto size = sizeof(HostInfo);
return buf.sputn(reinterpret_cast<const char*>(this), size);
}
};
struct Host
{
//HostInfo* info;
unsigned char slots_remaining;
std::vector<Job> allocated_jobs;
//std::set<Job>
//[[nodiscard]] unsigned char slots_remaining() const { return max_slots - slots_used; }
void allocate_immediately(Job&& job, float cpu_factor)
{
auto estimated_time = job.cpu_time() / cpu_factor + job.non_cpu_time();
job.set_finish_time(estimated_time);
push_and_sort(job);
}
void allocate(Job&& job, uint32_t delay, float cpu_factor)
{
auto estimated_time = job.cpu_time() / cpu_factor + job.non_cpu_time();
job.set_finish_time(estimated_time, delay);
push_and_sort(job);
}
void push_and_sort(Job& job)
{
allocated_jobs.push_back(job);
std::sort(allocated_jobs.begin(), allocated_jobs.end(),
[](Job& a, Job& b)
{
return a.finish_time() > b.finish_time();
});
slots_remaining -= job.slots();
}
};
}
| [
"[email protected]"
] | |
81b768b035a60e46d75126d6c497f20ab5ad879e | 417fb2309408c418b4ec643512ac38172c4338a2 | /src/src/AST/unary_operator.cpp | 945c61dc783b19d7f95f883b79a695fafa6cc4c7 | [
"MIT"
] | permissive | allen880117/NCTU-compiler-f19-hw5 | 03bcae8fb02ef3847b70a3e753b56caeae240108 | 61dba0ef91977b08c4be66d6bb5dd3aca8592ac0 | refs/heads/master | 2022-04-03T13:37:05.697683 | 2020-02-12T12:33:18 | 2020-02-12T12:33:18 | 235,929,961 | 0 | 1 | null | 2020-02-12T12:33:19 | 2020-01-24T02:55:05 | C++ | UTF-8 | C++ | false | false | 912 | cpp | #include "AST/unary_operator.hpp"
#include <cstdlib>
#include <iomanip>
#include <iostream>
#include <string>
UnaryOperatorNode::UnaryOperatorNode(int _line_number, int _col_number,
EnumOperator _op, Node _operand) {
this->line_number = _line_number;
this->col_number = _col_number;
this->op = _op;
this->operand = _operand;
}
UnaryOperatorNode::~UnaryOperatorNode() { SAFE_DELETE(this->operand) }
void UnaryOperatorNode::print() {
std::cout << "unary operator <line: " << line_number
<< ", col: " << col_number << "> ";
// cout << operator
switch (op) {
case EnumOperator::OP_NOT:
std::cout << "not";
break;
case EnumOperator::OP_MINUS:
std::cout << "neg";
break;
default:
std::cout << "unknown";
break;
}
// cout << operator END
std::cout << std::endl;
} | [
"[email protected]"
] | |
bf9e3403b96e6b9b4c91251c16fc4a0e07649f5e | 1f87be9520c0722833a5c3d49c06a33b546e4926 | /Motus/main.cpp | fd03062ef81833efd708d052f35329e27576d065 | [] | no_license | FredericCanaud/AlgorithmesC-CPP | 28277f79da9368f0c0e1d7d25a54ac14e5f382a3 | 6685f33177c673c9ce7f376a970aa9c3381c5687 | refs/heads/master | 2021-04-10T16:19:19.862655 | 2020-03-21T09:44:02 | 2020-03-21T09:44:02 | 248,945,945 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,767 | cpp | #include <iostream>
#include <string>
using namespace std;
const int MAX_NOM = 50;
int main()
{
void Majuscule(string nom[MAX_NOM], int nb_nom);
void Palindrome(string nom[MAX_NOM], int nb_nom);
void NombreVoyelles(string nom[MAX_NOM], int nb_nom);
void SaisieNoms(string nom[MAX_NOM], int &nb_nom);
string nom[MAX_NOM];
int choix;
int nb_nom;
string mot;
nb_nom = 0;
cout << " Programme noms :" << endl << endl;
do {
cout << " 1 - Saisir le tableau de noms." << endl;
cout << " 2 - Afficher le nombre de voyelles de chaque nom." << endl;
cout << " 3 - Verifier si les noms sont des palindromes." << endl;
cout << " 4 - Mettre toutes les lettres de chaque mot en majuscules." << endl;
cout << " 5 - Quitter." << endl << endl;
cout << " Entrez votre choix : ";
cin >> choix;
cout << endl;
switch (choix)
{
case 1:
SaisieNoms(nom, nb_nom);
cout << endl;
break;
case 2:
if (nb_nom == 0)
{
cout << " Erreur : il n'y a aucun nom saisi dans le tableau. " << endl << endl;
break;
}
else
{
NombreVoyelles(nom, nb_nom);
cout << endl;
break;
}
case 3:
if (nb_nom == 0)
{
cout << " Erreur : il n'y a aucun nom saisi dans le tableau. " << endl << endl;
break;
}
else
{
Palindrome(nom, nb_nom);
cout << endl;
break;
}
case 4:
if (nb_nom == 0)
{
cout << " Erreur : il n'y a aucun nom saisi dans le tableau. " << endl << endl;
break;
}
else
{
Majuscule(nom, nb_nom);
cout << endl;
break;
}
case 5:
cout << " Au revoir !" << endl;
break;
default:
cout << " Erreur : choix." << endl;
}
} while (choix != 5);
system("PAUSE");
} | [
"[email protected]"
] | |
5e6f8654dcf4a61f844d4c420e9b7ae157ac1625 | 8d63452d9dbc650884966b07a5652975f1e71961 | /dlls/ai_memory.cpp | 8f1f912c6b676a0539c8d326798138416ad3e6c0 | [] | no_license | 0TheSpy/hl2sdk | d2656cb99304ca8b7be7b67631e45f416539f02c | 8b2833d5909f27219d90000260887a3aeb32d485 | refs/heads/master | 2023-03-15T20:28:37.485807 | 2012-05-30T01:09:21 | 2012-05-30T01:09:21 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 19,353 | cpp | //========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose: An NPC's memory of potential enemies
//
//=============================================================================//
#include "cbase.h"
#include "isaverestore.h"
#include "ai_debug.h"
#include "ai_memory.h"
#include "ai_basenpc.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
#define EMEMORY_POOL_SIZE 64
#define AI_FREE_KNOWLEDGE_DURATION 1.75
//-----------------------------------------------------------------------------
// AI_EnemyInfo_t
//
//-----------------------------------------------------------------------------
DEFINE_FIXEDSIZE_ALLOCATOR( AI_EnemyInfo_t, EMEMORY_POOL_SIZE, CMemoryPool::GROW_FAST );
//-----------------------------------------------------------------------------
AI_EnemyInfo_t::AI_EnemyInfo_t(void)
{
hEnemy = NULL;
vLastKnownLocation = vec3_origin;
vLastSeenLocation = vec3_origin;
timeLastSeen = 0;
timeFirstSeen = 0;
timeLastReacquired = 0;
timeValidEnemy = 0;
timeLastReceivedDamageFrom = 0;
timeAtFirstHand = AI_INVALID_TIME;
bDangerMemory = 0;
bEludedMe = 0;
bUnforgettable = 0;
bMobbedMe = 0;
}
//-----------------------------------------------------------------------------
// CAI_EnemiesListSaveRestoreOps
//
// Purpose: Handles save and load for enemy memories
//
//-----------------------------------------------------------------------------
class CAI_EnemiesListSaveRestoreOps : public CDefSaveRestoreOps
{
public:
CAI_EnemiesListSaveRestoreOps()
{
}
virtual void Save( const SaveRestoreFieldInfo_t &fieldInfo, ISave *pSave )
{
CAI_Enemies::CMemMap *pMemMap = (CAI_Enemies::CMemMap *)fieldInfo.pField;
int nMemories = pMemMap->Count();
pSave->WriteInt( &nMemories );
for ( CAI_Enemies::CMemMap::IndexType_t i = pMemMap->FirstInorder(); i != pMemMap->InvalidIndex(); i = pMemMap->NextInorder( i ) )
{
pSave->WriteAll( (*pMemMap)[i] );
}
}
virtual void Restore( const SaveRestoreFieldInfo_t &fieldInfo, IRestore *pRestore )
{
CAI_Enemies::CMemMap *pMemMap = (CAI_Enemies::CMemMap *)fieldInfo.pField;
Assert( pMemMap->Count() == 0 );
int nMemories = pRestore->ReadInt();
while ( nMemories-- )
{
AI_EnemyInfo_t *pAddMemory = new AI_EnemyInfo_t;
pRestore->ReadAll( pAddMemory );
if ( pAddMemory->hEnemy != NULL )
{
pMemMap->Insert( pAddMemory->hEnemy, pAddMemory );
}
else
delete pAddMemory;
}
}
virtual void MakeEmpty( const SaveRestoreFieldInfo_t &fieldInfo )
{
CAI_Enemies::CMemMap *pMemMap = (CAI_Enemies::CMemMap *)fieldInfo.pField;
for ( CAI_Enemies::CMemMap::IndexType_t i = pMemMap->FirstInorder(); i != pMemMap->InvalidIndex(); i = pMemMap->NextInorder( i ) )
{
delete (*pMemMap)[i];
}
pMemMap->RemoveAll();
}
virtual bool IsEmpty( const SaveRestoreFieldInfo_t &fieldInfo )
{
CAI_Enemies::CMemMap *pMemMap = (CAI_Enemies::CMemMap *)fieldInfo.pField;
return ( pMemMap->Count() == 0 );
}
} g_AI_MemoryListSaveRestoreOps;
//-----------------------------------------------------------------------------
// CAI_Enemies
//
// Purpose: Stores a set of AI_EnemyInfo_t's
//
//-----------------------------------------------------------------------------
BEGIN_SIMPLE_DATADESC( CAI_Enemies )
DEFINE_CUSTOM_FIELD( m_Map, &g_AI_MemoryListSaveRestoreOps ),
DEFINE_FIELD( m_flFreeKnowledgeDuration, FIELD_FLOAT ),
DEFINE_FIELD( m_flEnemyDiscardTime, FIELD_FLOAT ),
DEFINE_FIELD( m_vecDefaultLKP, FIELD_POSITION_VECTOR ),
DEFINE_FIELD( m_vecDefaultLSP, FIELD_POSITION_VECTOR ),
DEFINE_FIELD( m_serial, FIELD_INTEGER ),
END_DATADESC()
BEGIN_SIMPLE_DATADESC( AI_EnemyInfo_t )
DEFINE_FIELD( vLastKnownLocation, FIELD_POSITION_VECTOR ),
DEFINE_FIELD( vLastSeenLocation, FIELD_POSITION_VECTOR ),
DEFINE_FIELD( hEnemy, FIELD_EHANDLE ),
DEFINE_FIELD( timeLastSeen, FIELD_TIME ),
DEFINE_FIELD( timeFirstSeen, FIELD_TIME ),
DEFINE_FIELD( timeLastReacquired, FIELD_TIME ),
DEFINE_FIELD( timeValidEnemy, FIELD_TIME ),
DEFINE_FIELD( timeLastReceivedDamageFrom, FIELD_TIME ),
DEFINE_FIELD( timeAtFirstHand, FIELD_TIME ),
DEFINE_FIELD( bDangerMemory, FIELD_BOOLEAN ),
DEFINE_FIELD( bEludedMe, FIELD_BOOLEAN ),
DEFINE_FIELD( bUnforgettable, FIELD_BOOLEAN ),
DEFINE_FIELD( bMobbedMe, FIELD_BOOLEAN ),
// NOT SAVED nextEMemory
END_DATADESC()
//-----------------------------------------------------------------------------
CAI_Enemies::CAI_Enemies(void)
{
m_flFreeKnowledgeDuration = AI_FREE_KNOWLEDGE_DURATION;
m_flEnemyDiscardTime = AI_DEF_ENEMY_DISCARD_TIME;
m_vecDefaultLKP = vec3_invalid;
m_vecDefaultLSP = vec3_invalid;
m_serial = 0;
SetDefLessFunc( m_Map );
}
//-----------------------------------------------------------------------------
CAI_Enemies::~CAI_Enemies()
{
for ( CMemMap::IndexType_t i = m_Map.FirstInorder(); i != m_Map.InvalidIndex(); i = m_Map.NextInorder( i ) )
{
delete m_Map[i];
}
}
//-----------------------------------------------------------------------------
// Purpose: Purges any dead enemies from memory
//-----------------------------------------------------------------------------
AI_EnemyInfo_t *CAI_Enemies::GetFirst( AIEnemiesIter_t *pIter )
{
CMemMap::IndexType_t i = m_Map.FirstInorder();
*pIter = (AIEnemiesIter_t)(unsigned)i;
if ( i == m_Map.InvalidIndex() )
return NULL;
if ( m_Map[i]->hEnemy == NULL )
return GetNext( pIter );
return m_Map[i];
}
//-----------------------------------------------------------------------------
AI_EnemyInfo_t *CAI_Enemies::GetNext( AIEnemiesIter_t *pIter )
{
CMemMap::IndexType_t i = (CMemMap::IndexType_t)((unsigned)(*pIter));
if ( i == m_Map.InvalidIndex() )
return NULL;
i = m_Map.NextInorder( i );
*pIter = (AIEnemiesIter_t)(unsigned)i;
if ( i == m_Map.InvalidIndex() )
return NULL;
if ( m_Map[i]->hEnemy == NULL )
return GetNext( pIter );
return m_Map[i];
}
//-----------------------------------------------------------------------------
AI_EnemyInfo_t *CAI_Enemies::Find( CBaseEntity *pEntity, bool bTryDangerMemory )
{
if ( pEntity == AI_UNKNOWN_ENEMY )
pEntity = NULL;
CMemMap::IndexType_t i = m_Map.Find( pEntity );
if ( i == m_Map.InvalidIndex() )
{
if ( !bTryDangerMemory || ( i = m_Map.Find( NULL ) ) == m_Map.InvalidIndex() )
return NULL;
Assert(m_Map[i]->bDangerMemory == true);
}
return m_Map[i];
}
//-----------------------------------------------------------------------------
AI_EnemyInfo_t *CAI_Enemies::GetDangerMemory()
{
CMemMap::IndexType_t i = m_Map.Find( NULL );
if ( i == m_Map.InvalidIndex() )
return NULL;
Assert(m_Map[i]->bDangerMemory == true);
return m_Map[i];
}
//-----------------------------------------------------------------------------
bool CAI_Enemies::ShouldDiscardMemory( AI_EnemyInfo_t *pMemory )
{
CBaseEntity *pEnemy = pMemory->hEnemy;
if ( pEnemy )
{
CAI_BaseNPC *pEnemyNPC = pEnemy->MyNPCPointer();
if ( pEnemyNPC && pEnemyNPC->GetState() == NPC_STATE_DEAD )
return true;
}
else
{
if ( !pMemory->bDangerMemory )
return true;
}
if ( !pMemory->bUnforgettable &&
gpGlobals->curtime > pMemory->timeLastSeen + m_flEnemyDiscardTime )
{
return true;
}
return false;
}
//-----------------------------------------------------------------------------
void CAI_Enemies::RefreshMemories(void)
{
AI_PROFILE_SCOPE(CAI_Enemies_RefreshMemories);
// -------------------
// Check each record
// -------------------
CMemMap::IndexType_t i = m_Map.FirstInorder();
while ( i != m_Map.InvalidIndex() )
{
AI_EnemyInfo_t *pMemory = m_Map[i];
CMemMap::IndexType_t iNext = m_Map.NextInorder( i ); // save so can remove
if ( ShouldDiscardMemory( pMemory ) )
{
delete pMemory;
m_Map.RemoveAt(i);
}
else if ( pMemory->hEnemy )
{
if ( gpGlobals->curtime <= pMemory->timeLastSeen + m_flFreeKnowledgeDuration )
{
// Free knowledge is ignored if the target has notarget on
if ( !(pMemory->hEnemy->GetFlags() & FL_NOTARGET) )
{
pMemory->vLastKnownLocation = pMemory->hEnemy->GetAbsOrigin();
}
}
if ( gpGlobals->curtime <= pMemory->timeLastSeen )
{
pMemory->vLastSeenLocation = pMemory->hEnemy->GetAbsOrigin();
}
}
i = iNext;
}
}
//-----------------------------------------------------------------------------
// Purpose: Updates information about our enemies
// Output : Returns true if new enemy, false if already know of enemy
//-----------------------------------------------------------------------------
bool CAI_Enemies::UpdateMemory(CAI_Network* pAINet, CBaseEntity *pEnemy, const Vector &vPosition, float reactionDelay, bool firstHand )
{
if ( pEnemy == AI_UNKNOWN_ENEMY )
pEnemy = NULL;
const float DIST_TRIGGER_REACQUIRE_SQ = Square(20.0 * 12.0);
const float TIME_TRIGGER_REACQUIRE = 4.0;
const float MIN_DIST_TIME_TRIGGER_REACQUIRE_SQ = Square(4.0 * 12.0);
AI_EnemyInfo_t *pMemory = Find( pEnemy );
// -------------------------------------------
// Otherwise just update my own
// -------------------------------------------
// Update enemy information
if ( pMemory )
{
Assert(pEnemy || pMemory->bDangerMemory == true);
if ( firstHand )
pMemory->timeLastSeen = gpGlobals->curtime;
pMemory->bEludedMe = false;
float deltaDist = (pMemory->vLastKnownLocation - vPosition).LengthSqr();
if (deltaDist>DIST_TRIGGER_REACQUIRE_SQ || ( deltaDist>MIN_DIST_TIME_TRIGGER_REACQUIRE_SQ && ( gpGlobals->curtime - pMemory->timeLastSeen ) > TIME_TRIGGER_REACQUIRE ) )
{
pMemory->timeLastReacquired = gpGlobals->curtime;
}
// Only update if the enemy has moved
if (deltaDist>Square(12.0))
{
pMemory->vLastKnownLocation = vPosition;
}
// Update the time at which we first saw him firsthand
if ( firstHand && pMemory->timeAtFirstHand == AI_INVALID_TIME )
{
pMemory->timeAtFirstHand = gpGlobals->curtime;
}
return false;
}
// If not on my list of enemies add it
AI_EnemyInfo_t *pAddMemory = new AI_EnemyInfo_t;
pAddMemory->vLastKnownLocation = vPosition;
if ( firstHand )
{
pAddMemory->timeLastReacquired = pAddMemory->timeFirstSeen = pAddMemory->timeLastSeen = pAddMemory->timeAtFirstHand = gpGlobals->curtime;
}
else
{
// Block free knowledge
pAddMemory->timeLastReacquired = pAddMemory->timeFirstSeen = pAddMemory->timeLastSeen = ( gpGlobals->curtime - (m_flFreeKnowledgeDuration + 0.01) );
pAddMemory->timeAtFirstHand = AI_INVALID_TIME;
}
if ( reactionDelay > 0.0 )
pAddMemory->timeValidEnemy = gpGlobals->curtime + reactionDelay;
pAddMemory->bEludedMe = false;
// I'm either remembering a postion of an enmey of just a danger position
pAddMemory->hEnemy = pEnemy;
pAddMemory->bDangerMemory = ( pEnemy == NULL );
// add to the list
m_Map.Insert( pEnemy, pAddMemory );
m_serial++;
return true;
}
//------------------------------------------------------------------------------
// Purpose : Returns true if this enemy is part of my memory
//------------------------------------------------------------------------------
void CAI_Enemies::OnTookDamageFrom( CBaseEntity *pEnemy )
{
AI_EnemyInfo_t *pMemory = Find( pEnemy, true );
if ( pMemory )
pMemory->timeLastReceivedDamageFrom = gpGlobals->curtime;
}
//------------------------------------------------------------------------------
// Purpose : Returns true if this enemy is part of my memory
//------------------------------------------------------------------------------
bool CAI_Enemies::HasMemory( CBaseEntity *pEnemy )
{
return ( Find( pEnemy ) != NULL );
}
//-----------------------------------------------------------------------------
// Purpose: Clear information about our enemy
//-----------------------------------------------------------------------------
void CAI_Enemies::ClearMemory(CBaseEntity *pEnemy)
{
CMemMap::IndexType_t i = m_Map.Find( pEnemy );
if ( i != m_Map.InvalidIndex() )
{
delete m_Map[i];
m_Map.RemoveAt( i );
}
}
//-----------------------------------------------------------------------------
// Purpose: Notes that the given enemy has eluded me
//-----------------------------------------------------------------------------
void CAI_Enemies::MarkAsEluded( CBaseEntity *pEnemy )
{
AI_EnemyInfo_t *pMemory = Find( pEnemy );
if ( pMemory )
{
pMemory->bEludedMe = true;
}
}
//-----------------------------------------------------------------------------
// Purpose: Returns last known posiiton of given enemy
//-----------------------------------------------------------------------------
const Vector &CAI_Enemies::LastKnownPosition( CBaseEntity *pEnemy )
{
AI_EnemyInfo_t *pMemory = Find( pEnemy, true );
if ( pMemory )
{
m_vecDefaultLKP = pMemory->vLastKnownLocation;
}
else
{
DevWarning( 2,"Asking LastKnownPosition for enemy that's not in my memory!!\n");
}
return m_vecDefaultLKP;
}
//-----------------------------------------------------------------------------
// Purpose: Returns the last position the enemy was SEEN at. This will always be
// different than LastKnownPosition() when the enemy is out of sight, because
// the last KNOWN position will be updated for a number of seconds after the
// player disappears.
//-----------------------------------------------------------------------------
const Vector &CAI_Enemies::LastSeenPosition( CBaseEntity *pEnemy )
{
AI_EnemyInfo_t *pMemory = Find( pEnemy, true );
if ( pMemory )
{
m_vecDefaultLSP = pMemory->vLastSeenLocation;
}
else
{
DevWarning( 2,"Asking LastSeenPosition for enemy that's not in my memory!!\n");
}
return m_vecDefaultLSP;
}
float CAI_Enemies::TimeLastReacquired( CBaseEntity *pEnemy )
{
// I've never seen something that doesn't exist
if (!pEnemy)
return 0;
AI_EnemyInfo_t *pMemory = Find( pEnemy, true );
if ( pMemory )
return pMemory->timeLastReacquired;
if ( pEnemy != AI_UNKNOWN_ENEMY )
DevWarning( 2,"Asking TimeLastReacquired for enemy that's not in my memory!!\n");
return AI_INVALID_TIME;
}
//-----------------------------------------------------------------------------
// Purpose: Sets position to the last known position of an enemy. If enemy
// was not found returns last memory of danger position if it exists
// Output : Returns false is no position is known
//-----------------------------------------------------------------------------
float CAI_Enemies::LastTimeSeen( CBaseEntity *pEnemy, bool bCheckDangerMemory /*= true*/ )
{
// I've never seen something that doesn't exist
if (!pEnemy)
return 0;
AI_EnemyInfo_t *pMemory = Find( pEnemy, bCheckDangerMemory );
if ( pMemory )
return pMemory->timeLastSeen;
if ( pEnemy != AI_UNKNOWN_ENEMY )
DevWarning( 2,"Asking LastTimeSeen for enemy that's not in my memory!!\n");
return AI_INVALID_TIME;
}
//-----------------------------------------------------------------------------
// Purpose: Get the time at which the enemy was first seen.
// Output : Returns false is no position is known
//-----------------------------------------------------------------------------
float CAI_Enemies::FirstTimeSeen( CBaseEntity *pEnemy)
{
// I've never seen something that doesn't exist
if (!pEnemy)
return 0;
AI_EnemyInfo_t *pMemory = Find( pEnemy, true );
if ( pMemory )
return pMemory->timeFirstSeen;
if ( pEnemy != AI_UNKNOWN_ENEMY )
DevWarning( 2,"Asking FirstTimeSeen for enemy that's not in my memory!!\n");
return AI_INVALID_TIME;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *pEnemy -
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CAI_Enemies::HasFreeKnowledgeOf( CBaseEntity *pEnemy )
{
// I've never seen something that doesn't exist
if (!pEnemy)
return 0;
AI_EnemyInfo_t *pMemory = Find( pEnemy, true );
if ( pMemory )
{
float flFreeKnowledgeTime = pMemory->timeLastSeen + m_flFreeKnowledgeDuration;
return ( gpGlobals->curtime < flFreeKnowledgeTime );
}
if ( pEnemy != AI_UNKNOWN_ENEMY )
DevWarning( 2,"Asking HasFreeKnowledgeOf for enemy that's not in my memory!!\n");
return AI_INVALID_TIME;
}
//-----------------------------------------------------------------------------
float CAI_Enemies::LastTimeTookDamageFrom( CBaseEntity *pEnemy)
{
// I've never seen something that doesn't exist
if (!pEnemy)
return 0;
AI_EnemyInfo_t *pMemory = Find( pEnemy, true );
if ( pMemory )
return pMemory->timeLastReceivedDamageFrom;
if ( pEnemy != AI_UNKNOWN_ENEMY )
DevWarning( 2,"Asking LastTimeTookDamageFrom for enemy that's not in my memory!!\n");
return AI_INVALID_TIME;
}
//-----------------------------------------------------------------------------
// Purpose: Returns the time at which the enemy was first seen firsthand
// Input : *pEnemy -
// Output : float
//-----------------------------------------------------------------------------
float CAI_Enemies::TimeAtFirstHand( CBaseEntity *pEnemy )
{
// I've never seen something that doesn't exist
if (!pEnemy)
return 0;
AI_EnemyInfo_t *pMemory = Find( pEnemy, true );
if ( pMemory )
return pMemory->timeAtFirstHand;
if ( pEnemy != AI_UNKNOWN_ENEMY )
DevWarning( 2,"Asking TimeAtFirstHand for enemy that's not in my memory!!\n");
return AI_INVALID_TIME;
}
//-----------------------------------------------------------------------------
// Purpose: Sets position to the last known position of an enemy. If enemy
// was not found returns last memory of danger position if it exists
// Output : Returns false is no position is known
//-----------------------------------------------------------------------------
bool CAI_Enemies::HasEludedMe( CBaseEntity *pEnemy )
{
AI_EnemyInfo_t *pMemory = Find( pEnemy );
if ( pMemory )
return pMemory->bEludedMe;
return false;
}
void CAI_Enemies::SetTimeValidEnemy( CBaseEntity *pEnemy, float flTime )
{
AI_EnemyInfo_t *pMemory = Find( pEnemy );
if ( pMemory )
pMemory->timeValidEnemy = flTime;
}
//-----------------------------------------------------------------------------
void CAI_Enemies::SetUnforgettable( CBaseEntity *pEnemy, bool bUnforgettable )
{
AI_EnemyInfo_t *pMemory = Find( pEnemy );
if ( pMemory )
pMemory->bUnforgettable = bUnforgettable;
}
//-----------------------------------------------------------------------------
void CAI_Enemies::SetMobbedMe( CBaseEntity *pEnemy, bool bMobbedMe )
{
AI_EnemyInfo_t *pMemory = Find( pEnemy );
if ( pMemory )
pMemory->bMobbedMe = bMobbedMe;
}
//-----------------------------------------------------------------------------
void CAI_Enemies::SetFreeKnowledgeDuration( float flDuration )
{
m_flFreeKnowledgeDuration = flDuration;
// If your free knowledge time is greater than your discard time,
// you'll forget about secondhand enemies passed to you by squadmates
// as soon as you're given them.
Assert( m_flFreeKnowledgeDuration < m_flEnemyDiscardTime );
}
//-----------------------------------------------------------------------------
void CAI_Enemies::SetEnemyDiscardTime( float flTime )
{
m_flEnemyDiscardTime = flTime;
// If your free knowledge time is greater than your discard time,
// you'll forget about secondhand enemies passed to you by squadmates
// as soon as you're given them.
Assert( m_flFreeKnowledgeDuration < m_flEnemyDiscardTime );
}
| [
"[email protected]"
] | |
25072a7b21037297af95b3ed00e45ce540a8e6e1 | 0751c521d8d475472a270739740b44e07880b18b | /troublemaker.cpp | 04417d7e3d31fcf6ef2ca5f82ce470c4abe83d4f | [] | no_license | hatkirby/troublemaker | c14d97113b977de9199fd78ea766bdff045b3def | 406fc323645878c6cdbd0033f504b80fdd4062d2 | refs/heads/master | 2021-01-09T20:43:30.634498 | 2016-06-21T03:17:28 | 2016-06-21T03:17:28 | 60,995,503 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,299 | cpp | #include <twitter.h>
#include <mutex>
#include <thread>
#include <chrono>
#include <cstdlib>
#include <ctime>
#include <map>
#include <set>
#include <algorithm>
#include <iostream>
#include <list>
#include <yaml-cpp/yaml.h>
#include <fstream>
struct userstats {
int total = 0;
int days = 1;
int day1 = 0;
int day2 = 0;
int day3 = 0;
int day4 = 0;
int day5 = 0;
int day6 = 0;
int day7 = 0;
};
int main(int argc, char** argv)
{
srand(time(NULL));
rand(); rand(); rand(); rand();
YAML::Node config = YAML::LoadFile("config.yml");
twitter::auth auth;
auth.setConsumerKey(config["consumer_key"].as<std::string>());
auth.setConsumerSecret(config["consumer_secret"].as<std::string>());
auth.setAccessKey(config["access_key"].as<std::string>());
auth.setAccessSecret(config["access_secret"].as<std::string>());
std::set<twitter::user_id> friends;
std::mutex friends_mutex;
std::map<twitter::user_id, userstats> stats;
std::mutex stats_mutex;
// Read in old data
{
std::ifstream datafile("data.txt");
if (datafile.is_open())
{
std::string line;
while (std::getline(datafile, line))
{
std::istringstream iss(line);
twitter::user_id uid;
iss >> uid;
userstats& s = stats[uid];
iss >> s.total;
iss >> s.days;
iss >> s.day2;
iss >> s.day3;
iss >> s.day4;
iss >> s.day5;
iss >> s.day6;
iss >> s.day7;
}
}
}
twitter::client client(auth);
client.setUserStreamNotifyCallback([&] (twitter::notification n) {
std::lock_guard<std::mutex> friend_guard(friends_mutex);
if (n.getType() == twitter::notification::type::friends)
{
friends = n.getFriends();
} else if (n.getType() == twitter::notification::type::follow)
{
friends.insert(n.getUser().getID());
} else if (n.getType() == twitter::notification::type::unfollow)
{
friends.erase(n.getUser().getID());
} else if (n.getType() == twitter::notification::type::tweet)
{
if (
(friends.count(n.getTweet().getAuthor().getID()) == 1) // Only monitor people you are following
&& (!n.getTweet().isRetweet()) // Ignore retweets
&& (n.getTweet().getText().front() != '@') // Ignore messages
)
{
std::lock_guard<std::mutex> stats_guard(stats_mutex);
userstats& s = stats[n.getTweet().getAuthor().getID()];
s.total++;
s.day1++;
if (s.days >= 7)
{
int outof = s.total;
if (outof < 200)
{
outof = 200;
}
if (rand() % outof == 0)
{
std::cout << "@" << n.getTweet().getAuthor().getScreenName() << "'s one of " << outof << "!" << std::endl;
std::string doc = client.generateReplyPrefill(n.getTweet()) + "is this a subtweet?";
twitter::tweet theTweet;
twitter::response resp = client.updateStatus(doc, theTweet, n.getTweet());
if (resp != twitter::response::ok)
{
std::cout << "Error tweeting witty joke: " << resp << std::endl;
}
}
}
}
} else if (n.getType() == twitter::notification::type::followed)
{
twitter::response resp = client.follow(n.getUser());
if (resp != twitter::response::ok)
{
std::cout << "Twitter error while following @" << n.getUser().getScreenName() << ": " << resp << std::endl;
}
}
});
std::this_thread::sleep_for(std::chrono::minutes(1));
std::cout << "Starting streaming" << std::endl;
client.startUserStream();
for (;;)
{
std::this_thread::sleep_for(std::chrono::hours(24));
// Unfollow people who have unfollowed us
std::set<twitter::user_id> friends;
std::set<twitter::user_id> followers;
twitter::response resp = client.getFriends(friends);
if (resp == twitter::response::ok)
{
resp = client.getFollowers(followers);
if (resp == twitter::response::ok)
{
std::list<twitter::user_id> old_friends, new_followers;
std::set_difference(std::begin(friends), std::end(friends), std::begin(followers), std::end(followers), std::back_inserter(old_friends));
std::set_difference(std::begin(followers), std::end(followers), std::begin(friends), std::end(friends), std::back_inserter(new_followers));
for (auto f : old_friends)
{
std::lock_guard<std::mutex> friend_guard(friends_mutex);
friends.erase(f);
resp = client.unfollow(f);
if (resp != twitter::response::ok)
{
std::cout << "Twitter error while unfollowing" << std::endl;
}
}
for (auto f : new_followers)
{
resp = client.follow(f);
if (resp != twitter::response::ok)
{
std::cout << "Twitter error while following" << std::endl;
}
}
} else {
std::cout << "Twitter error while getting followers: " << resp << std::endl;
}
} else {
std::cout << "Twitter error while getting friends: " << resp << std::endl;
}
std::cout << "stat rotation" << std::endl;
// This is all just for stats rotation
{
std::lock_guard<std::mutex> stats_guard(stats_mutex);
std::ofstream datafile("data.txt", std::ofstream::out | std::ofstream::trunc);
for (auto& mapping : stats)
{
auto& s = mapping.second;
if (s.days < 7)
{
s.days++;
}
s.day7 = s.day6;
s.day6 = s.day5;
s.day5 = s.day4;
s.day4 = s.day3;
s.day3 = s.day2;
s.day2 = s.day1;
s.day1 = 0;
s.total = s.day2 + s.day3 + s.day4 + s.day5 + s.day6 + s.day7;
datafile << mapping.first << " ";
datafile << s.total << " ";
datafile << s.days << " ";
datafile << s.day2 << " ";
datafile << s.day3 << " ";
datafile << s.day4 << " ";
datafile << s.day5 << " ";
datafile << s.day6 << " ";
datafile << s.day7 << std::endl;
}
}
}
}
| [
"[email protected]"
] | |
281ced35b5232e5d1a97ead71873c574684016d2 | ce9359ee8df60a1e4047924537054119f80ae885 | /sigapp/sig/src/sigogl/gl_loader.cpp | 1b9f5441c51a54b43e0abd6cc12020c9d7848db0 | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | permissive | manofthelionarmy/CSE170_PA3 | 964a0d4d99f48c2682085d6d27191f241d6bd541 | bae9148db103ec21b69873ee60ec9bff338197dd | refs/heads/master | 2021-04-28T08:41:00.419280 | 2018-02-23T02:04:17 | 2018-02-23T02:04:17 | 122,255,512 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,099 | cpp | /*=======================================================================
Copyright (c) 2017-onwards Marcelo Kallmann.
This software is distributed under the Apache License, Version 2.0.
All copies must contain the full copyright notice licence.txt located
at the base folder of the distribution.
=======================================================================*/
# include <sig/gs_var.h>
# include <sig/gs_output.h>
# include <sigogl/gl_core.h>
# include <sigogl/gl_resources.h>
# include <sigogl/ws_osinterface.h>
//# define GS_USE_TRACE_COUNTER
//# define GS_USE_TRACE1 // OGL version
# include <sig/gs_trace.h>
//=========================== OpenGL Function Loading ==========================================
static unsigned OglLoaded=0;
// GetProc is called from wsi_opengl_glinit.inc
static void *GetProc ( const char *name )
{
void *p = wsi_get_ogl_procedure ( name );
if (!p) { gsout<<"COULD NOT LOAD: "<<name<<gsnl; } else OglLoaded++;
return p;
}
# undef PFNGLDECLTYPE
# define PFNGLDECLTYPE
# undef glcorearb_functions_h
# include <sigogl/glcorearb_functions.h>
# include <sigogl/gl_tools.h>
# include <sigogl/glr_base.h>
unsigned gl_loaded ()
{
return OglLoaded;
}
static void _loadogl ( int n )
{
int c=0; // counter of how many functions were loaded
# include "gl_loader_functions.inc" // counter will be used for early return
}
void gl_load_and_initialize ()
{
// All our OpenGL contexts are shared, so do not load functions twice:
if ( OglLoaded>0 ) return;
// Attach ogl renderer instantiators to the classes derived from SnShape:
GlrBase::init ();
// Load core OpenGL functions:
int n = 400; // Number of OGL functions to load
const GsVar* v = GlResources::configuration("oglfuncs");
if (v) { n=v->geti(); if(n<300) n=300; } // use custom value, up to a limit
_loadogl ( n );
// Declare shaders:
GlResources::declare_default_shaders();
GS_TRACE1("OGL Version: "<<gl_version());
GS_TRACE1("GLSL Version: "<<glsl_version());
}
//================================ End of File =================================================
| [
"[email protected]"
] | |
1a92e2e39fac27b7aff299d255eeb982189be151 | d681b93f80b75d2b79b77ec621773e66efcf6cba | /include/mqf/distributions/levy.h | 4c68b34ada3891bd4a8eb0561a100d351357afc2 | [] | no_license | gansuranga/mqf | 0ebcf6bd2607afc5cc9bbfd28b35c3f301742508 | 25de0f3df1cc2edadb2bac87cfd7ed4238646b4d | refs/heads/master | 2020-03-28T12:48:31.289331 | 2015-07-21T00:01:08 | 2015-07-21T00:01:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,255 | h | #ifndef INCLUDED_MQF_DISTRIBUTIONS_LEVY
#define INCLUDED_MQF_DISTRIBUTIONS_LEVY
#include <cassert>
#include <cmath>
#include <limits>
#include "../distribution.h"
#include "../random_variable.h"
#include "../constants.h"
namespace mqf {
namespace Distributions {
struct Levy : Density<> {
double mu, c;
explicit Levy( double mu = 0.0, double c = 1.0 ) : mu(mu), c(c) {}
double mean() const {
return std::numeric_limits<double>::infinity();
}
double median() const {
return mu + c * ( 1.0 / ( 2.0 * InvErfHalf * InvErfHalf ) );
}
double mode() const {
return mu + c / 3.0;
}
double variance() const {
return std::numeric_limits<double>::infinity();
}
double operator()( double x ) const {
double y = (x - mu) / c;
return std::exp(-0.5 / y) / ( c * y * std::sqrt(2.0*Pi*y) );
}
double derivative( double x ) const {
double y = (x - mu) / c;
return ( std::exp(-0.5 / y) * ( 1.0 - 3.0 * y ) ) / ( 2.0 * c*c * y*y*y * std::sqrt(2.0*Pi*y) );
}
double cumulative( double x ) const {
return std::erfc( std::sqrt( 0.5 * c / (x-mu) ) );
}
};
struct StdLevy : Density<> {
double mean() const {
return std::numeric_limits<double>::infinity();
}
double median() const {
return 1.0 / ( 2.0 * InvErfHalf * InvErfHalf );
}
double mode() const {
return 1.0 / 3.0;
}
double variance() const {
return std::numeric_limits<double>::infinity();
}
double operator()( double x ) const {
return 1.0 / ( x * std::sqrt(2.0*Pi*x) ) * std::exp(-0.5 / x);
}
double derivative( double x ) const {
}
double cumlative( double x ) const {
return std::erfc( std::sqrt( 0.5 / x ) );
}
operator Levy() const {
return Levy( 0, 1 );
}
};
RV<Levy> operator*( const RV<Levy>& lhs, double rhs ) {
return MakeRV( Levy( lhs.dist.mu * rhs, lhs.dist.c * rhs ) );
}
RV<Levy> operator*( double lhs, const RV<Levy>& rhs ) {
return rhs * lhs;
}
RV<Levy> operator+( const RV<Levy>& lhs, double rhs ) {
return MakeRV( Levy( lhs.dist.mu + rhs, lhs.dist.c ) );
}
RV<Levy> operator+( double lhs, const RV<Levy>& rhs ) {
return rhs + lhs;
}
}
/* mle
1/N sum 1/(x_i - mu)^2 = 3 ( 1/N sum 1/(x_i - mu) )^2
c = harmonicMean(x_i - mu)
*/
}
#endif
| [
"[email protected]"
] | |
8aaf186e1598a850123e5be9c3701f06e731afc9 | 431b74ff7d3e4ee345ed0010d463409f92bc3bf8 | /ui/display/types/fake_display_controller.h | e90b457ed9383bf15d0b87a2dce1986a08eac337 | [] | no_license | wxz879526/yxbase | c24ff301f19988b195b5d4b340a33cc6b16b3380 | f669bedeba06f8de807eb53e4a24eb0ffe05b4a8 | refs/heads/master | 2020-04-16T19:25:37.887882 | 2019-12-10T13:12:34 | 2019-12-10T13:12:34 | 165,858,963 | 0 | 0 | null | 2019-01-15T13:49:56 | 2019-01-15T13:49:56 | null | UTF-8 | C++ | false | false | 1,398 | h | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_DISPLAY_TYPES_FAKE_DISPLAY_CONTROLLER_H_
#define UI_DISPLAY_TYPES_FAKE_DISPLAY_CONTROLLER_H_
#include <stdint.h>
#include <memory>
#include "ui/display/types/display_types_export.h"
namespace gfx {
class Size;
}
namespace display {
class DisplaySnapshot;
// Controls the fake display state. Provided by the NativeDisplayDelegate if
// it is intended for use off device where there are no physical displays and
// we need to fake the display state.
class DISPLAY_TYPES_EXPORT FakeDisplayController {
public:
// Adds a fake display with the specified size, returns the display id or
// |kInvalidDisplayId| if it fails.
virtual int64_t AddDisplay(const gfx::Size& display_size) = 0;
// Adds |display| to the list of displays and returns true if successful. Will
// fail if an existing display has the same id as |display|.
virtual bool AddDisplay(std::unique_ptr<DisplaySnapshot> display) = 0;
// Removes a fake display with specified id, returns true if successful.
virtual bool RemoveDisplay(int64_t display_id) = 0;
protected:
virtual ~FakeDisplayController() {}
};
} // namespace display
#endif // UI_DISPLAY_TYPES_FAKE_DISPLAY_CONTROLLER_H_
| [
"[email protected]"
] | |
20c5602514f610ca9b51ff2a36a9ea23e422f4ee | 24004e1c3b8005af26d5890091d3c207427a799e | /Win32/NXOPEN/NXOpen/Motion_CouplerCableBuilder.hxx | 1984db64f68eeee55a32bdd9e8300b221a5d35e6 | [] | no_license | 15831944/PHStart | 068ca6f86b736a9cc857d7db391b2f20d2f52ba9 | f79280bca2ec7e5f344067ead05f98b7d592ae39 | refs/heads/master | 2022-02-20T04:07:46.994182 | 2019-09-29T06:15:37 | 2019-09-29T06:15:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,279 | hxx | #ifndef NXOpen_MOTION_COUPLERCABLEBUILDER_HXX_INCLUDED
#define NXOpen_MOTION_COUPLERCABLEBUILDER_HXX_INCLUDED
//--------------------------------------------------------------------------
// Header for C++ interface to JA API
//--------------------------------------------------------------------------
//
// Source File:
// Motion_CouplerCableBuilder.ja
//
// Generated by:
// apiwrap
//
// WARNING:
// This file is automatically generated - do not edit by hand
//
#ifdef _MSC_VER
#pragma once
#endif
#include <NXOpen/NXDeprecation.hxx>
#include <vector>
#include <NXOpen/NXString.hxx>
#include <NXOpen/Callback.hxx>
#include <NXOpen/Motion_CouplerBuilder.hxx>
#include <NXOpen/libnxopencpp_motion_exports.hxx>
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable:4996)
#endif
#ifdef __GNUC__
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#endif
namespace NXOpen
{
namespace Motion
{
class CouplerCableBuilder;
}
namespace Motion
{
class CouplerBuilder;
}
namespace Motion
{
class _CouplerCableBuilderBuilder;
class CouplerCableBuilderImpl;
/** Represents a @link Motion::CouplerCableBuilder Motion::CouplerCableBuilder@endlink <br> To create a new instance of this class, use @link Motion::CouplerCollection::CreateCouplerCableBuilder Motion::CouplerCollection::CreateCouplerCableBuilder@endlink <br>
Default values.
<table border="1">
<tr><th>
Property</th> <th>
Value</th> </tr>
<tr><td>
Ratio (deprecated) </td> <td>
1.0 </td> </tr>
</table>
<br> Created in NX6.0.0. <br>
*/
class NXOPENCPP_MOTIONEXPORT CouplerCableBuilder : public Motion::CouplerBuilder
{
private: CouplerCableBuilderImpl * m_couplercablebuilder_impl;
private: friend class _CouplerCableBuilderBuilder;
protected: CouplerCableBuilder();
public: ~CouplerCableBuilder();
};
}
}
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#ifdef __GNUC__
#ifndef NX_NO_GCC_DEPRECATION_WARNINGS
#pragma GCC diagnostic warning "-Wdeprecated-declarations"
#endif
#endif
#undef EXPORTLIBRARY
#endif
| [
"[email protected]"
] | |
0cc9693d6787eca4a8d8a6d0bd8105895088cced | c8d5e1053481640ae1fff7c77a349a728d6d2eff | /flattening_of_linked_list.cpp | 810f6b009daec89a2ef78400d8552b289558cbbf | [] | no_license | 7566565794/must_do_linked_list | 585a92e6df61d26f9e643b6a1481e3455f26af88 | 82ed011a32e0dc5f679d847a18237422ea57ccfd | refs/heads/master | 2022-01-15T20:19:01.204340 | 2019-07-25T04:39:56 | 2019-07-25T04:39:56 | 198,066,444 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,366 | cpp | Node *flatten(Node *root)
{
int size=0;
Node *right=root;
Node *down=root;
while(right!=NULL){
down=right;
while(down!=NULL){
down=down->bottom;
size++;
}
right=right->next;
}
// cout<<size;
int i;
i=0;
int arr[size];
right=root;
down=root;
while(right!=NULL){
down=right;
while(down!=NULL){
// cout<<"hello"<<down->data;
arr[i]=down->data;
down=down->bottom;
i++;
}
right=right->next;
}
sort(arr,arr+size);
for(int j=0;j<size;j++){
cout<<arr[j]<<" ";
}
// cout<<endl;
return NULL;
}
//Another method to flatten a linked list
/* Node structure used in the program
struct Node{
int data;
struct Node * next;
struct Node * bottom ;
}; */
/* Function which returns the root of
the flattened linked list. */
Node *merge(Node *x, Node *y){
if(!x)
return y;
if(!y)
return x;
Node *result = NULL;
if(x->data<y->data){
result = x;
result->bottom = merge(x->bottom,y);
}
else{
result = y;
result->bottom = merge(x,y->bottom);
}
return result;
}
Node *flatten(Node *root)
{
// Your code here
if(!root || !root->next)
return root;
return merge(root, flatten(root->next));
}
| [
"[email protected]"
] | |
5cf613d96317a7bcf4760f49166a9676695db3ae | 0ed94159731f436244e922ad6312fb2a83a98c17 | /src/game/map.h | b3e1401d527714dab23566d57bf96e49ee2071fe | [
"Zlib"
] | permissive | 4Che/LD49-brimstone | b22dd8db1d7e4a47cd3729ebd189381dafc48548 | 6fd67d0709600fdab1c7d4c6013047df58a26d67 | refs/heads/master | 2023-08-27T23:53:54.436301 | 2021-10-04T14:17:57 | 2021-10-04T14:17:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,749 | h | #pragma once
#include "gameutils/tiled_map.h"
class ParticleController;
inline constexpr int tile_size = 12;
enum class Tile
{
air,
wall,
dirt,
grass,
spike,
spike_down,
dirt_alt,
_count,
};
namespace TileFlavors
{
struct Invis {};
struct Random
{
int index = 0;
int count = 0;
};
struct Merged
{
int index = 0;
};
struct HorMergedWithRandom
{
int index = 0;
int rand_count = 0;
};
[[nodiscard]] bool ShouldMergeWith(Tile a, Tile b);
}
using TileDrawMethod = std::variant<TileFlavors::Invis, TileFlavors::Random, TileFlavors::Merged, TileFlavors::HorMergedWithRandom>;
struct TileInfo
{
Tile tile = Tile::air;
bool solid = false;
bool kills = false;
bool corruptable = false;
TileDrawMethod vis;
};
[[nodiscard]] const TileInfo GetTileInfo(Tile tile);
struct Cell
{
Tile tile;
std::uint8_t random = 0;
static constexpr int
num_corruption_stages = 6,
corruption_stage_len = 15;
int corruption_stage = 0; // 0..num_corruption_stages
int corruption_start_time = 0; // Relative to `Map::Time()`.
int damage = 0;
int visual_damage = 0;
[[nodiscard]] int CalcVisualCorruptionStage() const;
};
class Map
{
int time = 1; // `0` is reserved for "never".
public:
Array2D<Cell> cells;
Tiled::PointLayer points;
Map() {}
Map(Stream::Input source);
void Tick(ParticleController &par);
void Render(ivec2 camera_pos) const;
void RenderCorruption(ivec2 camera_pos) const;
[[nodiscard]] int Time() const {return time;}
[[nodiscard]] bool PixelIsSolid(ivec2 pos) const;
void CorrputTile(ivec2 tile_pos, int stage);
};
| [
"[email protected]"
] | |
35136405bb990141a1f2efa674e844ffb4fb0b04 | 56212981670a9e25458340f8d5e2cd40806d003b | /KeepTalking/main.cpp | c1be787ab643f0a2767c785bea191e1c1cae8e1c | [] | no_license | majsterplan/KeepTalking | c75c41f26ece18c209aed9b3c2224e22f2e2dddd | 7149137475132197e30b3bbb83b336f6a671e4df | refs/heads/master | 2021-01-21T14:07:54.420120 | 2016-06-23T11:29:03 | 2016-06-23T11:29:03 | 57,339,746 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 27,194 | cpp | #include <QCoreApplication>
#include <iostream>
#include <winsock.h>
#include "server.h"
#include "usersmanager.h"
#include "conversationsmanager.h"
#include "commandparser.h"
#include "commandbuilder.h"
using namespace std;
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
// initialize WINSOCK
WSADATA wsaData;
if(WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
{
cout << "WSAStartup zakonczone porazka." << endl;
return -1;
}
cout << "WSAStartup zakonczone sukcesem." << endl;
Server server(1025);
cout << "Port 1025..." << endl;
if(!server.createListeningSocket())
{
cout << "Problem z utworzeniem gniazda." << endl;
return -1;
}
cout << "Gniazdo utworzone." << endl;
if(!server.bindListeningSocketToPort())
{
cout << "Problem przypisania gniazda do portu." << endl;
return -1;
}
if(!server.bindListeningSocketToPort())
{
cout << "Problem przypisania gniazda do portu." << endl;
return -1;
}
cout << "Gniazdo przypisane do portu." << endl;
if(!server.startListening())
{
cout << "Problem z rozpoczęciem nasłuchiwania." << endl;
return -1;
}
cout << "Slucham..." << endl;
UsersManager usersManager;
ConversationsManager conversationsManager;
while(true)
{
fd_set socketsDescriptors = server.getSocketsDescriptors();
server.checkReadableSockets(&socketsDescriptors);
for(int descriptor = 0; descriptor <= server.getMaxSocketDescriptor(); descriptor++)
{
if(server.isSocketSet(descriptor, &socketsDescriptors) > 0)
{
if(descriptor == server.getListeningSocketDescriptor())
{
int newSocketDescriptor;
if((newSocketDescriptor = server.acceptPendingConnection()) == -1)
cout << "Problem akceptacji połączenia." << endl;
else
{
server.addSocketDescriptor(newSocketDescriptor);
cout << "Mamy nowe polaczenie. Deskryptor nowego gniazda to " << newSocketDescriptor << "." << endl;
}
}
else
{
int receivedBytes = 0;
receivedBytes = server.readMessage(descriptor);
if(receivedBytes == 0)
{
User *user = usersManager.findUserByDescriptor(descriptor);
if(user != NULL)
{
if(user->getLoggedIn())
user->leaveAllConversations(&conversationsManager);
usersManager.removeUser(descriptor);
QString code = "LISTA_UZYTKOWNIKOW";
QStringList parameters;
QVector<User *> others = usersManager.getUsers(true);
parameters.append(QString::number(others.size()));
for(int i = 0; i < others.size(); i++)
parameters.append({others.at(i)->getName(), QString::number(static_cast<int>(others.at(i)->getStatus()))});
CommandBuilder commandBuilder;
QString messageToOthers = commandBuilder.build(code, parameters);
for(int i = 0; i < others.size(); i++)
{
server.sendMessage(messageToOthers, others.at(i)->getDescriptor());
}
}
server.closeSocket(descriptor);
server.deleteSocketDescriptor(descriptor);
cout << "Gniazdo o deskryptorze " << descriptor << " odlaczone." << endl;
}
else if(receivedBytes == -1)
cout << "Problemy z odczytem." << endl;
else
{
if(!server.getIsMessage())
{
QString request = server.getMessage();
QString requestToShow = "";
QString requestCode = "";
QStringList requestParameters;
QString response = "";
QString responseToShow = "";
QString responseCode = "";
QStringList responseParameters;
if(request.endsWith("\r\n"))
requestToShow = request.mid(0, request.length() - 2);
else
requestToShow = request;
cout << descriptor << "(klient) mowi: " << requestToShow.toStdString() << "." << endl;
CommandParser commandParser;
CommandBuilder commandBuilder;
bool validCommand = commandParser.parse(request, requestCode, requestParameters);
if(!validCommand)
{
responseCode = "ERROR";
responseParameters.append("BLAD_KOMENDY");
}
else
{
if(requestCode == "POTRZASANIE")
{
if(requestParameters.at(0).toInt() != CommandParser::getProtocolVersion())
responseCode = "ODRZUCENIE";
else
{
usersManager.addUser(descriptor);
QString code = "LISTA_KONWERSACJI";
QStringList parameters;
QVector<Conversation *> conversations = conversationsManager.getConversations();
parameters.append(QString::number(conversations.size()));
for(int i = 0; i < conversations.size(); i ++)
parameters.append(conversations.at(i)->getName());
QString message = commandBuilder.build(code, parameters);
server.sendMessage(message, descriptor);
responseCode = "POTWIERDZENIE";
}
}
else if(requestCode == "REJESTRACJA" || requestCode == "AUTORYZACJA")
{
bool readyToContinue = false;
QSqlDatabase *database = usersManager.getDatabase();
if(!database->isOpen())
{
database->open();
if(!database->isOpen())
{
responseCode = "ERROR";
responseParameters.append("BLAD_BAZY_DANYCH");
}
else
readyToContinue = true;
}
else
readyToContinue = true;
if(readyToContinue)
{
User *user = usersManager.findUserByDescriptor(descriptor);
if(user != NULL)
{
if(!user->getLoggedIn())
{
if(requestCode == "REJESTRACJA")
{
RegistrationProgress progress = user->signup(requestParameters.at(0), requestParameters.at(1));
responseCode = "ODP_REJESTRACJA";
responseParameters.append(QString::number(static_cast<int>(progress)));
}
else
{
bool success = user->login(requestParameters.at(0), requestParameters.at(1));
if(!success)
responseCode = "ODRZUCENIE";
else
{
QString code = "LISTA_UZYTKOWNIKOW";
QStringList parameters;
QVector<User *> others = usersManager.getUsers(true);
parameters.append(QString::number(others.size()));
for(int i = 0; i < others.size(); i++)
parameters.append({others.at(i)->getName(), QString::number(static_cast<int>(others.at(i)->getStatus()))});
QString messageToOthers = commandBuilder.build(code, parameters);
for(int i = 0; i < others.size(); i++)
{
server.sendMessage(messageToOthers, others.at(i)->getDescriptor());
}
responseCode = "POTWIERDZENIE";
}
}
}
else
{
responseCode = "ERROR";
responseParameters.append("BLAD_UZYTKOWNIKA");
}
}
else
{
responseCode = "ERROR";
responseParameters.append("BLAD_UZYTKOWNIKA");
}
database->close();
}
}
else if(requestCode == "USTAW_STATUS")
{
User *user = usersManager.findUserByDescriptor(descriptor);
if(user != NULL)
{
if(user->getLoggedIn())
{
bool success = user->changeStatus(static_cast<Status>(requestParameters.at(0).toInt()));
if(!success)
responseCode = "ODRZUCENIE";
else
{
QString code = "ZMIANA_STATUSU";
QStringList parameters = {user->getName(), QString::number(static_cast<int>(user->getStatus()))};
QString message = commandBuilder.build(code, parameters);
QVector<User *> others = usersManager.getUsers(true);
for(int i = 0; i < others.size(); i++)
server.sendMessage(message, others.at(i)->getDescriptor());
responseCode = "POTWIERDZENIE";
}
}
else
{
responseCode = "ERROR";
responseParameters.append("BLAD_UZYTKOWNIKA");
}
}
else
{
responseCode = "ERROR";
responseParameters.append("BLAD_UZYTKOWNIKA");
}
}
else if(requestCode == "WIADOMOSC")
{
User *user = usersManager.findUserByDescriptor(descriptor);
if(user != NULL)
{
if(user->getLoggedIn())
{
QString code = "WIADOMOSC";
QStringList parameters;
QString message;
QVector<User *> receivers;
if(requestParameters.at(1).isEmpty())
{
parameters.append({user->getName(), "", requestParameters.at(2)});
message = commandBuilder.build(code, parameters);
receivers = usersManager.findUsersByName(requestParameters.at(0));
}
else
{
Conversation *conversation = conversationsManager.findConversationByName(requestParameters.at(1));
bool readyToContinue = false;
if(conversation != NULL)
{
bool userInConversation = conversation->isUserInConversation(user->getDescriptor());
if(!userInConversation)
responseCode = "ODRZUCENIE";
else
readyToContinue = true;
}
else
{
conversationsManager.addConversation(requestParameters.at(1));
conversation = conversationsManager.findConversationByName(requestParameters.at(1));
conversation->addUser(user);
QString extraCode = "LISTA_KONWERSACJI";
QStringList extraParameters;
QVector<Conversation *> conversations = conversationsManager.getConversations();
extraParameters.append(QString::number(conversations.size()));
for(int i = 0; i < conversations.size(); i ++)
extraParameters.append(conversations.at(i)->getName());
QString extraMessage = commandBuilder.build(extraCode, extraParameters);
QVector<User *> others = usersManager.getUsers();
for(int i = 0; i < others.size(); i++)
server.sendMessage(extraMessage, others.at(i)->getDescriptor());
readyToContinue = true;
}
if(readyToContinue)
{
parameters.append({user->getName(), conversation->getName(), requestParameters.at(2)});
message = commandBuilder.build(code, parameters);
receivers = usersManager.findUsersByName(requestParameters.at(0));
QVector<User *> newUsersInConversation = usersManager.findUsersByName(requestParameters.at(0));
for(int i = 0; i < newUsersInConversation.size(); i++)
conversation->addUser(newUsersInConversation.at(i));
receivers = conversation->getUsers();
}
}
if(receivers.size() > 0)
{
QVector<int> descriptors;
for(int i = 0; i < receivers.size(); i++)
if(receivers.at(i)->getDescriptor() != user->getDescriptor())
descriptors.append(receivers.at(i)->getDescriptor());
user->sendMessage(&server, message, descriptors);
responseCode = "POTWIERDZENIE";
}
else
responseCode = "ODRZUCENIE";
}
else
{
responseCode = "ERROR";
responseParameters.append("BLAD_UZYTKOWNIKA");
}
}
else
{
responseCode = "ERROR";
responseParameters.append("BLAD_UZYTKOWNIKA");
}
}
else if(requestCode == "KTO_W_KONWERSACJI")
{
Conversation *conversation = conversationsManager.findConversationByName(requestParameters.at(0));
if(conversation != NULL)
{
responseCode = "LISTA_W_KONWERSACJI";
QVector<User *> usersInConversation = conversation->getUsers();
responseParameters.append(QString::number(usersInConversation.size()));
for(int i = 0; i < usersInConversation.size(); i++)
responseParameters.append(usersInConversation.at(i)->getName());
}
else
{
responseCode = "ERROR";
responseParameters.append("BLAD_KONWERSACJI");
}
}
else if(requestCode == "DOLACZ")
{
Conversation *conversation = conversationsManager.findConversationByName(requestParameters.at(0));
if(conversation != NULL)
{
User *user = usersManager.findUserByDescriptor(descriptor);
if(user != NULL)
{
if(user->getLoggedIn())
{
bool success = user->joinConversation(conversation);
if(success)
responseCode = "POTWIERDZENIE";
else
responseCode = "ODRZUCENIE";
}
else
{
responseCode = "ERROR";
responseParameters.append("BLAD_UZYTKOWNIKA");
}
}
else
{
responseCode = "ERROR";
responseParameters.append("BLAD_UZYTKOWNIKA");
}
}
else
{
responseCode = "ERROR";
responseParameters.append("BLAD_KONWERSACJI");
}
}
else if(requestCode == "ZREZYGNUJ")
{
Conversation *conversation = conversationsManager.findConversationByName(requestParameters.at(0));
if(conversation != NULL)
{
User *user = usersManager.findUserByDescriptor(descriptor);
if(user != NULL)
{
if(user->getLoggedIn())
{
bool success = user->leaveConversation(conversation);
if(success)
responseCode = "POTWIERDZENIE";
else
responseCode = "ODRZUCENIE";
}
else
{
responseCode = "ERROR";
responseParameters.append("BLAD_UZYTKOWNIKA");
}
}
else
{
responseCode = "ERROR";
responseParameters.append("BLAD_UZYTKOWNIKA");
}
}
else
{
responseCode = "ERROR";
responseParameters.append("BLAD_KONWERSACJI");
}
}
else if(requestCode == "BYWAJ")
{
User *user = usersManager.findUserByDescriptor(descriptor);
if(user != NULL)
{
if(user->getLoggedIn())
{
user->leaveAllConversations(&conversationsManager);
user->logout();
}
else
{
responseCode = "ERROR";
responseParameters.append("BLAD_UZYTKOWNIKA");
}
}
else
{
responseCode = "ERROR";
responseParameters.append("BLAD_UZYTKOWNIKA");
}
}
}
response = commandBuilder.build(responseCode, responseParameters);
if(response != "\r\n")
server.sendMessage(response, descriptor);
if(response.endsWith("\r\n"))
responseToShow = response.mid(0, response.length() - 2);
else
responseToShow = response;
if(!responseToShow.isEmpty())
cout << server.getListeningSocketDescriptor() << "(serwer) odpowiada: " << responseToShow.toStdString() << "." << endl;
}
}
}
}
}
}
return a.exec();
}
| [
"[email protected]"
] | |
e65ea033c8e93191bcd19f3c789b55411034719a | 9df8ef4f5e25aefb4c9c952df106fb4df95f7509 | /TenFold/Plugins/BLUI/Intermediate/Build/Win64/UE4Editor/Development/BluLoader/PCH.BluLoaderPrivatePCH.h.cpp | e5d71effb1a7d53607f475d9b0c712a9634b7841 | [
"MIT"
] | permissive | Truemedia/TenFold | 6f4dc88ab66b434f56b9c35171c1166ebef69a01 | 001e3ce71549be1a7b47c230a6a64df3f7b37539 | refs/heads/master | 2021-01-18T07:40:17.547409 | 2016-02-13T14:25:45 | 2016-02-13T14:25:45 | 51,644,855 | 0 | 0 | null | 2016-02-13T12:23:49 | 2016-02-13T12:23:48 | null | UTF-8 | C++ | false | false | 137 | cpp | #include "C:\Users\Wade Penistone\Documents\Unreal Projects\TenFold\TenFold\Plugins\BLUI\Source\BluLoader\Private\BluLoaderPrivatePCH.h"
| [
"[email protected]"
] | |
39fd9ac4a7e6589598c203eff20670a632ee1f7f | dda672f0bd67fcafc14aae0e8abc3aa7c8d801ac | /core/geometry/rorgeometry_utilities.hh | 2bb2fc17d09d640d44ba5424a59a864cb04fd446 | [
"MIT"
] | permissive | abbaswasim/roar | 0ee809b048d7597aca82f4e340f412387993e552 | c845daf5fb1e76c628b4d3d7a346ca0bbfe0641e | refs/heads/master | 2023-08-04T10:32:31.010407 | 2023-08-02T19:21:13 | 2023-08-02T19:21:13 | 182,329,573 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 20,938 | hh | // Roar Source Code
// Wasim Abbas
// http://www.waZim.com
// Copyright (c) 2008-2020
//
// 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.
//
// Version: 1.0.0
#pragma once
#include "foundation/rortypes.hpp"
#include "math/rormatrix4_functions.hpp"
#include "math/rorvector3.hpp"
#include "rorgeometry_utilities.hpp"
#include <cstddef>
#include <cstdint>
#include <functional>
#include <vector>
#define PAR_OCTASPHERE_IMPLEMENTATION
#include "par/par_octasphere.h"
#define PAR_SHAPES_IMPLEMENTATION
#include "par/par_shapes.h"
namespace ror
{
/**
* @brief Returns 8 corners for a cube or 4 corners of a box
* @param a_minimum Starting point of the box
* @param a_maximum Finishing point of the box
* @param a_corners The amount of corners requested (8, 4)
* @param a_output Corners are returned here
*/
template <class _type>
FORCE_INLINE void _box_corners_internal(const _type &a_minimum, const _type &a_maximum, uint32_t a_corners, std::vector<_type> &a_output)
{
a_output.reserve(a_output.size() + a_corners);
// https://github.com/sgorsten/linalg algoritm for creating cube
for (uint32_t i = 0; i < a_corners; ++i)
{
// Two copies of Vector3i or Vector2i arn't good but this isn't suppose to be real time
_type corner = vector_select(vector_type<_type, uint32_t>(Vector3ui(i & 1, i & 2, i & 4)), a_minimum, a_maximum);
a_output.emplace_back(corner);
}
}
/**
* @brief Returns 8 corners for a cube or 4 corners of a box
* @param a_minimum Starting point of the box
* @param a_maximum Finishing point of the box
* @param a_vertex_buffer Corners are returned here
*/
template <class _type>
FORCE_INLINE void _box_points_internal(const _type &a_minimum, const _type &a_maximum, std::vector<_type> &a_vertex_buffer)
{
static_assert(!(std::is_same<_type, Vector4<typename _type::value_type>>::value), "Can't create a 4D Cube\n");
uint32_t corners = 8;
if constexpr (std::is_same<_type, Vector2<typename _type::value_type>>::value)
{
corners = 4;
}
_box_corners_internal(a_minimum, a_maximum, corners, a_vertex_buffer);
}
/**
* @brief Returns 12 or 2 triangles created from 8 corners of a cube or 4 corners of a box
* @param a_minimum Starting point of the box
* @param a_maximum Finishing point of the box
* @param a_vertex_buffer Corners are returned here
*/
template <class _type>
FORCE_INLINE void _box_triangles_internal(const _type &a_minimum, const _type &a_maximum, std::vector<_type> &a_vertex_buffer)
{
static_assert(!(std::is_same<_type, Vector4<typename _type::value_type>>::value), "Can't create a 4D Cube\n");
const size_t indices[] = {0, 1, 2, 1, 3, 2, 5, 4, 6, 5, 6, 7, 0, 2, 6, 4, 0, 6, 1, 5, 3, 5, 7, 3, 3, 7, 2, 7, 6, 2, 0, 4, 1, 4, 5, 1};
uint32_t corners = 8;
uint32_t triangles = 12;
if constexpr (std::is_same<_type, Vector2<typename _type::value_type>>::value)
{
corners = 4;
triangles = 2;
}
std::vector<_type> vertex_buffer;
_box_corners_internal(a_minimum, a_maximum, corners, vertex_buffer);
// Lets calculate index buffer and triangles
a_vertex_buffer.reserve(a_vertex_buffer.size() + triangles * 9);
for (uint32_t i = 0; i < triangles; ++i)
{
a_vertex_buffer.emplace_back(vertex_buffer[indices[3 * i]]);
a_vertex_buffer.emplace_back(vertex_buffer[indices[3 * i + 1]]);
a_vertex_buffer.emplace_back(vertex_buffer[indices[3 * i + 2]]);
}
}
/**
* @brief Returns indices for a_triangles amount of triangles for a Cube or Box
* @param a_index_buffer Triangle indices are returned here
* @param a_triangles Amount of triangles requested (2 for a box, 12 for a Cube)
*/
template <class _index_type = uint32_t>
FORCE_INLINE void _box_triangles_indices_internal(uint32_t a_triangles, std::vector<ror::Vector3<_index_type>> &a_index_buffer)
{
const std::vector<ror::Vector3<_index_type>> indices{{0, 1, 2}, {1, 3, 2}, {5, 4, 6}, {5, 6, 7}, {0, 2, 6}, {4, 0, 6}, {1, 5, 3}, {5, 7, 3}, {3, 7, 2}, {7, 6, 2}, {0, 4, 1}, {4, 5, 1}};
a_index_buffer.reserve(a_index_buffer.size() + a_triangles);
std::copy(indices.begin(), indices.begin() + a_triangles, std::back_inserter(a_index_buffer));
}
template <class _type>
FORCE_INLINE void _box_lines_internal(const _type &a_minimum, const _type &a_maximum, std::vector<_type> &a_vertex_buffer)
{
static_assert(!(std::is_same<_type, Vector4<typename _type::value_type>>::value), "Can't create a 4D Box\n");
const size_t indices[] = {0, 1, 1, 3, 3, 2, 2, 0, 0, 4, 1, 5, 2, 6, 3, 7, 4, 5, 5, 7, 7, 6, 6, 4};
uint32_t corners = 8;
uint32_t lines = 12;
if constexpr (std::is_same<_type, Vector2<typename _type::value_type>>::value)
{
corners = 4;
lines = 4;
}
std::vector<_type> vertex_buffer;
_box_corners_internal(a_minimum, a_maximum, corners, vertex_buffer);
// Lets calculate index buffer and lines
a_vertex_buffer.reserve(a_vertex_buffer.size() + lines);
for (uint32_t i = 0; i < lines; ++i)
{
a_vertex_buffer.emplace_back(vertex_buffer[indices[2 * i]]);
a_vertex_buffer.emplace_back(vertex_buffer[indices[2 * i + 1]]);
}
}
template <class _index_type = uint32_t>
FORCE_INLINE void _box_lines_indices_internal(uint32_t a_lines, std::vector<ror::Vector2<_index_type>> &a_index_buffer)
{
const std::vector<ror::Vector2<_index_type>> indices{{0, 1}, {1, 3}, {3, 2}, {2, 0}, {0, 4}, {1, 5}, {2, 6}, {3, 7}, {4, 5}, {5, 7}, {7, 6}, {6, 4}};
a_index_buffer.reserve(a_index_buffer.size() + a_lines);
std::copy(indices.begin(), indices.begin() + a_lines, std::back_inserter(a_index_buffer));
}
template <class _type>
FORCE_INLINE void make_box_triangles(std::vector<_type> &a_vertex_buffer, const _type &a_minimum, const _type &a_maximum)
{
_box_triangles_internal(a_minimum, a_maximum, a_vertex_buffer);
}
template <class _type>
FORCE_INLINE void make_box_triangles(const _type &a_size, const _type &a_origin, std::vector<_type> &a_vertex_buffer)
{
_type half_size = (a_size / 2);
_type minimum{a_origin - half_size}, maximum{half_size + a_origin};
_box_triangles_internal(minimum, maximum, a_vertex_buffer);
}
template <class _type>
FORCE_INLINE void make_box_triangles(float32_t a_size, const _type &a_origin, std::vector<_type> &a_vertex_buffer)
{
make_box_triangles(_type(a_size), a_origin, a_vertex_buffer);
}
template <class _type>
FORCE_INLINE void make_box_triangles(float32_t a_size, std::vector<_type> &a_vertex_buffer)
{
make_box_triangles(_type(a_size), _type(0), a_vertex_buffer);
}
template <class _type>
FORCE_INLINE std::vector<_type> make_box_triangles(float32_t a_size)
{
std::vector<_type> a_vertex_buffer;
make_box_triangles(_type(a_size), _type(0), a_vertex_buffer);
return a_vertex_buffer;
}
template <class _type, class _index_type>
FORCE_INLINE void make_box_triangles_indexed(const _type &a_size, const _type &a_origin,
std::vector<_type> &a_vertex_buffer,
std::vector<ror::Vector3<_index_type>> &a_index_buffer)
{
uint32_t triangles = 12;
if constexpr (std::is_same<_type, Vector2<typename _type::value_type>>::value)
{
triangles = 2;
}
_type half_size = (a_size / 2);
_type minimum{a_origin - half_size}, maximum{half_size + a_origin};
_box_points_internal(minimum, maximum, a_vertex_buffer);
_box_triangles_indices_internal(triangles, a_index_buffer);
}
template <class _type, class _index_type>
FORCE_INLINE void make_box_triangles_indexed(std::vector<_type> &a_vertex_buffer, std::vector<ror::Vector3<_index_type>> &a_index_buffer)
{
make_box_triangles_indexed(_type(1), _type(0), a_vertex_buffer, a_index_buffer);
}
// Same set of functions for box but this time for lines instead of triangles
template <class _type>
FORCE_INLINE void make_box_lines(std::vector<_type> &a_vertex_buffer, const _type &a_minimum, const _type &a_maximum)
{
_box_lines_internal(a_minimum, a_maximum, a_vertex_buffer);
}
template <class _type>
FORCE_INLINE void make_box_lines(const _type &a_size, const _type &a_origin, std::vector<_type> &a_vertex_buffer)
{
_type half_size = (a_size / 2);
_type minimum{a_origin - half_size}, maximum{half_size + a_origin};
_box_lines_internal(minimum, maximum, a_vertex_buffer);
}
template <class _type>
FORCE_INLINE void make_box_lines(float32_t a_size, const _type &a_origin, std::vector<_type> &a_vertex_buffer)
{
make_box_lines(_type(a_size), a_origin, a_vertex_buffer);
}
template <class _type>
FORCE_INLINE void make_box_lines(float32_t a_size, std::vector<_type> &a_vertex_buffer)
{
make_box_lines(_type(a_size), _type(0), a_vertex_buffer);
}
template <class _type>
FORCE_INLINE std::vector<_type> make_box_lines(float32_t a_size)
{
std::vector<_type> a_vertex_buffer;
make_box_lines(_type(a_size), _type(0), a_vertex_buffer);
return a_vertex_buffer;
}
template <class _type, class _index_type>
FORCE_INLINE void make_box_lines_indexed(const _type &a_size, const _type &a_origin,
std::vector<_type> &a_vertex_buffer,
std::vector<ror::Vector2<_index_type>> &a_index_buffer)
{
uint32_t lines = 12;
if constexpr (std::is_same<_type, Vector2<typename _type::value_type>>::value)
{
lines = 4;
}
_type half_size = (a_size / 2);
_type minimum{a_origin - half_size}, maximum{half_size + a_origin};
_box_points_internal(minimum, maximum, a_vertex_buffer);
_box_lines_indices_internal(lines, a_index_buffer);
}
template <class _type, class _index_type>
FORCE_INLINE void make_box_lines_indexed(std::vector<_type> &a_vertex_buffer, std::vector<ror::Vector2<_index_type>> &a_index_buffer)
{
make_box_lines_indexed(_type(1), _type(0), a_vertex_buffer, a_index_buffer);
}
void make_sphere_triangles(std::vector<ror::Vector3f> &a_vertex_buffer, int32_t a_subdivisions, float32_t a_cornder_radius)
{
par_octasphere_config cfg{};// = {
cfg.corner_radius = a_cornder_radius;
cfg.width = 0;
cfg.height = 0;
cfg.depth = 0;
cfg.num_subdivisions = a_subdivisions;
// cfg.uv_mode = PAR_OCTASPHERE_UV_LATLONG;
// cfg.normals_mode = PAR_OCTASPHERE_NORMALS_SMOOT;
//};
uint32_t num_indices;
uint32_t num_vertices;
par_octasphere_get_counts(&cfg, &num_indices, &num_vertices);
std::vector<ror::Vector3f> vertex_buffer{};
std::vector<uint16_t> indicies{};
vertex_buffer.resize(num_vertices * sizeof(ror::Vector3f));
indicies.resize(num_indices);
par_octasphere_mesh mesh{};// = {
mesh.positions = reinterpret_cast<float32_t *>(vertex_buffer.data());
mesh.normals = nullptr; // Don't want normals
mesh.texcoords = nullptr; // Don't want uvs
mesh.indices = indicies.data();
// mesh.num_indices = num_indices;
// mesh.num_vertices = num_vertices;
//};
// Generate vertex coordinates, ignoring normals, uv, and triangle indices.
par_octasphere_populate(&cfg, &mesh);
a_vertex_buffer.reserve(num_indices);
for (uint32_t i = 0; i < num_indices; ++i)
a_vertex_buffer.emplace_back(vertex_buffer[indicies[i]]);
}
static void shape_to_buffer(std::vector<ror::Vector3f> &a_vertex_buffer, const ror::Matrix4f &a_transform, par_shapes_mesh *a_shape)
{
a_vertex_buffer.reserve(a_vertex_buffer.size() + (static_cast<size_t>(a_shape->ntriangles) * 3));
for (int32_t i = 0; i < a_shape->ntriangles; ++i)
{
auto *ptr = a_shape->points;
auto *ts = a_shape->triangles;
auto ti = 3 * i;
for (int32_t j = 0; j < 3; ++j)
{
auto vid = ts[ti + j];
auto point = ror::Vector3f{ptr[vid * 3 + 0], ptr[vid * 3 + 1], ptr[vid * 3 + 2]};
point = a_transform * point;
a_vertex_buffer.emplace_back(point);
}
}
}
void make_cylinder_triangles(std::vector<ror::Vector3f> &a_vertex_buffer,
int32_t a_slices,
int32_t a_stackes)
{
auto *shape = par_shapes_create_cylinder(a_slices, a_stackes);
// Make the cylinder in roar y-axis and unit diameter
auto xform = ror::matrix4_rotation_around_x(ror::to_radians(-90.0f)) * ror::matrix4_scaling(0.5f, 0.5f, 1.0f);
shape_to_buffer(a_vertex_buffer, xform, shape);
delete shape;
}
void make_cone_triangles(std::vector<ror::Vector3f> &a_vertex_buffer,
int32_t a_slices,
int32_t a_stackes)
{
auto *shape = par_shapes_create_cone(a_slices, a_stackes);
// Make the cylinder in roar y-axis and unit diameter
auto xform = ror::matrix4_rotation_around_x(ror::to_radians(-90.0f)) * ror::matrix4_scaling(0.5f, 0.5f, 1.0f);
shape_to_buffer(a_vertex_buffer, xform, shape);
delete shape;
}
void make_tetrahedron_triangles(std::vector<ror::Vector3f> &a_vertex_buffer)
{
auto *shape = par_shapes_create_tetrahedron();
shape_to_buffer(a_vertex_buffer, ror::Matrix4f{}, shape);
delete shape;
}
void make_hemisphere_triangles(std::vector<ror::Vector3f> &a_vertex_buffer,
int32_t a_slices,
int32_t a_stackes)
{
auto *shape = par_shapes_create_hemisphere(a_slices, a_stackes);
shape_to_buffer(a_vertex_buffer, ror::Matrix4f{}, shape);
delete shape;
}
void make_disk_triangles(std::vector<ror::Vector3f> &a_vertex_buffer,
ror::Vector3f a_center,
ror::Vector3f a_normal,
float32_t a_radius,
int32_t a_slices)
{
// radius, slices, center, normal
auto *shape = par_shapes_create_disk(a_radius, a_slices, reinterpret_cast<float32_t *>(&a_center.x), reinterpret_cast<float32_t *>(&a_normal.x));
shape_to_buffer(a_vertex_buffer, ror::Matrix4f{}, shape);
delete shape;
}
template <class _type, class _index_type>
void make_sphere_triangles(std::vector<ror::Vector3<_type>> &a_vertex_buffer, std::vector<ror::Vector3<_index_type>> &a_index_buffer, uint32_t a_samples) // 50 samples are enough for normal use
{
// Sphere motivations
// https://stackoverflow.com/a/26127012 for Fibonacci sphere
// And convex hull solution from convhull_3d https://github.com/leomccormack/convhull_3d
_type offset = static_cast<_type>(2.0f) / static_cast<_type>(a_samples);
_type increment = ror_pi * (static_cast<_type>(3.0f) - std::sqrt(static_cast<_type>(5.0f)));
ch_vertex *vertices = new ch_vertex[a_samples];
for (uint32_t sample = 0; sample < a_samples; ++sample)
{
_type u = static_cast<_type>(sample);
_type y = ((u * offset) - static_cast<_type>(1.0f)) + (offset / static_cast<_type>(2.0f));
_type r = std::sqrt(static_cast<_type>(1.0f) - std::pow(y, static_cast<_type>(2.0f)));
_type phi = static_cast<_type>((sample) % a_samples) * increment;
_type x = std::cos(phi) * r;
_type z = std::sin(phi) * r;
vertices[sample].x = x;
vertices[sample].y = y;
vertices[sample].z = z;
// Save my vertices
a_vertex_buffer.emplace_back(ror::Vector3<_type>(x, y, z));
}
int32_t *face_indices = nullptr;
int32_t face_count;
convhull_3d_build(vertices, static_cast<int32_t>(a_samples), &face_indices, &face_count);
for (int32_t i = 0; i < face_count * 3; i += 3)
{
// Save my indices
a_index_buffer.emplace_back(ror::Vector3<_index_type>(
static_cast<uint32_t>(face_indices[i]),
static_cast<uint32_t>(face_indices[i + 1]),
static_cast<uint32_t>(face_indices[i + 2])));
}
delete[] vertices;
delete[] face_indices;
}
void create_arrow(std::vector<ror::Vector3f> &arrow_triangles_data, ror::Vector3f a_scale)
{
std::vector<ror::Vector3f> cylinder_triangles_data{};
std::vector<ror::Vector3f> cone_triangles_data{};
std::vector<ror::Vector3f> disk_triangles_data{};
make_cylinder_triangles(cylinder_triangles_data);
make_cone_triangles(cone_triangles_data);
make_disk_triangles(disk_triangles_data, ror::Vector3f{}, ror::Vector3f{0.0, -1.0, 0.0});
auto smat = ror::matrix4_scaling(0.01f * a_scale.x, 0.5f * a_scale.y, 0.01f * a_scale.z);
auto smat2 = ror::matrix4_scaling(0.03f * a_scale.x, 0.04f * a_scale.y, 0.03f * a_scale.z);
auto smat3 = ror::matrix4_scaling(0.015f * a_scale.x, 0.04f * a_scale.y, 0.015f * a_scale.z);
auto tmat = ror::matrix4_translation(0.0f * a_scale.x, 0.5f * a_scale.y, 0.0f * a_scale.z);
auto rmat = ror::matrix4_rotation_around_y(ror::to_radians(18.0f));
arrow_triangles_data.reserve(cylinder_triangles_data.size() + cone_triangles_data.size() + disk_triangles_data.size());
// Lets make an arrow from the three objects, cylinder, cone and disk
for (auto &p : cylinder_triangles_data)
arrow_triangles_data.emplace_back(smat * p);
for (auto &p : cone_triangles_data)
arrow_triangles_data.emplace_back(tmat * smat2 * p);
for (auto &p : disk_triangles_data)
arrow_triangles_data.emplace_back(tmat * rmat * smat3 * p);
}
void create_axis(std::vector<std::vector<float32_t>> &debug_data, std::vector<rhi::PrimitiveTopology> &topology_data)
{
std::vector<float32_t> points_colors{};
auto add_point = [&points_colors](ror::Vector3f &point, ror::Vector4f &color, ror::Matrix4f xform) {
auto xpoint = xform * point;
points_colors.push_back(xpoint.x);
points_colors.push_back(xpoint.y);
points_colors.push_back(xpoint.z);
points_colors.push_back(0.0f);
points_colors.push_back(color.x);
points_colors.push_back(color.y);
points_colors.push_back(color.z);
points_colors.push_back(color.w);
};
std::vector<ror::Vector3f> arrow_triangles_data{};
create_arrow(arrow_triangles_data, ror::Vector3f{1.0f});
float32_t color_intensity = 1.0f;
float32_t color_fade = 0.2f;
auto redcolor_p = ror::Vector4f{color_intensity, color_fade, color_fade, 1.0f};
auto redcolor_n = redcolor_p * ror::Vector4f(color_fade, color_fade, color_fade, 1.0);
auto greencolor_p = ror::Vector4f{color_fade, color_intensity, color_fade, 1.0f};
auto greencolor_n = greencolor_p * ror::Vector4f(color_fade, color_fade, color_fade, 1.0);
auto bluecolor_p = ror::Vector4f{color_fade, color_fade, color_intensity, 1.0f};
auto bluecolor_n = bluecolor_p * ror::Vector4f(color_fade, color_fade, color_fade, 1.0);
// +X
for (auto &p : arrow_triangles_data)
add_point(p, redcolor_p, ror::matrix4_rotation_around_z(ror::to_radians(-90.0f)));
// -X
for (auto &p : arrow_triangles_data)
add_point(p, redcolor_n, ror::matrix4_rotation_around_z(ror::to_radians(90.0f)));
// +Y
for (auto &p : arrow_triangles_data)
add_point(p, greencolor_p, {});
// -Y
for (auto &p : arrow_triangles_data)
add_point(p, greencolor_n, ror::matrix4_rotation_around_x(ror::to_radians(180.0f)));
// +Z
for (auto &p : arrow_triangles_data)
add_point(p, bluecolor_p, ror::matrix4_rotation_around_x(ror::to_radians(90.0f)));
// -Z
for (auto &p : arrow_triangles_data)
add_point(p, bluecolor_n, ror::matrix4_rotation_around_x(ror::to_radians(-90.0f)));
debug_data.emplace_back(points_colors);
topology_data.emplace_back(rhi::PrimitiveTopology::triangles);
}
template <class _type>
FORCE_INLINE void make_sphere_triangles(uint32_t a_samples)
{
(void) a_samples;
}
template <class _type>
FORCE_INLINE void add_normals(const std::vector<_type> &a_vertex_buffer,
uint32_t a_size, std::vector<_type> &a_output,
const std::vector<_type> *a_index_buffer)
{
(void) a_vertex_buffer;
(void) a_size;
(void) a_output;
(void) a_index_buffer;
}
template <class _type>
FORCE_INLINE void add_colors(const std::vector<_type> &a_vertex_buffer,
uint32_t a_size, std::vector<_type> &a_output,
const std::vector<_type> *a_index_buffer)
{
(void) a_vertex_buffer;
(void) a_size;
(void) a_output;
(void) a_index_buffer;
}
} // namespace ror
| [
"[email protected]"
] | |
e10e2f363ecfaa5f91ba35ddb9914330896eef79 | 886edaaf18a5086e12ff5e6017cb969b19dddaf9 | /snowman.cpp | cf3c91dce4956911641810090ce9925e52aa5de1 | [] | no_license | HodayaYehuda/snowman_a | 73f7b49f7efe8506c43f2d49bfff8a7dab162395 | 6b4f1520941eb25a1586906f0db72a3f26a0524e | refs/heads/master | 2023-03-22T17:19:31.941076 | 2021-03-10T11:23:26 | 2021-03-10T11:23:26 | 346,279,368 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 144 | cpp | #include <iostream>
#include <string>
#include "snowman.hpp"
using namespace std;
namespace ariel{
string snowman(int num)
{
return "";
}
}
| [
"[email protected]"
] | |
ed333e184fa31115a8e3235ba53d8fed98857c84 | 78cdbfbfa915497c5b0415d0a6e09dcc749fd6ba | /gotcloud/src/bamUtil/src/Diff.h | 058184abafa1926ee5e4c2ffbcced378dcbae6a6 | [
"Apache-2.0"
] | permissive | statgen/topmed_freeze3_calling | 9b00ee64804165e320ae5690ebb42e01345c24e2 | b01a53468e1e989988b09fd74f3e9ce9faa62a99 | refs/heads/master | 2018-12-12T20:02:46.909940 | 2018-12-05T01:35:08 | 2018-12-05T01:35:08 | 68,630,437 | 11 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 5,732 | h | /*
* Copyright (C) 2011 Regents of the University of Michigan
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//////////////////////////////////////////////////////////////////////////
// This file contains the processing for the executable option "diff"
// which reads two SAM/BAM files and writes the differences.
#ifndef __DIFF_H__
#define __DIFF_H__
#include <stack>
#include <list>
#include <map>
#include "BamExecutable.h"
#include "SamFile.h"
class Diff : public BamExecutable
{
public:
Diff();
~Diff();
static void diffDescription();
void description();
void usage();
int execute(int argc, char **argv);
virtual const char* getProgramName() {return("bam:diff");}
private:
struct diffStruct
{
bool posDiff;
bool cigarDiff;
bool flagDiff;
bool mapqDiff;
bool mateDiff;
bool isizeDiff;
bool seqDiff;
bool qualDiff;
bool tagsDiff;
} myDiffStruct;
class FileInfo
{
public:
SamFile file;
SamFileHeader header;
};
class UnmatchedRecords
{
public:
UnmatchedRecords()
: myListUnmatched(),
myFragmentMaps(4),
myUnmatchedFileIter()
{
}
// Return the number of elements in this unmatched record container.
inline int size() { return(myListUnmatched.size()); }
// Add the specified record to the list of unmatched records.
void addUnmatchedRecord(SamRecord& record);
// Get and remove the record that matches the specified record's
// query(read) name and fragment (first/last/mid/unknown).
// If no match is found, return NULL.
SamRecord* removeFragmentMatch(SamRecord& record);
// Remove the first entry from this unmatched file container, returning a pointer
// to the record.
SamRecord* removeFirst();
// Get the first entry from this unmatched file container, returning a pointer
// to the record without removing it.
SamRecord* getFirst();
private:
typedef std::map<std::string, std::list<SamRecord*>::iterator> mapType;
std::list<SamRecord*> myListUnmatched;
std::vector<mapType> myFragmentMaps;
std::map<std::string,std::list<SamRecord*>::iterator>::iterator myUnmatchedFileIter;
};
// Check to see if the two records are a match - same read name & fragment.
// Return true if they match, false if not.
bool matchingRecs(SamRecord* rec1, SamRecord* rec2);
// Compare two records. Returns true if the first record chrom/pos are less than or
// equal to record2's chrom/pos, false if rec2 is less than rec1.
// Threshold is a value to be added to rec1's position before comparing to rec2. It is
// a way to determine if rec1 is more than a certain number of positions less than rec2.
// Threshold is defaulted to 0, so the excact positions are compared.
// If they are on different chromosomes, threshold is not used.
bool lessThan(SamRecord* rec1, SamRecord* rec2, int threshold = 0);
void writeBamDiffs(SamRecord* rec1, SamRecord* rec2);
void writeDiffDiffs(SamRecord* rec1, SamRecord* rec2);
void writeDiffs(SamRecord* rec1, SamRecord* rec2);
bool getDiffs(SamRecord* rec1, SamRecord* rec2);
bool writeReadName(SamRecord& record);
SamRecord* getSamRecord();
// If record is not NULL, adds it back to the free list. If record is NULL, nothing is done.
void releaseSamRecord(SamRecord* record);
bool checkDiffFile();
static const char* FLAG_DIFF_TAG;
static const char* POS_DIFF_TAG;
static const char* CIGAR_DIFF_TAG;
static const char* MAPQ_DIFF_TAG;
static const char* MATE_DIFF_TAG;
static const char* ISIZE_DIFF_TAG;
static const char* SEQ_DIFF_TAG;
static const char* QUAL_DIFF_TAG;
static const char* TAGS_DIFF_TAG;
static const char POS_DIFF_TYPE = 'Z';
static const char MATE_DIFF_TYPE = 'Z';
static const char CIGAR_DIFF_TYPE = 'Z';
static const char SEQ_DIFF_TYPE = 'Z';
static const char QUAL_DIFF_TYPE = 'Z';
static const char TAGS_DIFF_TYPE = 'Z';
std::stack<SamRecord*> myFreeSamRecords;
UnmatchedRecords myFile1Unmatched;
UnmatchedRecords myFile2Unmatched;
bool myCompAll;
bool myCompCigar;
bool myCompPos;
bool myCompBaseQual;
bool myCompSeq;
bool myCompFlag;
bool myCompMapQ;
bool myCompMate;
bool myCompISize;
String myTags;
bool myEveryTag;
bool myOnlyDiffs;
bool myBamOut;
int myMaxAllowedRecs;
int myAllocatedRecs;
int myThreshold;
int myNumPoolOverflows;
FileInfo myFile1;
FileInfo myFile2;
String myDiffFileName;
String myBamOnly1Name;
String myBamOnly2Name;
String myBamDiffName;
IFILE myDiffFile;
SamFile myBamOnly1;
SamFile myBamOnly2;
SamFile myBamDiff;
String myDiff1;
String myDiff2;
String myTags1;
String myTags2;
String myTempBuffer;
};
#endif
| [
"[email protected]"
] | |
81aee5d201a56a3704da1d91639adc7be93df818 | deba51efd716ed3c4ebe80c035cc7a861ce7c505 | /PracticalApplications5/Task7.cpp | 99096ae85b787a204f0834d6b22a413ff7c9b994 | [] | no_license | RickardBolin/Cpp---Linneuniversitet | ee78c2bdfd06f42eb42c78f5c6895cbdbe7069c7 | 02e8f3d7ac0fbfc9d72c62dff1de04e14b4c1dd5 | refs/heads/main | 2023-02-20T15:25:59.243564 | 2021-01-24T15:41:32 | 2021-01-24T15:41:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,880 | cpp | // Filename: Task7.cpp
// Created by Rickard Bolin on 2019-12-28.
//
// This program asks the user to input two matrices and performs matrix
// multiplication on them.
#include <iostream>
#include <iomanip>
using namespace std;
const int MAXDIM = 5;
typedef double Matrix[MAXDIM][MAXDIM];
void readDimensions(int &rows, int &cols);
void readMatrix(Matrix M, int row, int col);
void multMatrix(const Matrix A, const Matrix B, Matrix C, int m, int n, int p);
void printMatrix(const Matrix M, int row, int col);
int main() {
char answer;
do {
Matrix A, B, C;
int rowsA, colsA, rowsB, colsB;
cout << "Enter dimension of matrix A (row x col) with space between: ";
readDimensions(rowsA, colsA);
cout << "Enter matrix A in free format:" << endl;
readMatrix(A, rowsA, colsA);
cout << "Enter dimension of matrix B (row x col) with space between: ";
readDimensions(rowsB, colsB);
cout << "Enter matrix B in free format:" << endl;
readMatrix(B, rowsB, colsB);
if (colsA == rowsB) {
cout << "---------------------------" << endl
<< "ANSWER" << endl;
multMatrix(A, B, C, rowsA, colsB, colsA);
printMatrix(C, rowsA, colsB);
} else {
cout << "Dimensions doesn't match, can't perform matrix multiplication!" << endl;
cin.clear();
cin.ignore(80, '\n');
}
cout << endl << "One more time (Y/N)? ";
cin >> answer;
cin.clear();
cin.ignore(80, '\n');
} while (answer == 'y' || answer == 'Y');
return 0;
}
/**
This function asks the user to input a matrix of size rows*cols
@param M - The matrix where the user input is stored
@param row - Number of rows in M
@param col - Number of columns in M
*/
void readMatrix(Matrix M, int row, int col) {
bool badInput;
do {
badInput = false;
for (int r = 0; r < row; r++) {
for (int c = 0; c < col; c++) {
cin >> M[r][c];
}
}
if (cin.fail()) {
cout << "Invalid input, try again:" << endl;
badInput = true;
cin.clear();
cin.ignore(80, '\n');
}
} while (badInput);
}
/**
This function asks the user to input the dimensions of a matrix
@param rows - The number of rows
@param cols - The number of columns
*/
void readDimensions(int &rows, int &cols) {
bool badInput;
do {
badInput = false;
cin >> rows;
cin >> cols;
if (cin.fail() || rows < 0 || rows > MAXDIM || cols < 0 || cols > MAXDIM) {
badInput = true;
cout << endl << "Invalid input, please choose again: ";
cin.clear();
cin.ignore(80, '\n');
}
} while (badInput);
}
/**
This function performs matrix multiplication of matrix A and B and stores in C
@param A - First matrix to be multiplied
@param B - Second matrix to be multiplied
@param C - The result of the multiplication
@param m - The number of rows in A
@param n - The number of columns in B
@param p - The number of columns in A and rows in B
*/
void multMatrix(const Matrix A, const Matrix B, Matrix C, int m, int n, int p) {
for (int r = 0; r < m; r++) {
for (int c = 0; c < n; c++) {
C[r][c] = 0;
for (int i = 0; i < p; i++) {
C[r][c] += A[r][i] * B[i][c];
}
}
}
}
/**
This function prints the matrix M.
@param M - The matrix to be printed
@param row - The number of rows in M
@param col - The number of cols in M
*/
void printMatrix(const Matrix M, int row, int col) {
cout << fixed << setprecision(1);
for (int r = 0; r < row; r++) {
for (int c = 0; c < col; c++) {
cout << setw(10) << M[r][c] << " ";
}
cout << endl;
}
}
| [
"[email protected]"
] | |
ecf9750278f6044e0c82eee0c7fb3c41c9623936 | 97f8be92810bafdbf68b77c8a938411462d5be4b | /3rdParty/iresearch/core/search/cost.hpp | f23640dd187d9d2ba3f9207b6a100d26df9268de | [
"Apache-2.0",
"BSD-3-Clause",
"ICU",
"LGPL-2.1-or-later",
"BSD-4-Clause",
"GPL-1.0-or-later",
"Python-2.0",
"OpenSSL",
"Bison-exception-2.2",
"JSON",
"ISC",
"GPL-2.0-only",
"MIT",
"BSL-1.0",
"LicenseRef-scancode-public-domain",
"CC0-1.0",
"BSD-2-Clause",
"LicenseRef-scancode-autoconf-simple-exception",
"LicenseRef-scancode-pcre",
"LicenseRef-scancode-unknown-license-reference",
"Zlib",
"Unicode-DFS-2016",
"LicenseRef-scancode-other-copyleft",
"LicenseRef-scancode-unicode",
"LicenseRef-scancode-warranty-disclaimer",
"GPL-3.0-only"
] | permissive | solisoft/arangodb | 022fefd77ca704bfa4ca240e6392e3afebdb474e | efd5a33bb1ad1ae3b63bfe1f9ce09b16116f62a2 | refs/heads/main | 2021-12-24T16:50:38.171240 | 2021-11-30T11:52:58 | 2021-11-30T11:52:58 | 436,619,840 | 2 | 0 | Apache-2.0 | 2021-12-09T13:05:46 | 2021-12-09T13:05:46 | null | UTF-8 | C++ | false | false | 3,684 | hpp | ////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2016 by EMC Corporation, All Rights Reserved
///
/// 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.
///
/// Copyright holder is EMC Corporation
///
/// @author Andrey Abramov
////////////////////////////////////////////////////////////////////////////////
#ifndef IRESEARCH_COST_H
#define IRESEARCH_COST_H
#include <functional>
#include "utils/attribute_provider.hpp"
#include "utils/attributes.hpp"
namespace iresearch {
//////////////////////////////////////////////////////////////////////////////
/// @class cost
/// @brief represents an estimated cost of the query execution
//////////////////////////////////////////////////////////////////////////////
class IRESEARCH_API cost final : public attribute {
public:
using cost_t = uint64_t;
using cost_f = std::function<cost_t()> ;
static constexpr string_ref type_name() noexcept {
return "iresearch::cost";
}
static constexpr cost_t MAX = std::numeric_limits<cost_t>::max();
cost() = default;
explicit cost(cost_t value) noexcept
: value_(value),
init_(true) {
}
explicit cost(cost_f&& func) noexcept(std::is_nothrow_move_constructible_v<cost_f>)
: func_(std::move(func)),
init_(false) {
}
//////////////////////////////////////////////////////////////////////////////
/// @returns a value of the "cost" attribute in the specified "src"
/// collection, or "def" value if there is no "cost" attribute in "src"
//////////////////////////////////////////////////////////////////////////////
template<typename Provider>
static cost_t extract(const Provider& src, cost_t def = MAX) noexcept {
cost::cost_t est = def;
auto* attr = irs::get<irs::cost>(src);
if (attr) {
est = attr->estimate();
}
return est;
}
//////////////////////////////////////////////////////////////////////////////
/// @brief sets the estimation value
//////////////////////////////////////////////////////////////////////////////
void reset(cost_t value) noexcept {
value_ = value;
init_ = true;
}
//////////////////////////////////////////////////////////////////////////////
/// @brief sets the estimation rule
//////////////////////////////////////////////////////////////////////////////
void reset(cost_f&& eval) noexcept(std::is_nothrow_move_assignable_v<cost_f>) {
assert(eval);
func_ = std::move(eval);
init_ = false;
}
//////////////////////////////////////////////////////////////////////////////
/// @brief estimate the query according to the provided estimation function
/// @return estimated cost
//////////////////////////////////////////////////////////////////////////////
cost_t estimate() const {
if (!init_) {
assert(func_);
value_ = func_();
init_ = true;
}
return value_;
}
private:
IRESEARCH_API_PRIVATE_VARIABLES_BEGIN
cost_f func_{[]{ return 0; }}; // evaluation function
mutable cost_t value_{ 0 };
mutable bool init_{ true };
IRESEARCH_API_PRIVATE_VARIABLES_END
}; // cost
} // ROOT
#endif // IRESEARCH_COST_H
| [
"[email protected]"
] | |
eb70347b06d2cd7a551bbcd1ffc13dd408f20662 | 055cb107600b9c34028b11882d88b375089b4a54 | /18 задание/2.cpp | e36b53f9b8eeac70c68226f723e0de2fe1bd6416 | [] | no_license | BatushkaSpecnasovez/- | 506012ff3ffd965e545e3e41bf3211ff29fb2a69 | 5df02472aa878c479e1dd7134f57c7544090a8b4 | refs/heads/master | 2023-02-13T04:22:59.966908 | 2021-01-16T13:36:00 | 2021-01-16T13:36:00 | 296,316,067 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 494 | cpp | #include <stdio.h>
int main(void)
{
float a[10], b[10];
int n;
printf("N: ");
scanf_s("%i", &n);
int k;
for (k = 0; k < n; ++k) {
printf("a[%i] : ", k + 1);
scanf_s("%f", &a[k]);
}
int i;
for (k = 0; k < n; ++k) {
b[k] = 0;
for (i = k; i < n; ++i) {
b[k] += a[i];
}
}
printf("B: \n");
for (k = 0; k < n; ++k) printf(" %i: %f\n", k + 1, b[k]);
return 0;
} | [
"[email protected]"
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.