blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
264
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
85
| license_type
stringclasses 2
values | repo_name
stringlengths 5
140
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 905
values | visit_date
timestamp[us]date 2015-08-09 11:21:18
2023-09-06 10:45:07
| revision_date
timestamp[us]date 1997-09-14 05:04:47
2023-09-17 19:19:19
| committer_date
timestamp[us]date 1997-09-14 05:04:47
2023-09-06 06:22:19
| github_id
int64 3.89k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us]date 2012-06-07 00:51:45
2023-09-14 21:58:39
⌀ | gha_created_at
timestamp[us]date 2008-03-27 23:40:48
2023-08-21 23:17:38
⌀ | gha_language
stringclasses 141
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
10.4M
| extension
stringclasses 115
values | content
stringlengths 3
10.4M
| authors
sequencelengths 1
1
| author_id
stringlengths 0
158
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
261964e406157eb1ed812e9e53b35f75dcfcba50 | 142e542c645b58a73d5381170fd3ee154623f961 | /kythe/cxx/indexer/cxx/testdata/bundle_self_test_unclaimed.cc | 6bffad7be1bf2379254ea2c0ffb0f031d9fb890c | [
"Apache-2.0"
] | permissive | mcanthony/kythe | 226ea028d7124c58cfe2839cf14d4915c2b26a90 | ded11436a91e9948439c64c2eda87b8cbd23acfc | refs/heads/master | 2021-01-15T12:53:41.421627 | 2015-10-13T18:25:24 | 2015-10-13T18:25:24 | 44,242,375 | 1 | 0 | null | 2015-10-14T11:08:22 | 2015-10-14T11:08:22 | null | UTF-8 | C++ | false | false | 400 | cc | #pragma kythe_claim
// This is a multiplexed test file. The default file will be named
// test.cc.
#include "a.h"
//- AnchorC.node/kind anchor
//- AnchorC childof vname("","bundle","","test.cc","c++")
#define C macroc
#example a.h
// This is now a header file called a.h. It is unclaimed.
//- !{ @A=AnchorA.node/kind anchor
//- AnchorA childof vname("","bundle","","a.h","c++") }
#define A macroa
| [
"[email protected]"
] | |
08a32268ac637a2becb15ef7934d2ff2641bdf7a | 9732270148d744ca01c5d43cbfaddbcaf313fb80 | /vjudge/CodeForces/766D/9993554_WA_15ms_2308kB.cpp | e14a9f11f6a1e39b9837a57ae44611d61f039115 | [] | no_license | Bocity/ACM | bbb7c414aa8abae6d88e2bb89c4ab1fd105a1c5a | 9ec1ece943a4608e96829b07374c3567edcd6872 | refs/heads/master | 2021-01-04T02:41:42.108269 | 2019-01-18T07:17:01 | 2019-01-18T07:17:01 | 76,115,460 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,394 | cpp | #include <bits/stdc++.h>
#define REP(i, x, n) for (int i = (x); i < (n); i++)
#define PER(i, x, n) for (int i = (x); i >= (n); i--)
#define endl "\n"
typedef long long ll;
using namespace std;
map<string, int> num;
int n, m, q;
int pre[100005], relation[10000];
string s1, s2;
int find(int x) {
if (pre[x] == x) return x;
int order = pre[x];
pre[x] = find(pre[x]);
relation[x] = (relation[x] + relation[order]) % 2;
return pre[x];
}
int main() {
cin >> n >> m >> q;
REP(i, 0, n) {
cin >> s1;
num[s1] = i;
}
REP(i, 0, n) {
pre[i] = i;
relation[i] = 0;
}
int x, y, z;
REP(i, 0, m) {
cin >> z >> s1 >> s2;
--z;
x = num[s1], y = num[s2];
int a = find(x), b = find(y);
if (a != b) {
cout << "YES" << endl;
pre[b] = a;
relation[b] = (relation[x] - relation[y] + z + 2) % 2;
} else {
int p = (relation[x] - relation[y]) % 2;
if (p == z)
cout << "YES";
else
cout << "NO" << endl;
}
}
REP(i, 0, q) {
cin >> s1 >> s2;
x = num[s1], y = num[s2];
int a = find(x), b = find(y);
if (a != b)
cout << "3" << endl;
else
cout << (relation[x] - relation[y] + 2) % 2 + 1 << endl;
}
return 0;
} | [
"[email protected]"
] | |
a2c7363c48567af6fc94504d57a8a014593f69d9 | 8c4b5f5efa196226763688fe49f55c74d2e7bbb0 | /src/ctrl/motioncommand.h | c2b153517cf23ce7276c09fc697a34d9d76acdf6 | [
"MIT"
] | permissive | moriarty/Team2AMR | 5844c9c0a95ae808710afa0dbfea3ea67cfa214a | 70ca05ddb74714d2779d3ee3c2dbc349e23625ef | refs/heads/master | 2021-01-22T05:10:19.207624 | 2013-12-03T00:13:15 | 2013-12-03T00:13:15 | 2,843,751 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,545 | h | /** @file src/ctrl/motioncommand.h
@ingroup CTRL
@brief Controller that takes motion commands..
@author Alex Moriarty <[email protected]>
@author Jacob Perron <[email protected]>
*/
#ifndef __CTRL_MOTIONCOMMAND_H_
#define __CTRL_MOTIONCOMMAND_H_
#include "controller.h"
#include "bug.h"
class MotionCommand : public Controller {
public:
/** Constructor.
*
* Calls Controller constructor.
*
* @param m : Reference to robot motor.
*/
MotionCommand(Motor& m);
/** Destructor. */
~MotionCommand();
/** Updates the controller actions.
*
* This function first checks for obstacles using ObjectDetector,
* followed by a continued execution by PathExecuter.
*/
virtual void update();
/** Executes a Command from the Console.
*
* Pays attention to the "goto", "move", and "turn" commands.
*
* @param cmd : Command from the Console.
*/
void executeCommand(const Command cmd);
/** Gives the Controller the robots current Position.
*
* @param pos : The robots Position.
*/
virtual void youAreHere(Position pos);
/** Sets the latest RangerData.
*
* Ranger data is passed on to ObjectDetector and the Bug controller.
*
* @param data : Latest RangerData to be used.
*/
void setRangerData(RangerData data);
/** String representation of this Controller. */
virtual std::string toString();
protected:
/** Current robot location. */
Position robotPos;
/** Bug controller used for Bug algorithms. */
Bug bug;
private:
/** Stores a more complex path with more than one motion command. */
Path* plannedPath;
/** The goal position for the last motion command. */
Position goal;
/** Determines if planning mode is activated. */
bool planning;
/** Determines whether bug2 algorithm is activated. */
bool isBug2;
/** Determines if controller is finished completing an algorithm. */
bool doingAlg;
/** Disable copy constructor. */
MotionCommand(const MotionCommand& source);
/** Disable assignment operator. */
MotionCommand& operator=(const MotionCommand& source);
/** Disable default constructor. */
MotionCommand();
};
#endif
| [
"[email protected]"
] | |
d2e78f0d9aa0de3510425dd2c024f71f0e7c92ae | 780ee3047decf62a5d03846d7062659448c0a91e | /Examples/decore.cpp | 17dfba2a84c0e9e7340a1e403c0cea8202a2e667 | [
"BSL-1.0"
] | permissive | LuisRGameloft/nana-demo | 6a217a56c8e43115a16351fa25af84548e7151f5 | 05e05dbc1ee8eb5d94b31282290dae0c7e2e3620 | refs/heads/master | 2020-04-30T12:59:10.978336 | 2019-06-03T17:59:02 | 2019-06-03T17:59:02 | 176,841,644 | 0 | 0 | BSL-1.0 | 2019-06-03T17:59:03 | 2019-03-21T01:00:34 | C++ | UTF-8 | C++ | false | false | 201 | cpp | #include <nana/gui/wvl.hpp>
int main()
{
using namespace nana;
form fm(API::make_center(240, 160), appear::decorate<appear::minimize, appear::maximize>());
fm.show();
exec();
}
| [
"[email protected]"
] | |
e4a334a3e12d39cb1a03647583e4e4ed30ff84d3 | 94e5a9e157d3520374d95c43fe6fec97f1fc3c9b | /OTHERS/cse week 2015/eBF.cpp | 331cbebdfab9bc533b67df033cdc9d5bec7199bb | [
"MIT"
] | permissive | dipta007/Competitive-Programming | 0127c550ad523884a84eb3ea333d08de8b4ba528 | 998d47f08984703c5b415b98365ddbc84ad289c4 | refs/heads/master | 2021-01-21T14:06:40.082553 | 2020-07-06T17:40:46 | 2020-07-06T17:40:46 | 54,851,014 | 8 | 4 | null | 2020-05-02T13:14:41 | 2016-03-27T22:30:02 | C++ | UTF-8 | C++ | false | false | 7,048 | cpp | #pragma comment(linker, "/stack:640000000")
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <climits>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iostream>
#include <iomanip>
#include <iterator>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <utility>
#include <vector>
using namespace std;
const double EPS = 1e-9;
const int INF = 0x7f7f7f7f;
const double PI=acos(-1.0);
#define READ(f) freopen(f, "r", stdin)
#define WRITE(f) freopen(f, "w", stdout)
#define MP(x, y) make_pair(x, y)
#define SZ(c) (int)c.size()
#define PB(x) push_back(x)
#define rep(i,n) for(i=1;i<=n;i++)
#define repI(i,n) for(i=0;i<n;i++)
#define F(i,L,R) for (int i = L; i < R; i++)
#define FF(i,L,R) for (int i = L; i <= R; i++)
#define FR(i,L,R) for (int i = L; i > R; i--)
#define FRF(i,L,R) for (int i = L; i >= R; i--)
#define FOREACH(i,t) for (typeof(t.begin()) i=t.begin(); i!=t.end(); i++)
#define ALL(p) p.begin(),p.end()
#define ALLR(p) p.rbegin(),p.rend()
#define SET(p) memset(p, -1, sizeof(p))
#define CLR(p) memset(p, 0, sizeof(p))
#define MEM(p, v) memset(p, v, sizeof(p))
#define CPY(d, s) memcpy(d, s, sizeof(s))
#define getI(a) scanf("%d", &a)
#define getII(a,b) scanf("%d%d", &a, &b)
#define getIII(a,b,c) scanf("%d%d%d", &a, &b, &c)
#define getL(a) scanf("%lld",&a)
#define getLL(a,b) scanf("%lld%lld",&a,&b)
#define getLLL(a,b,c) scanf("%lld%lld%lld",&a,&b,&c)
#define getC(n) scanf("%c",&n)
#define getF(n) scanf("%lf",&n)
#define getS(n) scanf("%s",n)
#define vi vector < int >
#define vii vector < vector < int > >
#define pii pair< int, int >
#define psi pair< string, int >
#define ff first
#define ss second
#define ll long long
#define ull unsigned long long
#define ui unsigned int
#define us unsigned short
#define ld long double
template< class T > inline T _abs(T n) { return ((n) < 0 ? -(n) : (n)); }
template< class T > inline T _max(T a, T b) { return (!((a)<(b))?(a):(b)); }
template< class T > inline T _min(T a, T b) { return (((a)<(b))?(a):(b)); }
template< class T > inline T _swap(T &a, T &b) { a=a^b;b=a^b;a=a^b;}
template< class T > inline T gcd(T a, T b) { return (b) == 0 ? (a) : gcd((b), ((a) % (b))); }
template< class T > inline T lcm(T a, T b) { return ((a) / gcd((a), (b)) * (b)); }
//******************DELETE****************
#define shubhashis
#ifdef shubhashis
#define debug(args...) {dbg,args; cerr<<endl;}
#else
#define debug(args...) // Just strip off all debug tokens
#endif
struct debugger{
template<typename T> debugger& operator , (const T& v){
cerr<<v<<" ";
return *this;
}
}dbg;
/// ********* debug template bt Bidhan Roy *********
template < typename F, typename S >
ostream& operator << ( ostream& os, const pair< F, S > & p ) {
return os << "(" << p.first << ", " << p.second << ")";
}
template < typename T >
ostream &operator << ( ostream & os, const vector< T > &v ) {
os << "{";
typename vector< T > :: const_iterator it;
for( it = v.begin(); it != v.end(); it++ ) {
if( it != v.begin() ) os << ", ";
os << *it;
}
return os << "}";
}
template < typename T >
ostream &operator << ( ostream & os, const set< T > &v ) {
os << "[";
typename set< T > :: const_iterator it;
for ( it = v.begin(); it != v.end(); it++ ) {
if( it != v.begin() ) os << ", ";
os << *it;
}
return os << "]";
}
template < typename F, typename S >
ostream &operator << ( ostream & os, const map< F, S > &v ) {
os << "[";
typename map< F , S >::const_iterator it;
for( it = v.begin(); it != v.end(); it++ ) {
if( it != v.begin() ) os << ", ";
os << it -> first << " = " << it -> second ;
}
return os << "]";
}
#define deb(x) cerr << #x << " = " << x << endl;
//******************DELETE****************
int Set(int N,int pos)
{
return N=N | (1<<pos);
}
int reset(int N,int pos)
{
return N=N & ~(1<<pos);
}
bool check(int N,int pos)
{
return (bool)(N & (1<<pos));
}
int main() {
//READ("in.txt");
//WRITE("out.txt");
ll res=0;
for(int a=1;a<=9;a++)
{
for(int b=0;b<=9;b++)
{
for(int c=0;c<=9;c++)
{
for(int d=0;d<=9;d++)
{
for(int e=0;e<=9;e++)
{
for(int f=0;f<=9;f++)
{
for(int g=0;g<=9;g++)
{
for(int h=0;h<=9;h++)
{
for(int i=0;i<=9;i++)
{
ll l=0;
l += 100000000*a;
l += 10000000*b;
l += 1000000*c;
l += 100000*d;
l += 10000*e;
l += 1000*f;
l += 100*g;
l += 10*h;
l += 1*i;
//debug(l)
// string s="";
// s.PB(a+'0');
// s.PB(b+'0');
// s.PB(c+'0');
// s.PB(d+'0');
// s.PB(e+'0');
// s.PB(f+'0');
// s.PB(g+'0');
// s.PB(h+'0');
// s.PB(i+'0');
// stringstream ss;
// ss << s;
// ll l;
// ss >> l;
ll k = l*l;
if(k%1000000000==987654321)
{
debug(l)
res++;
}
}
}
}
}
}
}
}
}
}
cout << res << endl;
return 0;
}
| [
"[email protected]"
] | |
670c57c91caa8673458bfa1bd4478b8e22a1fe08 | d2fa803d61836e9ac411ead501747bb99c56c839 | /plugins/channeltx/modnfm/nfmmodsettings.h | 6d1ab4f35f2cef56a3532b907b0a844079f46caf | [] | no_license | hmne/sdrangel | 9eac60c843cc8da3bf1f7fe4dfca24a45b28d120 | 1d442fd077981087fb7733dde486d8501885d56e | refs/heads/master | 2020-03-29T21:00:38.928842 | 2017-12-02T17:57:55 | 2017-12-02T17:57:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,555 | h | ///////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2017 Edouard Griffiths, F4EXB //
// //
// 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 as version 3 of the License, or //
// //
// 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 V3 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/>. //
///////////////////////////////////////////////////////////////////////////////////
#ifndef PLUGINS_CHANNELTX_MODNFM_NFMMODSETTINGS_H_
#define PLUGINS_CHANNELTX_MODNFM_NFMMODSETTINGS_H_
#include <QByteArray>
class Serializable;
struct NFMModSettings
{
static const int m_nbRfBW;
static const int m_rfBW[];
static const int m_nbCTCSSFreqs;
static const float m_ctcssFreqs[];
int m_basebandSampleRate;
int m_outputSampleRate;
qint64 m_inputFrequencyOffset;
Real m_rfBandwidth;
Real m_afBandwidth;
float m_fmDeviation;
float m_toneFrequency;
float m_volumeFactor;
quint32 m_audioSampleRate;
bool m_channelMute;
bool m_playLoop;
bool m_ctcssOn;
int m_ctcssIndex;
quint32 m_rgbColor;
QString m_title;
Serializable *m_channelMarker;
Serializable *m_cwKeyerGUI;
NFMModSettings();
void resetToDefaults();
void setChannelMarker(Serializable *channelMarker) { m_channelMarker = channelMarker; }
void setCWKeyerGUI(Serializable *cwKeyerGUI) { m_cwKeyerGUI = cwKeyerGUI; }
QByteArray serialize() const;
bool deserialize(const QByteArray& data);
static int getRFBW(int index);
static int getRFBWIndex(int rfbw);
static float getCTCSSFreq(int index);
static int getCTCSSFreqIndex(float ctcssFreq);
};
#endif /* PLUGINS_CHANNELTX_MODNFM_NFMMODSETTINGS_H_ */
| [
"[email protected]"
] | |
eb68261bd85eadd68beb12d93e3d5f92d0749dab | 944ef7cef16f08fb1fd7c3b35669430528e1a24d | /references/BedOccupancySensor/BedOccupancySensor.ino | f4a6776a06ba5af1ce02ca2a874c90cfbea059dc | [] | no_license | TeamScheire/intel.letto | 1eae63692c0e4dc4c78509265d231be8b5aa98e7 | b1d4ad72a5dbe794fb0d8f12c1d33cfe6ef53ffa | refs/heads/master | 2020-04-02T00:30:35.513446 | 2019-05-22T06:49:03 | 2019-05-22T06:49:03 | 153,808,362 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 9,383 | ino | /**
The MySensors Arduino library handles the wireless radio link and protocol
between your home built sensors/actuators and HA controller of choice.
The sensors forms a self healing radio network with optional repeaters. Each
repeater and gateway builds a routing tables in EEPROM which keeps track of the
network topology allowing messages to be routed to nodes.
Created by Henrik Ekblad <[email protected]>
Copyright (C) 2013-2015 Sensnology AB
Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors
Documentation: http://www.mysensors.org
Support Forum: http://forum.mysensors.org
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
version 2 as published by the Free Software Foundation.
*******************************
DESCRIPTION
Bed occupancy sensor using MPR121. Requires BareConductive MPR121 Library (https://github.com/BareConductive/mpr121)
This sketch will detect both sides of a bed (two people) but it can easily be modified to detect one person.
There is a customizable 5 second detection threshold. It will check every second to see if a the state has changed
and then trigger if all 5 states are the same. So, if you shift around in your sleep it won't keep triggering. You can also customize
the varianceValue to make it more or less sensitive. The lower the number the more senstive it will be (don't set
it below 4). I have found a value of 15 to work well even under a couple of blankets.
Check out the How To video here: https://youtu.be/KofnH0reWCQ
REVISION HISTORY
3/30/16 - PeteWill - Version 1.0
*/
#include <MySensor.h>
#include <SPI.h>
#include <Bounce2.h>
#include <MPR121.h>
#include <Wire.h>
#define SN "Bed Occupancy"
#define SV "1.0"
#define NODE_ID 34 //Change to AUTO if you want it to automatically assign it for you
#define RIGHT_BED_CHILD_ID 0
#define LEFT_BED_CHILD_ID 1
#define OCC_LED_RIGHT 7 // Arduino Digital I/O pin for the LED
#define OCC_LED_LEFT 4 // Arduino Digital I/O pin for the LED
MySensor gw;
unsigned long OccPreviousMillis;
//Store the state of current bed occupancy
uint8_t rightOccupied;
uint8_t leftOccupied;
//Store the state of previous bed occupancy. When current and previous differ, send update to gateway.
uint8_t rightOccPrev;
uint8_t leftOccPrev;
//Variables used to test if occupancy is true for the duration of occDelay * 5
uint8_t occStateRight[] = {0, 0, 0, 0, 0};
uint8_t occStateLeft[] = {0, 0, 0, 0, 0};
uint16_t occDelay = 1000; // delay (in milliseconds) between reading bed occupancy sensors
uint8_t varianceValue = 15; //if the difference between baseline data and filtered data is greater than this number it will flag occupied.
int filtValPrev[9]; //Used to keep track of the previous filtered values which will determine if the sensor is triggered
uint8_t occupied[9]; //Used to keep track of initial occupancy (tracked by the difference between baseline and filtered data). Make sure to update this array with the number of occupancy sensors used
uint8_t captured[9]; //Used to determine if the baseline and filtered data was already captured after an inital occupancy check. Make sure to update this array with the number of occupancy sensors used
int filterCapture[9]; //Used to keep track of what the filtered values were when the sensor was first triggered
MyMessage msgRightOcc(RIGHT_BED_CHILD_ID, V_TRIPPED);
MyMessage msgLeftOcc(LEFT_BED_CHILD_ID, V_TRIPPED);
#define DEBUG_ON // comment out to supress serial monitor output
#ifdef DEBUG_ON
#define DEBUG_PRINT(x) Serial.print(x)
#define DEBUG_PRINTLN(x) Serial.println(x)
#define SERIAL_START(x) Serial.begin(x)
#else
#define DEBUG_PRINT(x)
#define DEBUG_PRINTLN(x)
#define SERIAL_START(x)
#endif
void setup()
{
gw.begin(NULL, NODE_ID);
gw.sendSketchInfo(SN, SV);
// 0x5A is the default MPR121 I2C address
if (!MPR121.begin(0x5A)) {
DEBUG_PRINTLN(F("error setting up MPR121"));
switch (MPR121.getError()) {
case NO_ERROR:
DEBUG_PRINTLN(F("no error"));
break;
case ADDRESS_UNKNOWN:
DEBUG_PRINTLN(F("incorrect address"));
break;
case READBACK_FAIL:
DEBUG_PRINTLN(F("readback failure"));
break;
case OVERCURRENT_FLAG:
DEBUG_PRINTLN(F("overcurrent on REXT pin"));
break;
case OUT_OF_RANGE:
DEBUG_PRINTLN(F("electrode out of range"));
break;
case NOT_INITED:
DEBUG_PRINTLN(F("not initialised"));
break;
default:
DEBUG_PRINTLN(F("unknown error"));
break;
}
}
gw.present(RIGHT_BED_CHILD_ID, S_MOTION);
gw.present(LEFT_BED_CHILD_ID, S_MOTION);
//Set LED pins to Output
pinMode(OCC_LED_RIGHT, OUTPUT);
pinMode(OCC_LED_LEFT, OUTPUT);
//Set initial state of LEDs to off
digitalWrite(OCC_LED_RIGHT, LOW);
digitalWrite(OCC_LED_LEFT, LOW);
//Set occupancy to 0 when node is first turned on
msgRightOcc.set(0);
msgLeftOcc.set(0);
}
// Check if digital input has changed and send in new value
void loop()
{
unsigned long OccCurrentMillis = millis();
if (OccCurrentMillis - OccPreviousMillis > occDelay) {
OccPreviousMillis = OccCurrentMillis;
MPR121.updateFilteredData();
//First Bed Occupancy Sensor
rightOccupied = 0;
// Read bed occ state
for (uint8_t i = 0; i < 4; i++) { // adjust for the number of sensors used
int filtVal = MPR121.getFilteredData(i);
DEBUG_PRINT(F("Value of sensor "));
DEBUG_PRINT(i);
DEBUG_PRINT(F(": "));
DEBUG_PRINT(filtVal);
//Check if the state has changed
if (filtValPrev[i] - filtVal > varianceValue) {
//Someone is in the bed
if (occupied[i] == 0) {
filterCapture[i] = filtValPrev[i];
occupied[i] = 1;
}
}
else {
if (filtVal < filterCapture[i] - (varianceValue * 2)) {
//Still occupied
occupied[i] = 1;
}
else {
//The filtered value has gone back to the original value. We need to 0 out the tracking arrays.
occupied[i] = 0;
}
}
//Add occupied counter to rightOccupied var to keep track of any tripped sensors
rightOccupied += occupied[i];
filtValPrev[i] = filtVal;
}
//Assign previous readings to incremented variables
for (int i = 0; i < 4; i++) {
occStateRight[i] = occStateRight[i + 1];
}
//If more than one sensor was tripped, reduce rightOccupied var to 1 so it can be used in "tripped" logic
occStateRight[4] = rightOccupied >= 1 ? 1 : 0;
if ((occStateRight[0] == occStateRight[1]) && (occStateRight[1] == occStateRight[2]) && (occStateRight[2] == occStateRight[3]) && (occStateRight[3] == occStateRight[4])) {
DEBUG_PRINTLN(F("5 States are the same"));
if (occStateRight[4] != rightOccPrev) {
DEBUG_PRINTLN(F("Values are different. Send to gateway"));
// Send in the new value
gw.send(msgRightOcc.set(occStateRight[4])); // Send tripped value to gw
rightOccPrev = occStateRight[4];
if (rightOccPrev == 1) {
digitalWrite(OCC_LED_RIGHT, HIGH);
}
else {
digitalWrite(OCC_LED_RIGHT, LOW);
}
}
}
//Second Bed Occupancy Sensor. If only using one sensor delete or comment out code below.
leftOccupied = 0;
// Read bed occ state
for (uint8_t i = 4; i < 8; i++) { // adjust for the number of sensors used
int filtVal = MPR121.getFilteredData(i);
DEBUG_PRINT(F("Value of sensor "));
DEBUG_PRINT(i);
DEBUG_PRINT(F(": "));
DEBUG_PRINT(filtVal);
if (filtValPrev[i] - filtVal > varianceValue) {
if (occupied[i] == 0) {
filterCapture[i] = filtValPrev[i];
occupied[i] = 1;
}
}
else {
if (filtVal < filterCapture[i] - (varianceValue * 2)) {
//Still occupied
occupied[i] = 1;
}
else {
//The baseline has gone back to the normal value or the sensor is still not triggered. We need to 0 out the tracking arrays.
occupied[i] = 0;
}
}
//Add add occupied counter to leftOccupied var to keep track of any tripped sensors
leftOccupied += occupied[i];
filtValPrev[i] = filtVal;
}
//Assign previous readings to incremented variables
for (int i = 0; i < 4; i++) {
occStateLeft[i] = occStateLeft[i + 1];
}
//If more than one sensor was tripped, reduce leftOccupied var to 1 so it can be used in "tripped" logic
occStateLeft[4] = leftOccupied >= 1 ? 1 : 0;
if ((occStateLeft[0] == occStateLeft[1]) && (occStateLeft[1] == occStateLeft[2]) && (occStateLeft[2] == occStateLeft[3]) && (occStateLeft[3] == occStateLeft[4])) {
DEBUG_PRINTLN(F("5 States are the same"));
if (occStateLeft[4] != leftOccPrev) {
DEBUG_PRINTLN(F("Values are different. Send to gateway"));
// Send in the new value
gw.send(msgLeftOcc.set(occStateLeft[4])); // Send tripped value to gw
leftOccPrev = occStateLeft[4];
if (leftOccPrev == 1) {
digitalWrite(OCC_LED_LEFT, HIGH);
}
else {
digitalWrite(OCC_LED_LEFT, LOW);
}
}
}
}
}
| [
"[email protected]"
] | |
03450c3941256007acdb233e808b4cdb9167bf0e | c8423a09ce7ada0fbc87c2cba8ee7118a1f7e84e | /Dynamic-Programming/LCS-&-variations/minInsertionDeletion.cpp | 4225e29687ac31e4ba8ed8f5627052c7904f41e6 | [] | no_license | joat28/DSA-problems | 09901065adf9bfcfa1475189edfa237ea8c764e8 | e7c960ab8c757a93c01b9c85d9d4731200eb3923 | refs/heads/main | 2023-08-20T14:38:33.129403 | 2021-10-18T06:55:25 | 2021-10-18T06:55:25 | 321,247,210 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,036 | cpp | // Find the minimum insertions and deletions to convert s1 to s2;
#include <bits/stdc++.h>
using namespace std;
int lcsLength(string s1, string s2, int m, int n)
{
vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0)); // initialize dp vector(m+1 x n+1) to 0;
for (int i = 1; i <= m; ++i)
{
for (int j = 1; j <= n; ++j)
{
if (s1[i - 1] == s2[j - 1])
{
dp[i][j] = 1 + dp[i - 1][j - 1];
}
else
{
dp[i][j] = max(dp[i][j - 1], dp[i - 1][j]);
}
}
}
return dp[m][n];
}
int minID(string s1, string s2){
int m = s1.length();
int n = s2.length();
int lcsOfStrings = lcsLength(s1, s2, m, n);
// No of extra elements in s1 = m - lcs -> remove these -> deletions
// No of extra elements in s2 = n - lcs -> add these -> insertions
return (m + n - (2 * lcsOfStrings));
}
int main(){
string s1, s2;
cin >> s1 >> s2;
cout << minID(s1, s2) << endl;
return 0;
} | [
"[email protected]"
] | |
9058872dad24cdcf2cfce738868a559e8e00703d | 5de6dfc56c240917a09c9b25e76619176d35f51a | /CCGameFramework/base/clib2d/c2d.cpp | 7c277edc99342f3c2bddff1f2c1359cfe0031767 | [] | no_license | luhaibo/GameFramework | a87380a91e17463a0b7c7cf2ddd17b69ef34dfb2 | 029fd4fe23ee13222b3f0591fc23ba32fc6154da | refs/heads/master | 2020-11-26T21:09:43.599862 | 2019-12-20T02:28:02 | 2019-12-20T02:28:02 | 229,205,368 | 1 | 0 | null | 2019-12-20T06:37:26 | 2019-12-20T06:37:25 | null | UTF-8 | C++ | false | false | 551 | cpp | //
// Project: clib2d
// Created by bajdcc
//
#include "stdafx.h"
#include "c2d.h"
namespace clib {
decimal_inv::decimal_inv(decimal v) {
set(v);
}
void decimal_inv::set(decimal v) {
value = v;
if (std::isinf(value))
inv = 0;
else if (std::abs(value) < EPSILON)
inv = inf;
inv = 1 / value;
}
decimal_square::decimal_square(decimal v) {
set(v);
}
void decimal_square::set(decimal v) {
value = v;
square = value * value;
}
} | [
"[email protected]"
] | |
70b7c1a63c3d4f1b8c9a1c991142bd15509cb59d | f351065ac6695bce4abf89742554505a05bbf1cf | /week3/TurnOnLedOnPin3/TurnOnLedOnPin3.ino | 13a16a9e8e5ca171555fc8821b7771d2a3f1e111 | [] | no_license | ja-why-son/physcomp | 3e1e3d07a0817f030f7a8889893545548c5162d2 | 3c436218d2abc42cadd856a86ccbc98942a3c8fe | refs/heads/main | 2023-05-13T21:40:31.771457 | 2021-06-08T03:47:45 | 2021-06-08T03:47:45 | 359,061,482 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 329 | ino | void setup() {
// put your setup code here, to run once:
pinMode(3, OUTPUT);
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
digitalWrite(3, HIGH);
Serial.println("Pin 3 is HIGH (5V)");
delay(1000);
digitalWrite(3, LOW);
Serial.println("Pin 3 is LOW (0v)");
delay(1000);
}
| [
"[email protected]"
] | |
0f23f43280a8c6d15c911e636733819d71e1b545 | 7ada338e189a9e941a467f9d4eca3317f3ef8f4a | /Aufzugsimulator/Person.cpp | d0fc1763635d4ed730c8e2314c51cc097f1ede7a | [] | no_license | cbiehl/cpp_tutorials | 6927429b8bcd5f25e026a2fde064c43de8158b5f | ff83f8616bda4a17204d5f2097a7d4c292f4c94f | refs/heads/master | 2020-03-27T07:06:48.592670 | 2018-09-22T13:29:35 | 2018-09-22T13:29:35 | 146,163,377 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 620 | cpp | #include <iostream>
#include "Person.hpp"
Person::Person(int destinationFloor){
std::cout << "New Person created with destination floor " << destinationFloor << std::endl;
this->destinationFloor = destinationFloor;
}
Person::Person(const Person &other){
std::cout << "Person with destination floor " << other.getDestinationFloor() << " copied" << std::endl;
this->destinationFloor = other.getDestinationFloor();
}
Person::~Person(){
std::cout << "Person with destination floor " << this->destinationFloor << " destroyed" << std::endl;
}
const int Person::getDestinationFloor() const{
return destinationFloor;
} | [
"[email protected]"
] | |
570a975ba7574014b6ee6d997e34ea7c5b033545 | 7a28fd87d8a61c9df3e95173aad779f31a04be44 | /TeamServerCluster/TeamSource/TeamDL/DLServer/Logic/Table/DLGm.cpp | 8e206ba0e5662f8d63c81607eaf55fb1f4a3c702 | [] | no_license | kspine/TeamServer | e84a858254736c05cc33780978212f7f982e549e | 360de39453156f4c4fbb5d99325aef28d2a5f75c | refs/heads/master | 2021-01-22T05:15:55.186201 | 2016-11-30T02:53:35 | 2016-11-30T02:53:35 | 81,638,625 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 357 | cpp | #include "DLGm.h"
EQ_IMPLEMENT_CACHE(CDLGm, 100)
CDLGm::CDLGm()
{
m_nRoleId = 0;
m_GmId = 0;
m_GmActionType = 0;
m_strDescribe = "";
}
CDLGm::~CDLGm()
{
}
void CDLGm::SetGmProperty(int nRoleId, int nGmid, int nGmActionType, string strDescribe)
{
setRoleId(nRoleId);
setGmId(nGmid);
setGmActionType(nGmActionType);
setDescirbe(m_strDescribe);
} | [
"[email protected]"
] | |
3ed8e1b13dc3c33744857c9fc3b66e870a16d944 | cd0df1e5d6e4576776362fe9b35bb273acf69516 | /LambgineTest/LambgineTest.cpp | 52a09a90a1e72e582ac7c8f593aff2cf7f2988cb | [
"MIT"
] | permissive | lambage/Lambgine | 49bd340b4da2f0d4719bdf799952af977db78497 | e59836015469db797ef4706e42f65bebecfd86df | refs/heads/master | 2020-06-05T09:46:25.489133 | 2015-07-01T13:52:04 | 2015-07-01T13:52:04 | 38,120,339 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 459 | cpp | // LambgineTest.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <Lambgine/Lambgine.h>
#include <thread>
int _tmain(int argc, _TCHAR* argv[])
{
int retVal = 0;
try
{
Lambgine engine;
//engine.NewWindow("one", 640, 480, 0);
//engine.NewWindow("two", 640, 480, 0);
retVal = engine.Lua().DoTerminal();
}
catch (std::runtime_error ex)
{
LogError("%s\n", ex.what());
return -1;
}
return retVal;
}
| [
"[email protected]"
] | |
af9d2cade1a1ba37a420c76b185826e17a020647 | d9e74fb29f7fa307dfa6918e0e196a258782bcb8 | /src/mandelbrot.cpp | f44282fb8f101cb917169117a8be99694fa17e04 | [] | no_license | yboetz/mandelbrot | de932ee5aa0521518130802b55219a8afeec562d | bfeff339b57a691c57ffdf8101c9eadd2b9f5330 | refs/heads/master | 2021-05-10T21:33:31.544812 | 2018-02-09T20:50:01 | 2018-02-09T20:50:01 | 118,230,216 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,355 | cpp | #include <iostream>
#include <immintrin.h>
#include <chrono>
#include <vector>
inline __m128i modps_epi32(__m128 x, __m128 col)
{
__m128 div = _mm_div_ps(x,col);
__m128 res = _mm_round_ps(div,_MM_FROUND_TO_ZERO);
res = _mm_mul_ps(res,col);
res = _mm_sub_ps(x,res);
return _mm_cvtps_epi32(res);
}
void iterate(double xmin, double xmax, double ymin, double ymax, int xsize, int ysize, int maxit, int col, int* image)
{
double dx = (xmax - xmin) / xsize;
double dy = (ymax - ymin) / ysize;
int width = xsize / 4;
__m128 vcol = _mm_set1_ps((float)col);
__m256d vdx = _mm256_set1_pd(dx);
__m256d vdy = _mm256_set1_pd(-dy);
__m256d vxmin = _mm256_set1_pd(xmin);
__m256d vymax = _mm256_set1_pd(ymax);
__m256d one = _mm256_set1_pd(1.0);
__m256d two = _mm256_set1_pd(2.0);
__m256d four = _mm256_set1_pd(4.0);
#pragma omp parallel for schedule(dynamic)
for(int j = 0; j < ysize; j++)
{
__m256d cim = _mm256_fmadd_pd(_mm256_set1_pd(j),vdy,vymax);
__m256d incr = _mm256_setr_pd(0.0,1.0,2.0,3.0);
int ywidth = j*xsize;
for(int i = 0; i < width; i++)
{
__m256d cre = _mm256_fmadd_pd(incr,vdx,vxmin);
incr = _mm256_add_pd(incr,four);
__m256d re = _mm256_xor_pd(one,one); // Set to 0
__m256d im = _mm256_xor_pd(one,one);
__m256d re_2 = _mm256_xor_pd(one,one);
__m256d im_2 = _mm256_xor_pd(one,one);
__m256d counter = _mm256_xor_pd(one,one);
int test;
int k = 0;
do
{
im = _mm256_mul_pd(im,re);
im = _mm256_fmadd_pd(two,im,cim);
re = _mm256_sub_pd(re_2,im_2);
re = _mm256_add_pd(re,cre);
re_2 = _mm256_mul_pd(re,re);
im_2 = _mm256_mul_pd(im,im);
__m256d which = _mm256_add_pd(re_2,im_2);
which = _mm256_cmp_pd(which,four,_CMP_LT_OQ);
test = _mm256_movemask_pd(which);
which = _mm256_and_pd(which,one);
counter = _mm256_add_pd(counter,which);
}
while((test != 0) && (++k < maxit));
_mm_store_si128((__m128i*)(image + ywidth + 4*i),modps_epi32(_mm256_cvtpd_ps(counter),vcol));
}
}
}
class Mandelbrot
{
public:
int xsize, ysize;
double xmin, xmax, ymin, ymax;
int maxit, col;
int* image;
std::vector<int> tmp_image;
Mandelbrot(int, int, double, double, double, double, int, int, int*);
void setMaxIt(int);
void setCol(int);
void zoom(double);
void moveL(int);
void moveR(int);
void moveD(int);
void moveU(int);
void setExtent(double,double);
};
Mandelbrot::Mandelbrot(int x, int y, double xmi, double xma, double ymi, double yma, int max, int c, int* img)
{
xsize = x;
ysize = y;
xmin = xmi;
xmax = xma;
ymin = ymi;
ymax = yma;
maxit = max;
col = c;
image = img;
iterate(xmin, xmax, ymin, ymax, xsize, ysize, maxit, col, image);
}
void Mandelbrot::setMaxIt(int it)
{
maxit = it;
iterate(xmin, xmax, ymin, ymax, xsize, ysize, maxit, col, image);
}
void Mandelbrot::setCol(int c)
{
col = c;
iterate(xmin, xmax, ymin, ymax, xsize, ysize, maxit, col, image);
}
void Mandelbrot::zoom(double factor)
{
double dx = 0.5 * (xmax - xmin) * (factor - 1.0);
double dy = 0.5 * (ymax - ymin) * (factor - 1.0);
xmin -= dx;
xmax += dx;
ymin -= dy;
ymax += dy;
iterate(xmin, xmax, ymin, ymax, xsize, ysize, maxit, col, image);
}
void Mandelbrot::moveL(int step)
{
if(step == 0) return;
int stepSize = 4*step;
if(stepSize > xsize) return;
double dx = (xmax - xmin) / xsize * stepSize;
xmin -= dx;
xmax -= dx;
tmp_image.reserve(ysize*stepSize);
iterate(xmin, xmin + dx, ymin, ymax, stepSize, ysize, maxit, col, tmp_image.data());
int xstep = xsize/4 - step + 1;
for(int j = 0; j < ysize; j++)
{
int ywidth = j*xsize;
for(int i = 1; i < xstep; i++)
{
int _i = xsize - 4*i;
_mm_store_si128((__m128i*)(image + ywidth + _i), _mm_load_si128((__m128i*)(image + ywidth + _i - stepSize)));
}
for(int i = 0; i < step; i++)
{
int _i = 4*i;
_mm_store_si128((__m128i*)(image + ywidth + _i), _mm_load_si128((__m128i*)(tmp_image.data() + j*stepSize + _i)));
}
}
}
void Mandelbrot::moveR(int step)
{
if(step == 0) return;
int stepSize = 4*step;
if(stepSize > xsize) return;
double dx = (xmax - xmin) / xsize * stepSize;
xmin += dx;
xmax += dx;
tmp_image.reserve(ysize*stepSize);
iterate(xmax - dx, xmax, ymin, ymax, stepSize, ysize, maxit, col, tmp_image.data());
int xstep = xsize/4 - step;
for(int j = 0; j < ysize; j++)
{
int _j = j*xsize;
for(int i = 0; i < xstep; i++)
{
int _i = 4*i;
_mm_store_si128((__m128i*)(image + _j + _i), _mm_load_si128((__m128i*)(image + _j + _i + stepSize)));
}
for(int i = xstep; i < xstep + step; i++)
{
int _i = 4*i;
_mm_store_si128((__m128i*)(image + _j + _i), _mm_load_si128((__m128i*)(tmp_image.data() + j*stepSize + _i - xsize + stepSize)));
}
}
}
void Mandelbrot::moveD(int step)
{
if(step == 0) return;
int stepSize = 4*step;
if(stepSize > xsize) return;
double dy = (ymax - ymin) / ysize * stepSize;
ymin -= dy;
ymax -= dy;
tmp_image.reserve(xsize*stepSize);
iterate(xmin, xmax, ymin, ymin + dy, xsize, stepSize, maxit, col, tmp_image.data());
int xstep = xsize/4;
int ystep = ysize - stepSize;
int stepWidth = stepSize*xsize;
int stepWidthtmp = ystep*xsize;
for(int j = 0; j < ystep; j++)
{
int _j = j*xsize;
for(int i = 0; i < xstep; i++)
{
int _i = 4*i;
_mm_store_si128((__m128i*)(image + _j + _i), _mm_load_si128((__m128i*)(image + _j + _i + stepWidth)));
}
}
for(int j = ystep; j < ysize; j++)
{
int _j = j*xsize;
for(int i = 0; i < xstep; i++)
{
int _i = 4*i;
_mm_store_si128((__m128i*)(image + _j + _i), _mm_load_si128((__m128i*)(tmp_image.data() + _j - stepWidthtmp + _i)));
}
}
}
void Mandelbrot::moveU(int step)
{
if(step == 0) return;
int stepSize = 4*step;
if(stepSize > xsize) return;
double dy = (ymax - ymin) / ysize * stepSize;
ymin += dy;
ymax += dy;
tmp_image.reserve(xsize*stepSize);
iterate(xmin, xmax, ymax - dy, ymax, xsize, stepSize, maxit, col, tmp_image.data());
int xstep = xsize/4;
int ystep = ysize - stepSize + 1;
int stepWidth = stepSize*xsize;
for(int j = 1; j < ystep; j++)
{
int _j = (ysize-j)*xsize;
for(int i = 0; i < xstep; i++)
{
int _i = 4*i;
_mm_store_si128((__m128i*)(image + _j + _i), _mm_load_si128((__m128i*)(image + _j + _i - stepWidth)));
}
}
for(int j = 0; j < stepSize; j++)
{
int _j = j*xsize;
for(int i = 0; i < xstep; i++)
{
int _i = 4*i;
_mm_store_si128((__m128i*)(image + _j + _i), _mm_load_si128((__m128i*)(tmp_image.data() + _j + _i)));
}
}
}
// Sets new extent. x & y are pixel positions measured from top left, increasing to the right and down
void Mandelbrot::setExtent(double x, double y)
{
double xscale = (xmax - xmin);
double yscale = (ymax - ymin);
double xMiddle = xmin + xscale / xsize * x;
double yMiddle = ymax - yscale / ysize * y;
xmin = xMiddle - 0.5 * xscale;
xmax = xMiddle + 0.5 * xscale;
ymin = yMiddle - 0.5 * yscale;
ymax = yMiddle + 0.5 * yscale;
}
| [
"[email protected]"
] | |
4bc4db4c1175af55ac8721d3821a6940f1ffd799 | 46f157b7257a89cec68132ec69c6443f5b7469a7 | /mv/mvaxes.cpp | a968de76d65ebd2c517999066f51933bc8e6584c | [] | no_license | Phylian/modelview | 08cbce6866df6fd3fcf888e7393fcf92af4d1a24 | 36e02312d46bbba7c72f02be6209a74b1a2afc15 | refs/heads/master | 2021-06-25T02:55:44.926109 | 2017-08-24T23:53:15 | 2017-08-24T23:53:15 | 100,531,819 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,117 | cpp | #include "mvAxes.h"
#include "vtkAxes.h"
#include "vtkTubeFilter.h"
#include "vtkLookupTable.h"
mvAxes::mvAxes()
{
m_DefaultSize = 1;
m_DefaultTubeDiameter = 1;
m_DefaultPositions[0] = 0;
m_DefaultPositions[1] = 1;
m_DefaultPositions[2] = 0;
m_DefaultPositions[3] = 1;
m_DefaultPositions[4] = 0;
m_DefaultPositions[5] = 1;
m_NormalizedPosition[0] = 0;
m_NormalizedPosition[1] = 0;
m_NormalizedPosition[2] = 0;
m_Axes = vtkAxes::New();
m_Tube = vtkTubeFilter::New();
m_Tube->SetNumberOfSides(10);
m_Tube->SetInput(m_Axes->GetOutput());
m_LookupTable = vtkLookupTable::New();
m_LookupTable->SetNumberOfColors(3);
m_LookupTable->SetTableValue(0, 1, 0, 0, 1);
m_LookupTable->SetTableValue(1, 0, 1, 0, 1);
m_LookupTable->SetTableValue(2, 0, 0, 1, 1);
m_LookupTable->Build();
SetMapperInput(m_Tube->GetOutput());
m_Mapper->SetLookupTable(m_LookupTable);
m_Mapper->SetScalarRange(0, 0.5);
}
mvAxes::~mvAxes()
{
m_Axes->Delete();
m_Tube->Delete();
m_LookupTable->Delete();
}
void mvAxes::SetDefaultPositions(const float *p)
{
m_DefaultPositions[0] = p[0];
m_DefaultPositions[1] = p[1];
m_DefaultPositions[2] = p[2];
m_DefaultPositions[3] = p[3];
m_DefaultPositions[4] = p[4];
m_DefaultPositions[5] = p[5];
float xo = m_NormalizedPosition[0]*(p[1]-p[0]) + p[0];
float yo = m_NormalizedPosition[1]*(p[3]-p[2]) + p[2];
float zo = m_NormalizedPosition[2]*(p[5]-p[4]) + p[4];
m_Axes->SetOrigin(xo, yo, zo);
}
void mvAxes::SetDefaultSize(float s)
{
m_Axes->SetScaleFactor(GetNormalizedSize() * s);
m_DefaultSize = s;
}
void mvAxes::SetDefaultTubeDiameter(float d)
{
m_Tube->SetRadius(GetNormalizedTubeDiameter() * d / 2);
m_DefaultTubeDiameter = d;
}
void mvAxes::SetNormalizedPosition(float xn, float yn,float zn)
{
m_NormalizedPosition[0] = xn;
m_NormalizedPosition[1] = yn;
m_NormalizedPosition[2] = zn;
float xo = xn*(m_DefaultPositions[1]-m_DefaultPositions[0]) + m_DefaultPositions[0];
float yo = yn*(m_DefaultPositions[3]-m_DefaultPositions[2]) + m_DefaultPositions[2];
float zo = zn*(m_DefaultPositions[5]-m_DefaultPositions[4]) + m_DefaultPositions[4];
m_Axes->SetOrigin(xo, yo, zo);
}
void mvAxes::SetNormalizedSize(float sn)
{
m_Axes->SetScaleFactor(sn * m_DefaultSize);
}
void mvAxes::SetNormalizedTubeDiameter(float dn)
{
m_Tube->SetRadius(dn * m_DefaultTubeDiameter/2);
}
void mvAxes::SetRepresentationToTube()
{
SetMapperInput(m_Tube->GetOutput());
m_Actor->GetProperty()->SetAmbient(0.0);
m_Actor->GetProperty()->SetDiffuse(1.0);
}
void mvAxes::SetRepresentationToLine()
{
SetMapperInput(m_Axes->GetOutput());
m_Actor->GetProperty()->SetAmbient(1.0);
m_Actor->GetProperty()->SetDiffuse(0.0);
}
float mvAxes::GetNormalizedSize() const
{
return (m_Axes->GetScaleFactor()/m_DefaultSize);
}
float mvAxes::GetNormalizedTubeDiameter() const
{
return (2 * m_Tube->GetRadius() / m_DefaultTubeDiameter);
}
const float *mvAxes::GetNormalizedPosition() const
{
return m_NormalizedPosition;
}
int mvAxes::GetRepresentation() const
{
if (m_Mapper->GetInput() == m_Tube->GetOutput())
{
return 0; // tube
}
else
{
return 1; // line
}
}
| [
"[email protected]"
] | |
78a5d7eaa2c10d4543cc605e8026333b93254558 | 5c00983c03280e0f7f4b483f2e190346e8273dc7 | /Game.h | 1af440590fe0683297f430d8990b22febd56875c | [
"CC0-1.0"
] | permissive | TheSharpOwl/Breakout | b877e4000f3661fa49e7ad456ecd6fb51d2465ee | 03786020c851598ac2337d0c74bcc731cf773284 | refs/heads/master | 2022-12-28T03:21:33.396489 | 2020-10-16T17:34:53 | 2020-10-16T17:34:53 | 287,698,099 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,641 | h | #pragma once
#include<glad/glad.h>
#include<GLFW/glfw3.h>
#include "Gamelevel.h"
#include "PowerUp.hpp"
// forward decleration
class BallObject;
enum GameState
{
GAME_ACTIVE,
GAME_MENU,
GAME_WIN
};
enum Direction
{
UP,
RIGHT,
DOWN,
LEFT
};
using Collision = std::tuple<bool, Direction, glm::vec2>;
// Initial size of the player paddle
const glm::vec2 PLAYER_SIZE(100.0f, 20.0f);
// Initial velocity of the player paddle
const float PLAYER_VELOCITY(500.0f);
// To be defined in the cpp
bool CheckCollision(const GameObject& one, const GameObject& two);
bool CheckCollision(const BallObject& one, const GameObject& two);
Direction VectorDirection(glm::vec2 target);
Collision checkCollision(const BallObject& one, const GameObject& two);
// Holds all game state and functionality related things
class Game
{
public:
Game(unsigned int width, unsigned int height);
~Game();
GameState State;
bool Keys[1024];
// added because of the gui keyboard issue
///(https://learnopengl.com/In-Practice/2D-Game/Render-text) Level selection paragraph, after the picture
bool KeysProcessed[1024];
unsigned int Width, Height;
std::vector<GameLevel> Levels;
unsigned int Level;
std::vector<PowerUp> PowerUps;
unsigned int Lives;
//initialize game state (loading all shaders/textures/levels)
void Init();
//game loop
void ProcessInput(float dt);
void Update(float dt);
void Render();
void DoCollisions();
void ResetLevel();
void ResetPlayer();
// spawns a power up at the location of a given block
void SpawnPowerUps(GameObject& block);
// manages all active powerups
void UpdatePowerUps(float dt);
};
| [
"[email protected]"
] | |
3919a6a6255543aea28365055fbcb942612e64e5 | 36b07ada05805f564a3f61c28af073a22fdb0907 | /DGameFrame/GameTest.h | 24c54d661119a186042b366895b6b31a67f96263 | [] | no_license | hermitD/DTankGame | e5155153ab50546553bb6adcebdc34497e794c7b | e163a49da2c471d49e328519159c5bb1663bdf82 | refs/heads/master | 2021-01-10T20:06:34.426699 | 2015-01-02T05:57:22 | 2015-01-02T05:57:22 | 28,704,890 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 181 | h | #pragma once
#include "dthegame.h"
class CGameTest :
public CDTheGame
{
public:
CGameTest(void);
~CGameTest(void);
virtual void OnInit(void);
virtual void Draw(int dt);
};
| [
"[email protected]"
] | |
dd10a88129231f067753e5343b54e73b6c0329cd | bb864e905a69b6dbe07a97d6d31d9b47cc97dabb | /HackerRank/nextTopologicalSorting.cpp | 67991db60cb840073661db9ad034ee20521015a6 | [] | no_license | k--chow/CompetitiveProgramming | 74b7eb58dfaca6375e55cfe1aa097d43bc154d81 | d5b00609141ae33aaaf736fd265b3db4a47dbe62 | refs/heads/master | 2021-01-17T01:57:54.378698 | 2016-12-30T01:01:21 | 2016-12-30T01:01:21 | 40,216,189 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,578 | cpp | #include <algorithm>
#include <vector>
#include <string>
#include <iostream>
#include <math.h>
#include <stack>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <map>
#include <time.h>
#include <set>
using namespace std;
int main()
{
int nodes, edges; cin >> nodes >> edges;
vector< vector<int> > adj(nodes);
vector<int> degree(nodes, 0);
for(int i=0; i<edges; i++)
{
int u, v; cin >> u >> v;
adj[u-1].push_back(v-1);
degree[v-1]++;
}
vector<int> top;
string topo = "";
for(int i=0; i<nodes; i++)
{
int p; cin >> p;
top.push_back(p);
topo+= to_string(p);
}
//vector<int> visited(nodes, 0); no need for DAG
set<int> setty;
for(int i=0; i<nodes; i++)
{
if (degree[i] == 0)
{
setty.insert(i);
//cout << i << "found" << endl;
}
}
string ans = "";
int state = 1;
int index = -1;
int hi;
set<int>::iterator it;
//find index first
while (1)
{
//keep querying highest
hi = topo[index] - '0' - 1;
for(it=setty.begin(); it!= setty.end(); it++)
{
hi = max(hi, *it);
}
if (hi > topo[index] - '0' - 1)
{
index++;
} else {
break;
}
}
if (index == 0) {
cout << "-1" << endl;
} else
{
index--;
int j = 0;
while (1)
{
//cout << state << endl;
if (state == 1)
{
if (j != index)
{
hi = topo[j] - '0' - 1;
//cout << "hi " << hi << endl;
}
else
{
state = 2;
}
}
else //state 3
{
hi = 10001;
for(it=setty.begin(); it!= setty.end(); it++)
{
hi = min(hi, *it);
}
}
if (state == 2)
{
hi = (topo[index] - '0' - 1);
for(it = setty.begin(); it!= setty.end(); it++)
{
if (*it > (topo[index] - '0' - 1))
{
hi = *it;
break;
}
}
for(it = setty.begin(); it!= setty.end(); it++)
{
if (*it > (topo[index] - '0' - 1))
{
hi = min(hi, *it);
}
}
state = 3;
}
//remove degrees
setty.erase(hi);
for(int i=0; i<adj[hi].size(); i++)
{
degree[adj[hi][i]]--;
if (degree[adj[hi][i]] < 1) setty.insert(adj[hi][i]);
}
ans += to_string(hi+1);
j++;
if (ans.size() == nodes) break;
}
for(int n=0; n<ans.length(); n++)
{
cout << ans[n] << " ";
}
}
}
| [
"[email protected]"
] | |
950d95a884dbd2babce35d41ca0c721fc4fb9e55 | f7f3e3838a11c850576d2a3db0fa0a7182e0390a | /src/QtAES/maintest.cpp | b4ae8408b42fc24a9a8b575be1f09592431455d4 | [
"Unlicense"
] | permissive | 519984307/WeBookServer | 8f7327d7a3e842ff5021e64acfa8f0d14324a6d5 | 6108d4ef564abd1413090f72755d6bba45ff77c1 | refs/heads/master | 2023-03-21T07:46:33.206766 | 2020-07-25T03:51:21 | 2020-07-25T03:51:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 615 | cpp | #include <QCoreApplication>
#include <QTest>
#include "unit_test/aestest.h"
/******************************************************************************
** maintest *
** QAESEncryption *
*******************************************************************************/
int maintest(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
AesTest test1;
QTest::qExec(&test1);
return 0;
}
/* ***************************** End of File ******************************* */
| [
"[email protected]"
] | |
e941e2b8784348d08f424fc83ac08a52dd2e7a3e | c30cff1935d73d2fce146cde0590d82e1837f80f | /RougeLike/Source/Actors/Enemies/EnemyStates/EnemyState.h | 56c37f7db6d6cc12fc873bd239ece5997879f7d9 | [] | no_license | SamanGharatchorlou/RougeLike | e0fb743ec26278a0c115919b59b91c7b1f81438b | f9dbe76d48a1d832b3e525807557f61c81ef12a9 | refs/heads/master | 2021-07-02T05:42:03.232194 | 2021-06-17T14:14:09 | 2021-06-17T14:14:09 | 240,692,319 | 2 | 0 | null | 2020-02-15T12:40:49 | 2020-02-15T11:02:53 | C++ | UTF-8 | C++ | false | false | 1,262 | h | #pragma once
#include "States/State.h"
class Enemy;
struct EnemyState : public State
{
enum Type
{
None,
Wait,
Idle,
Run,
Patrol,
Alert,
Hit,
Stun,
PreAttack,
Attack,
Charge,
Dead,
Exit,
Count
};
EnemyState() : mEnemy(nullptr) { }
void set(Enemy* enemy) { mEnemy = enemy; }
virtual void render();
virtual const Type type() const = 0;
protected:
Enemy* mEnemy;
};
// The null state does nothing
struct EnemyNullState : public EnemyState
{
void init() override { }
void handleInput() override { }
void slowUpdate(float /*dt*/) override { }
void fastUpdate(float /*dt*/) override { }
void render() override { }
void exit() override { }
const Type type() const { return Type::None; }
};
// EnemyManager will remove any enemy in this state
struct EnemyExit : public EnemyState
{
void init() override { }
void handleInput() override { }
void slowUpdate(float /*dt*/) override { }
void fastUpdate(float /*dt*/) override { }
void render() override { }
void exit() override { }
const Type type() const { return Type::Exit; }
};
template<class T>
inline EnemyState::Type operator +(EnemyState::Type a, T b)
{
int sum = static_cast<int>(a) + static_cast<int>(b);
return static_cast<EnemyState::Type>(sum);
} | [
"[email protected]"
] | |
01d33be36b78f931e3e317f775563a8b37f86832 | 36a824cde9275a855d629d4c2d8f857db6a2259a | /include/interfaces/TempInterface.h | 0d924a15bff2557cdc3bccf3179cf4f1fb42051d | [] | no_license | chuffman93/fsw_comp | d35c48f45c89c8dfcdf0b74b0c8bf2eb7c0e8f86 | ddb6f4bd9ad95e2b8e119c1faab4d9f8a33ce3e6 | refs/heads/master | 2020-04-15T22:54:58.542021 | 2019-01-10T16:08:30 | 2019-01-10T16:08:30 | 165,089,098 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 545 | h | /*
* TempInterface.h
*
* Created on: Dec 28, 2017
* Author: cyborg9
*/
#ifndef TEMPINTERFACE_H_
#define TEMPINTERFACE_H_
#include "hal/OneWireManager.h"
#include "util/Logger.h"
class TempInterface{
public:
TempInterface(OneWireManager& onewireman, int id);
~TempInterface();
void beginSample();
float getSample();
private:
//! The reference to the one wire manager
OneWireManager& onewireman;
//! The id of the device on the bus
int id;
//! Tags to use when logging
LogTags tags;
};
#endif /* TEMPINTERFACE_H_ */
| [
"[email protected]"
] | |
1c42a2e741de6b78cb5ef5cef0cf3912f173cc18 | 38112c074f8bdf2cbaa93b802edbeeb7a94f7194 | /buscar_sig.cpp | 67ab5254a3c04532845974bd31297816039ca440 | [] | no_license | SofiaArancibia/File-System | 5bffee74d9f432ca83c730b9548ffe4a5ec9bfae | 75f2039b8521486562adefc69930b0c1bfb3fb5d | refs/heads/master | 2020-03-19T12:51:16.558864 | 2018-06-08T00:18:51 | 2018-06-08T00:18:51 | 136,544,775 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,164 | cpp | // Funcion que busca el siguiente "que" vacio
#include <stdio.h>
#include <string.h>
#include <vector>
#include <string>
#include <iostream>
#include <cstdio>
#include "inodo.h"
#include "bloque.h"
using namespace std;
extern vector <inodo> inodos;
extern vector < bloque > datos; //(64); //vector de datos
extern vector< vector<int> > enlaces; //(2000); //para enlaces indirectos simples y dobles
int buscar_sig(string que){
if (que=="bloque"){
int indx=-1;
for (unsigned int i=0; i< datos.size(); i++){
if(!datos[i].ocupado){
indx=i;
return indx;
}
}
return indx;
}else if (que=="inodo"){
int indx=-1;
for (unsigned int i=0; i< inodos.size(); i++){
inodo in=inodos[i];
if (in.ocupado==false){
indx = i;
return indx;
}
}
return indx;
}else if(que=="enlace"){
int indx=-1;
for (unsigned int i=0; i<enlaces.size(); i++){
if (enlaces[i].empty()){
indx=i;
return indx;
}
}
return indx;
} else if(que=="enlace++"){
int indx=-1;
for (unsigned int i=0; i<enlaces.size()-1; i++){
if (enlaces[i+2].empty()){
indx=i+2;
return indx;
}
}
return indx;
}
}
| [
"[email protected]"
] | |
ba48939023c475a5ac0a0f36646cafd013512a10 | 52505166e409b44caf7a0b144ef0c453b586fcee | /performance-eval/gb/s4/include/GBHigh_ila.h | f87979a20acd621e4ee8177e0ca1add90d90a009 | [] | no_license | yuex1994/ASPDAC-tandem | fb090975c65edbdda68c19a8d7e7a5f0ff96bcb8 | decdabc5743c2116d1fc0e339e434b9e13c430a8 | refs/heads/master | 2023-08-28T04:37:30.011721 | 2021-08-07T13:19:23 | 2021-08-07T13:19:30 | 419,089,461 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 294 | h | #include "GBHigh.h"
class Ilated {
public:
Ilated() {
i_top = new GBHigh();
}
~Ilated() {
delete i_top;
}
GBHigh* i_top;
uint32_t ila_pc = 0;
};
class i_in {
public:
bool GBHigh_arg_0_TREADY;
bool GBHigh_arg_1_TVALID;
uint8_t GBHigh_arg_1_TDATA;
};
| [
"[email protected]"
] | |
ad035e5635acd17645c49d7b408303a64981212b | b06b087bd36f4a1eef923d5ebe191cf5087646db | /QT_testVersion/poisson_sampler/build-poissonSampler-Desktop_Qt_5_9_6_MinGW_32bit-Debug/debug/moc_mainwindow.cpp | 9551bbd80ec807e1c73bde6fc1d1988b924de683 | [] | no_license | hanbollar/Chimera | 1a6eed4570dce58ecf3a58c35d681bab9ecb4c13 | 2e8cd51afcac0deecdf571f6b301a28907ac61f2 | refs/heads/master | 2020-04-23T13:01:07.246762 | 2019-05-08T06:15:36 | 2019-05-08T06:15:36 | 171,188,561 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,195 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'mainwindow.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.9.6)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../../PoissonSampler/src/mainwindow.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'mainwindow.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.9.6. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
struct qt_meta_stringdata_MainWindow_t {
QByteArrayData data[6];
char stringdata0[107];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_MainWindow_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_MainWindow_t qt_meta_stringdata_MainWindow = {
{
QT_MOC_LITERAL(0, 0, 10), // "MainWindow"
QT_MOC_LITERAL(1, 11, 23), // "on_actionQuit_triggered"
QT_MOC_LITERAL(2, 35, 0), // ""
QT_MOC_LITERAL(3, 36, 19), // "slot_ResizeToCamera"
QT_MOC_LITERAL(4, 56, 34), // "on_actionCamera_Controls_trig..."
QT_MOC_LITERAL(5, 91, 15) // "slot_DisableGUI"
},
"MainWindow\0on_actionQuit_triggered\0\0"
"slot_ResizeToCamera\0"
"on_actionCamera_Controls_triggered\0"
"slot_DisableGUI"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_MainWindow[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
4, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: name, argc, parameters, tag, flags
1, 0, 34, 2, 0x08 /* Private */,
3, 2, 35, 2, 0x08 /* Private */,
4, 0, 40, 2, 0x08 /* Private */,
5, 1, 41, 2, 0x0a /* Public */,
// slots: parameters
QMetaType::Void,
QMetaType::Void, QMetaType::Int, QMetaType::Int, 2, 2,
QMetaType::Void,
QMetaType::Void, QMetaType::Bool, 2,
0 // eod
};
void MainWindow::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
MainWindow *_t = static_cast<MainWindow *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->on_actionQuit_triggered(); break;
case 1: _t->slot_ResizeToCamera((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2]))); break;
case 2: _t->on_actionCamera_Controls_triggered(); break;
case 3: _t->slot_DisableGUI((*reinterpret_cast< bool(*)>(_a[1]))); break;
default: ;
}
}
}
const QMetaObject MainWindow::staticMetaObject = {
{ &QMainWindow::staticMetaObject, qt_meta_stringdata_MainWindow.data,
qt_meta_data_MainWindow, qt_static_metacall, nullptr, nullptr}
};
const QMetaObject *MainWindow::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *MainWindow::qt_metacast(const char *_clname)
{
if (!_clname) return nullptr;
if (!strcmp(_clname, qt_meta_stringdata_MainWindow.stringdata0))
return static_cast<void*>(this);
return QMainWindow::qt_metacast(_clname);
}
int MainWindow::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QMainWindow::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 4)
qt_static_metacall(this, _c, _id, _a);
_id -= 4;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 4)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 4;
}
return _id;
}
QT_WARNING_POP
QT_END_MOC_NAMESPACE
| [
"[email protected]"
] | |
1ed49c3ecd2a459230c096b70de6ae6a1dc43f78 | e0c3cb365c680fd2ceb247bfb8aa544f9b4423af | /src/devices/motorctrl/BrusaMotorController.cpp | 631f51e64079e8c6c630dfc116d15aa9f4fb9449 | [
"MIT"
] | permissive | mfkiwl/GEVCU7 | 1d236d5c23024a5db912f047f83be750257e72f7 | cfe7d2bf20fbc2bd86ab7b4c6ca5396e301153ce | refs/heads/main | 2023-08-23T04:34:26.219471 | 2021-10-14T00:31:07 | 2021-10-14T00:31:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,591 | cpp | /*
* BrusaMotorController.cpp
*
*
Copyright (c) 2013 Collin Kidder, Michael Neuweiler, Charles Galpin
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "BrusaMotorController.h"
/*
Warning:
At high speed disable the DMC_EnableRq can be dangerous because a field weakening current is
needed to achieve zero torque. Switching off the DMC in such a situation will make heavy regenerat-
ing torque that can't be controlled.
*/
/*
* Constructor
*/
BrusaMotorController::BrusaMotorController() : MotorController() {
torqueAvailable = 0;
maxPositiveTorque = 0;
minNegativeTorque = 0;
limiterStateNumber = 0;
tickCounter = 0;
commonName = "Brusa DMC5 Inverter";
shortName = "DMC5";
}
void BrusaMotorController::earlyInit()
{
prefsHandler = new PrefHandler(BRUSA_DMC5);
}
/*
* Setup the device if it is enabled in configuration.
*/
void BrusaMotorController::setup() {
tickHandler.detach(this);
Logger::info("add device: Brusa DMC5 (id: %X, %X)", BRUSA_DMC5, this);
loadConfiguration();
MotorController::setup(); // run the parent class version of this function
// register ourselves as observer of 0x258-0x268 and 0x458 can frames
canHandlerEv.attach(this, CAN_MASKED_ID_1, CAN_MASK_1, false);
canHandlerEv.attach(this, CAN_MASKED_ID_2, CAN_MASK_2, false);
tickHandler.attach(this, CFG_TICK_INTERVAL_MOTOR_CONTROLLER_BRUSA);
}
/*
* Process event from the tick handler.
*
* The super-class requests desired levels from the throttle and
* brake and decides which one to apply.
*/
void BrusaMotorController::handleTick() {
MotorController::handleTick(); // call parent
tickCounter++;
sendControl(); // send CTRL every 20ms
if (tickCounter > 4) {
sendControl2(); // send CTRL_2 every 100ms
sendLimits(); // send LIMIT every 100ms
tickCounter = 0;
}
}
/*
* Send DMC_CTRL message to the motor controller.
*
* This message controls the power-stage in the controller, clears the error latch
* in case errors were detected and requests the desired torque / speed.
*/
void BrusaMotorController::sendControl() {
BrusaMotorControllerConfiguration *config = (BrusaMotorControllerConfiguration *)getConfiguration();
prepareOutputFrame(CAN_ID_CONTROL);
speedRequested = 0;
torqueRequested = 0;
outputFrame.buf[0] = enablePositiveTorqueSpeed; // | enableNegativeTorqueSpeed;
if (faulted) {
outputFrame.buf[0] |= clearErrorLatch;
} else {
if ((running || speedActual > 1000) && !systemIO.getDigitalIn(1)) { // see warning about field weakening current to prevent uncontrollable regen
outputFrame.buf[0] |= enablePowerStage;
}
if (running) {
if (config->enableOscillationLimiter)
outputFrame.buf[0] |= enableOscillationLimiter;
if (powerMode == modeSpeed) {
outputFrame.buf[0] |= enableSpeedMode;
speedRequested = throttleRequested * config->speedMax / 1000;
torqueRequested = config->torqueMax; // positive number used for both speed directions
} else { // torque mode
speedRequested = config->speedMax; // positive number used for both torque directions
torqueRequested = throttleRequested * config->torqueMax / 1000;
}
// set the speed in rpm
outputFrame.buf[2] = (speedRequested & 0xFF00) >> 8;
outputFrame.buf[3] = (speedRequested & 0x00FF);
// set the torque in 0.01Nm (GEVCU uses 0.1Nm -> multiply by 10)
outputFrame.buf[4] = ((torqueRequested * 10) & 0xFF00) >> 8;
outputFrame.buf[5] = ((torqueRequested * 10) & 0x00FF);
}
}
if (Logger::isDebug())
Logger::debug(BRUSA_DMC5, "requested Speed: %i rpm, requested Torque: %f Nm", speedRequested, (float)torqueRequested/10.0F);
canHandlerEv.sendFrame(outputFrame);
}
/*
* Send DMC_CTRL2 message to the motor controller.
*
* This message controls the mechanical power limits for motor- and regen-mode.
*/
void BrusaMotorController::sendControl2() {
BrusaMotorControllerConfiguration *config = (BrusaMotorControllerConfiguration *)getConfiguration();
prepareOutputFrame(CAN_ID_CONTROL_2);
outputFrame.buf[0] = ((config->torqueSlewRate * 10) & 0xFF00) >> 8;
outputFrame.buf[1] = ((config->torqueSlewRate * 10) & 0x00FF);
outputFrame.buf[2] = (config->speedSlewRate & 0xFF00) >> 8;
outputFrame.buf[3] = (config->speedSlewRate & 0x00FF);
outputFrame.buf[4] = (config->maxMechanicalPowerMotor & 0xFF00) >> 8;
outputFrame.buf[5] = (config->maxMechanicalPowerMotor & 0x00FF);
outputFrame.buf[6] = (config->maxMechanicalPowerRegen & 0xFF00) >> 8;
outputFrame.buf[7] = (config->maxMechanicalPowerRegen & 0x00FF);
canHandlerEv.sendFrame(outputFrame);
}
/*
* Send DMC_LIM message to the motor controller.
*
* This message controls the electrical limits in the controller.
*/
void BrusaMotorController::sendLimits() {
BrusaMotorControllerConfiguration *config = (BrusaMotorControllerConfiguration *)getConfiguration();
prepareOutputFrame(CAN_ID_LIMIT);
outputFrame.buf[0] = (config->dcVoltLimitMotor & 0xFF00) >> 8;
outputFrame.buf[1] = (config->dcVoltLimitMotor & 0x00FF);
outputFrame.buf[2] = (config->dcVoltLimitRegen & 0xFF00) >> 8;
outputFrame.buf[3] = (config->dcVoltLimitRegen & 0x00FF);
outputFrame.buf[4] = (config->dcCurrentLimitMotor & 0xFF00) >> 8;
outputFrame.buf[5] = (config->dcCurrentLimitMotor & 0x00FF);
outputFrame.buf[6] = (config->dcCurrentLimitRegen & 0xFF00) >> 8;
outputFrame.buf[7] = (config->dcCurrentLimitRegen & 0x00FF);
canHandlerEv.sendFrame(outputFrame);
}
/*
* Prepare the CAN transmit frame.
* Re-sets all parameters in the re-used frame.
*/
void BrusaMotorController::prepareOutputFrame(uint32_t id) {
outputFrame.len = 8;
outputFrame.id = id;
outputFrame.flags.extended = 0;
outputFrame.buf[1] = 0;
outputFrame.buf[2] = 0;
outputFrame.buf[3] = 0;
outputFrame.buf[4] = 0;
outputFrame.buf[5] = 0;
outputFrame.buf[6] = 0;
outputFrame.buf[7] = 0;
}
/*
* Processes an event from the CanHandler.
*
* In case a CAN message was received which pass the masking and id filtering,
* this method is called. Depending on the ID of the CAN message, the data of
* the incoming message is processed.
*/
void BrusaMotorController::handleCanFrame( const CAN_message_t &frame) {
switch (frame.id) {
case CAN_ID_STATUS:
processStatus(frame.buf);
break;
case CAN_ID_ACTUAL_VALUES:
processActualValues(frame.buf);
break;
case CAN_ID_ERRORS:
processErrors(frame.buf);
break;
case CAN_ID_TORQUE_LIMIT:
processTorqueLimit(frame.buf);
break;
case CAN_ID_TEMP:
processTemperature(frame.buf);
break;
default:
Logger::warn(BRUSA_DMC5, "received unknown frame id %X", frame.id);
}
}
/*
* Process a DMC_TRQS message which was received from the motor controller.
*
* This message provides the general status of the controller as well as
* available and current torque and speed.
*/
void BrusaMotorController::processStatus(uint8_t data[]) {
statusBitfield1 = (uint32_t)(data[1] | (data[0] << 8));
torqueAvailable = (int16_t)(data[3] | (data[2] << 8)) / 10;
torqueActual = (int16_t)(data[5] | (data[4] << 8)) / 10;
speedActual = (int16_t)(data[7] | (data[6] << 8));
if(Logger::isDebug())
Logger::debug(BRUSA_DMC5, "status: %X, torque avail: %fNm, actual torque: %fNm, speed actual: %drpm", statusBitfield1, (float)torqueAvailable/100.0F, (float)torqueActual/100.0F, speedActual);
ready = (statusBitfield1 & stateReady) != 0 ? true : false;
running = (statusBitfield1 & stateRunning) != 0 ? true : false;
faulted = (statusBitfield1 & errorFlag) != 0 ? true : false;
warning = (statusBitfield1 & warningFlag) != 0 ? true : false;
}
/*
* Process a DMC_ACTV message which was received from the motor controller.
*
* This message provides information about current electrical conditions and
* applied mechanical power.
*/
void BrusaMotorController::processActualValues(uint8_t data[]) {
dcVoltage = (uint16_t)(data[1] | (data[0] << 8));
dcCurrent = (int16_t)(data[3] | (data[2] << 8));
acCurrent = (uint16_t)(data[5] | (data[4] << 8)) / 2.5;
mechanicalPower = (int16_t)(data[7] | (data[6] << 8)) / 6.25;
if (Logger::isDebug())
Logger::debug(BRUSA_DMC5, "actual values: DC Volts: %fV, DC current: %fA, AC current: %fA, mechPower: %fkW", (float)dcVoltage / 10.0F, (float)dcCurrent / 10.0F, (float)acCurrent / 10.0F, (float)mechanicalPower / 10.0F);
}
/*
* Process a DMC_ERRS message which was received from the motor controller.
*
* This message provides various error and warning status flags in a bitfield.
* The bitfield is not processed here but it is made available for other components
* (e.g. the webserver to display the various status flags)
*/
void BrusaMotorController::processErrors(uint8_t data[]) {
statusBitfield3 = (uint32_t)(data[1] | (data[0] << 8) | (data[5] << 16) | (data[4] << 24));
statusBitfield2 = (uint32_t)(data[7] | (data[6] << 8));
if (Logger::isDebug())
Logger::debug(BRUSA_DMC5, "errors: %X, warning: %X", statusBitfield3, statusBitfield2);
}
/*
* Process a DMC_TRQS2 message which was received from the motor controller.
*
* This message provides information about available torque.
*/
void BrusaMotorController::processTorqueLimit(uint8_t data[]) {
maxPositiveTorque = (int16_t)(data[1] | (data[0] << 8)) / 10;
minNegativeTorque = (int16_t)(data[3] | (data[2] << 8)) / 10;
limiterStateNumber = (uint8_t)data[4];
if (Logger::isDebug())
Logger::debug(BRUSA_DMC5, "torque limit: max positive: %fNm, min negative: %fNm", (float) maxPositiveTorque / 10.0F, (float) minNegativeTorque / 10.0F, limiterStateNumber);
}
/*
* Process a DMC_TEMP message which was received from the motor controller.
*
* This message provides information about motor and inverter temperatures.
*/
void BrusaMotorController::processTemperature(uint8_t data[]) {
temperatureInverter = (int16_t)(data[1] | (data[0] << 8)) * 5;
temperatureMotor = (int16_t)(data[3] | (data[2] << 8)) * 5;
temperatureSystem = (int16_t)(data[4] - 50) * 10;
if (Logger::isDebug())
Logger::debug(BRUSA_DMC5, "temperature: inverter: %fC, motor: %fC, system: %fC", (float)temperatureInverter / 10.0F, (float)temperatureMotor / 10.0F, (float)temperatureSystem / 10.0F);
}
/*
* Return the device id of this device
*/
DeviceId BrusaMotorController::getId() {
return BRUSA_DMC5;
}
/*
* Expose the tick interval of this controller
*/
uint32_t BrusaMotorController::getTickInterval() {
return CFG_TICK_INTERVAL_MOTOR_CONTROLLER_BRUSA;
}
/*
* Load configuration data from EEPROM.
*
* If not available or the checksum is invalid, default values are chosen.
*/
void BrusaMotorController::loadConfiguration() {
BrusaMotorControllerConfiguration *config = (BrusaMotorControllerConfiguration *)getConfiguration();
if(!config) { // as lowest sub-class make sure we have a config object
config = new BrusaMotorControllerConfiguration();
setConfiguration(config);
}
MotorController::loadConfiguration(); // call parent
#ifdef USE_HARD_CODED
if (false) {
#else
// if (prefsHandler->checksumValid()) { //checksum is good, read in the values stored in EEPROM
if (false) { //TODO: use eeprom, not fixed values
#endif
Logger::debug(BRUSA_DMC5, (char *)Constants::validChecksum);
// prefsHandler->read(EEMC_, &config->minimumLevel1);
} else { //checksum invalid. Reinitialize values and store to EEPROM
Logger::warn(BRUSA_DMC5, (char *)Constants::invalidChecksum);
config->maxMechanicalPowerMotor = 50000;
config->maxMechanicalPowerRegen = 0; //TODO: 50000; don't want regen yet !
config->dcVoltLimitMotor = 1000;
config->dcVoltLimitRegen = 0;//TODO: 1000; don't want regen yet !;
config->dcCurrentLimitMotor = 0;
config->dcCurrentLimitRegen = 0;
config->enableOscillationLimiter = false;
//saveConfiguration();
}
Logger::debug(BRUSA_DMC5, "Max mech power motor: %d kW, max mech power regen: %d ", config->maxMechanicalPowerMotor, config->maxMechanicalPowerRegen);
Logger::debug(BRUSA_DMC5, "DC limit motor: %d Volt, DC limit regen: %d Volt", config->dcVoltLimitMotor, config->dcVoltLimitRegen);
Logger::debug(BRUSA_DMC5, "DC limit motor: %d Amps, DC limit regen: %d Amps", config->dcCurrentLimitMotor, config->dcCurrentLimitRegen);
}
/*
* Store the current configuration parameters to EEPROM.
*/
void BrusaMotorController::saveConfiguration() {
BrusaMotorControllerConfiguration *config = (BrusaMotorControllerConfiguration *)getConfiguration();
MotorController::saveConfiguration(); // call parent
//TODO: store to eeprom
// prefsHandler->write(EEMC_, config->maxMechanicalPowerMotor);
// prefsHandler->write(EEMC_, config->maxMechanicalPowerRegen);
// prefsHandler->write(EEMC_, config->dcVoltLimitMotor);
// prefsHandler->write(EEMC_, config->dcVoltLimitRegen);
// prefsHandler->write(EEMC_, config->dcCurrentLimitMotor);
// prefsHandler->write(EEMC_, config->dcCurrentLimitRegen);
// prefsHandler->write(EEMC_, config->enableOscillationLimiter);
//prefsHandler->saveChecksum();
}
BrusaMotorController brusaMC;
| [
"[email protected]"
] | |
a874827f368cfc64c6fb27293a54c6b36ddbb53b | 8f709bedac6c678a4dc763a70a08671d10f61abe | /src/libstratum/ZcashStratum.cpp | 8d3deb3eee4dd54bf8dd0d6cdf9e332b7b0b46fe | [
"MIT"
] | permissive | lhl/zogminer | 6d01005229dca95b02d57b4a505a1d3413c98c8b | 83ce0bac9fea008dcbe67c4feac3fed36a1cae8b | refs/heads/master | 2021-01-11T07:51:48.230647 | 2016-11-02T13:18:27 | 2016-11-02T13:18:27 | 72,638,355 | 0 | 0 | null | 2016-11-02T12:35:21 | 2016-11-02T12:35:21 | null | UTF-8 | C++ | false | false | 12,466 | cpp | // Copyright (c) 2016 Jack Grigg <[email protected]>
// Copyright (c) 2016 Omar Alvarez <[email protected]>
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "ZcashStratum.h"
#include "chainparams.h"
#include "clientversion.h"
#include "crypto/equihash.h"
#include "streams.h"
#include "version.h"
#include "libzogminer/gpusolver.h"
#include <atomic>
void static ZcashMinerThread(ZcashMiner* miner, int size, int pos, GPUConfig conf)
{
LogPrintf("ZcashMinerThread started\n");
RenameThread("zcash-miner");
unsigned int n = Params().EquihashN();
unsigned int k = Params().EquihashK();
std::shared_ptr<std::mutex> m_zmt(new std::mutex);
CBlockHeader header;
arith_uint256 space;
size_t offset;
arith_uint256 inc;
arith_uint256 target;
std::atomic_bool workReady {false};
std::atomic_bool cancelSolver {false};
GPUSolver * solver;
if(conf.useGPU)
solver = new GPUSolver(conf.selGPU);
//TODO Free
uint8_t * tmp_header = (uint8_t *) calloc(ZCASH_BLOCK_HEADER_LEN, sizeof(uint8_t));
uint64_t nn= 0;
miner->NewJob.connect(NewJob_t::slot_type(
[&m_zmt, &header, &space, &offset, &inc, &target, &workReady, &cancelSolver]
(const ZcashJob* job) mutable {
std::lock_guard<std::mutex> lock{*m_zmt.get()};
if (job) {
header = job->header;
space = job->nonce2Space;
offset = job->nonce1Size * 4; // Hex length to bit length
inc = job->nonce2Inc;
target = job->serverTarget;
workReady.store(true);
if (job->clean) {
cancelSolver.store(true);
}
} else {
workReady.store(false);
cancelSolver.store(true);
}
}
).track_foreign(m_zmt)); // So the signal disconnects when the mining thread exits
try {
while (true) {
// Wait for work
bool expected;
do {
expected = true;
boost::this_thread::interruption_point();
MilliSleep(1000);
} while (!workReady.compare_exchange_weak(expected, false));
// TODO change atomically with workReady
cancelSolver.store(false);
// Calculate nonce limits
arith_uint256 nonce;
arith_uint256 nonceEnd;
{
std::lock_guard<std::mutex> lock{*m_zmt.get()};
arith_uint256 baseNonce = UintToArith256(header.nNonce);
nonce = baseNonce + ((space/size)*pos << offset);
nonceEnd = baseNonce + ((space/size)*(pos+1) << offset);
}
// Hash state
crypto_generichash_blake2b_state state;
EhInitialiseState(n, k, state);
// I = the block header minus nonce and solution.
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
{
std::lock_guard<std::mutex> lock{*m_zmt.get()};
CEquihashInput I{header};
ss << I;
}
memcpy(tmp_header, &ss[0], ss.size());
// H(I||...
crypto_generichash_blake2b_update(&state, (unsigned char*)&ss[0], ss.size());
// Start working
while (true) {
// H(I||V||...
crypto_generichash_blake2b_state curr_state;
curr_state = state;
auto bNonce = ArithToUint256(nonce);
for (size_t i = 0; i < ZCASH_NONCE_LEN; ++i)
tmp_header[108 + i] = bNonce.begin()[i];
// (x_1, x_2, ...) = A(I, V, n, k)
LogPrint("pow", "Running Equihash solver with nNonce = %s\n",
bNonce.ToString());
std::function<bool(std::vector<unsigned char>)> validBlock =
[&m_zmt, &header, &bNonce, &target, &miner]
(std::vector<unsigned char> soln) {
std::lock_guard<std::mutex> lock{*m_zmt.get()};
// Write the solution to the hash and compute the result.
LogPrint("pow", "- Checking solution against target...");
header.nNonce = bNonce;
header.nSolution = soln;
if (UintToArith256(header.GetHash()) > target) {
LogPrint("pow", " too large.\n");
return false;
}
// Found a solution
LogPrintf("Found solution satisfying the server target\n");
EquihashSolution solution {bNonce, soln};
miner->submitSolution(solution);
// We're a pooled miner, so try all solutions
return false;
};
std::function<bool(GPUSolverCancelCheck)> cancelledGPU =
[&cancelSolver](GPUSolverCancelCheck pos) {
boost::this_thread::interruption_point();
return cancelSolver.load();
};
std::function<bool(EhSolverCancelCheck)> cancelled =
[&cancelSolver](EhSolverCancelCheck pos) {
boost::this_thread::interruption_point();
return cancelSolver.load();
};
try {
// If we find a valid block, we get more work
if(!conf.useGPU) {
if (EhOptimisedSolve(n, k, curr_state, validBlock, cancelled)) {
break;
}
} else {
if (solver->run(n, k, tmp_header, ZCASH_BLOCK_HEADER_LEN, *((uint64_t *)(bNonce.begin()+sizeof(uint64_t)+4)), validBlock, cancelledGPU, curr_state)) {
break;
}
}
} catch (GPUSolverCancelledException&) {
LogPrint("pow", "Equihash solver cancelled\n");
cancelSolver.store(false);
break;
}
// Check for stop
boost::this_thread::interruption_point();
if (nonce == nonceEnd) {
break;
}
// Check for new work
if (workReady.load()) {
LogPrint("pow", "New work received, dropping current work\n");
break;
}
// Update nonce
nonce += inc;
}
}
}
catch (const boost::thread_interrupted&)
{
LogPrintf("ZcashMinerThread terminated\n");
if(conf.useGPU)
delete solver;
if(tmp_header)
free(tmp_header);
throw;
}
catch (const std::runtime_error &e)
{
LogPrintf("ZcashMinerThread runtime error: %s\n", e.what());
if(conf.useGPU)
delete solver;
if(tmp_header)
free(tmp_header);
return;
}
if(conf.useGPU)
delete solver;
if(tmp_header)
free(tmp_header);
}
ZcashJob* ZcashJob::clone() const
{
ZcashJob* ret = new ZcashJob();
ret->job = job;
ret->header = header;
ret->time = time;
ret->nonce1Size = nonce1Size;
ret->nonce2Space = nonce2Space;
ret->nonce2Inc = nonce2Inc;
ret->serverTarget = serverTarget;
ret->clean = clean;
return ret;
}
void ZcashJob::setTarget(std::string target)
{
if (target.size() > 0) {
serverTarget = UintToArith256(uint256S(target));
} else {
LogPrint("stratum", "New job but no server target, assuming powLimit\n");
serverTarget = UintToArith256(Params().GetConsensus().powLimit);
}
}
bool ZcashJob::evalSolution(const EquihashSolution* solution)
{
unsigned int n = Params().EquihashN();
unsigned int k = Params().EquihashK();
// Hash state
crypto_generichash_blake2b_state state;
EhInitialiseState(n, k, state);
// I = the block header minus nonce and solution.
CEquihashInput I{header};
// I||V
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << I;
ss << solution->nonce;
// H(I||V||...
crypto_generichash_blake2b_update(&state, (unsigned char*)&ss[0], ss.size());
bool isValid;
EhIsValidSolution(n, k, state, solution->solution, isValid);
return isValid;
}
std::string ZcashJob::getSubmission(const EquihashSolution* solution)
{
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss << solution->nonce;
ss << solution->solution;
std::string strHex = HexStr(ss.begin(), ss.end());
std::stringstream stream;
stream << "\"" << job;
stream << "\",\"" << time;
stream << "\",\"" << strHex.substr(nonce1Size, 64-nonce1Size);
stream << "\",\"" << strHex.substr(64);
stream << "\"";
return stream.str();
}
ZcashMiner::ZcashMiner(int threads, GPUConfig _conf)
: nThreads{threads}, minerThreads{nullptr}, conf(_conf)
{
if (nThreads < 0) {
nThreads = boost::thread::hardware_concurrency();
}
}
std::string ZcashMiner::userAgent()
{
return FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<std::string>());
}
void ZcashMiner::start()
{
if (minerThreads) {
stop();
}
if (nThreads == 0) {
return;
}
minerThreads = new boost::thread_group();
for (int i = 0; i < nThreads; i++) {
minerThreads->create_thread(boost::bind(&ZcashMinerThread, this, nThreads, i, conf));
}
}
void ZcashMiner::stop()
{
if (minerThreads) {
minerThreads->interrupt_all();
delete minerThreads;
minerThreads = nullptr;
}
}
void ZcashMiner::setServerNonce(const Array& params)
{
auto n1str = params[1].get_str();
std::vector<unsigned char> nonceData(ParseHex(n1str));
while (nonceData.size() < 32) {
nonceData.push_back(0);
}
CDataStream ss(nonceData, SER_NETWORK, PROTOCOL_VERSION);
ss >> nonce1;
nonce1Size = n1str.size();
size_t nonce1Bits = nonce1Size * 4; // Hex length to bit length
size_t nonce2Bits = 256 - nonce1Bits;
nonce2Space = 1;
nonce2Space <<= nonce2Bits;
nonce2Space -= 1;
nonce2Inc = 1;
nonce2Inc <<= nonce1Bits;
}
ZcashJob* ZcashMiner::parseJob(const Array& params)
{
if (params.size() < 2) {
throw std::logic_error("Invalid job params");
}
ZcashJob* ret = new ZcashJob();
ret->job = params[0].get_str();
int32_t version;
sscanf(params[1].get_str().c_str(), "%x", &version);
// TODO: On a LE host shouldn't this be le32toh?
ret->header.nVersion = be32toh(version);
if (ret->header.nVersion == 4) {
if (params.size() < 8) {
throw std::logic_error("Invalid job params");
}
std::stringstream ssHeader;
ssHeader << params[1].get_str()
<< params[2].get_str()
<< params[3].get_str()
<< params[4].get_str()
<< params[5].get_str()
<< params[6].get_str()
// Empty nonce
<< "0000000000000000000000000000000000000000000000000000000000000000"
<< "00"; // Empty solution
auto strHexHeader = ssHeader.str();
std::vector<unsigned char> headerData(ParseHex(strHexHeader));
CDataStream ss(headerData, SER_NETWORK, PROTOCOL_VERSION);
try {
ss >> ret->header;
} catch (const std::ios_base::failure& _e) {
throw std::logic_error("ZcashMiner::parseJob(): Invalid block header parameters");
}
ret->time = params[5].get_str();
ret->clean = params[7].get_bool();
} else {
throw std::logic_error("ZcashMiner::parseJob(): Invalid or unsupported block header version");
}
ret->header.nNonce = nonce1;
ret->nonce1Size = nonce1Size;
ret->nonce2Space = nonce2Space;
ret->nonce2Inc = nonce2Inc;
return ret;
}
void ZcashMiner::setJob(ZcashJob* job)
{
NewJob(job);
}
void ZcashMiner::onSolutionFound(
const std::function<bool(const EquihashSolution&)> callback)
{
solutionFoundCallback = callback;
}
void ZcashMiner::submitSolution(const EquihashSolution& solution)
{
solutionFoundCallback(solution);
}
void ZcashMiner::acceptedSolution(bool stale)
{
}
void ZcashMiner::rejectedSolution(bool stale)
{
}
void ZcashMiner::failedSolution()
{
}
| [
"[email protected]"
] | |
58b5a8f7ac9dd223a19bbcfb6d52a6be3449fe05 | bf0701721959efb5e860c996e50f564fa70fda6b | /Pass/PassRenderer.cpp | 6f5dcacd14542d132bdc535eb35b7658bea8848a | [] | no_license | Techno1109/DirecrtX12TrialCode | bf620bbc9ab0f3f756848a39f7512c135e9b1247 | 2398c4035c70cb3bb7bc9443b114ef1b76f420d2 | refs/heads/master | 2021-03-04T04:54:16.439578 | 2020-12-18T03:13:13 | 2020-12-18T03:13:13 | 246,009,311 | 1 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 6,971 | cpp | #include "PassRenderer.h"
#include "Tool.h"
#include "Imgui/imgui.h"
#include <assert.h>
#include <vector>
#include <d3dx12.h>
#include <d3dcompiler.h>
#include <DirectXMath.h>
#pragma comment(lib,"d3d12.lib")
#pragma comment(lib,"d3dcompiler.lib ")
PassRenderer::PassRenderer(Microsoft::WRL::ComPtr<ID3D12Device>& Dev, std::string ShaderPath, int Priority, PassType Type):_Dev(Dev),_Priority(Priority)
{
_ShaderPath=ShaderPath;
ActiveFlag = true;
}
PassRenderer::~PassRenderer()
{
}
void PassRenderer::DrawSetting(Microsoft::WRL::ComPtr<ID3D12GraphicsCommandList>& _CmdList, D3D12_VIEWPORT & _ViewPort, D3D12_RECT & _ScissorRect)
{
//ルートシグネチャをセット
_CmdList->SetGraphicsRootSignature(_RootSigunature.Get());
//ビューポートをセット
_CmdList->RSSetViewports(1, &_ViewPort);
//シザーをセット
_CmdList->RSSetScissorRects(1, &_ScissorRect);
//パイプラインをセット
_CmdList->SetPipelineState(_PipelineState.Get());
}
void PassRenderer::PassDraw(Microsoft::WRL::ComPtr<ID3D12GraphicsCommandList>& _CmdList)
{
_CmdList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP);
////頂点バッファをセット
_CmdList->IASetVertexBuffers(0, 1, &_VertexBufferView);
_CmdList->DrawInstanced(4, 1, 0, 0);
}
bool PassRenderer::Init(std::string ShaderPath)
{
if (!LoadShader(ShaderPath))
{
assert(false);
return false;
}
if (!CreateRootSignature())
{
assert(false);
return false;
}
if (!CreatePipeLineState())
{
assert(false);
return false;
}
if (!CreatePassPoly())
{
assert(false);
return false;
}
for (int i=0;i<BufferTag::MAX;i++)
{
BufferFlag[i] = false;
}
return true;
}
void PassRenderer::ImGuiDraw()
{
if (ImGui::TreeNode(_ShaderPath.c_str()))
{
ImGui::Checkbox("Active", (bool*)&ActiveFlag);
ImGuiDrawBase();
ImGui::TreePop();
}
}
void PassRenderer::ImGuiDrawBase()
{
}
bool& PassRenderer::GetActiveFlag()
{
return ActiveFlag;
}
void PassRenderer::PassClearAndSetRendererTarget(Microsoft::WRL::ComPtr<ID3D12GraphicsCommandList>& _CmdList, Microsoft::WRL::ComPtr<ID3D12DescriptorHeap>& _DepthStencilViewHeap,bool First)
{
auto HeapPointer = _Rtv_DescriptorHeap->GetCPUDescriptorHandleForHeapStart();
//レンダリング
AddBarrier(_CmdList,D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE, D3D12_RESOURCE_STATE_RENDER_TARGET);
if (First==true)
{
_CmdList->OMSetRenderTargets(1, &HeapPointer, false, &_DepthStencilViewHeap->GetCPUDescriptorHandleForHeapStart());
}
else
{
_CmdList->OMSetRenderTargets(1, &HeapPointer, false,nullptr);
}
FLOAT ClsColor[4] = { 0,0, 0,1.0 };
_CmdList->ClearRenderTargetView(HeapPointer, ClsColor, 0, nullptr);
}
Microsoft::WRL::ComPtr<ID3D12PipelineState>& PassRenderer::GetPipeLineState()
{
return _PipelineState;
}
Microsoft::WRL::ComPtr<ID3D12RootSignature>& PassRenderer::GetRootSignature()
{
return _RootSigunature;
}
Microsoft::WRL::ComPtr<ID3D12Resource>& PassRenderer::GetBuffer()
{
return _Buffer;
}
D3D12_VERTEX_BUFFER_VIEW& PassRenderer::GetVertexBufferView()
{
return _VertexBufferView;
}
Microsoft::WRL::ComPtr<ID3D12Resource>& PassRenderer::GetVertexBuffer()
{
return _VertexBuffer;
}
Microsoft::WRL::ComPtr<ID3D12DescriptorHeap> PassRenderer::GetRtv_DescriptorHeap()
{
return _Rtv_DescriptorHeap;
}
Microsoft::WRL::ComPtr<ID3D12DescriptorHeap> PassRenderer::GetSrv_DescriptorHeap()
{
return _Srv_DescriptorHeap;
}
std::array<bool, PassRenderer::BufferTag::MAX>& PassRenderer::GetUseBufferFlag()
{
return BufferFlag;
}
PassRenderer::PassType & PassRenderer::GetPassType()
{
return ThisPassType;
}
const int & PassRenderer::GetPriority()
{
return _Priority;
}
bool PassRenderer::LoadShader(std::string ShaderPath)
{
HRESULT Result = S_OK;
Microsoft::WRL::ComPtr <ID3DBlob> E;
Result = D3DCompileFromFile(GetWideString(ShaderPath).c_str(), nullptr, nullptr, "BasicVS", "vs_5_0", D3DCOMPILE_DEBUG
| D3DCOMPILE_SKIP_OPTIMIZATION, 0, &_VertexShader, &E);
if (FAILED(Result))
{
std::string CheckString;
CheckString.resize(E.Get()->GetBufferSize());
std::copy_n((char*)E.Get()->GetBufferPointer(), E.Get()->GetBufferSize(), CheckString.begin());
OutputDebugString(CheckString.c_str());
return false;
}
Result = D3DCompileFromFile(GetWideString(ShaderPath).c_str(), nullptr, nullptr, "BasicPS", "ps_5_0", D3DCOMPILE_DEBUG
| D3DCOMPILE_SKIP_OPTIMIZATION, 0, &_PixelShader, &E);
if (FAILED(Result))
{
std::string CheckString;
CheckString.resize(E.Get()->GetBufferSize());
std::copy_n((char*)E.Get()->GetBufferPointer(), E.Get()->GetBufferSize(),CheckString.begin());
OutputDebugString(CheckString.c_str());
return false;
}
return true;
}
void PassRenderer::AddBarrier(Microsoft::WRL::ComPtr<ID3D12GraphicsCommandList>& _CmdList, D3D12_RESOURCE_STATES StateBefore, D3D12_RESOURCE_STATES StateAfter)
{
//リソースバリアを設定
D3D12_RESOURCE_BARRIER BarrierDesc = {};
BarrierDesc.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION;
BarrierDesc.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE;
BarrierDesc.Transition.StateBefore = StateBefore;
BarrierDesc.Transition.StateAfter = StateAfter;
BarrierDesc.Transition.pResource = _Buffer.Get();
BarrierDesc.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES;
//レンダリング前にバリアを追加
_CmdList->ResourceBarrier(1, &BarrierDesc);
}
bool PassRenderer::CreatePassPoly()
{
HRESULT Result = S_OK;
struct Vertex
{
DirectX::XMFLOAT3 pos;
DirectX::XMFLOAT2 uv;
};
Vertex Vertices[4];
Vertices[0] = { { -1,-1 ,0.0f } , {0,1} };
Vertices[1] = { { -1,1 ,0.0f } , {0,0} };
Vertices[2] = { { 1 ,-1 ,0.0f } , {1,1} };
Vertices[3] = { { 1 ,1 ,0.0f } , {1,0} };
D3D12_HEAP_PROPERTIES HeapProp = {};
HeapProp.Type = D3D12_HEAP_TYPE_UPLOAD;
HeapProp.CPUPageProperty = D3D12_CPU_PAGE_PROPERTY_UNKNOWN;
HeapProp.MemoryPoolPreference = D3D12_MEMORY_POOL_UNKNOWN;
D3D12_RESOURCE_DESC ResourceDesc{};
ResourceDesc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER;
ResourceDesc.Width = sizeof(Vertices);
ResourceDesc.Height = 1;
ResourceDesc.DepthOrArraySize = 1;
ResourceDesc.MipLevels = 1;
ResourceDesc.Format = DXGI_FORMAT_UNKNOWN;
ResourceDesc.SampleDesc.Count = 1;
ResourceDesc.Flags = D3D12_RESOURCE_FLAG_NONE;
ResourceDesc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR;
Result = _Dev->CreateCommittedResource(&HeapProp,
D3D12_HEAP_FLAG_NONE,
&ResourceDesc,
D3D12_RESOURCE_STATE_GENERIC_READ,
nullptr,
IID_PPV_ARGS(&_VertexBuffer));
if (FAILED(Result))
{
return false;
}
//頂点Map作成
Vertex* _VertexMap = nullptr;
Result = _VertexBuffer->Map(0, nullptr, (void**)&_VertexMap);
std::copy(std::begin(Vertices), std::end(Vertices), _VertexMap);
_VertexBuffer->Unmap(0, nullptr);
//頂点バッファビュー作成
_VertexBufferView.BufferLocation = _VertexBuffer->GetGPUVirtualAddress();
_VertexBufferView.StrideInBytes = sizeof(Vertices[0]);
_VertexBufferView.SizeInBytes = sizeof(Vertices);
return true;
}
| [
"[email protected]"
] | |
41f157153f1d1740cdefa967ba057aa6e7b5df20 | 6c64c25a2bf2eb306218e096efb005339a4fa192 | /base64.cpp | b63c180527dc91aa3c7e1d4d7e2b28de59beae5e | [] | no_license | HFTrader/common | b50f8cd1b419cb2a5cc0e670e3bb7415fc3f1db3 | f0e1cf0140682dbbc71e431f7cbb05477d92d136 | refs/heads/master | 2020-12-11T03:39:14.519825 | 2015-06-10T01:54:57 | 2015-06-10T02:47:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,167 | cpp | #include "base64.h"
#include <ios>
#include <stdexcept>
static constexpr char encode[64] = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'
};
bool Base64Encoder::process(uint8_t * _restrict &out, size_t n_out, const uint8_t *&in, size_t n_in) {
uint b0, b1;
switch (state) {
case 0:
goto state0;
case 1:
b0 = buf;
goto state1;
case 2:
b1 = buf;
goto state2;
case 3:
b0 = buf;
goto state3;
default:
throw std::logic_error("illegal state");
}
for (;;) {
state0:
if (n_in == 0) {
state = 0;
return true;
}
if (n_out == 0) {
state = 0;
return false;
}
b0 = *in++, --n_in;
*out++ = encode[b0 >> 2], --n_out;
state1:
if (n_in == 0) {
state = 1, buf = static_cast<uint8_t>(b0);
return true;
}
if (n_out == 0) {
state = 1, buf = static_cast<uint8_t>(b0);
return false;
}
b1 = *in++, --n_in;
*out++ = encode[b0 << 4 & 0x3F | b1 >> 4], --n_out;
state2:
if (n_in == 0) {
state = 2, buf = static_cast<uint8_t>(b1);
return true;
}
if (n_out == 0) {
state = 2, buf = static_cast<uint8_t>(b1);
return false;
}
b0 = *in++, --n_in;
*out++ = encode[b1 << 2 & 0x3F | b0 >> 6], --n_out;
state3:
if (n_out == 0) {
state = 3, buf = static_cast<uint8_t>(b0);
return false;
}
*out++ = encode[b0 & 0x3F], --n_out;
}
}
bool Base64Encoder::finish(uint8_t *&out, size_t n_out) {
switch (state) {
case 0:
state = 6;
return true;
case 1:
if (n_out == 0) {
return false;
}
*out++ = encode[buf << 4 & 0x3F], --n_out;
case 4:
if (n_out == 0) {
state = 4;
return false;
}
*out++ = '=', --n_out;
goto state5;
case 2:
if (n_out == 0) {
return false;
}
*out++ = encode[buf << 2 & 0x3F], --n_out;
case 5:
state5:
if (n_out == 0) {
state = 5;
return false;
}
*out++ = '=', --n_out;
state = 6;
return true;
case 3:
if (n_out == 0) {
return false;
}
*out++ = encode[buf & 0x3F], --n_out;
state = 6;
case 6:
return true;
default:
throw std::logic_error("illegal state");
}
}
bool Base64Decoder::process(uint8_t * _restrict &out, size_t n_out, const uint8_t *&in, size_t n_in) {
static constexpr int8_t decode[80] = {
62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1,
-1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31,
32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51
};
uint b0, b1;
switch (state) {
case 0:
goto state0;
case 1:
b0 = buf;
goto state1;
case 2:
b1 = buf;
goto state2;
case 3:
b0 = buf;
goto state3;
case 4:
goto state4;
case 5:
goto state5;
}
for (;;) {
state0:
if (n_in == 0) {
state = 0;
return true;
}
b0 = *in++, --n_in;
if ((b0 -= '+') > 'z' - '+' || static_cast<int>(b0 = decode[b0]) < 0) {
throw std::ios_base::failure("invalid base64");
}
state1:
if (n_in == 0) {
state = 1, buf = static_cast<uint8_t>(b0);
return true;
}
if (n_out == 0) {
state = 1, buf = static_cast<uint8_t>(b0);
return false;
}
b1 = *in++, --n_in;
if ((b1 -= '+') > 'z' - '+' || static_cast<int>(b1 = decode[b1]) < 0) {
throw std::ios_base::failure("invalid base64");
}
*out++ = static_cast<uint8_t>(b0 << 2 | b1 >> 4), --n_out;
state2:
if (n_in == 0) {
state = 2, buf = static_cast<uint8_t>(b1);
return true;
}
if (*in == '=') {
++in, --n_in;
goto state4;
}
if (n_out == 0) {
state = 2, buf = static_cast<uint8_t>(b1);
return false;
}
b0 = *in++, --n_in;
if ((b0 -= '+') > 'z' - '+' || static_cast<int>(b0 = decode[b0]) < 0) {
throw std::ios_base::failure("invalid base64");
}
*out++ = static_cast<uint8_t>(b1 << 4 | b0 >> 2), --n_out;
state3:
if (n_in == 0) {
state = 3, buf = static_cast<uint8_t>(b0);
return true;
}
if (*in == '=') {
++in, --n_in;
goto state5;
}
if (n_out == 0) {
state = 3, buf = static_cast<uint8_t>(b0);
return false;
}
b1 = *in++, --n_in;
if ((b1 -= '+') > 'z' - '+' || static_cast<int>(b1 = decode[b1]) < 0) {
throw std::ios_base::failure("invalid base64");
}
*out++ = static_cast<uint8_t>(b0 << 6 | b1), --n_out;
}
state4:
if (n_in == 0) {
state = 4;
return true;
}
if (*in != '=') {
throw std::ios_base::failure("invalid base64");
}
++in, --n_in;
state5:
if (n_in == 0) {
state = 5;
return true;
}
throw std::ios_base::failure("invalid base64");
}
bool Base64Decoder::finish(uint8_t *&, size_t) {
if (state != 0 && state != 5) {
throw std::ios_base::failure("invalid base64");
}
return true;
}
#include "codec.tcc"
template class CodecSource<Base64Encoder>;
template class CodecSource<Base64Decoder>;
template class CodecSink<Base64Encoder>;
template class CodecSink<Base64Decoder>;
| [
"[email protected]"
] | |
f9f328a75efd7b5255d185ed8f3e7ca72766d4d1 | 48d4cc56a3494276df563013e46cc29c22931bcf | /vs2017/ui/GeneratedFiles/Release/moc_ChatWidget.cpp | 857b933d50cfdf5c22c31a3f55e9467ea56a6e34 | [
"MIT"
] | permissive | cheechang/cppcc | 8e8fde9eedc84641b3bc64efac116a32471ffa1d | 0292e9a9b27e0579970c83b4f6a75dcdae1558bf | refs/heads/main | 2023-03-16T23:09:56.725184 | 2021-03-05T09:46:28 | 2021-03-05T09:46:28 | 344,737,972 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 32,450 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'ChatWidget.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.12.3)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../../mainwindow/chat/ChatWidget.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'ChatWidget.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.12.3. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
struct qt_meta_stringdata_ui__ChatWidget_t {
QByteArrayData data[96];
char stringdata0[1307];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_ui__ChatWidget_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_ui__ChatWidget_t qt_meta_stringdata_ui__ChatWidget = {
{
QT_MOC_LITERAL(0, 0, 14), // "ui::ChatWidget"
QT_MOC_LITERAL(1, 15, 20), // "signalSerGetGroupMem"
QT_MOC_LITERAL(2, 36, 0), // ""
QT_MOC_LITERAL(3, 37, 4), // "code"
QT_MOC_LITERAL(4, 42, 13), // "data::Member&"
QT_MOC_LITERAL(5, 56, 3), // "mem"
QT_MOC_LITERAL(6, 60, 15), // "addIsReceiptMsg"
QT_MOC_LITERAL(7, 76, 5), // "int64"
QT_MOC_LITERAL(8, 82, 25), // "signalSerSendisReceiptMsg"
QT_MOC_LITERAL(9, 108, 3), // "err"
QT_MOC_LITERAL(10, 112, 7), // "msgtime"
QT_MOC_LITERAL(11, 120, 5), // "msgid"
QT_MOC_LITERAL(12, 126, 21), // "CSharedPtr<data::Msg>"
QT_MOC_LITERAL(13, 148, 3), // "msg"
QT_MOC_LITERAL(14, 152, 19), // "sendMsgHotKeyUpdate"
QT_MOC_LITERAL(15, 172, 14), // "signalShakeWin"
QT_MOC_LITERAL(16, 187, 7), // "openUrl"
QT_MOC_LITERAL(17, 195, 11), // "std::string"
QT_MOC_LITERAL(18, 207, 3), // "url"
QT_MOC_LITERAL(19, 211, 11), // "viewBurnMsg"
QT_MOC_LITERAL(20, 223, 22), // "CSharedPtr<data::Msg>&"
QT_MOC_LITERAL(21, 246, 15), // "addChatListItem"
QT_MOC_LITERAL(22, 262, 27), // "CSharedPtr<data::ChatInfo>&"
QT_MOC_LITERAL(23, 290, 9), // "startChat"
QT_MOC_LITERAL(24, 300, 16), // "signalScreenShot"
QT_MOC_LITERAL(25, 317, 4), // "flag"
QT_MOC_LITERAL(26, 322, 15), // "signalSendImage"
QT_MOC_LITERAL(27, 338, 17), // "signalSendMsgShot"
QT_MOC_LITERAL(28, 356, 3), // "key"
QT_MOC_LITERAL(29, 360, 24), // "signalSetSecretIsvisible"
QT_MOC_LITERAL(30, 385, 27), // "signalSerGroupRefreshUpdate"
QT_MOC_LITERAL(31, 413, 4), // "int8"
QT_MOC_LITERAL(32, 418, 11), // "data::Group"
QT_MOC_LITERAL(33, 430, 19), // "signalSerGetUrlInfo"
QT_MOC_LITERAL(34, 450, 4), // "text"
QT_MOC_LITERAL(35, 455, 29), // "signalSerGroupMemCountRefresh"
QT_MOC_LITERAL(36, 485, 20), // "signalSerGetUserInfo"
QT_MOC_LITERAL(37, 506, 15), // "data::UserData&"
QT_MOC_LITERAL(38, 522, 24), // "signalSerbtnCloseSession"
QT_MOC_LITERAL(39, 547, 18), // "signalSerGetTopMsg"
QT_MOC_LITERAL(40, 566, 5), // "int32"
QT_MOC_LITERAL(41, 572, 36), // "std::vector<data::ZxTopInform..."
QT_MOC_LITERAL(42, 609, 21), // "signalSerCancelTopMsg"
QT_MOC_LITERAL(43, 631, 22), // "signalSerGetMemberInfo"
QT_MOC_LITERAL(44, 654, 12), // "std::string&"
QT_MOC_LITERAL(45, 667, 16), // "onSerGetGroupMem"
QT_MOC_LITERAL(46, 684, 21), // "onSerSendisReceiptMsg"
QT_MOC_LITERAL(47, 706, 14), // "onSendDelayMsg"
QT_MOC_LITERAL(48, 721, 4), // "time"
QT_MOC_LITERAL(49, 726, 12), // "onSendDnyMsg"
QT_MOC_LITERAL(50, 739, 8), // "fileName"
QT_MOC_LITERAL(51, 748, 10), // "onSendCard"
QT_MOC_LITERAL(52, 759, 6), // "cardId"
QT_MOC_LITERAL(53, 766, 6), // "isburn"
QT_MOC_LITERAL(54, 773, 7), // "isdelay"
QT_MOC_LITERAL(55, 781, 9), // "isreceipt"
QT_MOC_LITERAL(56, 791, 9), // "onSendMsg"
QT_MOC_LITERAL(57, 801, 9), // "imagelist"
QT_MOC_LITERAL(58, 811, 8), // "filelist"
QT_MOC_LITERAL(59, 820, 18), // "std::vector<int64>"
QT_MOC_LITERAL(60, 839, 6), // "atlist"
QT_MOC_LITERAL(61, 846, 19), // "onShowGroupAtMsgTip"
QT_MOC_LITERAL(62, 866, 15), // "onSerGetUrlInfo"
QT_MOC_LITERAL(63, 882, 5), // "title"
QT_MOC_LITERAL(64, 888, 7), // "imgPath"
QT_MOC_LITERAL(65, 896, 4), // "desc"
QT_MOC_LITERAL(66, 901, 15), // "onSetPrivateKey"
QT_MOC_LITERAL(67, 917, 8), // "QString&"
QT_MOC_LITERAL(68, 926, 9), // "pPassword"
QT_MOC_LITERAL(69, 936, 23), // "onSerGroupRefreshUpdate"
QT_MOC_LITERAL(70, 960, 19), // "onSerGetContactInfo"
QT_MOC_LITERAL(71, 980, 17), // "onShakeWinClicked"
QT_MOC_LITERAL(72, 998, 15), // "onShowRecordWin"
QT_MOC_LITERAL(73, 1014, 14), // "onRecordResult"
QT_MOC_LITERAL(74, 1029, 4), // "path"
QT_MOC_LITERAL(75, 1034, 16), // "onSerGetUserInfo"
QT_MOC_LITERAL(76, 1051, 4), // "user"
QT_MOC_LITERAL(77, 1056, 19), // "onSerChickMsgReaded"
QT_MOC_LITERAL(78, 1076, 6), // "pmsgid"
QT_MOC_LITERAL(79, 1083, 14), // "SetTileContent"
QT_MOC_LITERAL(80, 1098, 4), // "type"
QT_MOC_LITERAL(81, 1103, 8), // "MemCount"
QT_MOC_LITERAL(82, 1112, 25), // "onSerGroupMemCountRefresh"
QT_MOC_LITERAL(83, 1138, 9), // "pMemCount"
QT_MOC_LITERAL(84, 1148, 18), // "onSerSendMsgByType"
QT_MOC_LITERAL(85, 1167, 15), // "onSerMoretopMsg"
QT_MOC_LITERAL(86, 1183, 17), // "onSerCanceltopMsg"
QT_MOC_LITERAL(87, 1201, 18), // "onSerGetMemberInfo"
QT_MOC_LITERAL(88, 1220, 6), // "member"
QT_MOC_LITERAL(89, 1227, 7), // "content"
QT_MOC_LITERAL(90, 1235, 11), // "onHideAtWin"
QT_MOC_LITERAL(91, 1247, 14), // "onSerGetTopMsg"
QT_MOC_LITERAL(92, 1262, 17), // "onSerCancelTopMsg"
QT_MOC_LITERAL(93, 1280, 7), // "pageNum"
QT_MOC_LITERAL(94, 1288, 5), // "Count"
QT_MOC_LITERAL(95, 1294, 12) // "ResultTopMsg"
},
"ui::ChatWidget\0signalSerGetGroupMem\0"
"\0code\0data::Member&\0mem\0addIsReceiptMsg\0"
"int64\0signalSerSendisReceiptMsg\0err\0"
"msgtime\0msgid\0CSharedPtr<data::Msg>\0"
"msg\0sendMsgHotKeyUpdate\0signalShakeWin\0"
"openUrl\0std::string\0url\0viewBurnMsg\0"
"CSharedPtr<data::Msg>&\0addChatListItem\0"
"CSharedPtr<data::ChatInfo>&\0startChat\0"
"signalScreenShot\0flag\0signalSendImage\0"
"signalSendMsgShot\0key\0signalSetSecretIsvisible\0"
"signalSerGroupRefreshUpdate\0int8\0"
"data::Group\0signalSerGetUrlInfo\0text\0"
"signalSerGroupMemCountRefresh\0"
"signalSerGetUserInfo\0data::UserData&\0"
"signalSerbtnCloseSession\0signalSerGetTopMsg\0"
"int32\0std::vector<data::ZxTopInformation>&\0"
"signalSerCancelTopMsg\0signalSerGetMemberInfo\0"
"std::string&\0onSerGetGroupMem\0"
"onSerSendisReceiptMsg\0onSendDelayMsg\0"
"time\0onSendDnyMsg\0fileName\0onSendCard\0"
"cardId\0isburn\0isdelay\0isreceipt\0"
"onSendMsg\0imagelist\0filelist\0"
"std::vector<int64>\0atlist\0onShowGroupAtMsgTip\0"
"onSerGetUrlInfo\0title\0imgPath\0desc\0"
"onSetPrivateKey\0QString&\0pPassword\0"
"onSerGroupRefreshUpdate\0onSerGetContactInfo\0"
"onShakeWinClicked\0onShowRecordWin\0"
"onRecordResult\0path\0onSerGetUserInfo\0"
"user\0onSerChickMsgReaded\0pmsgid\0"
"SetTileContent\0type\0MemCount\0"
"onSerGroupMemCountRefresh\0pMemCount\0"
"onSerSendMsgByType\0onSerMoretopMsg\0"
"onSerCanceltopMsg\0onSerGetMemberInfo\0"
"member\0content\0onHideAtWin\0onSerGetTopMsg\0"
"onSerCancelTopMsg\0pageNum\0Count\0"
"ResultTopMsg"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_ui__ChatWidget[] = {
// content:
8, // revision
0, // classname
0, 0, // classinfo
46, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
21, // signalCount
// signals: name, argc, parameters, tag, flags
1, 2, 244, 2, 0x06 /* Public */,
6, 1, 249, 2, 0x06 /* Public */,
8, 4, 252, 2, 0x06 /* Public */,
14, 1, 261, 2, 0x06 /* Public */,
15, 0, 264, 2, 0x06 /* Public */,
16, 1, 265, 2, 0x06 /* Public */,
19, 1, 268, 2, 0x06 /* Public */,
21, 1, 271, 2, 0x06 /* Public */,
23, 1, 274, 2, 0x06 /* Public */,
24, 1, 277, 2, 0x06 /* Public */,
26, 1, 280, 2, 0x06 /* Public */,
27, 1, 283, 2, 0x06 /* Public */,
29, 2, 286, 2, 0x06 /* Public */,
30, 2, 291, 2, 0x06 /* Public */,
33, 6, 296, 2, 0x06 /* Public */,
35, 2, 309, 2, 0x06 /* Public */,
36, 2, 314, 2, 0x06 /* Public */,
38, 1, 319, 2, 0x06 /* Public */,
39, 4, 322, 2, 0x06 /* Public */,
42, 4, 331, 2, 0x06 /* Public */,
43, 3, 340, 2, 0x06 /* Public */,
// slots: name, argc, parameters, tag, flags
45, 2, 347, 2, 0x0a /* Public */,
46, 4, 352, 2, 0x0a /* Public */,
47, 2, 361, 2, 0x0a /* Public */,
49, 1, 366, 2, 0x0a /* Public */,
51, 4, 369, 2, 0x0a /* Public */,
56, 7, 378, 2, 0x0a /* Public */,
61, 1, 393, 2, 0x0a /* Public */,
62, 6, 396, 2, 0x0a /* Public */,
66, 1, 409, 2, 0x0a /* Public */,
69, 2, 412, 2, 0x0a /* Public */,
70, 0, 417, 2, 0x0a /* Public */,
71, 0, 418, 2, 0x0a /* Public */,
72, 0, 419, 2, 0x0a /* Public */,
73, 2, 420, 2, 0x0a /* Public */,
75, 2, 425, 2, 0x0a /* Public */,
77, 1, 430, 2, 0x0a /* Public */,
79, 2, 433, 2, 0x0a /* Public */,
82, 2, 438, 2, 0x0a /* Public */,
84, 1, 443, 2, 0x0a /* Public */,
85, 0, 446, 2, 0x0a /* Public */,
86, 0, 447, 2, 0x0a /* Public */,
87, 3, 448, 2, 0x0a /* Public */,
90, 0, 455, 2, 0x0a /* Public */,
91, 4, 456, 2, 0x0a /* Public */,
92, 4, 465, 2, 0x0a /* Public */,
// signals: parameters
QMetaType::Void, QMetaType::Int, 0x80000000 | 4, 3, 5,
QMetaType::Void, 0x80000000 | 7, 2,
QMetaType::Void, QMetaType::Int, 0x80000000 | 7, 0x80000000 | 7, 0x80000000 | 12, 9, 10, 11, 13,
QMetaType::Void, QMetaType::Int, 2,
QMetaType::Void,
QMetaType::Void, 0x80000000 | 17, 18,
QMetaType::Void, 0x80000000 | 20, 13,
QMetaType::Void, 0x80000000 | 22, 2,
QMetaType::Void, 0x80000000 | 22, 2,
QMetaType::Void, QMetaType::Int, 25,
QMetaType::Void, QMetaType::QString, 2,
QMetaType::Void, QMetaType::Int, 28,
QMetaType::Void, QMetaType::Bool, QMetaType::Bool, 2, 2,
QMetaType::Void, 0x80000000 | 31, 0x80000000 | 32, 2, 2,
QMetaType::Void, QMetaType::QString, QMetaType::Int, 0x80000000 | 17, 0x80000000 | 17, 0x80000000 | 17, 0x80000000 | 17, 34, 2, 2, 2, 2, 2,
QMetaType::Void, QMetaType::Int, 0x80000000 | 7, 2, 2,
QMetaType::Void, QMetaType::Int, 0x80000000 | 37, 2, 2,
QMetaType::Void, QMetaType::Bool, 2,
QMetaType::Void, QMetaType::Int, 0x80000000 | 40, 0x80000000 | 40, 0x80000000 | 41, 2, 2, 2, 2,
QMetaType::Void, QMetaType::Int, 0x80000000 | 40, 0x80000000 | 40, 0x80000000 | 41, 2, 2, 2, 2,
QMetaType::Void, QMetaType::Int, 0x80000000 | 4, 0x80000000 | 44, 2, 2, 2,
// slots: parameters
QMetaType::Void, QMetaType::Int, 0x80000000 | 4, 3, 5,
QMetaType::Void, QMetaType::Int, 0x80000000 | 7, 0x80000000 | 7, 0x80000000 | 12, 9, 10, 11, 13,
QMetaType::Void, 0x80000000 | 7, QMetaType::QString, 48, 34,
QMetaType::Void, QMetaType::QString, 50,
QMetaType::Void, 0x80000000 | 7, QMetaType::Bool, QMetaType::Bool, QMetaType::Bool, 52, 53, 54, 55,
QMetaType::Void, QMetaType::QString, QMetaType::QStringList, QMetaType::QStringList, 0x80000000 | 59, QMetaType::Bool, QMetaType::Bool, QMetaType::Bool, 34, 57, 58, 60, 53, 54, 55,
QMetaType::Void, 0x80000000 | 12, 13,
QMetaType::Void, QMetaType::QString, QMetaType::Int, 0x80000000 | 17, 0x80000000 | 17, 0x80000000 | 17, 0x80000000 | 17, 34, 3, 18, 63, 64, 65,
QMetaType::Void, 0x80000000 | 67, 68,
QMetaType::Void, 0x80000000 | 31, 0x80000000 | 32, 2, 2,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void, QMetaType::QString, QMetaType::Int, 74, 48,
QMetaType::Void, QMetaType::Int, 0x80000000 | 37, 3, 76,
QMetaType::Void, 0x80000000 | 7, 78,
QMetaType::Void, QMetaType::Int, 0x80000000 | 7, 80, 81,
QMetaType::Void, QMetaType::Int, 0x80000000 | 7, 80, 83,
QMetaType::Void, QMetaType::Int, 80,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void, QMetaType::Int, 0x80000000 | 4, 0x80000000 | 44, 3, 88, 89,
QMetaType::Void,
QMetaType::Void, QMetaType::Int, 0x80000000 | 40, 0x80000000 | 40, 0x80000000 | 41, 2, 2, 2, 2,
QMetaType::Void, QMetaType::Int, 0x80000000 | 40, 0x80000000 | 40, 0x80000000 | 41, 3, 93, 94, 95,
0 // eod
};
void ui::ChatWidget::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
auto *_t = static_cast<ChatWidget *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->signalSerGetGroupMem((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< data::Member(*)>(_a[2]))); break;
case 1: _t->addIsReceiptMsg((*reinterpret_cast< int64(*)>(_a[1]))); break;
case 2: _t->signalSerSendisReceiptMsg((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< int64(*)>(_a[2])),(*reinterpret_cast< int64(*)>(_a[3])),(*reinterpret_cast< CSharedPtr<data::Msg>(*)>(_a[4]))); break;
case 3: _t->sendMsgHotKeyUpdate((*reinterpret_cast< int(*)>(_a[1]))); break;
case 4: _t->signalShakeWin(); break;
case 5: _t->openUrl((*reinterpret_cast< std::string(*)>(_a[1]))); break;
case 6: _t->viewBurnMsg((*reinterpret_cast< CSharedPtr<data::Msg>(*)>(_a[1]))); break;
case 7: _t->addChatListItem((*reinterpret_cast< CSharedPtr<data::ChatInfo>(*)>(_a[1]))); break;
case 8: _t->startChat((*reinterpret_cast< CSharedPtr<data::ChatInfo>(*)>(_a[1]))); break;
case 9: _t->signalScreenShot((*reinterpret_cast< int(*)>(_a[1]))); break;
case 10: _t->signalSendImage((*reinterpret_cast< const QString(*)>(_a[1]))); break;
case 11: _t->signalSendMsgShot((*reinterpret_cast< int(*)>(_a[1]))); break;
case 12: _t->signalSetSecretIsvisible((*reinterpret_cast< bool(*)>(_a[1])),(*reinterpret_cast< bool(*)>(_a[2]))); break;
case 13: _t->signalSerGroupRefreshUpdate((*reinterpret_cast< int8(*)>(_a[1])),(*reinterpret_cast< const data::Group(*)>(_a[2]))); break;
case 14: _t->signalSerGetUrlInfo((*reinterpret_cast< QString(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2])),(*reinterpret_cast< const std::string(*)>(_a[3])),(*reinterpret_cast< const std::string(*)>(_a[4])),(*reinterpret_cast< const std::string(*)>(_a[5])),(*reinterpret_cast< const std::string(*)>(_a[6]))); break;
case 15: _t->signalSerGroupMemCountRefresh((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< int64(*)>(_a[2]))); break;
case 16: _t->signalSerGetUserInfo((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< data::UserData(*)>(_a[2]))); break;
case 17: _t->signalSerbtnCloseSession((*reinterpret_cast< bool(*)>(_a[1]))); break;
case 18: _t->signalSerGetTopMsg((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< int32(*)>(_a[2])),(*reinterpret_cast< int32(*)>(_a[3])),(*reinterpret_cast< std::vector<data::ZxTopInformation>(*)>(_a[4]))); break;
case 19: _t->signalSerCancelTopMsg((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< int32(*)>(_a[2])),(*reinterpret_cast< int32(*)>(_a[3])),(*reinterpret_cast< std::vector<data::ZxTopInformation>(*)>(_a[4]))); break;
case 20: _t->signalSerGetMemberInfo((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< data::Member(*)>(_a[2])),(*reinterpret_cast< std::string(*)>(_a[3]))); break;
case 21: _t->onSerGetGroupMem((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< data::Member(*)>(_a[2]))); break;
case 22: _t->onSerSendisReceiptMsg((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< int64(*)>(_a[2])),(*reinterpret_cast< int64(*)>(_a[3])),(*reinterpret_cast< CSharedPtr<data::Msg>(*)>(_a[4]))); break;
case 23: _t->onSendDelayMsg((*reinterpret_cast< int64(*)>(_a[1])),(*reinterpret_cast< QString(*)>(_a[2]))); break;
case 24: _t->onSendDnyMsg((*reinterpret_cast< QString(*)>(_a[1]))); break;
case 25: _t->onSendCard((*reinterpret_cast< int64(*)>(_a[1])),(*reinterpret_cast< bool(*)>(_a[2])),(*reinterpret_cast< bool(*)>(_a[3])),(*reinterpret_cast< bool(*)>(_a[4]))); break;
case 26: _t->onSendMsg((*reinterpret_cast< QString(*)>(_a[1])),(*reinterpret_cast< QStringList(*)>(_a[2])),(*reinterpret_cast< QStringList(*)>(_a[3])),(*reinterpret_cast< std::vector<int64>(*)>(_a[4])),(*reinterpret_cast< bool(*)>(_a[5])),(*reinterpret_cast< bool(*)>(_a[6])),(*reinterpret_cast< bool(*)>(_a[7]))); break;
case 27: _t->onShowGroupAtMsgTip((*reinterpret_cast< CSharedPtr<data::Msg>(*)>(_a[1]))); break;
case 28: _t->onSerGetUrlInfo((*reinterpret_cast< QString(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2])),(*reinterpret_cast< const std::string(*)>(_a[3])),(*reinterpret_cast< const std::string(*)>(_a[4])),(*reinterpret_cast< const std::string(*)>(_a[5])),(*reinterpret_cast< const std::string(*)>(_a[6]))); break;
case 29: _t->onSetPrivateKey((*reinterpret_cast< QString(*)>(_a[1]))); break;
case 30: _t->onSerGroupRefreshUpdate((*reinterpret_cast< int8(*)>(_a[1])),(*reinterpret_cast< const data::Group(*)>(_a[2]))); break;
case 31: _t->onSerGetContactInfo(); break;
case 32: _t->onShakeWinClicked(); break;
case 33: _t->onShowRecordWin(); break;
case 34: _t->onRecordResult((*reinterpret_cast< QString(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2]))); break;
case 35: _t->onSerGetUserInfo((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< data::UserData(*)>(_a[2]))); break;
case 36: _t->onSerChickMsgReaded((*reinterpret_cast< int64(*)>(_a[1]))); break;
case 37: _t->SetTileContent((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< int64(*)>(_a[2]))); break;
case 38: _t->onSerGroupMemCountRefresh((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< int64(*)>(_a[2]))); break;
case 39: _t->onSerSendMsgByType((*reinterpret_cast< int(*)>(_a[1]))); break;
case 40: _t->onSerMoretopMsg(); break;
case 41: _t->onSerCanceltopMsg(); break;
case 42: _t->onSerGetMemberInfo((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< data::Member(*)>(_a[2])),(*reinterpret_cast< std::string(*)>(_a[3]))); break;
case 43: _t->onHideAtWin(); break;
case 44: _t->onSerGetTopMsg((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< int32(*)>(_a[2])),(*reinterpret_cast< int32(*)>(_a[3])),(*reinterpret_cast< std::vector<data::ZxTopInformation>(*)>(_a[4]))); break;
case 45: _t->onSerCancelTopMsg((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< int32(*)>(_a[2])),(*reinterpret_cast< int32(*)>(_a[3])),(*reinterpret_cast< std::vector<data::ZxTopInformation>(*)>(_a[4]))); break;
default: ;
}
} else if (_c == QMetaObject::IndexOfMethod) {
int *result = reinterpret_cast<int *>(_a[0]);
{
using _t = void (ChatWidget::*)(int , data::Member & );
if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&ChatWidget::signalSerGetGroupMem)) {
*result = 0;
return;
}
}
{
using _t = void (ChatWidget::*)(int64 );
if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&ChatWidget::addIsReceiptMsg)) {
*result = 1;
return;
}
}
{
using _t = void (ChatWidget::*)(int , int64 , int64 , CSharedPtr<data::Msg> );
if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&ChatWidget::signalSerSendisReceiptMsg)) {
*result = 2;
return;
}
}
{
using _t = void (ChatWidget::*)(int );
if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&ChatWidget::sendMsgHotKeyUpdate)) {
*result = 3;
return;
}
}
{
using _t = void (ChatWidget::*)();
if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&ChatWidget::signalShakeWin)) {
*result = 4;
return;
}
}
{
using _t = void (ChatWidget::*)(std::string );
if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&ChatWidget::openUrl)) {
*result = 5;
return;
}
}
{
using _t = void (ChatWidget::*)(CSharedPtr<data::Msg> & );
if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&ChatWidget::viewBurnMsg)) {
*result = 6;
return;
}
}
{
using _t = void (ChatWidget::*)(CSharedPtr<data::ChatInfo> & );
if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&ChatWidget::addChatListItem)) {
*result = 7;
return;
}
}
{
using _t = void (ChatWidget::*)(CSharedPtr<data::ChatInfo> & );
if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&ChatWidget::startChat)) {
*result = 8;
return;
}
}
{
using _t = void (ChatWidget::*)(int );
if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&ChatWidget::signalScreenShot)) {
*result = 9;
return;
}
}
{
using _t = void (ChatWidget::*)(const QString );
if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&ChatWidget::signalSendImage)) {
*result = 10;
return;
}
}
{
using _t = void (ChatWidget::*)(int );
if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&ChatWidget::signalSendMsgShot)) {
*result = 11;
return;
}
}
{
using _t = void (ChatWidget::*)(bool , bool );
if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&ChatWidget::signalSetSecretIsvisible)) {
*result = 12;
return;
}
}
{
using _t = void (ChatWidget::*)(int8 , const data::Group & );
if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&ChatWidget::signalSerGroupRefreshUpdate)) {
*result = 13;
return;
}
}
{
using _t = void (ChatWidget::*)(QString , int , const std::string & , const std::string & , const std::string & , const std::string & );
if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&ChatWidget::signalSerGetUrlInfo)) {
*result = 14;
return;
}
}
{
using _t = void (ChatWidget::*)(int , int64 );
if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&ChatWidget::signalSerGroupMemCountRefresh)) {
*result = 15;
return;
}
}
{
using _t = void (ChatWidget::*)(int , data::UserData & );
if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&ChatWidget::signalSerGetUserInfo)) {
*result = 16;
return;
}
}
{
using _t = void (ChatWidget::*)(bool );
if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&ChatWidget::signalSerbtnCloseSession)) {
*result = 17;
return;
}
}
{
using _t = void (ChatWidget::*)(int , int32 , int32 , std::vector<data::ZxTopInformation> & );
if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&ChatWidget::signalSerGetTopMsg)) {
*result = 18;
return;
}
}
{
using _t = void (ChatWidget::*)(int , int32 , int32 , std::vector<data::ZxTopInformation> & );
if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&ChatWidget::signalSerCancelTopMsg)) {
*result = 19;
return;
}
}
{
using _t = void (ChatWidget::*)(int , data::Member & , std::string & );
if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&ChatWidget::signalSerGetMemberInfo)) {
*result = 20;
return;
}
}
}
}
QT_INIT_METAOBJECT const QMetaObject ui::ChatWidget::staticMetaObject = { {
&QWidget::staticMetaObject,
qt_meta_stringdata_ui__ChatWidget.data,
qt_meta_data_ui__ChatWidget,
qt_static_metacall,
nullptr,
nullptr
} };
const QMetaObject *ui::ChatWidget::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *ui::ChatWidget::qt_metacast(const char *_clname)
{
if (!_clname) return nullptr;
if (!strcmp(_clname, qt_meta_stringdata_ui__ChatWidget.stringdata0))
return static_cast<void*>(this);
return QWidget::qt_metacast(_clname);
}
int ui::ChatWidget::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QWidget::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 46)
qt_static_metacall(this, _c, _id, _a);
_id -= 46;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 46)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 46;
}
return _id;
}
// SIGNAL 0
void ui::ChatWidget::signalSerGetGroupMem(int _t1, data::Member & _t2)
{
void *_a[] = { nullptr, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)) };
QMetaObject::activate(this, &staticMetaObject, 0, _a);
}
// SIGNAL 1
void ui::ChatWidget::addIsReceiptMsg(int64 _t1)
{
void *_a[] = { nullptr, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
QMetaObject::activate(this, &staticMetaObject, 1, _a);
}
// SIGNAL 2
void ui::ChatWidget::signalSerSendisReceiptMsg(int _t1, int64 _t2, int64 _t3, CSharedPtr<data::Msg> _t4)
{
void *_a[] = { nullptr, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)), const_cast<void*>(reinterpret_cast<const void*>(&_t3)), const_cast<void*>(reinterpret_cast<const void*>(&_t4)) };
QMetaObject::activate(this, &staticMetaObject, 2, _a);
}
// SIGNAL 3
void ui::ChatWidget::sendMsgHotKeyUpdate(int _t1)
{
void *_a[] = { nullptr, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
QMetaObject::activate(this, &staticMetaObject, 3, _a);
}
// SIGNAL 4
void ui::ChatWidget::signalShakeWin()
{
QMetaObject::activate(this, &staticMetaObject, 4, nullptr);
}
// SIGNAL 5
void ui::ChatWidget::openUrl(std::string _t1)
{
void *_a[] = { nullptr, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
QMetaObject::activate(this, &staticMetaObject, 5, _a);
}
// SIGNAL 6
void ui::ChatWidget::viewBurnMsg(CSharedPtr<data::Msg> & _t1)
{
void *_a[] = { nullptr, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
QMetaObject::activate(this, &staticMetaObject, 6, _a);
}
// SIGNAL 7
void ui::ChatWidget::addChatListItem(CSharedPtr<data::ChatInfo> & _t1)
{
void *_a[] = { nullptr, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
QMetaObject::activate(this, &staticMetaObject, 7, _a);
}
// SIGNAL 8
void ui::ChatWidget::startChat(CSharedPtr<data::ChatInfo> & _t1)
{
void *_a[] = { nullptr, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
QMetaObject::activate(this, &staticMetaObject, 8, _a);
}
// SIGNAL 9
void ui::ChatWidget::signalScreenShot(int _t1)
{
void *_a[] = { nullptr, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
QMetaObject::activate(this, &staticMetaObject, 9, _a);
}
// SIGNAL 10
void ui::ChatWidget::signalSendImage(const QString _t1)
{
void *_a[] = { nullptr, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
QMetaObject::activate(this, &staticMetaObject, 10, _a);
}
// SIGNAL 11
void ui::ChatWidget::signalSendMsgShot(int _t1)
{
void *_a[] = { nullptr, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
QMetaObject::activate(this, &staticMetaObject, 11, _a);
}
// SIGNAL 12
void ui::ChatWidget::signalSetSecretIsvisible(bool _t1, bool _t2)
{
void *_a[] = { nullptr, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)) };
QMetaObject::activate(this, &staticMetaObject, 12, _a);
}
// SIGNAL 13
void ui::ChatWidget::signalSerGroupRefreshUpdate(int8 _t1, const data::Group & _t2)
{
void *_a[] = { nullptr, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)) };
QMetaObject::activate(this, &staticMetaObject, 13, _a);
}
// SIGNAL 14
void ui::ChatWidget::signalSerGetUrlInfo(QString _t1, int _t2, const std::string & _t3, const std::string & _t4, const std::string & _t5, const std::string & _t6)
{
void *_a[] = { nullptr, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)), const_cast<void*>(reinterpret_cast<const void*>(&_t3)), const_cast<void*>(reinterpret_cast<const void*>(&_t4)), const_cast<void*>(reinterpret_cast<const void*>(&_t5)), const_cast<void*>(reinterpret_cast<const void*>(&_t6)) };
QMetaObject::activate(this, &staticMetaObject, 14, _a);
}
// SIGNAL 15
void ui::ChatWidget::signalSerGroupMemCountRefresh(int _t1, int64 _t2)
{
void *_a[] = { nullptr, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)) };
QMetaObject::activate(this, &staticMetaObject, 15, _a);
}
// SIGNAL 16
void ui::ChatWidget::signalSerGetUserInfo(int _t1, data::UserData & _t2)
{
void *_a[] = { nullptr, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)) };
QMetaObject::activate(this, &staticMetaObject, 16, _a);
}
// SIGNAL 17
void ui::ChatWidget::signalSerbtnCloseSession(bool _t1)
{
void *_a[] = { nullptr, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
QMetaObject::activate(this, &staticMetaObject, 17, _a);
}
// SIGNAL 18
void ui::ChatWidget::signalSerGetTopMsg(int _t1, int32 _t2, int32 _t3, std::vector<data::ZxTopInformation> & _t4)
{
void *_a[] = { nullptr, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)), const_cast<void*>(reinterpret_cast<const void*>(&_t3)), const_cast<void*>(reinterpret_cast<const void*>(&_t4)) };
QMetaObject::activate(this, &staticMetaObject, 18, _a);
}
// SIGNAL 19
void ui::ChatWidget::signalSerCancelTopMsg(int _t1, int32 _t2, int32 _t3, std::vector<data::ZxTopInformation> & _t4)
{
void *_a[] = { nullptr, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)), const_cast<void*>(reinterpret_cast<const void*>(&_t3)), const_cast<void*>(reinterpret_cast<const void*>(&_t4)) };
QMetaObject::activate(this, &staticMetaObject, 19, _a);
}
// SIGNAL 20
void ui::ChatWidget::signalSerGetMemberInfo(int _t1, data::Member & _t2, std::string & _t3)
{
void *_a[] = { nullptr, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)), const_cast<void*>(reinterpret_cast<const void*>(&_t3)) };
QMetaObject::activate(this, &staticMetaObject, 20, _a);
}
QT_WARNING_POP
QT_END_MOC_NAMESPACE
| [
"[email protected]"
] | |
cb0c94dd1f40ae09cff43f287180420552a32cb9 | a186d7c63d5ccc74238dec82307a10454f92e499 | /Source/SBansheeEngine/Source/BsScriptMaterial.cpp | 2c46f2412221b8fe526dfaf8b15219920bc634db | [] | no_license | venscn/BansheeEngine | 9f48b89838fbab15c6bf73fc8f296ef3d538dc49 | e1daf513a521e59b702001da920165d23b4b9f50 | refs/heads/master | 2020-04-06T06:49:38.631456 | 2016-07-28T12:10:44 | 2016-07-28T12:10:44 | 64,410,616 | 2 | 0 | null | 2016-07-28T16:17:46 | 2016-07-28T16:17:44 | null | UTF-8 | C++ | false | false | 10,530 | cpp | //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
//**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
#include "BsScriptMaterial.h"
#include "BsScriptResourceManager.h"
#include "BsScriptMeta.h"
#include "BsMonoField.h"
#include "BsMonoClass.h"
#include "BsMonoManager.h"
#include "BsMonoUtil.h"
#include "BsScriptShader.h"
#include "BsScriptTexture2D.h"
#include "BsScriptTexture3D.h"
#include "BsScriptTextureCube.h"
#include <BsBuiltinResources.h>
namespace BansheeEngine
{
ScriptMaterial::ScriptMaterial(MonoObject* instance, const HMaterial& material)
:TScriptResource(instance, material)
{
}
void ScriptMaterial::initRuntimeData()
{
metaData.scriptClass->addInternalCall("Internal_CreateInstance", &ScriptMaterial::internal_CreateInstance);
metaData.scriptClass->addInternalCall("Internal_Clone", &ScriptMaterial::internal_Clone);
metaData.scriptClass->addInternalCall("Internal_GetShader", &ScriptMaterial::internal_GetShader);
metaData.scriptClass->addInternalCall("Internal_SetShader", &ScriptMaterial::internal_SetShader);
metaData.scriptClass->addInternalCall("Internal_SetFloat", &ScriptMaterial::internal_SetFloat);
metaData.scriptClass->addInternalCall("Internal_SetVector2", &ScriptMaterial::internal_SetVector2);
metaData.scriptClass->addInternalCall("Internal_SetVector3", &ScriptMaterial::internal_SetVector3);
metaData.scriptClass->addInternalCall("Internal_SetVector4", &ScriptMaterial::internal_SetVector4);
metaData.scriptClass->addInternalCall("Internal_SetMatrix3", &ScriptMaterial::internal_SetMatrix3);
metaData.scriptClass->addInternalCall("Internal_SetMatrix4", &ScriptMaterial::internal_SetMatrix4);
metaData.scriptClass->addInternalCall("Internal_SetColor", &ScriptMaterial::internal_SetColor);
metaData.scriptClass->addInternalCall("Internal_SetTexture2D", &ScriptMaterial::internal_SetTexture2D);
metaData.scriptClass->addInternalCall("Internal_SetTexture3D", &ScriptMaterial::internal_SetTexture3D);
metaData.scriptClass->addInternalCall("Internal_SetTextureCube", &ScriptMaterial::internal_SetTextureCube);
metaData.scriptClass->addInternalCall("Internal_GetFloat", &ScriptMaterial::internal_GetFloat);
metaData.scriptClass->addInternalCall("Internal_GetVector2", &ScriptMaterial::internal_GetVector2);
metaData.scriptClass->addInternalCall("Internal_GetVector3", &ScriptMaterial::internal_GetVector3);
metaData.scriptClass->addInternalCall("Internal_GetVector4", &ScriptMaterial::internal_GetVector4);
metaData.scriptClass->addInternalCall("Internal_GetMatrix3", &ScriptMaterial::internal_GetMatrix3);
metaData.scriptClass->addInternalCall("Internal_GetMatrix4", &ScriptMaterial::internal_GetMatrix4);
metaData.scriptClass->addInternalCall("Internal_GetColor", &ScriptMaterial::internal_GetColor);
metaData.scriptClass->addInternalCall("Internal_GetTexture2D", &ScriptMaterial::internal_GetTexture2D);
metaData.scriptClass->addInternalCall("Internal_GetTexture3D", &ScriptMaterial::internal_GetTexture3D);
metaData.scriptClass->addInternalCall("Internal_GetTextureCube", &ScriptMaterial::internal_GetTextureCube);
}
void ScriptMaterial::internal_CreateInstance(MonoObject* instance, ScriptShader* shader)
{
HShader nativeShader;
if (shader != nullptr)
nativeShader = shader->getHandle();
if (nativeShader == nullptr)
nativeShader = BuiltinResources::instance().getDiffuseShader();
HMaterial material = Material::create(nativeShader);
ScriptMaterial* scriptInstance;
ScriptResourceManager::instance().createScriptResource(instance, material, &scriptInstance);
}
MonoObject* ScriptMaterial::internal_Clone(ScriptMaterial* nativeInstance)
{
HMaterial clone = nativeInstance->getHandle()->clone();
ScriptMaterial* scriptClone;
ScriptResourceManager::instance().createScriptResource(clone, &scriptClone);
return scriptClone->getManagedInstance();
}
MonoObject* ScriptMaterial::internal_GetShader(ScriptMaterial* nativeInstance)
{
HShader shader = nativeInstance->getHandle()->getShader();
if (shader == nullptr)
return nullptr;
ScriptShader* scriptShader;
ScriptResourceManager::instance().getScriptResource(shader, &scriptShader, true);
return scriptShader->getManagedInstance();
}
void ScriptMaterial::internal_SetShader(ScriptMaterial* nativeInstance, ScriptShader* shader)
{
HShader nativeShader;
if (shader != nullptr)
nativeShader = shader->getHandle();
if (nativeShader == nullptr)
nativeShader = BuiltinResources::instance().getDiffuseShader();
nativeInstance->getHandle()->setShader(nativeShader);
}
void ScriptMaterial::internal_SetFloat(ScriptMaterial* nativeInstance, MonoString* name, float value)
{
String paramName = MonoUtil::monoToString(name);
nativeInstance->getHandle()->setFloat(paramName, value);
}
void ScriptMaterial::internal_SetVector2(ScriptMaterial* nativeInstance, MonoString* name, Vector2* value)
{
String paramName = MonoUtil::monoToString(name);
nativeInstance->getHandle()->setVec2(paramName, *value);
}
void ScriptMaterial::internal_SetVector3(ScriptMaterial* nativeInstance, MonoString* name, Vector3* value)
{
String paramName = MonoUtil::monoToString(name);
nativeInstance->getHandle()->setVec3(paramName, *value);
}
void ScriptMaterial::internal_SetVector4(ScriptMaterial* nativeInstance, MonoString* name, Vector4* value)
{
String paramName = MonoUtil::monoToString(name);
nativeInstance->getHandle()->setVec4(paramName, *value);
}
void ScriptMaterial::internal_SetMatrix3(ScriptMaterial* nativeInstance, MonoString* name, Matrix3* value)
{
String paramName = MonoUtil::monoToString(name);
nativeInstance->getHandle()->setMat3(paramName, *value);
}
void ScriptMaterial::internal_SetMatrix4(ScriptMaterial* nativeInstance, MonoString* name, Matrix4* value)
{
String paramName = MonoUtil::monoToString(name);
nativeInstance->getHandle()->setMat4(paramName, *value);
}
void ScriptMaterial::internal_SetColor(ScriptMaterial* nativeInstance, MonoString* name, Color* value)
{
String paramName = MonoUtil::monoToString(name);
nativeInstance->getHandle()->setColor(paramName, *value);
}
void ScriptMaterial::internal_SetTexture2D(ScriptMaterial* nativeInstance, MonoString* name, ScriptTexture2D* value)
{
String paramName = MonoUtil::monoToString(name);
HTexture texture;
if (value != nullptr)
texture = value->getHandle();
nativeInstance->getHandle()->setTexture(paramName, texture);
}
void ScriptMaterial::internal_SetTexture3D(ScriptMaterial* nativeInstance, MonoString* name, ScriptTexture3D* value)
{
String paramName = MonoUtil::monoToString(name);
HTexture texture;
if (value != nullptr)
texture = value->getHandle();
nativeInstance->getHandle()->setTexture(paramName, texture);
}
void ScriptMaterial::internal_SetTextureCube(ScriptMaterial* nativeInstance, MonoString* name, ScriptTextureCube* value)
{
String paramName = MonoUtil::monoToString(name);
HTexture texture;
if (value != nullptr)
texture = value->getHandle();
nativeInstance->getHandle()->setTexture(paramName, texture);
}
float ScriptMaterial::internal_GetFloat(ScriptMaterial* nativeInstance, MonoString* name)
{
String paramName = MonoUtil::monoToString(name);
return nativeInstance->getHandle()->getFloat(paramName);
}
void ScriptMaterial::internal_GetVector2(ScriptMaterial* nativeInstance, MonoString* name, Vector2* value)
{
String paramName = MonoUtil::monoToString(name);
*value = nativeInstance->getHandle()->getVec2(paramName);
}
void ScriptMaterial::internal_GetVector3(ScriptMaterial* nativeInstance, MonoString* name, Vector3* value)
{
String paramName = MonoUtil::monoToString(name);
*value = nativeInstance->getHandle()->getVec3(paramName);
}
void ScriptMaterial::internal_GetVector4(ScriptMaterial* nativeInstance, MonoString* name, Vector4* value)
{
String paramName = MonoUtil::monoToString(name);
*value = nativeInstance->getHandle()->getVec4(paramName);
}
void ScriptMaterial::internal_GetMatrix3(ScriptMaterial* nativeInstance, MonoString* name, Matrix3* value)
{
String paramName = MonoUtil::monoToString(name);
*value = nativeInstance->getHandle()->getMat3(paramName);
}
void ScriptMaterial::internal_GetMatrix4(ScriptMaterial* nativeInstance, MonoString* name, Matrix4* value)
{
String paramName = MonoUtil::monoToString(name);
*value = nativeInstance->getHandle()->getMat4(paramName);
}
void ScriptMaterial::internal_GetColor(ScriptMaterial* nativeInstance, MonoString* name, Color* value)
{
String paramName = MonoUtil::monoToString(name);
*value = nativeInstance->getHandle()->getColor(paramName);
}
MonoObject* ScriptMaterial::internal_GetTexture2D(ScriptMaterial* nativeInstance, MonoString* name)
{
String paramName = MonoUtil::monoToString(name);
HTexture texture = nativeInstance->getHandle()->getTexture(paramName);
if (texture == nullptr)
return nullptr;
ScriptTexture2D* scriptTexture;
ScriptResourceManager::instance().getScriptResource(texture, &scriptTexture, true);
return scriptTexture->getManagedInstance();
}
MonoObject* ScriptMaterial::internal_GetTexture3D(ScriptMaterial* nativeInstance, MonoString* name)
{
String paramName = MonoUtil::monoToString(name);
HTexture texture = nativeInstance->getHandle()->getTexture(paramName);
if (texture == nullptr)
return nullptr;
ScriptTexture3D* scriptTexture;
ScriptResourceManager::instance().getScriptResource(texture, &scriptTexture, true);
return scriptTexture->getManagedInstance();
}
MonoObject* ScriptMaterial::internal_GetTextureCube(ScriptMaterial* nativeInstance, MonoString* name)
{
String paramName = MonoUtil::monoToString(name);
HTexture texture = nativeInstance->getHandle()->getTexture(paramName);
if (texture == nullptr)
return nullptr;
ScriptTextureCube* scriptTexture;
ScriptResourceManager::instance().getScriptResource(texture, &scriptTexture, true);
return scriptTexture->getManagedInstance();
}
MonoObject* ScriptMaterial::createInstance()
{
bool dummy = false;
void* params[1];
params[0] = &dummy;
return metaData.scriptClass->createInstance("bool", params);
}
MonoObject* ScriptMaterial::_createManagedInstance(bool construct)
{
if (construct)
return createInstance();
return metaData.scriptClass->createInstance(false);
}
} | [
"[email protected]"
] | |
e47a0011b4bfb0ff5dbe2d8f9a978596a82ea376 | 75c84d5b591fb87e28983475235f0fd13ec12fd4 | /GameFrameWork/Include/Coll/Collider.cpp | fd51eec48219206b25ba629c980df4cc55aef6e6 | [] | no_license | qjagh95/Project_RiskOfRain | 6702139ac152931701e7ba9129b540ca2ef161bc | fea34586698af6f8783c6c2c9ed424226276dc3e | refs/heads/master | 2020-04-01T07:36:41.426355 | 2018-10-14T18:08:35 | 2018-10-14T18:08:35 | 152,996,077 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 6,779 | cpp | #include "../stdafx.h"
#include "Collider.h"
#include "../Object/Object.h"
Collider::Collider()
{
m_GroupName = "Default";
m_IsUI = false;
}
Collider::Collider(const Collider & Value)
{
*this = Value;
}
Collider::~Collider()
{
list<Collider*>::iterator StartIter = m_PrevCollList.begin();
list<Collider*>::iterator EndIter= m_PrevCollList.end();
for (; StartIter != EndIter; StartIter++)
{
(*StartIter)->DeletePrevCollider(this);
(*StartIter)->OnCollsionEnd(this, 0.0f);
}
}
bool Collider::Init()
{
return true;
}
int Collider::Update(float DeltaTime)
{
return 0;
}
void Collider::Render(HDC hDC, float DeltaTime)
{
}
Collider * Collider::Clone() const
{
return NULL;
}
void Collider::Save(FILE * pFile)
{
fwrite(&m_Pivot, sizeof(Vector2), 1, pFile);
int iLength = (int)m_GroupName.length();
fwrite(&iLength, sizeof(int), 1, pFile);
fwrite(m_GroupName.c_str(), sizeof(char), iLength, pFile);
iLength = (int)m_CollsionTypeName.length();
fwrite(&iLength, sizeof(int), 1, pFile);
fwrite(m_CollsionTypeName.c_str(), sizeof(char), iLength, pFile);
fwrite(&m_IsUI, sizeof(bool), 1, pFile);
}
void Collider::Load(FILE * pFile)
{
fread(&m_Pivot, sizeof(Vector2), 1, pFile);
int iLength = 0;
fread(&iLength, sizeof(int), 1, pFile);
char strText[256] = {};
fread(strText, sizeof(char), iLength, pFile);
m_GroupName = strText;
memset(strText, 0, sizeof(char) * 256);
fread(&iLength, sizeof(int), 1, pFile);
fread(strText, sizeof(char), iLength, pFile);
m_CollsionTypeName = strText;
fread(&m_IsUI, sizeof(bool), 1, pFile);
}
Object * Collider::GetCurObject() const
{
m_Object->AddRefCount();
return m_Object;
}
void Collider::OnCollsionFirst(Collider * pDest, float DeltaTime)
{
list<function<void(Collider*, Collider*, float)>>::iterator StartIter = m_CallBack[CS_COLFIRST].begin();
list<function<void(Collider*, Collider*, float)>>::iterator EndIter = m_CallBack[CS_COLFIRST].end();
for ( ;StartIter != EndIter; StartIter++)
(*StartIter)(this, pDest, DeltaTime);
}
void Collider::OnCollsionDoing(Collider * pDest, float DeltaTime)
{
list<function<void(Collider*, Collider*, float)>>::iterator StartIter = m_CallBack[CS_COLDOING].begin();
list<function<void(Collider*, Collider*, float)>>::iterator EndIter = m_CallBack[CS_COLDOING].end();
for (;StartIter != EndIter; StartIter++)
(*StartIter)(this, pDest, DeltaTime);
}
void Collider::OnCollsionEnd(Collider * pDest, float DeltaTime)
{
list<function<void(Collider*, Collider*, float)>>::iterator StartIter = m_CallBack[CS_COLEND].begin();
list<function<void(Collider*, Collider*, float)>>::iterator EndIter = m_CallBack[CS_COLEND].end();
for (;StartIter != EndIter; StartIter++)
(*StartIter)(this, pDest, DeltaTime);
}
Vector2 Collider::GetPos() const
{
return m_Object->GetPos();
}
bool Collider::CollsionRectToRect(const Rect & Left, const Rect & Right)
{
if (Left.Left > Right.Right)
return false;
else if (Left.Right < Right.Left)
return false;
else if (Left.Top > Right.Bottom)
return false;
else if (Left.Bottom < Right.Top)
return false;
//충돌된위치에 Rect를 만든다
Rect TempRect;
if (Left.Left > Right.Left)
TempRect.Left = Left.Left;
else
TempRect.Left = Right.Left;
if (Left.Right > Right.Right)
TempRect.Right = Left.Right;
else
TempRect.Right = Left.Right;
if (Left.Top > Right.Top)
TempRect.Top = Left.Top;
else
TempRect.Top = Right.Top;
if (Left.Bottom > Right.Bottom)
TempRect.Bottom = Right.Bottom;
else
TempRect.Bottom = Left.Bottom;
m_CollsionPos.x = (TempRect.Right + TempRect.Left) / 2.0f;
m_CollsionPos.y = (TempRect.Bottom + TempRect.Top) / 2.0f;
return true;
}
bool Collider::CollsionCircleToCircle(const Circle & Left, const Circle & Right)
{
return Math::GetDistance(Left.m_CenterPos, Right.m_CenterPos) <= Left.m_Radius + Right.m_Radius;
}
bool Collider::CollsionRectToCircle(const Rect & Left, const Circle & Right)
{
Rect LeftRect;
Vector2 cPos = Right.m_CenterPos;
if ((Left.Left <= cPos.x && Left.Right >= cPos.x) || (Left.Top <= cPos.y, Left.Bottom >= cPos.y))
{
LeftRect.Left = Left.Left - Right.m_Radius;
LeftRect.Top = Left.Top - Right.m_Radius;
LeftRect.Right = Left.Right + Right.m_Radius;
LeftRect.Bottom = Left.Bottom + Right.m_Radius;
if ((LeftRect.Left < cPos.x && LeftRect.Right > cPos.x) && (LeftRect.Top < cPos.y && LeftRect.Bottom > cPos.y))
return true;
else
return false;
}
else
{
//대각선을 체크한다.
float l = Math::GetDistance(Vector2(Left.Left, Left.Top), cPos) < Right.m_Radius;
float t = Math::GetDistance(Vector2(Left.Right, Left.Top), cPos) < Right.m_Radius;
float r = Math::GetDistance(Vector2(Left.Left, Left.Bottom), cPos) < Right.m_Radius;
float b = Math::GetDistance(Vector2(Left.Right, Left.Bottom), cPos) < Right.m_Radius;
if (l || t || r || b)
return true;
}
return false;
}
bool Collider::CollsionRectToPoint(const Rect & Left, const Vector2 & Right)
{
if (Left.Left > Right.x)
return false;
else if (Left.Right < Right.x)
return false;
else if (Left.Top > Right.y)
return false;
else if (Left.Bottom < Right.y)
return false;
return true;
}
bool Collider::CollsionPointToPoint(const Vector2 & Left, const Vector2 & Right)
{
return Left.x == Right.x && Left.x == Right.x;
}
bool Collider::CollsionCircleToPoint(const Circle & Left, const Vector2 & Right)
{
return Math::GetDistance(Left.m_CenterPos, Right) <= Left.m_Radius;
}
bool Collider::CollsionRectToLine(const Rect & Left, const Vector2 & LineStart, const Vector2 & LineEnd)
{
return false;
}
bool Collider::CollsionRectToPixel(const Rect & Left, const PixelInfo & Right)
{
Rect TempRect = Left;
//전체 픽셀정보의 주소를 가져온다.
unsigned char* pPixel = (unsigned char*)Right.cPixel;
//전체 사이즈를 벗어났는지 체크한다.
if (TempRect.Left <= Right.Width && TempRect.Right >= 0.0f && TempRect.Top <= Right.Height && TempRect.Bottom >= 0.0f)
{
//사각형 영역을 체크한다.
int StartX = (int)(TempRect.Left <= 0.0f ? 0.0f : TempRect.Left);
int EndX = (int)(TempRect.Right >= Right.Width ? Right.Width : TempRect.Right);
int StartY = (int)(TempRect.Top <= 0.0f ? 0.0f: TempRect.Top);
int EndY = (int)(TempRect.Bottom >= Right.Height ? Right.Height : TempRect.Bottom);
for (int i = StartY; i < EndY ; i++)
{
for (int j = StartX; j < EndX; j++)
{
//인덱스 구하는 공식
int Index = (i * Right.Width + j) * Right.PixelSize;
//오브젝트 사각형영역의 픽셀정보와 픽셀충돌RGB값을 비교한다.
if (pPixel[Index] == Right.CollsionColor.r && pPixel[Index + 1] == Right.CollsionColor.g && pPixel[Index + 2] == Right.CollsionColor.b)
return true;
}//for(x)
}//for(y)
}//if
return false;
}
| [
"[email protected]"
] | |
5109105c5baf66361e82d3f62c7440cdd3c34b6a | 24f26275ffcd9324998d7570ea9fda82578eeb9e | /cc/paint/paint_shader.h | 2ce5770bf2db82b173730c5039d4579406945eaf | [
"BSD-3-Clause"
] | permissive | Vizionnation/chromenohistory | 70a51193c8538d7b995000a1b2a654e70603040f | 146feeb85985a6835f4b8826ad67be9195455402 | refs/heads/master | 2022-12-15T07:02:54.461083 | 2019-10-25T15:07:06 | 2019-10-25T15:07:06 | 217,557,501 | 2 | 1 | BSD-3-Clause | 2022-11-19T06:53:07 | 2019-10-25T14:58:54 | null | UTF-8 | C++ | false | false | 8,814 | 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 CC_PAINT_PAINT_SHADER_H_
#define CC_PAINT_PAINT_SHADER_H_
#include <memory>
#include <vector>
#include "base/optional.h"
#include "base/stl_util.h"
#include "cc/paint/image_analysis_state.h"
#include "cc/paint/paint_export.h"
#include "cc/paint/paint_image.h"
#include "third_party/skia/include/core/SkImage.h"
#include "third_party/skia/include/core/SkScalar.h"
#include "third_party/skia/include/core/SkShader.h"
#include "ui/gfx/color_space.h"
#include "ui/gfx/geometry/size_f.h"
namespace cc {
class ImageProvider;
class PaintOpBuffer;
using PaintRecord = PaintOpBuffer;
class CC_PAINT_EXPORT PaintShader : public SkRefCnt {
public:
enum class Type : uint8_t {
kEmpty,
kColor,
kLinearGradient,
kRadialGradient,
kTwoPointConicalGradient,
kSweepGradient,
kImage,
kPaintRecord,
kShaderCount
};
using RecordShaderId = uint32_t;
static const RecordShaderId kInvalidRecordShaderId;
// Scaling behavior dictates how a PaintRecord shader will behave. Use
// RasterAtScale to create a picture shader. Use FixedScale to create an image
// shader that is backed by the paint record.
enum class ScalingBehavior : uint8_t { kRasterAtScale, kFixedScale };
static sk_sp<PaintShader> MakeEmpty();
static sk_sp<PaintShader> MakeColor(SkColor color);
static sk_sp<PaintShader> MakeLinearGradient(
const SkPoint* points,
const SkColor* colors,
const SkScalar* pos,
int count,
SkTileMode mode,
uint32_t flags = 0,
const SkMatrix* local_matrix = nullptr,
SkColor fallback_color = SK_ColorTRANSPARENT);
static sk_sp<PaintShader> MakeRadialGradient(
const SkPoint& center,
SkScalar radius,
const SkColor colors[],
const SkScalar pos[],
int color_count,
SkTileMode mode,
uint32_t flags = 0,
const SkMatrix* local_matrix = nullptr,
SkColor fallback_color = SK_ColorTRANSPARENT);
static sk_sp<PaintShader> MakeTwoPointConicalGradient(
const SkPoint& start,
SkScalar start_radius,
const SkPoint& end,
SkScalar end_radius,
const SkColor colors[],
const SkScalar pos[],
int color_count,
SkTileMode mode,
uint32_t flags = 0,
const SkMatrix* local_matrix = nullptr,
SkColor fallback_color = SK_ColorTRANSPARENT);
static sk_sp<PaintShader> MakeSweepGradient(
SkScalar cx,
SkScalar cy,
const SkColor colors[],
const SkScalar pos[],
int color_count,
SkTileMode mode,
SkScalar start_degrees,
SkScalar end_degrees,
uint32_t flags = 0,
const SkMatrix* local_matrix = nullptr,
SkColor fallback_color = SK_ColorTRANSPARENT);
// |tile_rect| is not null only if the |image| is paint worklet backed.
static sk_sp<PaintShader> MakeImage(const PaintImage& image,
SkTileMode tx,
SkTileMode ty,
const SkMatrix* local_matrix,
const SkRect* tile_rect = nullptr);
static sk_sp<PaintShader> MakePaintRecord(
sk_sp<PaintRecord> record,
const SkRect& tile,
SkTileMode tx,
SkTileMode ty,
const SkMatrix* local_matrix,
ScalingBehavior scaling_behavior = ScalingBehavior::kRasterAtScale);
static size_t GetSerializedSize(const PaintShader* shader);
PaintShader(const PaintShader&) = delete;
~PaintShader() override;
PaintShader& operator=(const PaintShader&) = delete;
void set_has_animated_images(bool has_animated_images) {
image_analysis_state_ = has_animated_images
? ImageAnalysisState::kAnimatedImages
: ImageAnalysisState::kNoAnimatedImages;
}
ImageAnalysisState image_analysis_state() const {
return image_analysis_state_;
}
bool has_discardable_images() const;
SkMatrix GetLocalMatrix() const {
return local_matrix_ ? *local_matrix_ : SkMatrix::I();
}
Type shader_type() const { return shader_type_; }
const PaintImage& paint_image() const {
DCHECK_EQ(Type::kImage, shader_type_);
return image_;
}
const gfx::SizeF* tile_scale() const {
return base::OptionalOrNullptr(tile_scale_);
}
const sk_sp<PaintRecord>& paint_record() const { return record_; }
bool GetRasterizationTileRect(const SkMatrix& ctm, SkRect* tile_rect) const;
SkTileMode tx() const { return tx_; }
SkTileMode ty() const { return ty_; }
SkRect tile() const { return tile_; }
bool IsOpaque() const;
// Returns true if the shader looks like it is valid (ie the members required
// for this shader type all look reasonable. Returns false otherwise. Note
// that this is a best effort function since truly validating whether the
// shader is correct is hard.
bool IsValid() const;
bool operator==(const PaintShader& other) const;
bool operator!=(const PaintShader& other) const { return !(*this == other); }
RecordShaderId paint_record_shader_id() const {
DCHECK(id_ == kInvalidRecordShaderId || shader_type_ == Type::kPaintRecord);
return id_;
}
private:
friend class PaintFlags;
friend class PaintOpHelper;
friend class PaintOpReader;
friend class PaintOpSerializationTestUtils;
friend class PaintOpWriter;
friend class ScopedRasterFlags;
FRIEND_TEST_ALL_PREFIXES(PaintShaderTest, DecodePaintRecord);
FRIEND_TEST_ALL_PREFIXES(PaintOpBufferTest, PaintRecordShaderSerialization);
FRIEND_TEST_ALL_PREFIXES(PaintOpBufferTest, RecordShadersCached);
explicit PaintShader(Type type);
sk_sp<SkShader> GetSkShader() const;
void CreateSkShader(const gfx::SizeF* raster_scale = nullptr,
ImageProvider* image_provider = nullptr);
// Creates a PaintShader to be rasterized at the given ctm. |raster_scale| is
// set to the scale at which the record should be rasterized when the shader
// is used.
// Note that this does not create a skia backing for the shader.
// Valid only for PaintRecord backed shaders.
sk_sp<PaintShader> CreateScaledPaintRecord(const SkMatrix& ctm,
int max_texture_size,
gfx::SizeF* raster_scale) const;
// Creates a PaintShader with images from |image_provider| to be rasterized
// at the given ctm.
// |transfer_cache_entry_id| is set to the transfer cache id for the image, if
// the decode is backed by the transfer cache.
// |raster_quality| is set to the filter quality the shader should be
// rasterized with.
// Valid only for PaintImage backed shaders.
sk_sp<PaintShader> CreateDecodedImage(const SkMatrix& ctm,
SkFilterQuality requested_quality,
ImageProvider* image_provider,
uint32_t* transfer_cache_entry_id,
SkFilterQuality* raster_quality,
bool* needs_mips) const;
void SetColorsAndPositions(const SkColor* colors,
const SkScalar* positions,
int count);
void SetMatrixAndTiling(const SkMatrix* matrix, SkTileMode tx, SkTileMode ty);
void SetFlagsAndFallback(uint32_t flags, SkColor fallback_color);
Type shader_type_ = Type::kShaderCount;
uint32_t flags_ = 0;
SkScalar end_radius_ = 0;
SkScalar start_radius_ = 0;
SkTileMode tx_ = SkTileMode::kClamp;
SkTileMode ty_ = SkTileMode::kClamp;
SkColor fallback_color_ = SK_ColorTRANSPARENT;
ScalingBehavior scaling_behavior_ = ScalingBehavior::kRasterAtScale;
base::Optional<SkMatrix> local_matrix_;
SkPoint center_ = SkPoint::Make(0, 0);
SkRect tile_ = SkRect::MakeEmpty();
SkPoint start_point_ = SkPoint::Make(0, 0);
SkPoint end_point_ = SkPoint::Make(0, 0);
SkScalar start_degrees_ = 0;
SkScalar end_degrees_ = 0;
PaintImage image_;
sk_sp<PaintRecord> record_;
RecordShaderId id_ = kInvalidRecordShaderId;
// For decoded PaintRecord shaders, specifies the scale at which the record
// will be rasterized.
base::Optional<gfx::SizeF> tile_scale_;
std::vector<SkColor> colors_;
std::vector<SkScalar> positions_;
// The |cached_shader_| can be derived/creates from other inputs present in
// the PaintShader but we always construct it at creation time to ensure that
// accesses to it are thread-safe.
sk_sp<SkShader> cached_shader_;
ImageAnalysisState image_analysis_state_ = ImageAnalysisState::kNoAnalysis;
};
} // namespace cc
#endif // CC_PAINT_PAINT_SHADER_H_
| [
"[email protected]"
] | |
84e6dd50c6aded2c4efce14d859e456c0a2e77d1 | 64829fda6e8a31e8861711727918ba26bb3b0eee | /QuickEngine/Source/Utilities/Camera.h | f5d310c0f7d8b14230ac14b7c4ff389cca66b17f | [] | no_license | StephenAArredondo/QuickEngine | 48610c32f7d51d0690aa9bdb7f66e5289129aafe | 22efd3f01ba6ae9cf2e00d4e750a59b4021f9fa8 | refs/heads/master | 2021-03-30T16:52:34.356282 | 2015-04-20T11:44:58 | 2015-04-20T11:44:58 | 34,091,038 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,514 | h | #ifndef __CAMERA_H__
#define __CAMERA_H__
#define kSpeed 15.0f
class Camera
{
private:
QMatrix m_m4ProjectionMatrix;
QMatrix m_m4ViewMatrix;
float m_fSpeed;
unsigned int m_uiCameraID;
public:
Camera(void);
~Camera(void);
void SetCameraID(unsigned int _uiCameraID) { m_uiCameraID = _uiCameraID; }
void Look();
void CheckInput();
/*=====================================================================
Projection Matrix Functions
//===================================================================*/
QMatrix GetProjectionMatrix(void);
void SetProjectionMatrix(QMatrix *_mMatrix);
void BuildPerspective(float _fFieldOfView, float _fAspect, float _fZNear, float _fZFar);
/*=====================================================================
View Matrix Functions
//===================================================================*/
QMatrix GetViewMatrix(bool _bTranslate = true);
void SetViewMatrix(QMatrix *_mMatrix);
void NormalizeViewMatrix(void);
QVector3 GetViewXAxis(void);
void SetViewXAxis(QVector3 _vPosition);
void SetViewXAxis(float _fX, float _fY, float _fZ);
QVector3 GetViewYAxis(void);
void SetViewYAxis(QVector3 _vPosition);
void SetViewYAxis(float _fX, float _fY, float _fZ);
QVector3 GetViewZAxis(void);
void SetViewZAxis(QVector3 _vPosition);
void SetViewZAxis(float _fX, float _fY, float _fZ);
QVector3 GetViewPosition(void);
void SetViewPosition(QVector3 _vPosition);
void SetViewPosition(float _fX, float _fY, float _fZ);
/*=================================================================
Local Transform Functions
//===============================================================*/
void ViewRotateLocalX(float _fAngle);
void ViewRotateLocalY(float _fAngle);
void ViewRotateLocalZ(float _fAngle);
void ViewTranslateLocal(QVector3 _vAxis, bool _bFPS = false);
void ViewTranslateLocalX(float _fScale, bool _bFPS = false);
void ViewTranslateLocalY(float _fScale, bool _bFPS = false);
void ViewTranslateLocalZ(float _fScale, bool _bFPS = false);
/*=================================================================
Global Transform Functions
//===============================================================*/
void ViewRotateGlobalX(float _fAngle);
void ViewRotateGlobalY(float _fAngle);
void ViewRotateGlobalZ(float _fAngle);
void ViewTranslateGlobal(QVector3 _vAxis);
void ViewTranslateGlobalX(float _fScale);
void ViewTranslateGlobalY(float _fScale);
void ViewTranslateGlobalZ(float _fScale);
};
#endif//__CAMERA_H__ | [
"[email protected]"
] | |
42d0ac541b174fc44e9e5cbb0d327a4248c2284d | 28dba754ddf8211d754dd4a6b0704bbedb2bd373 | /Poj/P2699.cpp | 5c1456ac728ce10fb807927e4253a42d83dcbfe8 | [] | no_license | zjsxzy/algo | 599354679bd72ef20c724bb50b42fce65ceab76f | a84494969952f981bfdc38003f7269e5c80a142e | refs/heads/master | 2023-08-31T17:00:53.393421 | 2023-08-19T14:20:31 | 2023-08-19T14:20:31 | 10,140,040 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,124 | cpp | /*
* Author: Yang Zhang
* Created Time: 2012/8/13 21:11:53
* File Name: 2699.cpp
*/
#include <map>
#include <set>
#include <list>
#include <cmath>
#include <queue>
#include <stack>
#include <bitset>
#include <vector>
#include <cstdio>
#include <string>
#include <sstream>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
#define PB push_back
#define MP make_pair
#define SZ(v) ((int)(v).size())
#define abs(x) ((x) > 0 ? (x) : -(x))
typedef long long LL;
const int MAXN = 100 + 10;
const int inf = 0x3f3f3f3f;
struct SAP
{
int cap[MAXN][MAXN], flow[MAXN][MAXN], g[MAXN][MAXN];
int n;
int h[MAXN], vh[MAXN], source, sink;
void init(int n)
{
this->n = n;
memset(cap, 0, sizeof(cap));
}
void addCap(int i, int j, int val)
{
cap[i][j] += val;
g[i][j] = 1;
}
int sap(const int idx, const int maxCap)
{
if (idx == sink)
return maxCap;
int l = maxCap, d, minH = n;
for (int i = 0; i < n; i++)
{
if (cap[idx][i] - flow[idx][i] > 0)
{
if (h[idx] == h[i] + 1)
{
d = sap(i, min(l, cap[idx][i] - flow[idx][i]));
flow[idx][i] += d;
flow[i][idx] -= d;
l -= d;
if (h[source] == n || l == 0) return maxCap - l;
}
minH = min(minH, h[i] + 1);
}
}
if (l == maxCap)
{
vh[h[idx]]--;
vh[minH]++;
if (vh[h[idx]] == 0)
h[source] = n;
h[idx] = minH;
}
return maxCap - l;
}
int solve(int source, int sink)
{
if (source == sink) return inf;
this->sink = sink;
this->source = source;
memset(flow, 0, sizeof(flow));
memset(h, 0, sizeof(h));
memset(vh, 0, sizeof(vh));
int ans = 0;
while (h[source] != n)
ans += sap(source, inf);
return ans;
}
}sap;
vector<int> win;
int sum;
map<pair<int, int>, int> mp;
void work() {
int Max = 0, ret = 0, cnt = 0, n = SZ(win);
for (int i = 0; i < n; i++)
Max = max(Max, win[i]);
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++) {
mp[MP(i, j)] = ++cnt;
}
for (int st = 0; st < (1 << n); st++) {
bool flag = true;
for (int i = 0; i < n; i++)
if (win[i] == Max && !(st & (1 << i))) {
flag = false;
break;
}
if (!flag) continue;
sap.init(n + cnt + 2);
int source = 0, sink = n + cnt + 1;
for (int i = 0; i < n; i++)
sap.addCap(source, i + 1, win[i]);
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++) {
int num = mp[MP(i, j)];
if (win[i] < win[j] && (st & (1 << i))) {
sap.addCap(i + 1, n + num, 1);
} else if (win[j] < win[i] && (st & (1 << j))) {
sap.addCap(j + 1, n + num, 1);
} else {
sap.addCap(i + 1, n + num, 1);
sap.addCap(j + 1, n + num, 1);
}
}
for (int i = 1; i <= cnt; i++)
sap.addCap(n + i, sink, 1);
int flow = sap.solve(source, sink);
if (flow == sum) {
int tot = 0;
for (int i = 0; i < n; i++)
if (st & (1 << i)) tot++;
ret = max(ret, tot);
}
}
printf("%d\n", ret);
}
int main() {
freopen("in.txt", "r", stdin);
int Test;
scanf("%d\n", &Test);
while (Test--) {
win.clear();
sum = 0;
string input;
getline(cin, input);
istringstream iss;
iss.str(input);
int x;
while (iss >> x) {
win.PB(x);
sum += x;
}
if (SZ(win) == 1) {
puts("1");
continue;
}
work();
}
return 0;
}
| [
"[email protected]"
] | |
43fb7a1bbd66379909407f458a7b79128ab77040 | 58f2cf2f41c207c326a5fc00673333054d1c08f5 | /datatypes/types.cpp | b8b626bd506e9168a3eeb0ab972acdfec191d1de | [] | no_license | Vamsi995/Hackerrank-Cpp | af0255f9efeeb7d4ad5d7f81866de6c8000ce982 | 058f0960a7382d7eea236c6a1a041431cfdcf210 | refs/heads/main | 2023-01-06T05:58:09.297906 | 2020-11-04T13:24:13 | 2020-11-04T13:24:13 | 308,053,073 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 308 | cpp | #include<iostream>
using namespace std;
int main(void)
{
int a;
long int b;
char c;
float d;
double e;
cin >> a >> b >> c >> d >> e;
// cout << a << b << c << d << e << endl;
printf("%d\n",a);
printf("%ld\n",b);
printf("%c\n",c);
printf("%.3f\n",d);
printf("%.9lf\n",e);
return 0;
}
| [
"[email protected]"
] | |
31f30f070ccbce8713d2bd3032e8e2261d751ab4 | 53a910dfc6d58d0e1c1c9601fb3fa1452dd49d86 | /C++/examples/VectorsAndMaps/vectors.cpp | f9e14f93b9c8af7f27b0228647eac1d0e13faa44 | [] | no_license | mrodozov/Homeworks | 342510c1154d21f730d5080d379b555d08da9a6e | 77aaf9219819f2e9dd1accc4b8d26cd428ba0031 | refs/heads/master | 2021-01-22T04:57:05.907980 | 2016-08-19T04:57:42 | 2016-08-19T04:57:42 | 32,219,484 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,212 | cpp | #include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <new>
#include <stdlib.h>
#include <vector>
using namespace std;
class MySecClass {
public:
int firstfield;
};
class MyExampleClass {
public:
int someIntegerField;
string someStringField;
MySecClass secclassfield;
};
int main (){
vector<int> vector_its;
vector<double> vector_doubles;
vector<MyExampleClass> vectorOfUserDefinedObjects;
for (int i = 0; i < 50 ; i++){
vector_its.push_back( i*10 );
}
cout << vector_its.at(49) << endl;
for (int i = 0 ; i < vector_its.size() ; i++ ){
cout << vector_its.at(i) << endl;
}
cout << "end of vector of integers" << endl;
MyExampleClass obj1, obj2, obj3;
obj1.someIntegerField = 10;
obj1.secclassfield.firstfield = 5;
//obj2.someIntegerField = 21;
//obj3. someIntegerField = 33;
vectorOfUserDefinedObjects.push_back(obj1);
vectorOfUserDefinedObjects.push_back(obj2);
vectorOfUserDefinedObjects.push_back(obj3);
cout << vectorOfUserDefinedObjects.at(0).someIntegerField << endl;
cout << vectorOfUserDefinedObjects.at(0).secclassfield.firstfield << endl;
return 0;
}
| [
"[email protected]"
] | |
fe87b50f6a4bdbd2707abec01150b0f3b0e79137 | cb0e94e234814236e706d30c7d940e813f07fd00 | /distributions/bivariate/DiscreteBivariateDistribution.cpp | 6b9e755364f59f04a0c0f2662331a4c16abc3be0 | [
"MIT"
] | permissive | vishalbelsare/RandLib | 9cd2278fc8c6eb59548631ce11b20e1a963475af | 6536dadd6e532316848cade7e48f84fb40135767 | refs/heads/master | 2023-06-23T04:49:20.008681 | 2023-06-20T12:00:53 | 2023-06-20T12:00:53 | 146,628,254 | 0 | 0 | MIT | 2023-06-20T21:18:04 | 2018-08-29T16:30:03 | C++ | UTF-8 | C++ | false | false | 411 | cpp | #include "DiscreteBivariateDistribution.h"
#include "../univariate/discrete/BinomialRand.h"
template class DiscreteBivariateDistribution< BinomialRand<int>, BinomialRand<int>, int >;
template class DiscreteBivariateDistribution< BinomialRand<long int>, BinomialRand<long int>, long int >;
template class DiscreteBivariateDistribution< BinomialRand<long long int>, BinomialRand<long long int>, long long int >;
| [
"[email protected]"
] | |
b76d6fcc482694636765f30a5991c7007edd9bc0 | 57dde4ae85512d71a412b1a9b7bac8f4a22c7ea8 | /5. Number Theory/Spoj boring factorial.cpp | a870042f7db68ef74d55a11ab195a3222383ade7 | [] | no_license | HemantKr79/CB-Competitive-Programming-Solutions | 0efec4f60df03fe54b747c0d561a4eeab568c75e | 5170aeba51730eca8f1e5f31782a6bb5e556b16b | refs/heads/main | 2023-03-22T20:00:18.305515 | 2021-03-01T02:20:46 | 2021-03-01T02:20:46 | 343,264,988 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 693 | cpp | #include<iostream>
using namespace std;
#define ll long long
ll mulitplicative_modulo_inverse(ll a,ll p,ll mod) {
ll ans = 1;
ll tmp = a;
while(p>0) {
if(p&1) {
ans = (ans*tmp)%mod;
}
tmp = (tmp*tmp)%mod;
p = p>>1;
}
return ans;
}
ll compute(ll n,ll p) {
ll ans = -1;
for(ll i=(n+1);i<=(p-1);i++) {
ans = ans*mulitplicative_modulo_inverse(i,p-2,p);
ans = ans%p;
}
return ans+p;
}
int main() {
ll t;
cin>>t;
while(t--) {
ll n,p;
cin>>n>>p;
if(p<=n) {
cout<<0<<endl;
}
else {
cout<<compute(n,p)<<endl;
}
}
} | [
"[email protected]"
] | |
e93c44e5ad40ec6be4a18dbb0d2120649f39c187 | a548daec11dad02c401d8c9c167d083847fffc71 | /src/vectorlikeTReconstructionHypothesisDiscriminators.cxx | 9b34c2b463193b5e595d6cd0968ee06f9af89346 | [] | no_license | llpwilhelm/vectorlikeT | 4dd4548506c2470f3f2c6087ea85e39d869f817f | 30b5dbb96e9d6ba8440944867e0a578492c495d9 | refs/heads/master | 2020-07-07T00:51:05.750052 | 2019-08-19T14:13:33 | 2019-08-19T14:13:33 | 203,191,362 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,013 | cxx | #include "UHH2/vectorlikeT/include/vectorlikeTReconstructionHypothesisDiscriminators.h"
#include "UHH2/core/include/Utils.h"
#include <set>
using namespace uhh2;
using namespace std;
namespace {
// invariant mass of a lorentzVector, but save for timelike / spacelike vectors
float inv_mass(const LorentzVector & p4){
if(p4.isTimelike()) return p4.mass();
else return -sqrt(-p4.mass2());
}
}
const vectorlikeTReconstructionHypothesis * get_best_hypothesis(const std::vector<vectorlikeTReconstructionHypothesis> & hyps, const std::string & label){
const vectorlikeTReconstructionHypothesis * best = nullptr;
float current_best_disc = numeric_limits<float>::infinity();
for(const auto & hyp : hyps){
if(!hyp.has_discriminator(label)) continue;
auto disc = hyp.discriminator(label);
if(disc < current_best_disc){
best = &hyp;
current_best_disc = disc;
}
}
if(std::isfinite(current_best_disc)){
return best;
}
else{
return nullptr;
}
}
vectorlikeTChi2Discriminator::vectorlikeTChi2Discriminator(Context & ctx, const cfg & config_): config(config_){
h_hyps = ctx.get_handle<vector<vectorlikeTReconstructionHypothesis>>("TprimeHypotheses");
}
bool vectorlikeTChi2Discriminator::process(uhh2::Event & event){
auto & hyps = event.get(h_hyps);
const double mass_tlep = 173.;
const double mass_tlep_sigma = 22.;
const double mass_higgs = 121.;
const double mass_higgs_sigma = 13.;
for(auto & hyp: hyps){
double mass_tlep_rec = inv_mass(hyp.toplep_v4());
double mass_higgs_rec = inv_mass(hyp.higgs_v4());
double chi2_top = pow((mass_tlep_rec - mass_tlep)/(mass_tlep_sigma),2);
double chi2_higgs = pow((mass_higgs_rec - mass_higgs)/(mass_higgs_sigma),2);
hyp.set_discriminator(config.discriminator_label + "_top", chi2_top);
hyp.set_discriminator(config.discriminator_label + "_higgs", chi2_higgs);
hyp.set_discriminator(config.discriminator_label, chi2_higgs + chi2_top); // modified
}
return true;
}
| [
"[email protected]"
] | |
34d5075171058288dc40f05795292046cdf825ce | 144204c519069fe75ecf084a5aefefea142542b7 | /apps/packetizer-gemalto/Copy.h | 42e31360f530b88cda3be10b7354164a3e45c657 | [] | no_license | bopopescu/UnitedSafety | fcb6baf9b3382cc1b45c58079da1dcc33b95d434 | baea1b16c2fd44e224fb9120d026da2535123bd7 | refs/heads/master | 2022-10-10T04:04:58.528055 | 2020-06-11T18:29:19 | 2020-06-11T18:29:19 | 282,259,268 | 1 | 0 | null | 2020-07-24T15:48:24 | 2020-07-24T15:48:24 | null | UTF-8 | C++ | false | false | 287 | h | #pragma once
#include "ats-common.h"
#include "state_machine.h"
#include "DB.h"
class Copy: public StateMachine
{
public:
Copy(MyData&);
~Copy();
virtual void start();
private:
void (Copy::*m_state_fn)();
void state_0();
void state_1();
DB * m_dbreader;
MyData* m_data;
};
| [
"[email protected]"
] | |
a3e6f223eadced49a6825dae5c0ed5bfb112b67f | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/httpd/gumtree/httpd_new_log_3787.cpp | 277952b32e9d3e3b788b75b95c46d1c8838ea14b | [] | 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 | 128 | cpp | ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, data->r, APLOGNO(01221)
"poll failed waiting for CGI child"); | [
"[email protected]"
] | |
e3a65637ce466cbd4e05a7532e5548d019949051 | 24bc4990e9d0bef6a42a6f86dc783785b10dbd42 | /gpu/command_buffer/service/shared_image/shared_image_representation.cc | 8020b9c96a241c49ce9ec7ee0e66aa180b4e6c07 | [
"BSD-3-Clause"
] | permissive | nwjs/chromium.src | 7736ce86a9a0b810449a3b80a4af15de9ef9115d | 454f26d09b2f6204c096b47f778705eab1e3ba46 | refs/heads/nw75 | 2023-08-31T08:01:39.796085 | 2023-04-19T17:25:53 | 2023-04-19T17:25:53 | 50,512,158 | 161 | 201 | BSD-3-Clause | 2023-05-08T03:19:09 | 2016-01-27T14:17:03 | null | UTF-8 | C++ | false | false | 21,062 | cc | // Copyright 2018 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "gpu/command_buffer/service/shared_image/shared_image_representation.h"
#include "base/debug/dump_without_crashing.h"
#include "base/strings/stringprintf.h"
#include "build/build_config.h"
#include "components/viz/common/resources/resource_format_utils.h"
#include "gpu/command_buffer/service/shared_context_state.h"
#include "gpu/command_buffer/service/shared_image/shared_image_format_utils.h"
#include "gpu/command_buffer/service/texture_manager.h"
#include "third_party/skia/include/core/SkColorSpace.h"
#include "third_party/skia/include/core/SkPromiseImageTexture.h"
#include "third_party/skia/include/gpu/GrBackendSurfaceMutableState.h"
#include "third_party/skia/include/gpu/GrDirectContext.h"
#include "third_party/skia/include/gpu/GrYUVABackendTextures.h"
#include "ui/gl/gl_fence.h"
namespace gpu {
SharedImageRepresentation::SharedImageRepresentation(
SharedImageManager* manager,
SharedImageBacking* backing,
MemoryTypeTracker* owning_tracker)
: manager_(manager), backing_(backing), tracker_(owning_tracker) {
DCHECK(tracker_);
// TODO(hitawala): Rewrite the reference counting so that
// SharedImageRepresentation does not need manager and manager attaches to
// backing in Register().
if (manager_ && backing_->is_ref_counted()) {
backing_->AddRef(this);
}
}
SharedImageRepresentation::~SharedImageRepresentation() {
// CHECK here as we'll crash later anyway, and this makes it clearer what the
// error is.
CHECK(!has_scoped_access_) << "Destroying a SharedImageRepresentation with "
"outstanding Scoped*Access objects.";
if (manager_ && backing_->is_ref_counted()) {
manager_->OnRepresentationDestroyed(backing_.ExtractAsDangling()->mailbox(),
this);
}
}
size_t SharedImageRepresentation::NumPlanesExpected() const {
if (format().PrefersExternalSampler()) {
return 1;
}
return static_cast<size_t>(format().NumberOfPlanes());
}
std::unique_ptr<GLTextureImageRepresentation::ScopedAccess>
GLTextureImageRepresentationBase::BeginScopedAccess(
GLenum mode,
AllowUnclearedAccess allow_uncleared) {
if (allow_uncleared != AllowUnclearedAccess::kYes && !IsCleared()) {
LOG(ERROR) << "Attempt to access an uninitialized SharedImage";
return nullptr;
}
if (!BeginAccess(mode))
return nullptr;
UpdateClearedStateOnBeginAccess();
if (mode == kReadAccessMode)
backing()->OnReadSucceeded();
else
backing()->OnWriteSucceeded();
return std::make_unique<ScopedAccess>(
base::PassKey<GLTextureImageRepresentationBase>(), this);
}
gpu::TextureBase* GLTextureImageRepresentationBase::GetTextureBase() {
DCHECK(format().is_single_plane());
return GetTextureBase(0);
}
bool GLTextureImageRepresentationBase::SupportsMultipleConcurrentReadAccess() {
return false;
}
gpu::TextureBase* GLTextureImageRepresentation::GetTextureBase(
int plane_index) {
return GetTexture(plane_index);
}
gles2::Texture* GLTextureImageRepresentation::GetTexture() {
DCHECK(format().is_single_plane());
return GetTexture(0);
}
void GLTextureImageRepresentation::UpdateClearedStateOnEndAccess() {
auto* texture = GetTexture();
// Operations on the gles2::Texture may have cleared or uncleared it. Make
// sure this state is reflected back in the SharedImage.
gfx::Rect cleared_rect = texture->GetLevelClearedRect(texture->target(), 0);
if (cleared_rect != ClearedRect())
SetClearedRect(cleared_rect);
}
void GLTextureImageRepresentation::UpdateClearedStateOnBeginAccess() {
auto* texture = GetTexture();
// Operations outside of the gles2::Texture may have cleared or uncleared it.
// Make sure this state is reflected back in gles2::Texture.
gfx::Rect cleared_rect = ClearedRect();
if (cleared_rect != texture->GetLevelClearedRect(texture->target(), 0))
texture->SetLevelClearedRect(texture->target(), 0, cleared_rect);
}
gpu::TextureBase* GLTexturePassthroughImageRepresentation::GetTextureBase(
int plane_index) {
return GetTexturePassthrough(plane_index).get();
}
const scoped_refptr<gles2::TexturePassthrough>&
GLTexturePassthroughImageRepresentation::GetTexturePassthrough() {
DCHECK(format().is_single_plane());
return GetTexturePassthrough(0);
}
bool GLTexturePassthroughImageRepresentation::
NeedsSuspendAccessForDXGIKeyedMutex() const {
return false;
}
bool SkiaImageRepresentation::SupportsMultipleConcurrentReadAccess() {
return false;
}
SkiaImageRepresentation::ScopedWriteAccess::ScopedWriteAccess(
base::PassKey<SkiaImageRepresentation> /* pass_key */,
SkiaImageRepresentation* representation,
std::vector<sk_sp<SkSurface>> surfaces,
std::unique_ptr<GrBackendSurfaceMutableState> end_state)
: ScopedAccessBase(representation),
surfaces_(std::move(surfaces)),
end_state_(std::move(end_state)) {
DCHECK(!surfaces_.empty());
}
SkiaImageRepresentation::ScopedWriteAccess::ScopedWriteAccess(
base::PassKey<SkiaImageRepresentation> /* pass_key */,
SkiaImageRepresentation* representation,
std::vector<sk_sp<SkPromiseImageTexture>> promise_image_textures,
std::unique_ptr<GrBackendSurfaceMutableState> end_state)
: ScopedAccessBase(representation),
promise_image_textures_(std::move(promise_image_textures)),
end_state_(std::move(end_state)) {
DCHECK(!promise_image_textures_.empty());
}
SkiaImageRepresentation::ScopedWriteAccess::~ScopedWriteAccess() {
if (end_state_) {
NOTREACHED() << "Before ending write access TakeEndState() must be called "
"and the result passed to skia to make sure all layout and "
"ownership transitions are done.";
static std::atomic_int count = 0;
if (count++ < 3)
base::debug::DumpWithoutCrashing();
}
// Ensure no one uses `surfaces_` by dropping the reference before calling
// EndWriteAccess.
surfaces_.clear();
representation()->EndWriteAccess();
}
std::unique_ptr<GrBackendSurfaceMutableState>
SkiaImageRepresentation::ScopedWriteAccess::TakeEndState() {
return std::move(end_state_);
}
std::unique_ptr<SkiaImageRepresentation::ScopedWriteAccess>
SkiaImageRepresentation::BeginScopedWriteAccess(
int final_msaa_count,
const SkSurfaceProps& surface_props,
const gfx::Rect& update_rect,
std::vector<GrBackendSemaphore>* begin_semaphores,
std::vector<GrBackendSemaphore>* end_semaphores,
AllowUnclearedAccess allow_uncleared,
bool use_sk_surface) {
if (allow_uncleared != AllowUnclearedAccess::kYes && !IsCleared()) {
LOG(ERROR) << "Attempt to write to an uninitialized SharedImage";
return nullptr;
}
std::unique_ptr<GrBackendSurfaceMutableState> end_state;
if (use_sk_surface) {
std::vector<sk_sp<SkSurface>> surfaces =
BeginWriteAccess(final_msaa_count, surface_props, update_rect,
begin_semaphores, end_semaphores, &end_state);
if (surfaces.empty()) {
LOG(ERROR) << "Unable to initialize SkSurface";
return nullptr;
}
backing()->OnWriteSucceeded();
return std::make_unique<ScopedWriteAccess>(
base::PassKey<SkiaImageRepresentation>(), this, std::move(surfaces),
std::move(end_state));
}
std::vector<sk_sp<SkPromiseImageTexture>> promise_image_textures =
BeginWriteAccess(begin_semaphores, end_semaphores, &end_state);
if (promise_image_textures.empty()) {
LOG(ERROR) << "Unable to initialize SkPromiseImageTexture";
return nullptr;
}
backing()->OnWriteSucceeded();
return std::make_unique<ScopedWriteAccess>(
base::PassKey<SkiaImageRepresentation>(), this,
std::move(promise_image_textures), std::move(end_state));
}
std::unique_ptr<SkiaImageRepresentation::ScopedWriteAccess>
SkiaImageRepresentation::BeginScopedWriteAccess(
int final_msaa_count,
const SkSurfaceProps& surface_props,
std::vector<GrBackendSemaphore>* begin_semaphores,
std::vector<GrBackendSemaphore>* end_semaphores,
AllowUnclearedAccess allow_uncleared,
bool use_sk_surface) {
return BeginScopedWriteAccess(
final_msaa_count, surface_props, gfx::Rect(size()), begin_semaphores,
end_semaphores, allow_uncleared, use_sk_surface);
}
std::unique_ptr<SkiaImageRepresentation::ScopedWriteAccess>
SkiaImageRepresentation::BeginScopedWriteAccess(
std::vector<GrBackendSemaphore>* begin_semaphores,
std::vector<GrBackendSemaphore>* end_semaphores,
AllowUnclearedAccess allow_uncleared,
bool use_sk_surface) {
return BeginScopedWriteAccess(
/*final_msaa_count=*/1,
SkSurfaceProps(0 /* flags */, kUnknown_SkPixelGeometry), begin_semaphores,
end_semaphores, allow_uncleared, use_sk_surface);
}
SkiaImageRepresentation::ScopedReadAccess::ScopedReadAccess(
base::PassKey<SkiaImageRepresentation> /* pass_key */,
SkiaImageRepresentation* representation,
std::vector<sk_sp<SkPromiseImageTexture>> promise_image_textures,
std::unique_ptr<GrBackendSurfaceMutableState> end_state)
: ScopedAccessBase(representation),
promise_image_textures_(std::move(promise_image_textures)),
end_state_(std::move(end_state)) {
DCHECK(!promise_image_textures_.empty());
}
SkiaImageRepresentation::ScopedReadAccess::~ScopedReadAccess() {
if (end_state_) {
NOTREACHED() << "Before ending read access TakeEndState() must be called "
"and the result passed to skia to make sure all layout and "
"ownership transitions are done.";
static std::atomic_int count = 0;
if (count++ < 3)
base::debug::DumpWithoutCrashing();
}
representation()->EndReadAccess();
}
sk_sp<SkImage> SkiaImageRepresentation::ScopedReadAccess::CreateSkImage(
GrDirectContext* context,
SkImage::TextureReleaseProc texture_release_proc,
SkImage::ReleaseContext release_context) const {
auto format = representation()->format();
auto surface_origin = representation()->surface_origin();
auto sk_color_space =
representation()->color_space().GetAsFullRangeRGB().ToSkColorSpace();
if (format.is_single_plane() || format.PrefersExternalSampler()) {
DCHECK_EQ(static_cast<int>(promise_image_textures_.size()), 1);
auto alpha_type = representation()->alpha_type();
auto color_type =
viz::ToClosestSkColorType(/*gpu_compositing=*/true, format);
return SkImage::MakeFromTexture(
context, promise_image_texture()->backendTexture(), surface_origin,
color_type, alpha_type, sk_color_space, texture_release_proc,
release_context);
} else {
DCHECK_EQ(static_cast<int>(promise_image_textures_.size()),
format.NumberOfPlanes());
std::array<GrBackendTexture, SkYUVAInfo::kMaxPlanes> yuva_textures;
// Get the texture per plane.
for (int plane_index = 0; plane_index < format.NumberOfPlanes();
plane_index++) {
yuva_textures[plane_index] =
promise_image_texture(plane_index)->backendTexture();
}
SkISize sk_size = gfx::SizeToSkISize(representation()->size());
// TODO(crbug.com/828599): This should really default to rec709.
SkYUVColorSpace yuv_color_space = kRec601_SkYUVColorSpace;
representation()->color_space().ToSkYUVColorSpace(
format.MultiplanarBitDepth(), &yuv_color_space);
SkYUVAInfo yuva_info(sk_size, ToSkYUVAPlaneConfig(format),
ToSkYUVASubsampling(format), yuv_color_space);
GrYUVABackendTextures yuva_backend_textures(yuva_info, yuva_textures.data(),
surface_origin);
return SkImage::MakeFromYUVATextures(context, yuva_backend_textures,
sk_color_space, texture_release_proc,
release_context);
}
}
sk_sp<SkImage> SkiaImageRepresentation::ScopedReadAccess::CreateSkImageForPlane(
int plane_index,
GrDirectContext* context) const {
auto format = representation()->format();
DCHECK(format.is_multi_plane());
DCHECK_EQ(static_cast<int>(promise_image_textures_.size()),
format.NumberOfPlanes());
auto surface_origin = representation()->surface_origin();
auto alpha_type = SkAlphaType::kOpaque_SkAlphaType;
auto color_type =
viz::ToClosestSkColorType(/*gpu_compositing=*/true, format, plane_index);
return SkImage::MakeFromTexture(
context, promise_image_texture(plane_index)->backendTexture(),
surface_origin, color_type, alpha_type, /*sk_color_space=*/nullptr);
}
std::unique_ptr<GrBackendSurfaceMutableState>
SkiaImageRepresentation::ScopedReadAccess::TakeEndState() {
return std::move(end_state_);
}
std::unique_ptr<SkiaImageRepresentation::ScopedReadAccess>
SkiaImageRepresentation::BeginScopedReadAccess(
std::vector<GrBackendSemaphore>* begin_semaphores,
std::vector<GrBackendSemaphore>* end_semaphores) {
if (!IsCleared()) {
auto cr = ClearedRect();
LOG(ERROR) << base::StringPrintf(
"Attempt to read from an uninitialized SharedImage. "
"Initialized region: (%d, %d, %d, %d) Size: (%d, %d)",
cr.x(), cr.y(), cr.width(), cr.height(), size().width(),
size().height());
return nullptr;
}
std::unique_ptr<GrBackendSurfaceMutableState> end_state;
std::vector<sk_sp<SkPromiseImageTexture>> promise_image_textures =
BeginReadAccess(begin_semaphores, end_semaphores, &end_state);
if (promise_image_textures.empty())
return nullptr;
backing()->OnReadSucceeded();
return std::make_unique<ScopedReadAccess>(
base::PassKey<SkiaImageRepresentation>(), this,
std::move(promise_image_textures), std::move(end_state));
}
#if BUILDFLAG(IS_ANDROID)
AHardwareBuffer* OverlayImageRepresentation::GetAHardwareBuffer() {
NOTREACHED();
return nullptr;
}
std::unique_ptr<base::android::ScopedHardwareBufferFenceSync>
OverlayImageRepresentation::GetAHardwareBufferFenceSync() {
NOTREACHED();
return nullptr;
}
#elif BUILDFLAG(IS_OZONE)
scoped_refptr<gfx::NativePixmap> OverlayImageRepresentation::GetNativePixmap() {
return backing()->GetNativePixmap();
}
#elif BUILDFLAG(IS_WIN)
absl::optional<gl::DCLayerOverlayImage>
OverlayImageRepresentation::GetDCLayerOverlayImage() {
NOTREACHED();
return absl::nullopt;
}
#elif BUILDFLAG(IS_APPLE)
gfx::ScopedIOSurface OverlayImageRepresentation::GetIOSurface() const {
return gfx::ScopedIOSurface();
}
bool OverlayImageRepresentation::IsInUseByWindowServer() const {
return false;
}
#endif
OverlayImageRepresentation::ScopedReadAccess::ScopedReadAccess(
base::PassKey<OverlayImageRepresentation> pass_key,
OverlayImageRepresentation* representation,
gfx::GpuFenceHandle acquire_fence)
: ScopedAccessBase(representation),
acquire_fence_(std::move(acquire_fence)) {}
OverlayImageRepresentation::ScopedReadAccess::~ScopedReadAccess() {
representation()->EndReadAccess(std::move(release_fence_));
}
std::unique_ptr<OverlayImageRepresentation::ScopedReadAccess>
OverlayImageRepresentation::BeginScopedReadAccess() {
if (!IsCleared()) {
LOG(ERROR) << "Attempt to read from an uninitialized SharedImage";
return nullptr;
}
gfx::GpuFenceHandle acquire_fence;
if (!BeginReadAccess(acquire_fence))
return nullptr;
backing()->OnReadSucceeded();
return std::make_unique<ScopedReadAccess>(
base::PassKey<OverlayImageRepresentation>(), this,
std::move(acquire_fence));
}
DawnImageRepresentation::ScopedAccess::ScopedAccess(
base::PassKey<DawnImageRepresentation> /* pass_key */,
DawnImageRepresentation* representation,
WGPUTexture texture)
: ScopedAccessBase(representation), texture_(texture) {}
DawnImageRepresentation::ScopedAccess::~ScopedAccess() {
representation()->EndAccess();
}
std::unique_ptr<DawnImageRepresentation::ScopedAccess>
DawnImageRepresentation::BeginScopedAccess(
WGPUTextureUsage usage,
AllowUnclearedAccess allow_uncleared) {
if (allow_uncleared != AllowUnclearedAccess::kYes && !IsCleared()) {
LOG(ERROR) << "Attempt to access an uninitialized SharedImage";
return nullptr;
}
WGPUTexture texture = BeginAccess(usage);
if (!texture)
return nullptr;
if (usage & kWriteUsage) {
backing()->OnWriteSucceeded();
} else {
backing()->OnReadSucceeded();
}
return std::make_unique<ScopedAccess>(
base::PassKey<DawnImageRepresentation>(), this, texture);
}
SharedImageRepresentationFactoryRef::~SharedImageRepresentationFactoryRef() {
backing()->UnregisterImageFactory();
backing()->MarkForDestruction();
}
VaapiImageRepresentation::VaapiImageRepresentation(
SharedImageManager* manager,
SharedImageBacking* backing,
MemoryTypeTracker* tracker,
VaapiDependencies* vaapi_deps)
: SharedImageRepresentation(manager, backing, tracker),
vaapi_deps_(vaapi_deps) {}
VaapiImageRepresentation::~VaapiImageRepresentation() = default;
VaapiImageRepresentation::ScopedWriteAccess::ScopedWriteAccess(
base::PassKey<VaapiImageRepresentation> /* pass_key */,
VaapiImageRepresentation* representation)
: ScopedAccessBase(representation) {}
VaapiImageRepresentation::ScopedWriteAccess::~ScopedWriteAccess() {
representation()->EndAccess();
}
const media::VASurface*
VaapiImageRepresentation::ScopedWriteAccess::va_surface() {
return representation()->vaapi_deps_->GetVaSurface();
}
std::unique_ptr<VaapiImageRepresentation::ScopedWriteAccess>
VaapiImageRepresentation::BeginScopedWriteAccess() {
return std::make_unique<ScopedWriteAccess>(
base::PassKey<VaapiImageRepresentation>(), this);
}
MemoryImageRepresentation::ScopedReadAccess::ScopedReadAccess(
base::PassKey<MemoryImageRepresentation> pass_key,
MemoryImageRepresentation* representation,
SkPixmap pixmap)
: ScopedAccessBase(representation), pixmap_(pixmap) {}
MemoryImageRepresentation::ScopedReadAccess::~ScopedReadAccess() = default;
std::unique_ptr<MemoryImageRepresentation::ScopedReadAccess>
MemoryImageRepresentation::BeginScopedReadAccess() {
return std::make_unique<ScopedReadAccess>(
base::PassKey<MemoryImageRepresentation>(), this, BeginReadAccess());
}
RasterImageRepresentation::ScopedReadAccess::ScopedReadAccess(
base::PassKey<RasterImageRepresentation> pass_key,
RasterImageRepresentation* representation,
const cc::PaintOpBuffer* paint_op_buffer,
const absl::optional<SkColor4f>& clear_color)
: ScopedAccessBase(representation),
paint_op_buffer_(paint_op_buffer),
clear_color_(clear_color) {}
RasterImageRepresentation::ScopedReadAccess::~ScopedReadAccess() {
representation()->EndReadAccess();
}
RasterImageRepresentation::ScopedWriteAccess::ScopedWriteAccess(
base::PassKey<RasterImageRepresentation> pass_key,
RasterImageRepresentation* representation,
cc::PaintOpBuffer* paint_op_buffer)
: ScopedAccessBase(representation), paint_op_buffer_(paint_op_buffer) {}
RasterImageRepresentation::ScopedWriteAccess::~ScopedWriteAccess() {
representation()->EndWriteAccess(std::move(callback_));
}
std::unique_ptr<RasterImageRepresentation::ScopedReadAccess>
RasterImageRepresentation::BeginScopedReadAccess() {
absl::optional<SkColor4f> clear_color;
auto* paint_op_buffer = BeginReadAccess(clear_color);
if (!paint_op_buffer)
return nullptr;
return std::make_unique<ScopedReadAccess>(
base::PassKey<RasterImageRepresentation>(), this, paint_op_buffer,
clear_color);
}
std::unique_ptr<RasterImageRepresentation::ScopedWriteAccess>
RasterImageRepresentation::BeginScopedWriteAccess(
scoped_refptr<SharedContextState> context_state,
int final_msaa_count,
const SkSurfaceProps& surface_props,
const absl::optional<SkColor4f>& clear_color,
bool visible) {
return std::make_unique<ScopedWriteAccess>(
base::PassKey<RasterImageRepresentation>(), this,
BeginWriteAccess(std::move(context_state), final_msaa_count,
surface_props, clear_color, visible));
}
VideoDecodeImageRepresentation::VideoDecodeImageRepresentation(
SharedImageManager* manager,
SharedImageBacking* backing,
MemoryTypeTracker* tracker)
: SharedImageRepresentation(manager, backing, tracker) {}
VideoDecodeImageRepresentation::~VideoDecodeImageRepresentation() = default;
VideoDecodeImageRepresentation::ScopedWriteAccess::ScopedWriteAccess(
base::PassKey<VideoDecodeImageRepresentation> /* pass_key */,
VideoDecodeImageRepresentation* representation)
: ScopedAccessBase(representation) {}
VideoDecodeImageRepresentation::ScopedWriteAccess::~ScopedWriteAccess() {
representation()->EndWriteAccess();
}
std::unique_ptr<VideoDecodeImageRepresentation::ScopedWriteAccess>
VideoDecodeImageRepresentation::BeginScopedWriteAccess() {
if (!BeginWriteAccess())
return nullptr;
return std::make_unique<ScopedWriteAccess>(
base::PassKey<VideoDecodeImageRepresentation>(), this);
}
} // namespace gpu
| [
"[email protected]"
] | |
a9343e1d502025e7c4c12918366a85ef3215d5cf | 4b32cbc767e8cc0d61e7771b8a6d5c7c9b324a97 | /C++/10866(덱).cpp | 471bc0e4b2a95e2ae8847c808732e0f5b2b2e275 | [] | no_license | Jongminfire/Baekjoon | 45e554c983fa583ca7a1709e1ac435e1a38e075b | 8dc0ec58ddc43de2dd44b3b1af9346f708c1208e | refs/heads/master | 2023-07-29T10:35:52.648825 | 2021-09-14T15:12:22 | 2021-09-14T15:12:22 | 247,514,920 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 2,314 | cpp | //#include <iostream>
//#include <deque>
//#include <string>
//
//using namespace std;
//
//int main()
//{
// cin.tie(nullptr);
// ios_base::sync_with_stdio(false);
//
// int N;
// cin >> N;
//
// deque<int> dq;
//
// for (int i = 0;i < N;i++)
// {
// string s;
// int num;
// cin >> s;
//
// if (s == "push_front")
// {
// cin >> num;
// dq.push_front(num);
// }
// else if (s == "push_back")
// {
// cin >> num;
// dq.push_back(num);
// }
// else if (s == "pop_front")
// {
// if (dq.empty())
// cout << "-1\n";
// else
// {
// cout << dq.front() << "\n";
// dq.pop_front();
// }
// }
// else if (s == "pop_back")
// {
// if (dq.empty())
// cout << "-1\n";
// else
// {
// cout << dq.back() << "\n";
// dq.pop_back();
// }
// }
// else if (s == "size")
// {
// cout << dq.size() << "\n";
// }
// else if (s == "empty")
// {
// if (dq.empty())
// cout << "1\n";
// else
// cout << "0\n";
// }
// else if (s == "front")
// {
// if (dq.empty())
// cout << "-1\n";
// else
// cout << dq.front() << "\n";
// }
// else if (s == "back")
// {
// if (dq.empty())
// cout << "-1\n";
// else
// cout << dq.back() << "\n";
// }
// }
//
// return 0;
//}
//
///*
//
//정수를 저장하는 덱(Deque)를 구현한 다음, 입력으로 주어지는 명령을 처리하는 프로그램을 작성하시오.
//
//명령은 총 여덟 가지이다.
//
//push_front X: 정수 X를 덱의 앞에 넣는다.
//push_back X: 정수 X를 덱의 뒤에 넣는다.
//pop_front: 덱의 가장 앞에 있는 수를 빼고, 그 수를 출력한다. 만약, 덱에 들어있는 정수가 없는 경우에는 -1을 출력한다.
//pop_back: 덱의 가장 뒤에 있는 수를 빼고, 그 수를 출력한다. 만약, 덱에 들어있는 정수가 없는 경우에는 -1을 출력한다.
//size: 덱에 들어있는 정수의 개수를 출력한다.
//empty: 덱이 비어있으면 1을, 아니면 0을 출력한다.
//front: 덱의 가장 앞에 있는 정수를 출력한다. 만약 덱에 들어있는 정수가 없는 경우에는 -1을 출력한다.
//back: 덱의 가장 뒤에 있는 정수를 출력한다. 만약 덱에 들어있는 정수가 없는 경우에는 -1을 출력한다.
//
//https://www.acmicpc.net/problem/10866
//
//*/ | [
"[email protected]"
] | |
6521523e750ec55233533065a28eb7b5518b76f3 | 3ef746945fd6978890de874541cd11b8f8aa10f6 | /game/Tile.h | fc67fb7ed80e95248770f2b2449021ec7bb1b719 | [] | no_license | ashehata/PA3 | 142ea333aefe126c8ce9e2ca87bfdac2de700421 | 4b544697ac502a85a0d99075b3d552c43bffa83e | refs/heads/master | 2021-01-22T00:59:08.678364 | 2014-04-30T06:04:14 | 2014-04-30T06:04:14 | 19,096,120 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 380 | h | //
// Tile.h
// pa1.2
//
// Created by Aly Shehata on 3/15/14.
// Copyright (c) 2014 Aly Shehata. All rights reserved.
//
#ifndef pa1_2_Tile_h
#define pa1_2_Tile_h
class Tile
{
public:
Tile ();
Tile (char tileChar);
void setDisplayChar(char tileChar);
char getDisplayChar();
private:
char myChar;
};
#endif
| [
"[email protected]"
] | |
b671ec39f8610a386a5db7cdf1c0fb03157db290 | 55903a9564931b4579e5c5030376f0989d15b00e | /P2pNet/ace/Module.h | 638a2a335db7184c53781c323061d61b885ada8d | [] | no_license | zhenyouluo/liveshow_r2 | 04b391fd9ba4e809a88aa1e4eed1477ac4e9ef88 | 300441c14ed31cfa10ec0459bac5a67693f592ea | refs/heads/master | 2020-12-26T00:35:26.403288 | 2012-09-10T02:28:22 | 2012-09-10T02:28:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,572 | h | // -*- C++ -*-
//==========================================================================
/**
* @file Module.h
*
* $Id: Module.h 77152 2007-02-15 13:41:25Z johnnyw $
*
* @author Douglas C. Schmidt <[email protected]>
*/
//==========================================================================
#ifndef ACE_MODULE_H
#define ACE_MODULE_H
#include /**/ "ace/pre.h"
#include /**/ "ace/ACE_export.h"
#if !defined (ACE_LACKS_PRAGMA_ONCE)
# pragma once
#endif /* ACE_LACKS_PRAGMA_ONCE */
#include "ace/Task_T.h"
#include "ace/os_include/os_dirent.h"
ACE_BEGIN_VERSIONED_NAMESPACE_DECL
/**
* @class ACE_Module_Base
*
* @brief Workaround HP/C++ compiler bug with enums in templates.
*
* Certain C++ compilers, e.g., the HP/UX 10.x and 9.x compilers,
* seem to fail if enums are defined inside a template, hence we
* have to move them into a base class.
*/
class ACE_Export ACE_Module_Base
{
public:
enum
{
/// Indicates that the flags have not been set
M_FLAGS_NOT_SET = 0,
/// Indicates that <close> should delete the writer Task.
M_DELETE_READER = 1,
/// Indicates that <close> should delete the reader Task.
M_DELETE_WRITER = 2,
/// Indicates that <close> deletes the Tasks.
/**
* Don't change this value without updating the same enum in class
* ACE_Stream...
* The <M_DELETE_READER> and <M_DELETE_WRITER> flags may be or'ed
* together.
*/
M_DELETE = 3,
/// Indicates that <close> should not delete any Tasks.
M_DELETE_NONE = 4
};
};
/**
* @class ACE_Module
*
* @brief An abstraction for managing a bi-directional flow of messages.
*
* This is based on the Module concept in System V Streams,
* which contains a pair of Tasks, one for handling upstream
* processing, one for handling downstream processing. In
* general, you shouldn't subclass from this class, but instead
* subclass from the ACE_Task.
*/
template <ACE_SYNCH_DECL>
class ACE_Module : public ACE_Module_Base
{
public:
// = Initialization and termination methods.
/// Create an empty Module.
ACE_Module (void);
/// Shutdown the Module.
virtual ~ACE_Module (void);
/// Create an initialized module with @a module_name as its identity
/// and @a reader and @a writer as its tasks.
ACE_Module (const ACE_TCHAR *module_name,
ACE_Task<ACE_SYNCH_USE> *writer = 0,
ACE_Task<ACE_SYNCH_USE> *reader = 0,
void *args = 0,
int flags = M_DELETE);
/**
* Initialize the module with <module_name> as its identity
* and <reader> and <writer> as its tasks. Previously register
* reader or writers or closed down and deleted according to the
* value of flags_. Should not be called from within
* <ACE_Task::module_closed>.
*/
int open (const ACE_TCHAR *module_name,
ACE_Task<ACE_SYNCH_USE> *writer = 0,
ACE_Task<ACE_SYNCH_USE> *reader = 0,
void *a = 0,
int flags = M_DELETE);
/**
* Close down the module and its tasks. The flags argument can be
* used to override the default behaviour, which depends on previous
* <flags> values in calls to c'tor, <open>, <reader>, and <writer>.
* A previous value M_DELETE[_XXX] can not be overridden. Should
* not be called from within <ACE_Task::module_closed>.
*/
int close (int flags = M_DELETE_NONE);
// = ACE_Task manipulation routines
/// Get the writer task.
ACE_Task<ACE_SYNCH_USE> *writer (void);
/**
* Set the writer task. @a flags can be used to indicate that the
* module should delete the writer during a call to close or to the
* destructor. If a previous writer exists, it is closed. It may
* also be deleted, depending on the old flags_ value. Should not
* be called from within <ACE_Task::module_closed>.
*/
void writer (ACE_Task<ACE_SYNCH_USE> *q, int flags = M_DELETE_WRITER);
/// Get the reader task.
ACE_Task<ACE_SYNCH_USE> *reader (void);
/**
* Set the reader task. @a flags can be used to indicate that the
* module should delete the reader during a call to close or to the
* destructor. If a previous reader exists, it is closed. It may
* also be deleted, depending on the old flags_ value. Should not
* be called from within <ACE_Task::module_closed>.
*/
void reader (ACE_Task<ACE_SYNCH_USE> *q, int flags = M_DELETE_READER);
/// Set and get pointer to sibling ACE_Task in an ACE_Module
ACE_Task<ACE_SYNCH_USE> *sibling (ACE_Task<ACE_SYNCH_USE> *orig);
// = Identify the module
/// Get the module name.
const ACE_TCHAR *name (void) const;
/// Set the module name.
void name (const ACE_TCHAR *);
// = Argument to the Tasks.
/// Get the argument passed to the tasks.
void *arg (void) const;
/// Set the argument passed to the tasks.
void arg (void *);
/// Link to other modules in the ustream stack
void link (ACE_Module<ACE_SYNCH_USE> *m);
/// Get the next pointer to the module above in the stream.
ACE_Module<ACE_SYNCH_USE> *next (void);
/// Set the next pointer to the module above in the stream.
void next (ACE_Module<ACE_SYNCH_USE> *m);
/// Dump the state of an object.
void dump (void) const;
/// Declare the dynamic allocation hooks.
ACE_ALLOC_HOOK_DECLARE;
private:
/// Implements the close operation for either the reader or the
/// writer task (depending on <which>).
int close_i (int which, int flags);
/// Pair of Tasks that form the "read-side" and "write-side" of the
/// ACE_Module partitioning.
ACE_Task<ACE_SYNCH_USE> *q_pair_[2];
/// Name of the ACE_Module.
ACE_TCHAR name_[MAXPATHLEN + 1];
/// Next ACE_Module in the stack.
ACE_Module<ACE_SYNCH_USE> *next_;
/// Argument passed through to the reader and writer task when they
/// are opened.
void *arg_;
/// Holds flags which are used to determine if the reader and writer
/// task have to be deleted on exit
int flags_;
};
ACE_END_VERSIONED_NAMESPACE_DECL
#if defined (__ACE_INLINE__)
#include "ace/Module.inl"
#endif /* __ACE_INLINE__ */
#if defined (ACE_TEMPLATES_REQUIRE_SOURCE)
#include "ace/Module.cpp"
#endif /* ACE_TEMPLATES_REQUIRE_SOURCE */
#if defined (ACE_TEMPLATES_REQUIRE_PRAGMA)
#pragma implementation ("Module.cpp")
#endif /* ACE_TEMPLATES_REQUIRE_PRAGMA */
#include /**/ "ace/post.h"
#endif /* ACE_MODULE_H */
| [
"[email protected]"
] | |
f9ff0d0c429ddf526302945e38d2e5050b9b46ec | cdb55dbdd700a3f456bc67775374dd2a5f99f049 | /AIEngine/src/input/AIWorld.cpp | cf42349816a2ab6af6d07535eabd2a3eed778bcf | [
"MIT"
] | permissive | wangscript007/urchinEngine | 1bfd6fb9ae6ed30154d29b082856101b9a8ef202 | 88f5f70d319299e2df6c006cdeabd6bfb622437b | refs/heads/master | 2022-12-30T18:06:53.231268 | 2020-10-07T19:03:56 | 2020-10-07T19:03:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,129 | cpp | #include <algorithm>
#include "AIWorld.h"
namespace urchin
{
AIWorld::AIWorld()
{
entities.reserve(50); //estimated memory size
}
void AIWorld::addEntity(const std::shared_ptr<AIEntity> &aiEntity)
{
std::lock_guard<std::mutex> lock(mutex);
entities.push_back(aiEntity);
}
void AIWorld::removeEntity(const std::shared_ptr<AIEntity> &aiEntity)
{
std::lock_guard<std::mutex> lock(mutex);
entitiesToRemove.push_back(aiEntity);
}
std::vector<std::shared_ptr<AIEntity>> AIWorld::getEntities() const
{
std::lock_guard<std::mutex> lock(mutex);
return entities;
}
std::vector<std::shared_ptr<AIEntity>> AIWorld::getEntitiesToRemoveAndReset()
{
std::lock_guard<std::mutex> lock(mutex);
std::vector<std::shared_ptr<AIEntity>> result = entitiesToRemove;
for(const auto &objectToRemove : entitiesToRemove)
{
entities.erase(std::remove(entities.begin(), entities.end(), objectToRemove), entities.end());
}
entitiesToRemove.clear();
return result;
}
}
| [
"[email protected]"
] | |
1ffa11fc9cadd88bdc480aac014ec5f006f4fc81 | 05c4046a62047d8274cf68082e36cc754d225c0b | /inc/texture_manager.hpp | c3f9591fc42d3f586e94bbb134d8aa9dea9ee560 | [] | no_license | Eremiell/ld40 | d7f7d9b651698402d40b2d9ba027d5405595d4f2 | a83ba62d4fc221c7a34135cd60f9bd864846b53d | refs/heads/master | 2021-08-31T01:06:39.208233 | 2017-12-20T02:43:29 | 2017-12-20T02:43:29 | 112,795,407 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 834 | hpp | #pragma once
#ifndef TEXTURE_MANAGER_HPP
#define TEXTURE_MANAGER_HPP
#include <unordered_map>
#include <string>
#include <memory>
#include <utility>
#include <string_view>
#ifndef _WIN32
#include <experimental/filesystem>
#endif
#include <SFML/Graphics/Texture.hpp>
#include <SFML/Graphics/Rect.hpp>
namespace ld40 {
class TextureManager {
public:
void load_sheet(std::string sheet);
std::pair<const sf::Texture*, sf::Rect<int>> get_texture(std::string texture) const;
private:
std::unordered_map<std::string, std::unique_ptr<sf::Texture>> sheets;
std::unordered_map<std::string, std::pair<const sf::Texture*, sf::Rect<int>>> textures;
#ifndef _WIN32
std::experimental::filesystem::path get_full_path(std::string_view filename);
#else
std::string get_full_path(std::string_view filename);
#endif
};
}
#endif | [
"[email protected]"
] | |
74cad76007b43b7f63b4f1b80595ecb9ba03a0d6 | dffd5d8466b51e0f3019b93042166cd96eef23b1 | /poo/carte-main5/Date.hxx | cbf065cab47d1f7bfa113eef722093c1ce1abbaa | [] | no_license | maxux/inpres-2eme | 72dcc30dc17ce77c78484f9a302ef7a98717d655 | 3a33b9822d20458996ca87ddf458895e820c88e3 | refs/heads/master | 2021-01-02T09:32:45.395891 | 2015-03-11T23:01:47 | 2015-03-11T23:01:47 | 32,045,819 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 491 | hxx | #ifndef __DATE_HEADER_H
#define __DATE_HEADER_H
using namespace std;
class Date {
public:
Date();
Date(Date &original);
Date(char *date);
virtual ~Date();
/* Setters */
void setDate(const char *date);
/* Getters */
const char * getDate() const;
unsigned short getDay();
unsigned short getMonth();
unsigned short getYear();
private:
unsigned short _day;
unsigned short _month;
unsigned short _year;
char *_to_char;
};
#endif
| [
"[email protected]"
] | |
b0546c564dbd1b97157500284cbac5f5f0358b17 | c42ecbc5bb6bc33acc9833b738996e537d092041 | /pothos-serialization/include/Pothos/serialization/impl/function/function8.hpp | 652b2b7017f38a4820e437b104bdcfa96711be3f | [
"BSL-1.0"
] | permissive | lrmodesgh/pothos | abd652bc9b880139fa9fb2016b88cb21e0be1f0a | 542c6cd19e1aa2ee1fda47fbc131431ed351ae31 | refs/heads/master | 2020-12-26T02:10:22.037019 | 2015-07-13T08:28:57 | 2015-07-13T08:28:57 | 39,064,513 | 1 | 0 | null | 2015-07-14T08:56:33 | 2015-07-14T08:56:33 | null | UTF-8 | C++ | false | false | 459 | hpp | // Boost.Function library
// Copyright Douglas Gregor 2002-2003. Use, modification and
// distribution is subject to the Boost Software License, Version
// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// For more information, see http://www.boost.org
#define POTHOS_FUNCTION_NUM_ARGS 8
#include <Pothos/serialization/impl/function/detail/maybe_include.hpp>
#undef POTHOS_FUNCTION_NUM_ARGS
| [
"[email protected]"
] | |
39f267e93f5b4f7d9d34bf95f9d33b45559182b4 | ed27c2e31ec84826b3b66d2b3c159fb17ca3fbbf | /Advanced shaders/NormalMapping/Shader.cpp | 9572b579a72d7a78c9b31fd99925ae57b11c6d74 | [] | no_license | LiliVeszeli/Graphics | 69c3f8b5266b554039fc34ba262d4f2f545d28e1 | a079675849959a3278bad36851ac8bc7c49f08cd | refs/heads/master | 2022-05-30T22:49:12.800976 | 2020-05-03T10:36:20 | 2020-05-03T10:36:20 | 212,877,051 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,314 | cpp | //--------------------------------------------------------------------------------------
// Loading GPU shaders
// Creation of constant buffers to help send C++ values to shaders each frame
//--------------------------------------------------------------------------------------
#include "Shader.h"
#include <fstream>
#include <vector>
#include <d3dcompiler.h>
//--------------------------------------------------------------------------------------
// Global Variables
//--------------------------------------------------------------------------------------
// Globals used to keep code simpler, but try to architect your own code in a better way
//**** Update Shader.h if you add things here ****//
// Vertex and pixel shader DirectX objects
ID3D11VertexShader* gNormalMappingVertexShader = nullptr;
ID3D11PixelShader* gNormalMappingPixelShader = nullptr;
ID3D11VertexShader* gLightModelVertexShader = nullptr;
ID3D11PixelShader* gLightModelPixelShader = nullptr;
//--------------------------------------------------------------------------------------
// Shader creation / destruction
//--------------------------------------------------------------------------------------
// Load shaders required for this app, returns true on success
bool LoadShaders()
{
// Shaders must be added to the Visual Studio project to be compiled, they use the extension ".hlsl".
// To load them for use, include them here without the extension. Use the correct function for each.
// Ensure you release the shaders in the ShutdownDirect3D function below
gNormalMappingVertexShader = LoadVertexShader("NormalMapping_vs"); // Note how the shader files are named to show what type they are
gNormalMappingPixelShader = LoadPixelShader ("NormalMapping_ps");
gLightModelVertexShader = LoadVertexShader("TransformOnly_vs");
gLightModelPixelShader = LoadPixelShader ("TextureColour_ps");
if (gNormalMappingVertexShader == nullptr || gNormalMappingPixelShader == nullptr ||
gLightModelVertexShader == nullptr || gLightModelPixelShader == nullptr)
{
gLastError = "Error loading shaders";
return false;
}
return true;
}
void ReleaseShaders()
{
if (gLightModelVertexShader) gLightModelVertexShader->Release();
if (gLightModelPixelShader) gLightModelPixelShader->Release();
if (gNormalMappingVertexShader) gNormalMappingVertexShader->Release();
if (gNormalMappingPixelShader) gNormalMappingPixelShader->Release();
}
// Load a vertex shader, include the file in the project and pass the name (without the .hlsl extension)
// to this function. The returned pointer needs to be released before quitting. Returns nullptr on failure.
ID3D11VertexShader* LoadVertexShader(std::string shaderName)
{
// Open compiled shader object file
std::ifstream shaderFile(shaderName + ".cso", std::ios::in | std::ios::binary | std::ios::ate);
if (!shaderFile.is_open())
{
return nullptr;
}
// Read file into vector of chars
std::streamoff fileSize = shaderFile.tellg();
shaderFile.seekg(0, std::ios::beg);
std::vector<char> byteCode(fileSize);
shaderFile.read(&byteCode[0], fileSize);
if (shaderFile.fail())
{
return nullptr;
}
// Create shader object from loaded file (we will use the object later when rendering)
ID3D11VertexShader* shader;
HRESULT hr = gD3DDevice->CreateVertexShader(byteCode.data(), byteCode.size(), nullptr, &shader);
if (FAILED(hr))
{
return nullptr;
}
return shader;
}
// Load a pixel shader, include the file in the project and pass the name (without the .hlsl extension)
// to this function. The returned pointer needs to be released before quitting. Returns nullptr on failure.
// Basically the same code as above but for pixel shaders
ID3D11PixelShader* LoadPixelShader(std::string shaderName)
{
// Open compiled shader object file
std::ifstream shaderFile(shaderName + ".cso", std::ios::in | std::ios::binary | std::ios::ate);
if (!shaderFile.is_open())
{
return nullptr;
}
// Read file into vector of chars
std::streamoff fileSize = shaderFile.tellg();
shaderFile.seekg(0, std::ios::beg);
std::vector<char>byteCode(fileSize);
shaderFile.read(&byteCode[0], fileSize);
if (shaderFile.fail())
{
return nullptr;
}
// Create shader object from loaded file (we will use the object later when rendering)
ID3D11PixelShader* shader;
HRESULT hr = gD3DDevice->CreatePixelShader(byteCode.data(), byteCode.size(), nullptr, &shader);
if (FAILED(hr))
{
return nullptr;
}
return shader;
}
// Very advanced topic: When creating a vertex layout for geometry (see Scene.cpp), you need the signature
// (bytecode) of a shader that uses that vertex layout. This is an annoying requirement and tends to create
// unnecessary coupling between shaders and vertex buffers.
// This is a trick to simplify things - pass a vertex layout to this function and it will write and compile
// a temporary shader to match. You don't need to know about the actual shaders in use in the app.
// Release the signature (called a ID3DBlob!) after use. Returns nullptr on failure.
ID3DBlob* CreateSignatureForVertexLayout(const D3D11_INPUT_ELEMENT_DESC vertexLayout[], int numElements)
{
std::string shaderSource = "float4 main(";
for (int elt = 0; elt < numElements; ++elt)
{
auto& format = vertexLayout[elt].Format;
// This list should be more complete for production use
if (format == DXGI_FORMAT_R32G32B32A32_FLOAT) shaderSource += "float4";
else if (format == DXGI_FORMAT_R32G32B32_FLOAT) shaderSource += "float3";
else if (format == DXGI_FORMAT_R32G32_FLOAT) shaderSource += "float2";
else if (format == DXGI_FORMAT_R32_FLOAT) shaderSource += "float";
else return nullptr; // Unsupported type in layout
uint8_t index = static_cast<uint8_t>(vertexLayout[elt].SemanticIndex);
std::string semanticName = vertexLayout[elt].SemanticName;
semanticName += ('0' + index);
shaderSource += " ";
shaderSource += semanticName;
shaderSource += " : ";
shaderSource += semanticName;
if (elt != numElements - 1) shaderSource += " , ";
}
shaderSource += ") : SV_Position {return 0;}";
ID3DBlob* compiledShader;
HRESULT hr = D3DCompile(shaderSource.c_str(), shaderSource.length(), NULL, NULL, NULL, "main",
"vs_5_0", D3DCOMPILE_OPTIMIZATION_LEVEL0, 0, &compiledShader, NULL);
if (FAILED(hr))
{
return nullptr;
}
return compiledShader;
}
//--------------------------------------------------------------------------------------
// Constant buffer creation / destruction
//--------------------------------------------------------------------------------------
// Constant Buffers are a way of passing data from C++ to the GPU. They are called constants but that only means
// they are constant for the duration of a single GPU draw call. The "constants" correspond to variables in C++
// that we will change per-model, or per-frame etc.
//
// We typically set up a C++ structure to exactly match the values we need in a shader and then create a constant
// buffer the same size as the structure. That makes updating values from C++ to shader easy - see the main code.
// Create and return a constant buffer of the given size
// The returned pointer needs to be released before quitting. Returns nullptr on failure.
ID3D11Buffer* CreateConstantBuffer(int size)
{
D3D11_BUFFER_DESC cbDesc;
cbDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
cbDesc.ByteWidth = 16 * ((size + 15) / 16); // Constant buffer size must be a multiple of 16 - this maths rounds up to the nearest multiple
cbDesc.Usage = D3D11_USAGE_DYNAMIC; // Indicates that the buffer is frequently updated
cbDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; // CPU is only going to write to the constants (not read them)
cbDesc.MiscFlags = 0;
ID3D11Buffer* constantBuffer;
HRESULT hr = gD3DDevice->CreateBuffer(&cbDesc, nullptr, &constantBuffer);
if (FAILED(hr))
{
return nullptr;
}
return constantBuffer;
}
| [
"[email protected]"
] | |
98f3d47e34dec9f039760824988261e9b35701ca | b09a2217f08bbb5fb57bdc584912ccfdf436f2c0 | /include/Line.h | 2ebe935a476887b1b183bc3ff6bb94d10461bb08 | [] | no_license | MoraxAlvizo/ProyectoCC312 | 62c6d44d5db64836ad9d46e28072f6869e890612 | 489f3f78cc9202454a4108f736fa94771a64fd17 | refs/heads/master | 2016-09-01T17:37:04.050998 | 2013-05-26T21:15:02 | 2013-05-26T21:15:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 478 | h | #ifndef LINE_H
#define LINE_H
#include <GL/gl.h>
#include <GL/glu.h>
#include <iostream>
#include <cmath>
#include "Point.h"
class Line
{
public:
Line();
Line(Point i, Point f);
virtual ~Line();
/** Metodos **/
void exchangePoints();
void drawLine();
protected:
/** Atributos **/
Point i;
Point f;
GLfloat m;
private:
int signo(int);
};
#endif // LINE_H
| [
"[email protected]"
] | |
3b6bd9a3d086c1b8b3c70c83f178bd5efb751343 | 244b4eb938d3757469c4795dab375558cd915ad7 | /src/common/net/RDMAWriteImmSocket.cpp | e10d22d2b5a6b75a32666fdc7e0ff6eaecbc424c | [] | no_license | nao23/ramp-with-rdma | b5fef0fdcce33efff29e22ec130df760c761a7b7 | 6e2ca73063466887c97bb21953d6711273ec39b3 | refs/heads/master | 2021-01-01T03:46:59.067131 | 2016-12-12T03:36:37 | 2016-12-12T03:36:37 | 58,362,122 | 5 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,022 | cpp | #include "RDMAWriteImmSocket.h"
RDMAWriteImmSocket* RDMAWriteImmSocket::connect(const HostAndPort& hp) {
struct rdma_cm_id* client_id = NULL;
struct rdma_addrinfo hints, *res;
memset(&hints, 0, sizeof(hints));
hints.ai_port_space = RDMA_PS_TCP;
res = NULL;
char* hostname = const_cast<char*>(hp.hostname);
char* port_str = const_cast<char*>(hp.port_str);
if (rdma_getaddrinfo(hostname, port_str, &hints, &res) < 0) {
class_logger->error("rdma_getaddrinfo: {}", strerror(errno));
exit(EXIT_FAILURE);
}
struct ibv_qp_init_attr attr;
memset(&attr, 0, sizeof(attr));
attr.cap.max_send_wr = PACKET_WINDOW_SIZE;
attr.cap.max_recv_wr = PACKET_WINDOW_SIZE;
attr.cap.max_send_sge = 1;
attr.cap.max_recv_sge = 1;
attr.cap.max_inline_data = 0;
attr.sq_sig_all = 1;
if (rdma_create_ep(&client_id, res, NULL, &attr) < 0) {
class_logger->error("rdma_create_ep: {}", strerror(errno));
rdma_freeaddrinfo(res);
exit(EXIT_FAILURE);
}
rdma_freeaddrinfo(res);
if (rdma_connect(client_id, NULL) < 0) {
class_logger->error("rdma_connect: {}", strerror(errno));
rdma_destroy_ep(client_id);
exit(EXIT_FAILURE);
}
return new RDMAWriteImmSocket(client_id);
}
void RDMAWriteImmSocket::post_write_imm(const Buffer& buf, const RemoteKeyAndAddr& rka) {
if (rdma_post_write_imm(this->client_id, buf.addr, buf.addr, buf.size, this->verbs_mr, 0, rka.remote_addr, rka.rkey) < 0) {
this->logger->error("rdma_post_write_imm: {}", strerror(errno));
exit(EXIT_FAILURE);
}
}
void RDMAWriteImmSocket::send_msg(MessageHeader header, char* body) {
Buffer send_buf = this->get_send_buf();
int is_arrived = 0xffffffff;
send_buf.append(header).append(body, header.body_size).append(is_arrived);
this->post_write_imm(send_buf, this->rka);
}
void RDMAWriteImmSocket::recv_header(MessageHeader* header) {
this->msg_buf = this->get_recv_buf();
this->write_buf.read(header);
}
char* RDMAWriteImmSocket::get_body(size_t body_size) {
return (this->write_buf.addr + sizeof(MessageHeader));
}
void RDMAWriteImmSocket::clear_msg_buf() {
this->write_buf.clear();
this->post_recv(this->msg_buf);
}
void RDMAWriteImmSocket::send_close() {
Buffer send_buf = this->get_send_buf();
// clear send cq
struct ibv_wc wc[PACKET_WINDOW_SIZE];
int ret;
ret = ibv_poll_cq(this->client_id->send_cq, PACKET_WINDOW_SIZE, wc);
if (ret < 0) {
this->logger->error("ibv_poll_cq: {}", strerror(errno));
exit(EXIT_FAILURE);
}
// send close msg
MessageHeader header(MessageType::CLOSE, 0);
int is_arrived = 0xffffffff;
send_buf.append(header).append(is_arrived);
this->post_write_imm(send_buf, this->rka);
// check send
struct ibv_wc close_wc;
this->poll_send_cq(1, &close_wc);
}
std::shared_ptr<spdlog::logger> RDMAWriteImmSocket::class_logger = spdlog::stdout_logger_mt("RDMAWriteImmSocket", true);
| [
"[email protected]"
] | |
5b91c9444a25410b8c96d7d7c6193d6130b5503d | 0577b2cf606125f05a41b199ba70d0f56c2c3fdc | /histogramwidget.cpp | 7f8c72024e9bef4e773b1f905ca5cf9e1ae600a8 | [] | no_license | lanceleefeng/TasteSongPlayerExplore | b0c4bb697a5ffa0d2ad268e56ad3676ed8097b77 | 4bedb8b16bf8fc4e7f0b39d24ad1bd328c9bfc44 | refs/heads/master | 2021-01-23T00:15:34.938328 | 2017-03-21T14:21:29 | 2017-03-21T14:21:29 | 85,711,259 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 74 | cpp | #include "histogramwidget.h"
histogramwidget::histogramwidget()
{
}
| [
"[email protected]"
] | |
14168fda550dcf05e875d2dbb6888152babf75a5 | f712a65139113f637a0d854989ed2f931c02d79d | /P3/Carreres-Pablo-2305/carroceria.cpp | 0d58ed15d5d35ecad22afd4dc0fba19128994124 | [] | no_license | alsolanes/Carreres | 865679de291fb69c116574a2df4ab65106514eb8 | bad09aa608425e1a0745860f36c85ae34e16c36e | refs/heads/master | 2021-01-10T14:30:09.671738 | 2014-05-28T07:53:39 | 2014-05-28T07:53:39 | 17,371,003 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 410 | cpp | #include "carroceria.h"
Carroceria::Carroceria(int numVertex) : Objecte(numVertex)
{
this->material = new Material();
this->material->coef_a = 0.4;
this->material->ka = vec3(0.24725, 0.1995, 0.0745);
this->material->ks = vec3(0.628281, 0.555802, 0.366065);
this->material->kd = vec3(0.75164, 0.60648, 0.22648);
this->xRot = 0;
this->yRot = 0;
this->zRot = 0;
}
| [
"[email protected]"
] | |
2793099e44f615fc01bb80b2a28af2c55e88a671 | d0fb46aecc3b69983e7f6244331a81dff42d9595 | /elasticsearch/src/model/InstallSystemPluginRequest.cc | d6d68f6b6cc6efe1df55cb0faf046d18a97c4f33 | [
"Apache-2.0"
] | permissive | aliyun/aliyun-openapi-cpp-sdk | 3d8d051d44ad00753a429817dd03957614c0c66a | e862bd03c844bcb7ccaa90571bceaa2802c7f135 | refs/heads/master | 2023-08-29T11:54:00.525102 | 2023-08-29T03:32:48 | 2023-08-29T03:32:48 | 115,379,460 | 104 | 82 | NOASSERTION | 2023-09-14T06:13:33 | 2017-12-26T02:53:27 | C++ | UTF-8 | C++ | false | false | 1,841 | cc | /*
* Copyright 2009-2017 Alibaba Cloud 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.
*/
#include <alibabacloud/elasticsearch/model/InstallSystemPluginRequest.h>
using AlibabaCloud::Elasticsearch::Model::InstallSystemPluginRequest;
InstallSystemPluginRequest::InstallSystemPluginRequest()
: RoaServiceRequest("elasticsearch", "2017-06-13") {
setResourcePath("/openapi/instances/[InstanceId]/plugins/system/actions/install"};
setMethod(HttpRequest::Method::Post);
}
InstallSystemPluginRequest::~InstallSystemPluginRequest() {}
string InstallSystemPluginRequest::getInstanceId() const {
return instanceId_;
}
void InstallSystemPluginRequest::setInstanceId(string instanceId) {
instanceId_ = instanceId;
setParameter(std::string("InstanceId"), std::to_string(instanceId));
}
string InstallSystemPluginRequest::getClientToken() const {
return clientToken_;
}
void InstallSystemPluginRequest::setClientToken(string clientToken) {
clientToken_ = clientToken;
setParameter(std::string("clientToken"), std::to_string(clientToken));
}
string InstallSystemPluginRequest::getBody() const {
return body_;
}
void InstallSystemPluginRequest::setBody(string body) {
body_ = body;
setBodyParameter(std::string("body"), std::to_string(body));
}
| [
"[email protected]"
] | |
b3eff67382bdaba8c0f2a40ad3c04daa847e4347 | 297497957c531d81ba286bc91253fbbb78b4d8be | /third_party/highway/hwy/tests/demote_test.cc | 55c9ba0b44462a57203aa92ee725058706e7611a | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | 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 | 18,840 | cc |
#include <algorithm>
#include <cmath>
#undef HWY_TARGET_INCLUDE
#define HWY_TARGET_INCLUDE "tests/demote_test.cc"
#include "hwy/foreach_target.h"
#include "hwy/highway.h"
#include "hwy/tests/test_util-inl.h"
#if !HWY_IS_MSAN
HWY_BEFORE_NAMESPACE();
namespace hwy {
namespace HWY_NAMESPACE {
template <typename T, HWY_IF_FLOAT(T)>
bool IsFiniteT(T t) {
return std::isfinite(t);
}
template <typename T, HWY_IF_NOT_FLOAT(T)>
bool IsFiniteT(T ) {
return true;
}
template <typename ToT>
struct TestDemoteTo {
template <typename T, class D>
HWY_NOINLINE void operator()(T , D from_d) {
static_assert(!IsFloat<ToT>(), "Use TestDemoteToFloat for float output");
static_assert(sizeof(T) > sizeof(ToT), "Input type must be wider");
const Rebind<ToT, D> to_d;
const size_t N = Lanes(from_d);
auto from = AllocateAligned<T>(N);
auto expected = AllocateAligned<ToT>(N);
HWY_ASSERT(from && expected);
const T min = static_cast<T>(IsSigned<T>() ? LimitsMin<ToT>() : ToT{0});
const T max = LimitsMax<ToT>();
RandomState rng;
for (size_t rep = 0; rep < AdjustedReps(1000); ++rep) {
for (size_t i = 0; i < N; ++i) {
const uint64_t bits = rng();
CopyBytes<sizeof(T)>(&bits, &from[i]);
expected[i] = static_cast<ToT>(HWY_MIN(HWY_MAX(min, from[i]), max));
}
const auto in = Load(from_d, from.get());
HWY_ASSERT_VEC_EQ(to_d, expected.get(), DemoteTo(to_d, in));
}
for (size_t rep = 0; rep < AdjustedReps(1000); ++rep) {
for (size_t i = 0; i < N; ++i) {
const uint64_t bits = rng();
CopyBytes<sizeof(ToT)>(&bits, &expected[i]);
if (!IsSigned<T>() && IsSigned<ToT>()) {
expected[i] &= static_cast<ToT>(max);
}
from[i] = static_cast<T>(expected[i]);
}
const auto in = Load(from_d, from.get());
HWY_ASSERT_VEC_EQ(to_d, expected.get(), DemoteTo(to_d, in));
}
}
};
HWY_NOINLINE void TestAllDemoteToInt() {
const ForDemoteVectors<TestDemoteTo<uint8_t>> from_i16_to_u8;
from_i16_to_u8(int16_t());
from_i16_to_u8(uint16_t());
const ForDemoteVectors<TestDemoteTo<int8_t>> from_i16_to_i8;
from_i16_to_i8(int16_t());
from_i16_to_i8(uint16_t());
const ForDemoteVectors<TestDemoteTo<uint8_t>, 2> from_i32_to_u8;
from_i32_to_u8(int32_t());
from_i32_to_u8(uint32_t());
const ForDemoteVectors<TestDemoteTo<int8_t>, 2> from_i32_to_i8;
from_i32_to_i8(int32_t());
from_i32_to_i8(uint32_t());
#if HWY_HAVE_INTEGER64
const ForDemoteVectors<TestDemoteTo<uint8_t>, 3> from_i64_to_u8;
from_i64_to_u8(int64_t());
from_i64_to_u8(uint64_t());
const ForDemoteVectors<TestDemoteTo<int8_t>, 3> from_i64_to_i8;
from_i64_to_i8(int64_t());
from_i64_to_i8(uint64_t());
#endif
const ForDemoteVectors<TestDemoteTo<uint16_t>> from_i32_to_u16;
from_i32_to_u16(int32_t());
from_i32_to_u16(uint32_t());
const ForDemoteVectors<TestDemoteTo<int16_t>> from_i32_to_i16;
from_i32_to_i16(int32_t());
from_i32_to_i16(uint32_t());
#if HWY_HAVE_INTEGER64
const ForDemoteVectors<TestDemoteTo<uint16_t>, 2> from_i64_to_u16;
from_i64_to_u16(int64_t());
from_i64_to_u16(uint64_t());
const ForDemoteVectors<TestDemoteTo<int16_t>, 2> from_i64_to_i16;
from_i64_to_i16(int64_t());
from_i64_to_i16(uint64_t());
const ForDemoteVectors<TestDemoteTo<uint32_t>> from_i64_to_u32;
from_i64_to_u32(int64_t());
from_i64_to_u32(uint64_t());
const ForDemoteVectors<TestDemoteTo<int32_t>> from_i64_to_i32;
from_i64_to_i32(int64_t());
from_i64_to_i32(uint64_t());
#endif
}
HWY_NOINLINE void TestAllDemoteToMixed() {
#if HWY_HAVE_FLOAT64
const ForDemoteVectors<TestDemoteTo<int32_t>> to_i32;
to_i32(double());
#endif
}
template <typename ToT>
struct TestDemoteToFloat {
template <typename T, class D>
HWY_NOINLINE void operator()(T , D from_d) {
static_assert(IsFloat<ToT>(), "Use TestDemoteTo for integer output");
static_assert(sizeof(T) > sizeof(ToT), "Input type must be wider");
const Rebind<ToT, D> to_d;
const size_t N = Lanes(from_d);
auto from = AllocateAligned<T>(N);
auto expected = AllocateAligned<ToT>(N);
HWY_ASSERT(from && expected);
RandomState rng;
for (size_t rep = 0; rep < AdjustedReps(1000); ++rep) {
for (size_t i = 0; i < N; ++i) {
do {
const uint64_t bits = rng();
CopyBytes<sizeof(T)>(&bits, &from[i]);
} while (!IsFiniteT(from[i]));
const T magn = std::abs(from[i]);
const T max_abs = HighestValue<ToT>();
const T clipped = copysign(HWY_MIN(magn, max_abs), from[i]);
expected[i] = static_cast<ToT>(clipped);
}
HWY_ASSERT_VEC_EQ(to_d, expected.get(),
DemoteTo(to_d, Load(from_d, from.get())));
}
}
};
HWY_NOINLINE void TestAllDemoteToFloat() {
#if HWY_HAVE_FLOAT64
const ForDemoteVectors<TestDemoteToFloat<float>, 1> to_float;
to_float(double());
#endif
}
struct TestDemoteToBF16 {
template <typename T, class D>
HWY_NOINLINE void operator()(T , D from_d) {
static_assert(IsSame<T, float>(),
"TestDemoteToBF16 can only be called if T is float");
const Rebind<bfloat16_t, D> to_d;
const Rebind<uint32_t, D> du32;
const Rebind<uint16_t, D> du16;
const size_t N = Lanes(from_d);
auto from = AllocateAligned<T>(N);
auto expected = AllocateAligned<bfloat16_t>(N);
HWY_ASSERT(from && expected);
const auto u16_zero_vect = Zero(du16);
const auto u16_one_vect = Set(du16, 1);
RandomState rng;
for (size_t rep = 0; rep < AdjustedReps(1000); ++rep) {
for (size_t i = 0; i < N; ++i) {
do {
const uint64_t bits = rng();
CopyBytes<sizeof(T)>(&bits, &from[i]);
} while (!IsFiniteT(from[i]));
uint32_t fromBits;
CopyBytes<sizeof(uint32_t)>(&from[i], &fromBits);
uint16_t bf16Bits = static_cast<uint16_t>(fromBits >> 16);
CopyBytes<sizeof(uint16_t)>(&bf16Bits, &expected[i]);
}
const auto in = Load(from_d, from.get());
const auto actual = DemoteTo(to_d, in);
auto expected_vect = BitCast(du16, Load(to_d, expected.get()));
const auto low_f32_bits = TruncateTo(du16, BitCast(du32, in));
const auto max_diff_from_expected =
Add(VecFromMask(du16, Eq(low_f32_bits, u16_zero_vect)), u16_one_vect);
auto expected_adj =
And(max_diff_from_expected,
VecFromMask(du16, Eq(Sub(BitCast(du16, actual), expected_vect),
u16_one_vect)));
expected_vect = Add(expected_vect, expected_adj);
Store(BitCast(to_d, expected_vect), to_d, expected.get());
HWY_ASSERT_VEC_EQ(to_d, expected.get(), actual);
}
}
};
HWY_NOINLINE void TestAllDemoteToBF16() {
const ForDemoteVectors<TestDemoteToBF16, 1> to_bf16;
to_bf16(float());
}
template <class D>
AlignedFreeUniquePtr<float[]> ReorderBF16TestCases(D d, size_t& padded) {
const float test_cases[] = {
1.0f,
-1.0f,
0.0f,
-0.0f,
0.25f,
-0.25f,
4.0f,
-32.0f,
2.015625f,
3.984375f,
-2.015625f,
-3.984375f,
-2.0f,
-10.0f,
0.03125f,
1.03125f,
1.5f,
2.0f,
4.0f,
5.0f,
6.0f,
8.0f,
10.0f,
256.0f,
448.0f,
2080.0f,
};
const size_t kNumTestCases = sizeof(test_cases) / sizeof(test_cases[0]);
const size_t N = Lanes(d);
padded = RoundUpTo(kNumTestCases, 2 * N);
auto in = AllocateAligned<float>(padded);
auto expected = AllocateAligned<float>(padded);
HWY_ASSERT(in && expected);
std::copy(test_cases, test_cases + kNumTestCases, in.get());
std::fill(in.get() + kNumTestCases, in.get() + padded, 0.0f);
return in;
}
class TestReorderDemote2To {
void Sort(float* p, size_t count) {
for (size_t i = 0; i < count - 1; ++i) {
size_t idx_min = i;
for (size_t j = i + 1; j < count; j++) {
if (p[j] < p[idx_min]) {
idx_min = j;
}
}
const float tmp = p[i];
p[i] = p[idx_min];
p[idx_min] = tmp;
}
}
public:
template <typename TF32, class DF32>
HWY_NOINLINE void operator()(TF32 , DF32 d32) {
#if HWY_TARGET != HWY_SCALAR
size_t padded;
auto in = ReorderBF16TestCases(d32, padded);
using TBF16 = bfloat16_t;
const Repartition<TBF16, DF32> dbf16;
const Half<decltype(dbf16)> dbf16_half;
const size_t N = Lanes(d32);
auto temp16 = AllocateAligned<TBF16>(2 * N);
auto expected = AllocateAligned<float>(2 * N);
auto actual = AllocateAligned<float>(2 * N);
HWY_ASSERT(temp16 && expected && actual);
for (size_t i = 0; i < padded; i += 2 * N) {
const auto f0 = Load(d32, &in[i + 0]);
const auto f1 = Load(d32, &in[i + N]);
const auto v16 = ReorderDemote2To(dbf16, f0, f1);
Store(v16, dbf16, temp16.get());
const auto promoted0 = PromoteTo(d32, Load(dbf16_half, temp16.get() + 0));
const auto promoted1 = PromoteTo(d32, Load(dbf16_half, temp16.get() + N));
const auto sum_expected = ReduceSum(d32, Add(f0, f1));
const auto sum_actual = ReduceSum(d32, Add(promoted0, promoted1));
HWY_ASSERT(sum_expected - 1E-4 <= sum_actual &&
sum_actual <= sum_expected + 1E-4);
Store(f0, d32, expected.get() + 0);
Store(f1, d32, expected.get() + N);
Store(promoted0, d32, actual.get() + 0);
Store(promoted1, d32, actual.get() + N);
Sort(expected.get(), 2 * N);
Sort(actual.get(), 2 * N);
HWY_ASSERT_VEC_EQ(d32, expected.get() + 0, Load(d32, actual.get() + 0));
HWY_ASSERT_VEC_EQ(d32, expected.get() + N, Load(d32, actual.get() + N));
}
#else
(void)d32;
#endif
}
};
class TestIntegerReorderDemote2To {
#if HWY_TARGET != HWY_SCALAR
private:
template <class T>
static void Sort(T* p, size_t count) {
for (size_t i = 0; i < count - 1; ++i) {
size_t idx_min = i;
for (size_t j = i + 1; j < count; j++) {
if (p[j] < p[idx_min]) {
idx_min = j;
}
}
const T tmp = p[i];
p[i] = p[idx_min];
p[idx_min] = tmp;
}
}
template <class T, class D, class DN>
static void DoIntegerReorderDemote2ToTest(DN dn, T , D d) {
using TN = TFromD<DN>;
const size_t N = Lanes(d);
const size_t twiceN = N * 2;
auto from = AllocateAligned<T>(twiceN);
auto expected = AllocateAligned<TN>(twiceN);
auto actual = AllocateAligned<TN>(twiceN);
HWY_ASSERT(from && expected && actual);
const T min = static_cast<T>(IsSigned<T>() ? LimitsMin<TN>() : TN{0});
const T max = LimitsMax<TN>();
RandomState rng;
for (size_t rep = 0; rep < AdjustedReps(1000); ++rep) {
for (size_t i = 0; i < twiceN; ++i) {
const uint64_t bits = rng();
CopyBytes<sizeof(T)>(&bits, &from[i]);
expected[i] = static_cast<TN>(HWY_MIN(HWY_MAX(min, from[i]), max));
}
const auto in_1 = Load(d, from.get());
const auto in_2 = Load(d, from.get() + N);
const auto demoted_vect = ReorderDemote2To(dn, in_1, in_2);
Store(demoted_vect, dn, actual.get());
Sort(actual.get(), twiceN);
Sort(expected.get(), twiceN);
HWY_ASSERT_VEC_EQ(dn, expected.get(), Load(dn, actual.get()));
}
for (size_t rep = 0; rep < AdjustedReps(1000); ++rep) {
for (size_t i = 0; i < twiceN; ++i) {
const uint64_t bits = rng();
CopyBytes<sizeof(TN)>(&bits, &expected[i]);
if (!IsSigned<T>() && IsSigned<TN>()) {
expected[i] &= static_cast<TN>(max);
}
from[i] = static_cast<T>(expected[i]);
}
const auto in_1 = Load(d, from.get());
const auto in_2 = Load(d, from.get() + N);
const auto demoted_vect = ReorderDemote2To(dn, in_1, in_2);
Store(demoted_vect, dn, actual.get());
Sort(actual.get(), twiceN);
Sort(expected.get(), twiceN);
HWY_ASSERT_VEC_EQ(dn, expected.get(), Load(dn, actual.get()));
}
}
#endif
public:
template <typename T, class D>
HWY_NOINLINE void operator()(T , D d) {
#if HWY_TARGET != HWY_SCALAR
const RepartitionToNarrow<D> dn;
const RebindToSigned<decltype(dn)> dn_i;
const RebindToUnsigned<decltype(dn)> dn_u;
DoIntegerReorderDemote2ToTest(dn_i, T(), d);
DoIntegerReorderDemote2ToTest(dn_u, T(), d);
#else
(void)d;
#endif
}
};
HWY_NOINLINE void TestAllReorderDemote2To() {
ForUI163264(ForShrinkableVectors<TestIntegerReorderDemote2To>());
ForShrinkableVectors<TestReorderDemote2To>()(float());
}
struct TestFloatOrderedDemote2To {
template <typename TF, class DF>
HWY_NOINLINE void operator()(TF , DF df) {
#if HWY_TARGET != HWY_SCALAR
const Repartition<bfloat16_t, decltype(df)> dbf16;
const RebindToUnsigned<decltype(dbf16)> du16;
const RebindToUnsigned<decltype(df)> du32;
const Half<decltype(du16)> du16_half;
const size_t N = Lanes(df);
const size_t twiceN = N * 2;
auto from = AllocateAligned<TF>(twiceN);
auto expected = AllocateAligned<bfloat16_t>(twiceN);
HWY_ASSERT(from && expected);
const auto u16_zero_vect = Zero(du16);
const auto u16_one_vect = Set(du16, 1);
RandomState rng;
for (size_t rep = 0; rep < AdjustedReps(1000); ++rep) {
for (size_t i = 0; i < twiceN; ++i) {
do {
const uint64_t bits = rng();
CopyBytes<sizeof(TF)>(&bits, &from[i]);
} while (!IsFiniteT(from[i]));
uint32_t u32Bits;
CopyBytes<sizeof(uint32_t)>(&from[i], &u32Bits);
const uint16_t expected_bf16_bits =
static_cast<uint16_t>(u32Bits >> 16);
CopyBytes<sizeof(bfloat16_t)>(&expected_bf16_bits, &expected[i]);
}
const auto in_1 = Load(df, from.get());
const auto in_2 = Load(df, from.get() + N);
const auto actual = OrderedDemote2To(dbf16, in_1, in_2);
auto expected_vect = BitCast(du16, Load(dbf16, expected.get()));
const auto low_f32_bits =
Combine(du16, TruncateTo(du16_half, BitCast(du32, in_2)),
TruncateTo(du16_half, BitCast(du32, in_1)));
const auto max_diff_from_expected =
Add(VecFromMask(du16, Eq(low_f32_bits, u16_zero_vect)), u16_one_vect);
auto expected_adj =
And(max_diff_from_expected,
VecFromMask(du16, Eq(Sub(BitCast(du16, actual), expected_vect),
u16_one_vect)));
expected_vect = Add(expected_vect, expected_adj);
Store(BitCast(dbf16, expected_vect), dbf16, expected.get());
HWY_ASSERT_VEC_EQ(dbf16, expected.get(), actual);
}
#else
(void)df;
#endif
}
};
class TestIntegerOrderedDemote2To {
#if HWY_TARGET != HWY_SCALAR
private:
template <class T, class D, class DN>
static void DoIntegerOrderedDemote2ToTest(DN dn, T , D d) {
using TN = TFromD<DN>;
const size_t N = Lanes(d);
const size_t twiceN = N * 2;
auto from = AllocateAligned<T>(twiceN);
auto expected = AllocateAligned<TN>(twiceN);
HWY_ASSERT(from && expected);
const T min = static_cast<T>(IsSigned<T>() ? LimitsMin<TN>() : TN{0});
const T max = LimitsMax<TN>();
RandomState rng;
for (size_t rep = 0; rep < AdjustedReps(1000); ++rep) {
for (size_t i = 0; i < twiceN; ++i) {
const uint64_t bits = rng();
CopyBytes<sizeof(T)>(&bits, &from[i]);
expected[i] = static_cast<TN>(HWY_MIN(HWY_MAX(min, from[i]), max));
}
const auto in_1 = Load(d, from.get());
const auto in_2 = Load(d, from.get() + N);
const auto actual = OrderedDemote2To(dn, in_1, in_2);
HWY_ASSERT_VEC_EQ(dn, expected.get(), actual);
}
for (size_t rep = 0; rep < AdjustedReps(1000); ++rep) {
for (size_t i = 0; i < twiceN; ++i) {
const uint64_t bits = rng();
CopyBytes<sizeof(TN)>(&bits, &expected[i]);
if (!IsSigned<T>() && IsSigned<TN>()) {
expected[i] &= static_cast<TN>(max);
}
from[i] = static_cast<T>(expected[i]);
}
const auto in_1 = Load(d, from.get());
const auto in_2 = Load(d, from.get() + N);
const auto actual = OrderedDemote2To(dn, in_1, in_2);
HWY_ASSERT_VEC_EQ(dn, expected.get(), actual);
}
}
#endif
public:
template <typename T, class D>
HWY_NOINLINE void operator()(T , D d) {
#if HWY_TARGET != HWY_SCALAR
const RepartitionToNarrow<D> dn;
const RebindToSigned<decltype(dn)> dn_i;
const RebindToUnsigned<decltype(dn)> dn_u;
DoIntegerOrderedDemote2ToTest(dn_i, T(), d);
DoIntegerOrderedDemote2ToTest(dn_u, T(), d);
#else
(void)d;
#endif
}
};
HWY_NOINLINE void TestAllOrderedDemote2To() {
ForUI163264(ForShrinkableVectors<TestIntegerOrderedDemote2To>());
ForShrinkableVectors<TestFloatOrderedDemote2To>()(float());
}
struct TestI32F64 {
template <typename TF, class DF>
HWY_NOINLINE void operator()(TF , const DF df) {
using TI = int32_t;
const Rebind<TI, DF> di;
const size_t N = Lanes(df);
HWY_ASSERT_VEC_EQ(di, Iota(di, TI(4)), DemoteTo(di, Iota(df, TF(4.0))));
HWY_ASSERT_VEC_EQ(di, Iota(di, -TI(N)), DemoteTo(di, Iota(df, -TF(N))));
HWY_ASSERT_VEC_EQ(di, Iota(di, TI(2)), DemoteTo(di, Iota(df, TF(2.001))));
HWY_ASSERT_VEC_EQ(di, Iota(di, TI(3)), DemoteTo(di, Iota(df, TF(3.9999))));
const TF eps = static_cast<TF>(0.0001);
HWY_ASSERT_VEC_EQ(di, Iota(di, -TI(N)),
DemoteTo(di, Iota(df, -TF(N + 1) + eps)));
HWY_ASSERT_VEC_EQ(di, Iota(di, -TI(N + 1)),
DemoteTo(di, Iota(df, -TF(N + 1) - eps)));
HWY_ASSERT_VEC_EQ(di, Set(di, LimitsMax<TI>()),
DemoteTo(di, Set(df, TF(1E12))));
HWY_ASSERT_VEC_EQ(di, Set(di, LimitsMin<TI>()),
DemoteTo(di, Set(df, TF(-1E12))));
}
};
HWY_NOINLINE void TestAllI32F64() {
#if HWY_HAVE_FLOAT64
ForDemoteVectors<TestI32F64>()(double());
#endif
}
}
}
HWY_AFTER_NAMESPACE();
#endif
#if HWY_ONCE
namespace hwy {
#if !HWY_IS_MSAN
HWY_BEFORE_TEST(HwyDemoteTest);
HWY_EXPORT_AND_TEST_P(HwyDemoteTest, TestAllDemoteToInt);
HWY_EXPORT_AND_TEST_P(HwyDemoteTest, TestAllDemoteToMixed);
HWY_EXPORT_AND_TEST_P(HwyDemoteTest, TestAllDemoteToFloat);
HWY_EXPORT_AND_TEST_P(HwyDemoteTest, TestAllDemoteToBF16);
HWY_EXPORT_AND_TEST_P(HwyDemoteTest, TestAllReorderDemote2To);
HWY_EXPORT_AND_TEST_P(HwyDemoteTest, TestAllOrderedDemote2To);
HWY_EXPORT_AND_TEST_P(HwyDemoteTest, TestAllI32F64);
#endif
}
#endif
| [
"[email protected]"
] | |
1a79e62826fa691e9155eb163995f6837e6b0685 | 23c524e47a96829d3b8e0aa6792fd40a20f3dd41 | /.history/main_20210529184042.cpp | 56817381daf2814ed8d8778d38fad1c466541a9b | [] | no_license | nqqw/ft_containers | 4c16d32fb209aea2ce39e7ec25d7f6648aed92e8 | f043cf52059c7accd0cef7bffcaef0f6cb2c126b | refs/heads/master | 2023-06-25T16:08:19.762870 | 2021-07-23T17:28:09 | 2021-07-23T17:28:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,819 | cpp | #include "Map.hpp"
#include <memory>
#include <map>
#include <unistd.h>
#include <cmath>
#include <iterator>
#include <iostream>
#define red "\x1b[31m"
#define green "\x1b[32m"
#define yellow "\x1b[33m"
#define blue "\x1b[34m"
#define cend "\x1b[0m"
template <class Key, class T>
void print_map(ft::map<Key, T> &map)
{
typename ft::map<Key, T>::iterator it = map.begin();
typename ft::map<Key, T>::iterator ite = map.end();
while (it != ite)
{
std::cout << it->first << " ," << it->second << " | ";
++it;
}
std::cout << std::endl;
std::cout << std::endl;
}
void constructor_test()
{
std::cout << blue << "***************[ Default constructor test ]***************" << cend << std::endl;
std::cout << green << "Testing empty map int: " << cend << std::endl;
ft::map<int, int> mymap;
ft::map<int, int>::iterator it;
ft::map<int, int>::iterator ite;
std::map<int, int>::iterator its;
std::map<int, int>::iterator ites;
std::map<int, int> std_map;
// std_map[2] = 200;
// std_map[3] = 300;
// std_map[1] = 200;
// std_map[3] = 500;
// std_map[4] = 400;
// std_map[5] = 500;
// std_map[10] = 600;
// std::map<int, int>::iterator its;
// std::map<int, int>::iterator itse;
// its = std_map.begin();
// std::cout << "begin is: " << its->first << ", " << its->second << std::endl;
// itse = std_map.end();
// itse--;
// std::cout << "end-- is: " << itse->first << ", " << itse->second << std::endl;
// itse--;
// std::cout << "end-- is: " << itse->first << ", " << itse->second << std::endl;
// first insert function version (single parameter)
std::cout << "***************?//////////STD////////////////?*******************" << std::endl;
std_map.insert(std::pair<int, int>(5, 200));
std_map.insert(std::pair<int, int>(4, 400));
std::pair<std::map<int, int>::iterator, bool> ret1;
ret1 = std_map.insert(std::pair<int, int>(6, 100));
std::cout << "return value is (6): " << ret1.first->first << '\n';
std::cout << " with a value of " << ret1.first->second << '\n';
std::cout << "bool value is (1): " << ret1.second << '\n';
std_map.insert(std::pair<int, int>(3, 400));
std_map.insert(std::pair<int, int>(2, 400));
std_map.insert(std::pair<int, int>(1, 400));
std_map.insert(std::pair<int, int>(8, 100));
std::cout << "return value is (8): " << ret1.first->first << '\n';
std::cout << " with a value of " << ret1.first->second << '\n';
std::cout << "bool value is (1): " << ret1.second << '\n';
ret1 = std_map.insert(std::pair<int, int>(8, 100));
std::cout << "return value is (8): " << ret1.first->first << '\n';
std::cout << " with a value of " << ret1.first->second << '\n';
std::cout << "bool value is (0): " << ret1.second << '\n';
ret1 = std_map.insert(std::pair<int, int>(10, 100));
std::cout << "return value is (10): " << ret1.first->first << '\n';
std::cout << " with a value of " << ret1.first->second << '\n';
std::cout << "bool value is (1): " << ret1.second << '\n';
ret1 = std_map.insert(std::pair<int, int>(6, 100));
std::cout << "return value is (6): " << ret1.first->first << '\n';
std::cout << " with a value of " << ret1.first->second << '\n';
std::cout << "bool value is (0): " << ret1.second << '\n';
std_map.insert(std::pair<int, int>(7, 100));
ret1 = std_map.insert(std::pair<int, int>(7, 100));
std::cout << "return value is (7): " << ret1.first->first << '\n';
std::cout << " with a value of " << ret1.first->second << '\n';
std::cout << "bool value is (0): " << ret1.second << '\n';
its = std_map.begin();
ites = std_map.end();
while (its != ites)
{
std::cout << "contents of my map: " << its->first << ", " << its->second << std::endl;
++its;
}
std::cout << "size is : " << std_map.size() << std::endl;
std::cout << "**************************MY FUNCS********************************" << std::endl;
mymap.insert(std::pair<int, int>(5, 200));
mymap.insert(std::pair<int, int>(4, 400));
std::pair<ft::map<int, int>::iterator, bool> ret;
ret = mymap.insert(std::pair<int, int>(6, 100));
std::cout << "return value is (6): " << ret.first->first << '\n';
std::cout << " with a value of " << ret.first->second << '\n';
std::cout << "bool value is (1): " << ret.second << '\n';
mymap.insert(std::pair<int, int>(3, 400));
mymap.insert(std::pair<int, int>(2, 400));
mymap.insert(std::pair<int, int>(1, 400));
mymap.insert(std::pair<int, int>(8, 100));
std::cout << "return value is (8): " << ret.first->first << '\n';
std::cout << " with a value of " << ret.first->second << '\n';
std::cout << "bool value is (1): " << ret.second << '\n';
// ret = mymap.insert(std::pair<int, int>(8, 100));
// std::cout << "return value is (8): " << ret.first->first << '\n';
// std::cout << " with a value of " << ret.first->second << '\n';
// std::cout << "bool value is (0): " << ret.second << '\n';
ret = mymap.insert(std::pair<int, int>(10, 100));
std::cout << "return value is (10): " << ret.first->first << '\n';
std::cout << " with a value of " << ret.first->second << '\n';
std::cout << "bool value is (1): " << ret.second << '\n';
// ret = mymap.insert(std::pair<int, int>(6, 100));
// std::cout << "return value is (6): " << ret.first->first << '\n';
// std::cout << " with a value of " << ret.first->second << '\n';
// std::cout << "bool value is (0): " << ret.second << '\n';
mymap.insert(std::pair<int, int>(7, 100));
ret = mymap.insert(std::pair<int, int>(7, 100));
std::cout << "return value is (7): " << ret.first->first << '\n';
std::cout << " with a value of " << ret.first->second << '\n';
std::cout << "bool value is (0): " << ret.second << '\n';
ite = mymap.end();
// ite--;
// ite--;
std::cout << "begin is: " << mymap.begin()->first << std::endl;
std::cout << "end is: " << ite->first << std::endl;
//print_map(mymap);
std::cout << "size is : " << mymap.size() << std::endl;
mymap.treeprint();
it = mymap.begin();
ite = mymap.end();
while (it != ite)
{
std::cout << "contents of my map: " << it->first << ", " << it->second << std::endl;
++it;
}
// ite = mymap.end();
// it++;
// std::cout << "begin++ of my map is: " << it->first << ", "<< it->second << std::endl;
// it++;
// std::cout << "begin++ of my map is: " << it->first << ", "<< it->second << std::endl;
// it++;
// std::cout << "begin++ of my map is: " << it->first << ", "<< it->second << std::endl;
// it++;
// std::cout << "begin++ of my map is: " << it->first << ", "<< it->second << std::endl;
// it++;
// std::cout << "begin++ of my map is: " << it->first << ", "<< it->second << std::endl;
// it++;
// std::cout << "begin++ of my map is: " << it->first << ", "<< it->second << std::endl;
// it++;
// std::cout << "begin++ of my map is: " << it->first << ", "<< it->second << std::endl;
// it++;
// std::cout << "begin++ of my map is: " << it->first << ", "<< it->second << std::endl;
// it++;
// std::cout << "begin++ of my map is: " << it->first << ", "<< it->second << std::endl;
// std::cout << "end is: " << ite->first << ", "<< ite->second << std::endl;
// ite--;
// std::cout << "end-- is: " << ite->first << ", "<< ite->second << std::endl;
// ite--;
// std::cout << "end-- is: " << ite->first << ", "<< ite->second << std::endl;
// ite--;
// std::cout << "end-- is: " << ite->first << ", "<< ite->second << std::endl;
// std::cout << "list size is: " << lst.size() << std::endl
// << std::endl;
/*std::cout << blue << "***************[ Fill constructor test ]***************" << cend << std::endl;
std::cout << green << "Testing list<int> lst1(10, 42): " << cend << std::endl;
ft::list<int> lst1(10, 42);
print_list(lst1);
std::cout << std::endl;
std::cout << blue << "***************[ Range constructor test ]***************" << cend << std::endl;
ft::list<int> lst2;
for (int i = 0; i < 10; ++i)
{
lst2.push_back(i);
}
ft::list<int>::iterator it = lst2.begin();
ft::list<int>::iterator ite = lst2.end();
ft::list<int> lst3(it, ite);
print_list(lst3);
std::cout << std::endl;
std::cout << blue << "***************[ Copy constructor test ]***************" << cend << std::endl;
std::cout << green << "Making copy list<int> lst4(lst1): " << cend << std::endl;
ft::list<int> lst4(lst1);
print_list(lst4);
std::cout << blue << "***************[ Operator = test ]***************" << cend << std::endl;
std::cout << green << "Making list<int> lst5 = lst1: " << cend << std::endl;
ft::list<int> lst5(10, 4);
lst1 = lst5;
print_list(lst1);
std::cout << std::endl;
*/
//sleep(50);
}
int main()
{
// std::map<int, int> mapp;
// mapp.insert(std::pair<int,int>(5, 200));
// mapp.insert(std::pair<int,int>(10, 200));
// std::map<int, int>::reverse_iterator rit = --mapp.rend();
// // std::map<int, int>::iterator it = --mapp.begin();
// std::cout << rit->first << std::endl;
constructor_test();
return 0;
} | [
"[email protected]"
] | |
e8ee9b15c8389920ec075c8eafaaa5a5f16b8ec3 | d84967ba1e6adc72e120f84524c51ad57912df5a | /devel/electron20/files/patch-chromecast_browser_cast__browser__main__parts.cc | 582c9d2959a69a630816d846b39ad3eb7146ff7f | [
"BSD-3-Clause"
] | permissive | tagattie/FreeBSD-Electron | f191d03c067d03ad3007e7748de905da06ba67f9 | af26f766e772bb04db5eb95148ee071101301e4e | refs/heads/master | 2023-09-04T10:56:17.446818 | 2023-09-04T09:03:11 | 2023-09-04T09:03:11 | 176,520,396 | 73 | 9 | null | 2023-08-31T03:29:16 | 2019-03-19T13:41:20 | C++ | UTF-8 | C++ | false | false | 1,767 | cc | --- chromecast/browser/cast_browser_main_parts.cc.orig 2022-08-01 19:04:25 UTC
+++ chromecast/browser/cast_browser_main_parts.cc
@@ -91,7 +91,7 @@
#include "ui/base/ui_base_switches.h"
#include "ui/gl/gl_switches.h"
-#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
+#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_BSD)
#include <fontconfig/fontconfig.h>
#include <signal.h>
#include <sys/prctl.h>
@@ -278,7 +278,7 @@ class CastViewsDelegate : public views::ViewsDelegate
#endif // defined(USE_AURA)
-#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
+#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_BSD)
base::FilePath GetApplicationFontsDir() {
std::unique_ptr<base::Environment> env(base::Environment::Create());
@@ -324,7 +324,7 @@ const DefaultCommandLineSwitch kDefaultSwitches[] = {
{cc::switches::kDisableThreadedAnimation, ""},
#endif // BUILDFLAG(IS_ANDROID)
#endif // BUILDFLAG(IS_CAST_AUDIO_ONLY)
-#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
+#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_BSD)
#if defined(ARCH_CPU_X86_FAMILY)
// This is needed for now to enable the x11 Ozone platform to work with
// current Linux/NVidia OpenGL drivers.
@@ -512,7 +512,7 @@ void CastBrowserMainParts::ToolkitInitialized() {
views_delegate_ = std::make_unique<CastViewsDelegate>();
#endif // defined(USE_AURA)
-#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
+#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_BSD)
base::FilePath dir_font = GetApplicationFontsDir();
const FcChar8 *dir_font_char8 = reinterpret_cast<const FcChar8*>(dir_font.value().data());
if (!FcConfigAppFontAddDir(gfx::GetGlobalFontConfig(), dir_font_char8)) {
| [
"[email protected]"
] | |
0b0a1d257148c867027747fd588efb5f63fdb236 | 9bdc01fddc660053e23eaf89302f9b8e5daaefdf | /src/planner/cspace/cspace_geometric_Circular.h | 7e838b9533b83ec0968ec4a914b293c1111a3c80 | [] | no_license | hello-starry/MotionExplorer | 51d4ca1a1325567968ac2119de7c96b0345e5b10 | 01472004a1bc1272ce32a433fe6bde81eb962775 | refs/heads/master | 2023-08-14T21:20:22.073477 | 2021-09-07T17:51:20 | 2021-09-07T17:51:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 859 | h | #pragma once
#include "planner/cspace/cspace_geometric_Mobius.h"
class GeometricCSpaceOMPLCircular: public GeometricCSpaceOMPL
{
using BaseT = GeometricCSpaceOMPL;
public:
GeometricCSpaceOMPLCircular(RobotWorld *world_, int robot_idx);
virtual void initSpace();
virtual void ConfigToOMPLState(const Config &q, ob::State *qompl) override;
virtual Config OMPLStateToConfig(const ob::State *qompl) override;
virtual void print(std::ostream& out = std::cout) const override;
virtual Vector3 getXYZ(const ob::State*) override;
virtual bool IsPlanar() override;
virtual void DrawGL(GUIState& state) override;
protected:
double OMPLStateToSO2Value(const ob::State *qompl);
Vector3 ProjectToVector3(double u);
Config ProjectToConfig(double u);
private:
double radius_{1.0};
double zOffset_{-2.0};
};
| [
"[email protected]"
] | |
c048598a4f0e25b125b7df0d72d2cc7b9dbffc82 | 610891d98f89087d52886a02f6a9719c412fcf67 | /MetEnkephalinOptimization/ga/GAStatistics.h | 9ccc307a9ea19e9836885c9c9f860c8a1dbdb91b | [] | no_license | chenxianpao/memo | 771dfad74ecb0db030f1e07c720e5c39120ce892 | d5a7c2706d334f33fa593bc2f9c5968055659c59 | refs/heads/master | 2022-01-06T02:44:25.108209 | 2019-05-07T11:44:50 | 2019-05-07T11:44:50 | 125,970,955 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,938 | h | // $Header: /usr/people/mbwall/src/galib/ga/RCS/GAStatistics.h,v 1.3 1999/03/30 02:40:14 mbwall Exp $
/* ----------------------------------------------------------------------------
statistics.h
mbwall 14jul95
Copyright (c) 1995 Massachusetts Institute of Technology
- all rights reserved
DESCRIPTION:
Header for the statistics object used by the GA objects.
---------------------------------------------------------------------------- */
#ifndef _ga_statistics_h_
#define _ga_statistics_h_
#include <string.h>
#include <ga/gatypes.h>
#include <ga/gaconfig.h>
#include <ga/GAGenome.h>
#include <ga/GAPopulation.h>
// Default settings and their names.
extern int gaDefNumBestGenomes;
extern int gaDefScoreFrequency1;
extern int gaDefScoreFrequency2;
extern int gaDefFlushFrequency;
extern char gaDefScoreFilename[];
/* ----------------------------------------------------------------------------
Statistics class
We define this class as a storage object for the current state of the GA.
Whereas the parameters object keeps track of the user-definable settings for
the GA, the statistics object keeps track of the data that the GA generates
along the way.
---------------------------------------------------------------------------- */
class GAStatistics {
public:
enum {
NoScores=0x00,
Mean=0x01,
Maximum=0x02,
Minimum=0x04,
Deviation=0x08,
Diversity=0x10,
AllScores=0xff
};
GAStatistics();
GAStatistics(const GAStatistics&);
GAStatistics& operator=(const GAStatistics& orig){copy(orig); return *this;}
virtual ~GAStatistics();
void copy(const GAStatistics &);
float online() const {return on;}
float offlineMax() const {return offmax;}
float offlineMin() const {return offmin;}
float initial(int w=Maximum) const;
float current(int w=Maximum) const;
float maxEver() const {return maxever;}
float minEver() const {return minever;}
int generation() const {return curgen;}
unsigned long int selections() const {return numsel;}
unsigned long int crossovers() const {return numcro;}
unsigned long int mutations() const {return nummut;}
unsigned long int replacements() const {return numrep;}
unsigned long int indEvals() const {return numeval;}
unsigned long int popEvals() const {return numpeval;}
float convergence() const;
int nConvergence() const { return Nconv; }
int nConvergence(unsigned int);
int nBestGenomes(const GAGenome&, unsigned int);
int nBestGenomes() const { return(boa ? boa->size() : 0); }
int scoreFrequency(unsigned int x) { return(scoreFreq = x); }
int scoreFrequency() const { return scoreFreq; }
int flushFrequency(unsigned int x);
int flushFrequency() const { return Nscrs; }
const char* scoreFilename(const char *filename);
const char* scoreFilename() const { return scorefile; }
int selectScores(int w){ return which = w; }
int selectScores() const { return which; }
GABoolean recordDiversity(GABoolean flag){ return dodiv=flag; }
GABoolean recordDiversity() const { return dodiv; }
void flushScores();
void update(const GAPopulation & pop);
void reset(const GAPopulation & pop);
const GAPopulation & bestPopulation() const { return *boa; }
const GAGenome & bestIndividual(unsigned int n=0) const;
#ifndef NO_STREAMS
int scores(const char* filename, int which=NoScores);
int scores(ostream& os, int which=NoScores);
int write(const char* filename) const;
int write(ostream& os) const;
#endif
// These should be protected (accessible only to the GA class) but for now they
// are publicly accessible. Do not try to set these unless you know what you
// are doing!!
unsigned long int numsel; // number of selections since reset
unsigned long int numcro; // number of crossovers since reset
unsigned long int nummut; // number of mutations since reset
unsigned long int numrep; // number of replacements since reset
unsigned long int numeval; // number of individual evaluations since reset
unsigned long int numpeval; // number of population evals since reset
protected:
unsigned int curgen; // current generation number
unsigned int scoreFreq; // how often (in generations) to record scores
GABoolean dodiv; // should we record diversity?
float maxever; // maximum score since initialization
float minever; // minimum score since initialization
float on; // "on-line" performance (ave of all scores)
float offmax; // "off-line" performance (ave of maximum)
float offmin; // "off-line" performance (ave of minimum)
float aveInit; // stats from the initial population
float maxInit;
float minInit;
float devInit;
float divInit;
float aveCur; // stats from the current population
float maxCur;
float minCur;
float devCur;
float divCur;
unsigned int nconv, Nconv; // how many scores we're recording (flushFreq)
float * cscore; // best score of last n generations
unsigned int nscrs, Nscrs; // how many scores do we have?
int * gen; // generation number corresponding to scores
float * aveScore; // average scores of each generation
float * maxScore; // best scores of each generation
float * minScore; // worst scores of each generation
float * devScore; // stddev of each generation
float * divScore; // diversity of each generation
char * scorefile; // name of file to which scores get written
int which; // which data to write to file
GAPopulation * boa; // keep a copy of the best genomes
void setConvergence(float);
void setScore(const GAPopulation&);
void updateBestIndividual(const GAPopulation&, GABoolean flag=gaFalse);
void writeScores();
void resizeScores(unsigned int);
friend class GA;
};
inline const char* GAStatistics::scoreFilename(const char* filename){
delete [] scorefile;
scorefile = 0;
if(filename){
scorefile = new char[strlen(filename)+1];
strcpy(scorefile, filename);
}
return scorefile;
}
inline float GAStatistics::convergence() const {
double cnv = 0.0;
if(nconv >= Nconv-1 && cscore[nconv%Nconv] != 0)
cnv = (double)(cscore[(nconv+1)%Nconv]) / (double)(cscore[nconv%Nconv]);
return (float)cnv;
}
inline float GAStatistics::initial(int w) const {
float val = 0.0;
switch(w){
case Mean: val = aveInit; break;
case Maximum: val = maxInit; break;
case Minimum: val = minInit; break;
case Deviation: val = devInit; break;
case Diversity: val = divInit; break;
default: break;
}
return val;
}
inline float GAStatistics::current(int w) const {
float val = 0.0;
switch(w){
case Mean: val = aveCur; break;
case Maximum: val = maxCur; break;
case Minimum: val = minCur; break;
case Deviation: val = devCur; break;
case Diversity: val = divCur; break;
default: break;
}
return val;
}
#ifndef NO_STREAMS
inline ostream& operator<< (ostream& os, const GAStatistics& s)
{ s.write(os); return os; }
#endif
#endif
| [
"[email protected]"
] | |
3de70fae77642022760fb3f6eb64e3919180cffe | 32b934cb3ef99474b7295da510420ca4a03d6017 | /GamosUserActionMgr/src/GmUserStackingActionList.cc | 497186b10f74c9c9467a122bbd919c9a4c9a9e76 | [] | no_license | ethanlarochelle/GamosCore | 450fc0eeb4a5a6666da7fdb75bcf5ee23a026238 | 70612e9a2e45b3b1381713503eb0f405530d44f0 | refs/heads/master | 2022-03-24T16:03:39.569576 | 2018-01-20T12:43:43 | 2018-01-20T12:43:43 | 116,504,426 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,563 | cc | //
// ********************************************************************
// * License and Disclaimer *
// * *
// * The GAMOS software is copyright of the Copyright Holders of *
// * the GAMOS Collaboration. It is provided under the terms and *
// * conditions of the GAMOS Software License, included in the file *
// * LICENSE and available at http://fismed.ciemat.es/GAMOS/license .*
// * These include a list of copyright holders. *
// * *
// * Neither the authors of this software system, nor their employing *
// * institutes,nor the agencies providing financial support for this *
// * work make any representation or warranty, express or implied, *
// * regarding this software system or assume any liability for its *
// * use. Please see the license in the file LICENSE and URL above *
// * for the full disclaimer and the limitation of liability. *
// * *
// * This code implementation is the result of the scientific and *
// * technical work of the GAMOS collaboration. *
// * By using, copying, modifying or distributing the software (or *
// * any work based on the software) you agree to acknowledge its *
// * use in resulting scientific publications, and indicate your *
// * acceptance of all terms of the GAMOS Software license. *
// ********************************************************************
//
#include "GmUserStackingActionList.hh"
#include "GmUserStackingAction.hh"
#include "G4Track.hh"
#include "G4RunManager.hh"
#include <iostream>
#include "GamosCore/GamosUserActionMgr/include/GmUAVerbosity.hh"
#include "GamosCore/GamosBase/Base/include/GmVFilter.hh"
//-----------------------------------------------------------------------
GmUserStackingActionList::GmUserStackingActionList()
{
}
//-----------------------------------------------------------------------
GmUserStackingActionList::~GmUserStackingActionList()
{
}
//-----------------------------------------------------------------------
void GmUserStackingActionList::PrepareNewEvent()
{
vUStackingA::iterator aite;
for(aite = theStackingActions.begin(); aite != theStackingActions.end(); aite++ ){
#ifndef GAMOS_NO_VERBOSE
if( UAVerb(infoVerb) ) G4cout << " Stacking PrepareNewEvent action executing " << *aite << " " << (*aite)->GetName() << G4endl;
#endif
if( (*aite)->IsEnabled() ) (*aite)->PrepareNewEvent();
}
}
//-----------------------------------------------------------------------
G4ClassificationOfNewTrack GmUserStackingActionList::ClassifyNewTrack(const G4Track* aTrack)
{
G4ClassificationOfNewTrack newClassification = fUrgent;
std::vector<GmVFilter*>::const_iterator ite;
vUStackingA::iterator aite;
for(aite = theStackingActions.begin(); aite != theStackingActions.end();
aite++ ){
G4bool bAccept = TRUE;
if( (*aite)->ApplyFiltersToStacking() ) {
for( ite = (*aite)->theFilters.begin(); ite != (*aite)->theFilters.end(); ite++ ){
if( !(*ite)->AcceptTrack(aTrack) ) {
bAccept = FALSE;
if( !(*aite)->CheckAllFiltersAtStacking() ) break;
}
}
}
#ifndef GAMOS_NO_VERBOSE
if( UAVerb(infoVerb) ) G4cout << " Stacking ClassifyNewTrack action executing " << *aite << " " << (*aite)->GetName() << " bAccept " << bAccept << G4endl;
#endif
if( bAccept ) newClassification = (*aite)->ClassifyNewTrack( aTrack);
}
return newClassification;
}
//-----------------------------------------------------------------------
void GmUserStackingActionList::NewStage()
{
vUStackingA::iterator aite;
for(aite = theStackingActions.begin(); aite != theStackingActions.end();
aite++ ){
#ifndef GAMOS_NO_VERBOSE
if( UAVerb(infoVerb) ) G4cout << " Stacking NewStage action executing " << *aite << " " << (*aite)->GetName() << G4endl;
#endif
if( (*aite)->IsEnabled() ) (*aite)->NewStage();
}
}
//-----------------------------------------------------------------------
void GmUserStackingActionList::AddAction( GmUserStackingAction* ua )
{
theStackingActions.push_back( ua );
#ifndef GAMOS_NO_VERBOSE
if( UAVerb(infoVerb) ) G4cout << " GmUserStackingActionList::AddAction " << " N " << theStackingActions.size() << G4endl;
#endif
//--- first user action, register it to G4StackingManager
if( theStackingActions.size() == 1) G4RunManager::GetRunManager()->SetUserAction( this );
ua->SetStackManager( stackManager );
if( theStackingActions.size() >1) {
G4Exception("GmUserStackingActionList::AddAction ",
" more than 1 action registered",
JustWarning,
"The last action will be taken (run /gamos/verbosity GmUAVerbosity debug to get details");
}
}
//-----------------------------------------------------------------------
void GmUserStackingActionList::RemoveAction( GmUserStackingAction* ua )
{
vUStackingA::iterator ite = find(theStackingActions.begin(), theStackingActions.end(), ua );
if(ite != theStackingActions.end() ) {
theStackingActions.erase( ite );
//--- No user actions in list, unregister it to G4StackingManager
if( theStackingActions.size() == 0) G4RunManager::GetRunManager()->SetUserAction( (G4UserStackingAction*)0 );
} else {
G4cerr << " !!WARNING UserStackingActionaction is not in List " << ua->GetName() << G4endl;
}
}
//-----------------------------------------------------------------------
GmUserStackingAction* GmUserStackingActionList::FindAction( const G4String& name) const
{
vUStackingA::const_iterator ite;
for( ite = theStackingActions.begin(); ite != theStackingActions.end(); ite++ ) {
if( (*ite)->GetName() == name ) {
return *ite;
}
}
return 0;
}
//------------------------------------------------------------------------
G4int GmUserStackingActionList::CountActions( const G4String& name ) const
{
G4int nAct = 0;
vUStackingA::const_iterator ite;
for( ite = theStackingActions.begin(); ite != theStackingActions.end(); ite++ ) {
if( (*ite)->GetName() == name ) {
nAct++;
}
}
return nAct;
}
//-----------------------------------------------------------------------
G4int GmUserStackingActionList::DisableAction( const G4String& name)
{
G4int nActions = 0;
vUStackingA::iterator ite;
for( ite = theStackingActions.begin(); ite != theStackingActions.end(); ite++ ) {
if( (*ite)->GetName() == name ) {
(*ite)->Disable();
nActions++;
}
}
return nActions;
}
//-----------------------------------------------------------------------
G4int GmUserStackingActionList::EnableAction( const G4String& name)
{
G4int nActions = 0;
vUStackingA::iterator ite;
for( ite = theStackingActions.begin(); ite != theStackingActions.end(); ite++ ) {
if( (*ite)->GetName() == name ) {
(*ite)->Enable();
nActions++;
}
}
return nActions;
}
//-----------------------------------------------------------------------
void GmUserStackingActionList::DumpActions( std::ostream& out, G4int enabled)
{
G4String onoff[2] = {"OFF","ON"};
vUStackingA::iterator ite;
for( ite = theStackingActions.begin(); ite != theStackingActions.end(); ite++ ) {
if( enabled == 0
|| (enabled == 1 && (*ite)->IsEnabled() )
|| (enabled == -1 && !(*ite)->IsEnabled() ) ) {
out << " " << (*ite)->GetName() << " " << onoff[ int((*ite)->IsEnabled()) ] << G4endl;
}
}
}
| [
"[email protected]"
] | |
12b89032b91c5900b416ef78dbfbd9162b603eb5 | fc795f4644682e8844b4bc1d3eee3861ff9beb90 | /evaluation.cpp | 37ec9edd2058f8b40f425903dfad8c5b6759db6e | [] | no_license | KostasKotronis/Clustering_n-dimensional_vectors | a3c4a46d0d14c7ea51d30055db889009f8788a7a | 904de8e6c3bf9f684efb600cadff6c8df5b912b1 | refs/heads/master | 2020-04-08T13:49:55.542530 | 2018-12-13T23:27:03 | 2018-12-13T23:27:03 | 159,408,802 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,719 | cpp | #include "./hFiles/headers.h"
#include "./hFiles/evaluation.h"
#include "./hFiles/euclidean.h"
#include "./hFiles/cosine.h"
//evaluate a cluster: Compute average s (i) over all i in some cluster
void silhouette(vector<cluster> clusters, data &dataset, string &outputFileName) {
double sTotal = 0;
ofstream outputFile; //stream class to write on files
outputFile.open(outputFileName, std::ios::app);
if(!outputFile.is_open()) { //in case of open crashed
cout << "outputFile.open crashed. Program is terminating..." << endl;
exit (EXIT_FAILURE);
}
outputFile << "Silhouette: [";
for(int i=0; i<numberOfClusters; i++) { //for every cluster
int numberOfPoints = clusters[i].getNumberOfPoints();
double si = 0;
vector<double> centroid = clusters[i].getCentroid(); //get distance of centroid (a
for(int j=0; j<numberOfPoints; j++) { //for every point in cluster
double a = 0;
int index = clusters[i].getPoint(j);
vector<double> p = dataset.getdVector(index).getCoordinates();
if(dataset.getMetric() == "euclidean")
a = euclideanDistance(p, centroid);
if(dataset.getMetric() == "cosine")
a = cosineDistance(p, centroid);
double b = -1;
for(int z=0; z<numberOfClusters; z++) { //get distance of second closest centroid (b)
if(i != z) {
double bb;
vector<double> centroid2 = clusters[z].getCentroid();
if(dataset.getMetric() == "euclidean")
bb = euclideanDistance(p, centroid2);
if(dataset.getMetric() == "cosine")
bb = cosineDistance(p, centroid2);
if((bb < b) || (b == -1))
b = bb;
}
}
double s; //calculate s for every point
if (b > a)
s = (b - a) / b;
else
s = (b - a) / a;
//cout << index << ". " << s << endl;
if(!isnan(s))
si += s;
}
if(numberOfPoints)
si = si /numberOfPoints; //calculate average si for every cluster
else
si = 0;
//cout << i << ") " << si << endl;
outputFile << si <<",";
sTotal += si;
}
sTotal = sTotal / numberOfClusters; //calculate average s for the dataset
//cout << "sil: " << sTotal << endl;
outputFile << sTotal <<"]" << endl;
outputFile.close();
//cout << "stotal: " << sTotal << endl;
};
| [
"[email protected]"
] | |
99be210e7a3d3d83a554db4a81b1daf324608dca | 20b43bb89dc3f7f4713b750abcdb055ed1802871 | /ch12/ex12_07_test.cpp | 64ae9fb5d4480b71b1ad9b071821e528e3182847 | [] | no_license | icenaive/CppPrimer5Answer | d5a0a38cb0ac81b8aee0b60a235f0343db2324f5 | f3eb6bcdb64a2cd67b8ba42c5db1ece2346b0c80 | refs/heads/master | 2022-09-15T22:33:39.379533 | 2020-06-03T02:37:18 | 2020-06-03T02:37:18 | 261,181,141 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 190 | cpp | #include "ex12_07.hpp"
int main() {
shared_ptr<vector<int>> ptr_vec = vector_pointor_genator();
vector_pointor_process(ptr_vec);
vector_pointor_printer(ptr_vec);
return 0;
} | [
"[email protected]"
] | |
aa61fc33b30eef21048e6704a5456741feb90da1 | 4fbfa2d51a1d1fd5901df2cd618c86591ad7da7b | /HW/Fall_Project/Arduino_Codes/SerialReadForGCS/SerialReadForGCS.ino | fd2e380e5852c4bd36bbea47f8586e7ab97065bb | [] | no_license | unalfaruk/BUAA-MATLAB-2019 | 95c2ea38c7ff8448121686df6431d18af6f7d2f1 | f4c2fbce8d815039050f786a8a0e9c72406e1c42 | refs/heads/master | 2020-09-12T09:01:42.114688 | 2019-11-28T14:57:13 | 2019-11-28T14:57:13 | 222,376,259 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 426 | ino | void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
}
int incomingByte = 0; // for incoming serial data
void loop() {
// put your main code here, to run repeatedly:
if (Serial.available() > 0) {
// read the incoming byte:
incomingByte = Serial.read();
// say what you got:
//Serial.print("I received: ");
Serial.write(incomingByte);
//Serial.println("");
}
}
| [
"[email protected]"
] | |
fdd17ddff55a9fe1f9d6fb42f440fe2769a996d1 | 619f067fdfa074dc08018dff960453d59ae128ae | /ArduinoCo/Trinket/Trinket/Trinket.ino | d1a019d6f9af250ab70c8f699518c5df5fd10531 | [] | no_license | wearablesLab14/cmotion | b56c7607993bf3864f6db0c551864ff844a39a05 | 1c00d71a6f1173f16ad546c75bdb1b772849ad9d | refs/heads/master | 2016-09-15T17:26:03.869089 | 2015-02-15T19:17:23 | 2015-02-15T19:17:23 | 26,441,365 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,461 | ino | /*
Program for the Adafruit Pro Trinket 5V 16Mhz
This code allows the trinket to get data from an Adafruit 10dof sensor,
convert it to a quaternion and send it over serial.
It is encoded as a string with format:
q0w[w value]x[x value]y[y value]z[z value]e
*/
////////////////////////////////// Includes ///////////////////////////////
#include <Adafruit_Sensor.h>
#include <Adafruit_LSM303_U.h>
#include <Adafruit_L3GD20_U.h>
#include<stdlib.h>
#include "Wire.h"
#include "Adafruit10dofSensor.h"
////////////////////////////////// Fields /////////////////////////////////
// Array for the sensor result
float sensorResult[4];
// Adafruit sensor
Adafruit10dofSensor* sensor;
// pin for led (status led, should just be blinking)
int led = 13;
// led state (on/off)
bool ledState = false;
// Timer variable (just for led)
long oldTime = 0;
////////////////////////////////// Setup /////////////////////////////////
void setup() {
// Begin serial communication
Serial.begin(115200);
// Join I2C
Wire.begin();
// Initialize sensor
sensor = new Adafruit10dofSensor();
sensor->initialize();
}
////////////////////////////////// Output ////////////////////////////////
void output(float sensorResult[4])
{
// buffer for floats
char floatBuffer[16];
// string variable
String stringToSend = "";
// build string
stringToSend = String(stringToSend + "q0" +
"w" + dtostrf(sensorResult[0], 1, 6, floatBuffer) +
"x" + dtostrf(sensorResult[1], 1, 6, floatBuffer) +
"y" + dtostrf(sensorResult[2], 1, 6, floatBuffer) +
"z" + dtostrf(sensorResult[3], 1, 6, floatBuffer) + "e");
// Send over serial
Serial.print(stringToSend);
}
///////////////////////////// Blink status led //////////////////////////
void blinkLed() {
if(millis() - oldTime > 500) {
oldTime = millis();
ledState = !ledState;
if(ledState) digitalWrite(led, HIGH);
else digitalWrite(led, LOW);
}
}
////////////////////////////////// Loop ////////////////////////////////
void loop() {
// If the initialization worked
if(sensor->isReady()) {
// Measure
sensor->measure();
// get quaternion data
sensor->getQuaternion(sensorResult);
// write data to serial
output(sensorResult);
// blink with status led
blinkLed();
} else {
// status led should not blink
digitalWrite(led, LOW);
// We can't do anything
while(1){}
}
}
| [
"[email protected]"
] | |
6921875c11dbb8b0a1ba1b046456c74f586e82b2 | 5712a01bc06416cf32fb637e10b21b34b938961c | /Zerojudge/a290 新手訓練系列 - 圖論.cpp | fdca5443c722ef25a0ce7c0cea83bbc4a76d9783 | [] | no_license | WenShihKen/uva | 654a9f5f3e56935625e061795f152609899b79e5 | 03a3d603941dd9b9ec13e76fb99d24da6749a81b | refs/heads/master | 2021-01-10T14:34:29.580527 | 2020-06-25T15:34:23 | 2020-06-25T15:34:23 | 48,536,090 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 813 | cpp | #include<iostream>
#include<cmath>
#include<iostream>
#include<algorithm>
#include<stack>
#include<string>
#include<sstream>
#include<vector>
#include<queue>
#include<string.h>
#include<map>
using namespace std;
int n, m;
int start, endpoint;
bool visit[805] = {};
vector<int>graph[805];
void dfs(int s) {
for (int i = 0; i != graph[s].size(); i++) {
if (visit[graph[s][i]] == false) {
visit[graph[s][i]] = true;
dfs(graph[s][i]);
}
}
}
int main() {
while (scanf("%d%d", &n, &m) != EOF) {
for (int i = 0; i < 803; i++) {
visit[i] = false;
graph[i].clear();
}
for (int i = 0; i < m; i++) {
int t1, t2;
scanf("%d%d", &t1, &t2);
graph[t1].push_back(t2);
}
scanf("%d%d", &start, &endpoint);
dfs(start);
if (visit[endpoint])
puts("Yes!!!");
else
puts("No!!!");
}
}
| [
"[email protected]"
] | |
9edb1a40c84afbb8a416e3f3e709bfc5ae28d270 | 425363dd3190a998cc2b4f947fde5a254440e9c9 | /group2_final/src/order_manager.cpp | cbd745f5fc9f8e99116fb5f5d675f0800a9c5068 | [
"BSD-3-Clause"
] | permissive | ENPM809B/Backup | 2697f36c15ccf7d92bef578d62b0542360da5283 | 07a2d2ca22d5b6ed14d8c0ca5d2d323b2e477362 | refs/heads/master | 2022-05-16T09:17:50.434168 | 2020-04-29T15:16:53 | 2020-04-29T15:16:53 | 259,950,052 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 32,533 | cpp |
#include "order_manager.h"
#include <osrf_gear/AGVControl.h>
#include <ros/ros.h>
#include <std_srvs/Trigger.h>
#include <iomanip>
AriacOrderManager::AriacOrderManager(): arm1_{"arm1"}, arm2_{"arm2"}
{
order_subscriber_ = order_manager_nh_.subscribe(
"/ariac/orders", 10,
&AriacOrderManager::OrderCallback, this);
conveyor_part_found = false;
/* These are joint positions used for the home position
* [0] = linear_arm_actuator
* [1] = shoulder_pan_joint
* [2] = shoulder_lift_joint
* [3] = elbow_joint
* [4] = wrist_1_joint
* [5] = wrist_2_joint
* [6] = wrist_3_joint
*/
flipped_arm1_pose_1 = {1.18, 4.59, -0.50, 0.99, 4.31, -1.53, 0};
flipped_arm1_pose_2 = {1.18, 4.59, -1.50, 1.32, 4.31, -1.53, 0};
flipped_arm1_pose_3 = {1.11, 4.56, -1.00, 1.34, 4.31, -1.53, 0};
flipped_arm1_pose_4 = {1.11, 4.59, -1.00, 1.30, 4.31, -1.53, 0};
// for agv_id = 2
flipped_arm1_pose_5 = {0.50, 4.59, -0.50, 0.99, 4.32, 1.55, 0};
flipped_arm1_pose_6 = {-0.50, 4.59, -0.50, 0.99, 4.32, 1.55, 0};
flipped_arm2_pose_3 = {-0.59, 1.30, -1.37, 1.84, 4.10, -1.53, 0};
flipped_arm2_pose_4 = {-0.59, 1.30, -1.37, 1.97, 4.10, -1.53, 0};
flipped_arm2_pose_1 = {0.69, 1.40, -0.47, 0.95, 4.31, -1.53, 0};
flipped_arm2_pose_2 = {0.72, 1.40, -0.47, 0.85, 4.35, 1.51, 0};
flipped_arm2_pose_5 = {0.72, 1.40, -0.47, 1.00, 4.35, 1.51, 0};
kit_drop_pose_ = {2.65, 1.57, -1.60, 2.0, 4.30, -1.53, 0};
// for out of reach agv_id = 2 and arm1 out of reach
out_arm2_pose1 = {-1.18, 1.43, -0.50, 0.95, 4.25, -1.54, 0};
out_arm2_pose2 = {-1.18, 1.43, -1.13, 1.22, 4.25, -1.53, 0};
out_arm2_pose3 = {-1.11, 1.43, -0.88, 1.09, 4.57, -1.54, 0};
out_arm1_pose1 = {-0.59, 4.58, -0.30, 0.64, 4.43, -1.53, 0};
out_arm1_pose2 = {-0.59, 4.58, -0.30, 0.49, 4.43, 1.61, 0};
}
AriacOrderManager::~AriacOrderManager(){}
void AriacOrderManager::OrderCallback(const osrf_gear::Order::ConstPtr& order_msg) {
ROS_WARN_STREAM(">>>>> OrderCallback");
received_orders_.push_back(*order_msg);
bin1_part = camera_.LogicalCamera1PartType();
bin2_part = camera_.LogicalCamera2PartType();
bin3_part = camera_.LogicalCamera3PartType();
bin4_part = camera_.LogicalCamera4PartType();
bin5_part = camera_.LogicalCamera5PartType();
bin6_part = camera_.LogicalCamera6PartType();
bin_parts = {bin1_part, bin2_part, bin3_part,bin4_part, bin5_part, bin6_part};
// arm1_.SendRobot1();
// arm2_.SendRobot2();
for (const auto &order:received_orders_){
auto order_id = order.order_id;
ROS_INFO_STREAM(order_id);
auto shipments = order.shipments;
for (const auto &shipment: shipments){
auto shipment_type = shipment.shipment_type;
auto agv = shipment.agv_id.back();//--this returns a char
ROS_INFO_STREAM(agv);
int agv_id = (shipment.agv_id == "any") ? 1 : agv - '0';
auto products = shipment.products;
ROS_INFO_STREAM("Order ID: " << order_id);
ROS_INFO_STREAM("Shipment Type: " << shipment_type);
ROS_INFO_STREAM("AGV ID: " << agv_id);
for (const auto &product: products){
ROS_INFO_STREAM("Product"<<product);
product_type_pose_.first = product.type;
product_type_pose_.second = product.pose;
productlist_type.push_back(product.type);
productlist_pose.push_back(product.pose);
if (product.type == bin1_part and agv_id == 1) {
ROS_INFO_STREAM_THROTTLE(5, "Out of range for Arm1");
}
if (product.type == bin6_part and agv_id == 2) {
ROS_INFO_STREAM_THROTTLE(10, "Out of range for Arm2");
}
}
for (auto it = productlist_type.cbegin(); it != productlist_type.cend(); it++){
std::cout << *it << ',' << std::endl;;
if(*it == "piston_rod_part"){
piston_count_++;
}
else if(*it == "gear_part"){
gear_count_++;
}
}
// bin1_part = camera_.LogicalCamera1PartType();
// bin2_part = camera_.LogicalCamera2PartType();
// bin3_part = camera_.LogicalCamera3PartType();
// bin4_part = camera_.LogicalCamera4PartType();
// bin5_part = camera_.LogicalCamera5PartType();
// bin6_part = camera_.LogicalCamera6PartType();
// ROS_INFO_STREAM("Piston count in order: " << piston_count_);
// ROS_INFO_STREAM("Gear count in order " << gear_count_);
ROS_INFO_STREAM("Part read from bin 1: " << bin1_part);
ROS_INFO_STREAM("Part read from bin 2: " << bin2_part);
ROS_INFO_STREAM("Part read from bin 3: " << bin3_part);
ROS_INFO_STREAM("Part read from bin 4: " << bin4_part);
ROS_INFO_STREAM("Part read from bin 5: " << bin5_part);
ROS_INFO_STREAM("Part read from bin 6: " << bin6_part);
}
}
}
/**
* @brief Get the product frame for a product type
* @param product_type
* @return
*/
std::string AriacOrderManager::GetProductFrame(std::string product_type, geometry_msgs::Pose drop_pose) {
//--Grab the last one from the list then remove itle()
ROS_WARN_STREAM("Came Here");
if (!product_frame_list_.empty() && product_frame_list_.count(product_type)!=0) {
std::string frame = product_frame_list_[product_type].back();
// ROS_INFO_STREAM("Frame >>>> " << frame);
product_frame_list_[product_type].pop_back();
return frame;
}
// ROS_ERROR_STREAM("No product frame found for " << product_type);
// ROS_INFO_STREAM("Getting " << product_type << " from the conveyor Belt");
// // else return "NOO";
//
// bool failed_pick = arm1_.PickPartconveyor(product_type);
// // while(!failed_pick){
// // failed_pick = arm1_.PickPartconveyor(product_type); //robot_controller
// // }
// bin_pose.position.x=-0.2;
// bin_pose.position.y=-0.2;
// bin_pose.position.z=0.1;
//
// bin_pose.orientation.x=-0.703527;
// bin_pose.orientation.y=0.0254473;
// bin_pose.orientation.z=-0.710205;
// bin_pose.orientation.w=-0.0032328;
//
// geometry_msgs::PoseStamped StampedPose_in,StampedPose_out;
// // StampedPose_in.header.frame_id = "/bin6_frame";
// // StampedPose_in.pose = bin_pose;
// // part_tf_listener_.transformPose("/world",StampedPose_in,StampedPose_out);
//
// // Drop in the adjacent bin
// // arm1_.DropPart(StampedPose_out.pose);
// StampedPose_in.header.frame_id = "/kit_tray_1";
//
// StampedPose_in.pose = drop_pose;
// // ROS_INFO_STREAM("StampedPose_int (" << StampedPose_in.pose.position.x <<","<< StampedPose_in.pose.position.y << "," << StampedPose_in.pose.position.z<<")");
// part_tf_listener_.transformPose("/world",StampedPose_in,StampedPose_out);
// // StampedPose_out.pose.position.x += 0.2;
// // StampedPose_out.pose.position.y += 0.2;
//
//
// // This is checking if part is faulty ior not
// bool success = false;
// if( not success) {
// success = arm1_.DropPart(StampedPose_out.pose, 1);
// }
//
// // ros::spinOnce();
// // product_frame_list_ = camera_.get_product_frame_list();
// //
// // ROS_INFO_STREAM("Length"<<product_frame_list_.size());
// // std::string frame = product_frame_list_[product_type].back();
// //
// // product_frame_list_[product_type].pop_back();
// return frame;
//
//
// }
}
bool AriacOrderManager::PickAndPlace(const std::pair<std::string,geometry_msgs::Pose> product_type_pose, int agv_id) {
ros::spinOnce();
bool success = false;
std::string product_type = product_type_pose.first;
std::string product_frame;
geometry_msgs::Pose part_pose;
if (!product_frame_list_.empty() && product_frame_list_.count(product_type)!=0) {
product_frame = GetProductFrame(product_type, product_type_pose.second);
part_pose = camera_.GetPartPose("/world", product_frame);
} else {
ROS_ERROR_STREAM("No product frame found for " << product_type);
ROS_INFO_STREAM("Getting " << product_type << " from the conveyor Belt");
bool failed_pick = arm1_.PickPartconveyor(product_type);
conveyor = true;
ROS_INFO_STREAM("Conveyor" << conveyor);
// while(!failed_pick){
// failed_pick = arm1_.PickPartconveyor(product_type); //robot_controller
// }
bin_pose.position.x=-0.2;
bin_pose.position.y=-0.2;
bin_pose.position.z=0.1;
bin_pose.orientation.x=-0.703527;
bin_pose.orientation.y=0.0254473;
bin_pose.orientation.z=-0.710205;
bin_pose.orientation.w=-0.0032328;
geometry_msgs::PoseStamped StampedPose_in,StampedPose_out;
StampedPose_in.header.frame_id = "/kit_tray_1";
StampedPose_in.pose = product_type_pose.second;
part_tf_listener_.transformPose("/world",StampedPose_in,StampedPose_out);
// This is checking if part is faulty ior not
// success = false;
if( not success and agv_id == 1) {
success = arm1_.DropPart(StampedPose_out.pose, 1);
} else {
arm1_.SendRobotPosition(flipped_arm1_pose_1);
this->arm1_.GripperToggle(false);
arm1_.SendRobotPosition(flipped_arm1_pose_2);
this->arm2_.GripperToggle2(true);
arm2_.SendRobotPosition2(flipped_arm2_pose_1);
}
if(placed_parts.size()!=0){
if(placed_parts[placed_parts.size()-1].first==product_type && placed_parts[placed_parts.size()-1].second==StampedPose_out.pose){}
else{
placed_parts.push_back(std::make_pair(product_type,StampedPose_out.pose));
}
}
else {
placed_parts.push_back(std::make_pair(product_type,StampedPose_out.pose));
}
return success;
}
// std::string product_frame = GetProductFrame(product_type, product_type_pose.second);
if(product_type == "pulley_part")
part_pose.position.z += 0.05;
if(product_type == "piston_rod_part")
part_pose.position.z -= 0.0155;
if(product_type == "gear_part")
part_pose.position.z -= 0.011;
if(product_type == "disk_part")
part_pose.position.z = part_pose.position.z;
if(product_type == "gasket_part")
part_pose.position.z = part_pose.position.z;
//--task the robot to pick up this part again from the bin
if (isFlipped) {
FlippedPart(agv_id, part_pose);
}
if (agv_id == 1 and isFlipped == false) {
bool failed_pick = arm1_.PickPart(part_pose, agv_id);
}
if (agv_id == 2 and isFlipped == false) {
home_joint_pose_1 = {1.18, 3.11, -1.60, 2.0, 4.30, -1.53, 0};
arm1_.SendRobotPosition(home_joint_pose_1);
bool failed_pick = arm2_.PickPart(part_pose, agv_id);
}
//--get the pose of the object in the tray from the order
geometry_msgs::Pose drop_pose = product_type_pose.second;
geometry_msgs::PoseStamped StampedPose_in, StampedPose_out;
if(agv_id==1){
StampedPose_in.header.frame_id = "/kit_tray_1";
StampedPose_in.pose = drop_pose;
// ROS_INFO_STREAM("StampedPose_int (" << StampedPose_in.pose.position.x <<","<< StampedPose_in.pose.position.y << "," << StampedPose_in.pose.position.z<<")");
part_tf_listener_.transformPose("/world",StampedPose_in,StampedPose_out);
// StampedPose_out.pose.position.x += 0.2;
// StampedPose_out.pose.position.y += 0.2;
ROS_INFO_STREAM("StampedPose_out (" << StampedPose_out.pose.orientation.x <<","<< StampedPose_out.pose.orientation.y << "," << StampedPose_out.pose.orientation.z<<")");
}
if (agv_id == 2){
StampedPose_in.header.frame_id = "/kit_tray_2";
StampedPose_in.pose = drop_pose;
//ROS_INFO_STREAM("StampedPose_in " << StampedPose_in.pose.position.x);
part_tf_listener_.transformPose("/world",StampedPose_in,StampedPose_out);
// StampedPose_out.pose.position.z += 0.1;
// StampedPose_out.pose.position.y += 0.2;
//ROS_INFO_STREAM("StampedPose_out " << StampedPose_out.pose.position.x);
}
// This is checking if part is faulty ior not
if( not success and agv_id == 1) {
success = arm1_.DropPart(StampedPose_out.pose, agv_id); //robot_controller
} if (not success and agv_id == 2) {
success = arm2_.DropPart(StampedPose_out.pose, agv_id);
}
if(placed_parts.size()!=0 and conveyor == false){
if(placed_parts[placed_parts.size()-1].first==product_type && placed_parts[placed_parts.size()-1].second==StampedPose_out.pose){}
else{
placed_parts.push_back(std::make_pair(product_type,StampedPose_out.pose));
}
}
else {
placed_parts.push_back(std::make_pair(product_type,StampedPose_out.pose));
}
return success;
}
void AriacOrderManager::FlippedPart(int agv_id, auto pose) {
if (agv_id == 1 and isReachable == true) {
home_joint_pose_1 = {1.18, 3.11, -1.60, 2.0, 4.30, -1.53, 0};
arm1_.SendRobotPosition(home_joint_pose_1);
bool failed_pick = arm2_.PickPart(pose);
arm2_.SendRobotPosition2(flipped_arm2_pose_2);
this->arm1_.GripperToggle(true);
arm1_.SendRobotPosition(flipped_arm1_pose_4);
arm1_.SendRobotPosition(flipped_arm1_pose_3);
this->arm2_.GripperToggle2(false);
arm2_.SendRobotPosition2(flipped_arm2_pose_5);
arm2_.SendRobot2();
}
if (agv_id == 2 and isReachable == true) {
bool failed_pick = arm1_.PickPart(pose, 1);
arm1_.SendRobotPosition(flipped_arm1_pose_5);
arm1_.SendRobotPosition(flipped_arm1_pose_6);
arm2_.SendRobotPosition2(flipped_arm2_pose_3);
arm2_.SendRobotPosition2(flipped_arm2_pose_4);
this->arm2_.GripperToggle2(true);
this->arm1_.GripperToggle(false);
arm1_.SendRobot1();
}
if (agv_id == 1 and isReachable == false) {
bool failed_pick = arm1_.PickPart(pose, 1);
arm1_.SendRobotPosition(flipped_arm1_pose_1);
this->arm1_.GripperToggle(false);
arm1_.SendRobotPosition(flipped_arm1_pose_2);
this->arm2_.GripperToggle2(true);
arm2_.SendRobotPosition2(flipped_arm2_pose_1);
arm2_.SendRobotPosition2(flipped_arm2_pose_2);
this->arm1_.GripperToggle(true);
arm1_.SendRobotPosition(flipped_arm1_pose_3);
this->arm2_.GripperToggle2(false);
arm2_.SendRobot2();
}
if (agv_id == 2 and isReachable == false) {
bool failed_pick = arm2_.PickPart(pose);
arm2_.SendRobotPosition2(out_arm2_pose1);
this->arm2_.GripperToggle2(false);
this->arm1_.GripperToggle(true);
arm2_.SendRobotPosition2(out_arm2_pose2);
arm1_.SendRobotPosition(out_arm1_pose1);
arm1_.SendRobotPosition(out_arm1_pose2);
this->arm2_.GripperToggle2(true);
arm2_.SendRobotPosition2(out_arm2_pose3);
this->arm1_.GripperToggle(false);
arm1_.SendRobot1();
}
}
void AriacOrderManager::ExecuteOrder() {
ROS_WARN(">>>>>> Executing order...");
//scanned_objects_ = camera_.GetParts();
//-- used to check if pick and place was successful
bool pick_n_place_success{false};
std::list<std::pair<std::string,geometry_msgs::Pose>> failed_parts;
ros::spinOnce();
ros::Duration(1.0).sleep();
product_frame_list_ = camera_.get_product_frame_list();
int i=0;
bool update=false;
int flag=0;
geometry_msgs::PoseStamped StampedPose_in, StampedPose_out;
// for (const auto &order:received_orders_){
while(true) {
ROS_INFO_STREAM("in");
const auto &order=received_orders_[0];
int size=received_orders_.size();
auto order_id = order.order_id;
auto shipments = order.shipments;
for (const auto &shipment: shipments){
auto shipment_type = shipment.shipment_type;
auto agv = shipment.agv_id.back();//--this returns a char
//-- if agv is any then we use AGV1, else we convert agv id to int
//--agv-'0' converts '1' to 1 and '2' to 2
ROS_INFO_STREAM(agv);
int agv_id = (shipment.agv_id == "any") ? 2 : agv - '0';
auto products = shipment.products;
ROS_INFO_STREAM("Order ID: " << order_id);
ROS_INFO_STREAM("Shipment Type: " << shipment_type);
ROS_INFO_STREAM("AGV ID: " << agv_id);
for (const auto &product: products){
int num = 1;
// Check for Updated Order
ros::spinOnce();
int new_size=received_orders_.size();
if(size!=new_size) {
int diff=new_size-size;
update=checkOrderUpdate(i,diff,order_id, agv_id);
}
if(update==true)
{
break;
}
for (int a = 0; a < bin_parts.size(); a++) {
if (product.type == bin_parts[a]) {
num = 1;
break;
}
else {
num = 0;
}
}
if (num == 0) {
continue;
}
ROS_INFO_STREAM("Product"<<product);
// ros::spinOnce();
// product_frame_list_ = camera_.get_product_frame_list();
product_type_pose_.first = product.type;
//ROS_INFO_STREAM("Product type: " << product_type_pose_.first);
product_type_pose_.second = product.pose;
tf::quaternionMsgToTF(product.pose.orientation,q);
tf::Matrix3x3(q).getRPY(roll, pitch, yaw);
ROS_INFO_STREAM("Roll: " << roll);
if (roll != 0) {
ROS_INFO_STREAM("isFlipped made true");
isFlipped = true;
}
// isFlipped = true;
if (product.type == bin1_part and agv_id == 2 and isFlipped == true) {
isReachable = false;
}
if (product.type == bin6_part and agv_id == 1 and isFlipped == true) {
isReachable = false;
}
StampedPose_in.header.frame_id = "/kit_tray_1";
StampedPose_in.pose = product.pose;
part_tf_listener_.transformPose("/world",StampedPose_in,StampedPose_out);
auto f = std::make_pair(product.type, StampedPose_out.pose);
if(std::find(placed_parts.begin(),placed_parts.end(),f)==placed_parts.end())
{
// ros::spinOnce();
// product_frame_list_ = camera_.get_product_frame_list();
// bool pick_n_place_success = false;
// while (not pick_n_place_success){
if (product.type == bin1_part and agv_id == 1 and isFlipped == false) {
// bool pick_n_place_success = false;
// while (not pick_n_place_success){
std::string num;
for (int i = 0; i < bin_parts.size(); i++) {
if (bin_parts[i].empty() and i != 5) {
empty_bin = "bin" + std::to_string(i+1);
num = std::to_string(i+1);
break;
}
}
while(pick_n_place_success==false){
pick_n_place_success = PickAndPlace(product_type_pose_, empty_bin, agv_id);
}
OutOfReach("arm1", num, product_type_pose_, agv_id);
} else if(product.type == bin6_part and agv_id == 2 and isFlipped == false) {
std::string num;
for (int i = 0; i < bin_parts.size(); i++) {
if (bin_parts[i].empty() and i != 0) {
empty_bin = "bin" + std::to_string(i+1);
num = std::to_string(i+1);
break;
}
}
while(pick_n_place_success==false){
pick_n_place_success = PickAndPlace(product_type_pose_, empty_bin, agv_id);
}
OutOfReach("arm2", num, product_type_pose_, agv_id);
} else {
while(pick_n_place_success==false){
pick_n_place_success = PickAndPlace(product_type_pose_, agv_id);
}
}
// ROS_INFO_STREAM(placed_parts.size());
// ROS_INFO_STREAM(placed_parts[placed_parts.size()-1].first);
pick_n_place_success=false;
}
//--todo: What do we do if pick and place fails?
}
//wait 5 sec
if(update==false)
{
ros::Time a=ros::Time::now();
ros::Duration(5).sleep();
ros::Time b=ros::Time::now();
ros::Duration diffi1=b-a;
ros::Time lasttime=ros::Time::now();
ros::Time currtime=ros::Time::now();
ros::Duration diffi=currtime-lasttime;
while(diffi<diffi1)
{
ros::Time currtime=ros::Time::now();
diffi=currtime-lasttime;
ros::spinOnce();
}
int new_size=received_orders_.size();
if(size!=new_size) {
int diff=new_size-size;
update=checkOrderUpdate(i,diff,order_id, agv_id);
}
}
if(update==false) {
SubmitAGV(agv_id);
ROS_INFO_STREAM("Submitting AGV");
placed_parts.clear();
int finish=1;
}
else {
break;
}
}
received_orders_.erase(received_orders_.begin());
// ROS_INFO_STREAM(received_orders_.size());
update=false;
// Again check for update
if (received_orders_.size()==0)
{
break;
}
}
}
void AriacOrderManager::SubmitAGV(int num) {
std::string s = std::to_string(num);
ros::ServiceClient start_client =
order_manager_nh_.serviceClient<osrf_gear::AGVControl>("/ariac/agv"+s);
if (!start_client.exists()) {
// ROS_INFO("Waiting for the client to be ready...");
start_client.waitForExistence();
// ROS_INFO("Service started.");
}
osrf_gear::AGVControl srv;
// srv.request.kit_type = "order_0_kit_0";
start_client.call(srv);
if (!srv.response.success) {
// ROS_ERROR_STREAM("Service failed!");
} else{
// ROS_INFO("Service succeeded.");
}
}
void AriacOrderManager::dropallparts(std::vector<std::pair<std::string,geometry_msgs::Pose>> placed_parts, int agv_id)
{
home_joint_pose_1 = {0.0, 3.11, -1.60, 2.0, 4.30, -1.53, 0};
home_joint_pose_2 = {-1.18, 3.11, -1.60, 2.0, 4.30, -1.53, 0};
int i=0;
do {
// ROS_INFO_STREAM(i);
if (agv_id == 1) {
drop_pose_ = {2.4, 1.57, -1.60, 2.0, 4.30, -1.53, 0};
arm1_.PickPart(placed_parts[i].second, agv_id);
arm1_.SendRobotPosition(drop_pose_);
arm1_.GripperToggle(false);
} else {
drop_pose_ = {-0.89, -2.11, -1.60, 2.0, 4.30, -1.53, 0};
arm2_.PickPart(placed_parts[i].second, agv_id);
arm2_.SendRobotPosition(drop_pose_);
arm2_.GripperToggle2(false);
}
i++;
}while(i<placed_parts.size());
if (agv_id == 1) arm1_.SendRobotPosition(home_joint_pose_1);
else arm2_.SendRobotPosition2(home_joint_pose_2);
}
std::vector<std::string> AriacOrderManager::GetProductType(){
return productlist_type;
}
std::vector<geometry_msgs::Pose> AriacOrderManager::GetProductPose(){
return productlist_pose;
}
bool AriacOrderManager::checkOrderUpdate(int i,int diff, std::string order_id, int agv_id){
int update_no=0;
for(int k=i+1;k<diff+1;k++) {
const auto &var = received_orders_[k];
ROS_INFO_STREAM("Order"<<var.order_id);
auto new_order=var.order_id;
if(order_id+"_update_"+std::to_string(update_no)==new_order) {
ROS_INFO_STREAM("Found a New Order");
auto new_shipments = var.shipments;
const auto &var1 = new_shipments[0];
auto new_agv=var1.agv_id.back();
int new_agv_id = (var1.agv_id == "any") ? 2 : new_agv - '0';
auto new_products = var1.products;
int parts_in_order=0;
int parts_already_placed=0;
bool all_different=false;
std::vector<int> present;
std::vector<int> present_wrong_location;
// Check which parts exist at same location in new order
// Check which parts are at diffrent locations (Can be shuffled)
geometry_msgs::PoseStamped StampedPose_in, StampedPose_out;
if(new_agv_id==agv_id)
{
for (const auto &p: new_products)
{
parts_in_order++;
ROS_INFO_STREAM("new"<<p.type);
StampedPose_in.header.frame_id = "/kit_tray_1";
StampedPose_in.pose = p.pose;
part_tf_listener_.transformPose("/world",StampedPose_in,StampedPose_out);
ROS_INFO_STREAM("new"<<StampedPose_out.pose);
for(int q=0;q<placed_parts.size();q++)
{
ROS_INFO_STREAM("old"<<placed_parts[q].first);
ROS_INFO_STREAM("old"<<placed_parts[q].second);
if(p.type==placed_parts[q].first && StampedPose_out.pose==placed_parts[q].second)
{
present.push_back(q);
}
else if(p.type == placed_parts[q].first)
{
present_wrong_location.push_back(q);
}
}
}
ROS_INFO_STREAM("Length"<<present.size());
ROS_INFO_STREAM("Length"<<placed_parts.size());
std::vector<std::pair<std::string,geometry_msgs::Pose>> parts_to_remove;
parts_to_remove=placed_parts;
// Keep parts which are at right pose or can be shuffled
if(present.size()>0 )
{
ROS_INFO_STREAM("Dropping unrequired parts");
for(int l=0;l<present.size();l++){
parts_to_remove.erase(parts_to_remove.begin() + present[l]);
}
for(int h=0;h<placed_parts.size();h++)
{
if(std::find(present.begin(),present.end(),h)==present.end())
{
placed_parts.erase(placed_parts.begin() + h);
}
}
ROS_INFO_STREAM("Length"<<placed_parts.size());
dropallparts(parts_to_remove, agv_id);
return true;
}
}
// drop all parts if updated order on different AGV
// drop all parts if all parts are different
if(agv_id!=new_agv_id || (present.size()==0 && present_wrong_location.size()==0) )
{
ROS_INFO_STREAM("All parts in new order are different or on Other AGV");
ROS_INFO_STREAM("Dropping all parts in the kit");
dropallparts(placed_parts, agv_id);
placed_parts.clear();
return true;
}
}
update_no++;
}
return false;
}
bool AriacOrderManager::PickAndPlace(std::pair<std::string,geometry_msgs::Pose> product_type_pose, std::string empty_bin, int agv_id) {
std::string product_type = product_type_pose.first;
std::string product_frame = GetProductFrame(product_type, product_type_pose.second);
auto part_pose = camera_.GetPartPose("/world", product_frame);
if(product_type == "pulley_part")
part_pose.position.z += 0.08;
if(product_type == "piston_rod_part")
part_pose.position.z -= 0.0155;
if(product_type == "gear_part")
part_pose.position.z -= 0.011;
if(product_type == "disk_part")
part_pose.position.z = part_pose.position.z;
if(product_type == "gasket_part")
part_pose.position.z = part_pose.position.z;
home_joint_pose_1 = {0.0, 3.11, -1.60, 2.0, 4.30, -1.53, 0};
home_joint_pose_2 = {-1.18, 3.11, -1.60, 2.0, 4.30, -1.53, 0};
//--task the robot to pick up this part again from the bin
if (agv_id == 2) {
bool failed_pick = arm1_.PickPart(part_pose, 1);
} else {
arm1_.SendRobotPosition(home_joint_pose_1);
bool failed_pick = arm2_.PickPart(part_pose);
}
//--get the pose of the object in the tray from the order
geometry_msgs::Pose drop_pose = product_type_pose.second;
geometry_msgs::PoseStamped StampedPose_in, StampedPose_out;
StampedPose_in.header.frame_id = "/" + empty_bin + "_frame";
StampedPose_in.pose = drop_pose;
// ROS_INFO_STREAM("StampedPose_int (" << StampedPose_in.pose.position.x <<","<< StampedPose_in.pose.position.y << "," << StampedPose_in.pose.position.z<<")");
part_tf_listener_.transformPose("/world",StampedPose_in,StampedPose_out);
bool success = false;
if (agv_id == 2 and !success) {
success = arm1_.DropPart(StampedPose_out.pose);
} else {
success = arm2_.DropPart(StampedPose_out.pose);
}
return true;
}
void AriacOrderManager::OutOfReach(std::string arm, std::string num, std::pair<std::string,geometry_msgs::Pose> product, int agv_id) {
// geometry_msgs::Pose part_pose;
geometry_msgs::Pose part_pose = camera_.BinGetPartPose("/world", product.first, num);
home_joint_pose_1 = {0.0, 3.11, -1.60, 2.0, 4.30, -1.53, 0};
// bool pick_n_place_success_1 = arm1_.PickPart(product_type_pose_, agv_id);
if(product.first == "pulley_part")
part_pose.position.z += 0.08;
if(product.first == "piston_rod_part")
part_pose.position.z -= 0.0155;
if(product.first == "gear_part")
part_pose.position.z -= 0.011;
if(product.first == "disk_part")
part_pose.position.z = part_pose.position.z;
if(product.first == "gasket_part")
part_pose.position.z = part_pose.position.z;
//--task the robot to pick up this part again from the bin
if (arm == "arm1") {
// arm1_.SendRobotHome();
bool failed_pick = arm1_.PickPart(part_pose, agv_id);
} else {
arm1_.SendRobotPosition(home_joint_pose_1);
bool failed_pick = arm2_.PickPart(part_pose, agv_id);
}
//--get the pose of the object in the tray from the order
geometry_msgs::Pose drop_pose = product.second;
geometry_msgs::PoseStamped StampedPose_in, StampedPose_out;
if(arm == "arm1"){
StampedPose_in.header.frame_id = "/kit_tray_1";
StampedPose_in.pose = drop_pose;
// ROS_INFO_STREAM("StampedPose_int (" << StampedPose_in.pose.position.x <<","<< StampedPose_in.pose.position.y << "," << StampedPose_in.pose.position.z<<")");
part_tf_listener_.transformPose("/world",StampedPose_in,StampedPose_out);
// StampedPose_out.pose.position.x += 0.2;
// StampedPose_out.pose.position.y += 0.2;
// ROS_INFO_STREAM("StampedPose_out (" << StampedPose_out.pose.position.x <<","<< StampedPose_out.pose.position.y << "," << StampedPose_out.pose.position.z<<")");
}
else{
StampedPose_in.header.frame_id = "/kit_tray_2";
StampedPose_in.pose = drop_pose;
//ROS_INFO_STREAM("StampedPose_in " << StampedPose_in.pose.position.x);
part_tf_listener_.transformPose("/world",StampedPose_in,StampedPose_out);
// StampedPose_out.pose.position.z += 0.1;
// StampedPose_out.pose.position.y += 0.2;
//ROS_INFO_STREAM("StampedPose_out " << StampedPose_out.pose.position.x);
}
// This is checking if part is faulty ior not
bool success = false;
if( not success and arm == "arm1") {
// arm1_.SendRobotHome1();
success = arm1_.DropPart(StampedPose_out.pose, agv_id);
// bool failed_pick = arm2_.PickPart(part_pose, agv_id); //robot_controller
} else {
success = arm2_.DropPart(StampedPose_out.pose, agv_id);
// bool failed_pick = arm1_.PickPart(part_pose, agv_id);
}
placed_parts.push_back(std::make_pair(product.first,StampedPose_out.pose));
}
| [
"[email protected]"
] | |
aeaa286498514531ef8f4d5d9c904c303ea1c9c7 | 76261aae39cfc15a2b3444665ebcb23a657db361 | /Release/Source/Ripley/ModerationEmailManagementBuilder.cpp | 38b08accd50ed3443da4c529e52d07c47fe56529 | [] | no_license | rocketeerbkw/DNA | d208c72690ccfae261beb531fb52d1c2647783e3 | de5993d6d0f8dd735085ebca4c86f4363c498615 | refs/heads/master | 2021-01-21T13:29:52.930616 | 2015-10-01T17:05:40 | 2015-10-01T17:05:40 | 43,528,993 | 1 | 0 | null | 2015-10-02T00:43:08 | 2015-10-02T00:43:08 | null | UTF-8 | C++ | false | false | 18,409 | cpp | #include "stdafx.h"
#include ".\moderationemailmanagementbuilder.h"
#include ".\storedprocedure.h"
#include ".\emailtemplate.h"
#include ".\emailvocab.h"
#include ".\moderationclasses.h"
#include ".\basicsitelist.h"
CModerationEmailManagementBuilder::CModerationEmailManagementBuilder(CInputContext& inputContext) :
CXMLBuilder(inputContext),
m_emailInserts(inputContext),
m_iAccessID(0),
m_iViewID(0),
m_sViewObject("all"),
m_sAccessObject(""),
m_sViewType("default"),
m_iViewTypeID(0),
m_iClassID(0),
m_iSiteID(0),
m_iSavedClassID(0)
{
}
CModerationEmailManagementBuilder::~CModerationEmailManagementBuilder(void)
{
}
/*********************************************************************************
bool CModerationEmailManagementBuilder::Build(CWholePage* pPage)
Author: David Williams
Created: 11/01/2005
Inputs: -
Outputs: -
Returns: -
Purpose: Display Moderation Classes
Display Associated Sites
Display list of email templates for the mod class.
The ModerationManagementBuilder class displays the same thing.
*********************************************************************************/
bool CModerationEmailManagementBuilder::Build(CWholePage* pPage)
{
bool bResult = true;
m_pPage = pPage;
InitPage(m_pPage, "MOD-EMAIL-MANAGEMENT", true);
m_pViewer = m_InputContext.GetCurrentUser();
if (m_pViewer == NULL)
{
SetDNALastError("CModerrationEmailManagementBuilder", "MustBeLoggedIn", "The user must be logged in");
return pPage->AddInside("H2G2", GetLastErrorAsXMLString());
}
// This builder can only be used by a moderator
if (!m_pViewer->GetIsSuperuser())
{
SetDNALastError("CModerationEmailManagementBuilder", "InsufficientAccessRights", "The active user requires moderator access rights.");
return pPage->AddInside("H2G2", GetLastErrorAsXMLString());
}
//this method sets up some member variables indicating the
//class/site we are looking at, as chosen by the client
GetModeratorViewParameters();
// we will also make use of email templates in one way or another
CEmailTemplates emailTemplates(m_InputContext, m_iViewID, m_sViewObject);
// and email inserts.
m_emailInserts.Initialise(m_iViewID, m_sViewObject);
// there are a number of activities that can be performed on the templates
CTDVString sNextAction = "default";
CTDVString sStatus = "";
CTDVString sAction = "";
CTDVString sTemplateName = "";
CTDVString sInsertName = "";
CTDVString sSelectedSite = "0";
//default values
m_sViewType = m_sViewObject;
m_iViewTypeID = m_iViewID;
CTDVString sSiteXML;
BuildSitesList(sSiteXML);
pPage->AddInside("H2G2", sSiteXML);
int iModClassId = m_InputContext.GetParamInt("modclassid");
if (m_InputContext.ParamExists("action"))
{
m_InputContext.GetParamString("action", sAction);
m_InputContext.GetParamString("emailtemplatename", sTemplateName);
m_InputContext.GetParamString("insertname", sInsertName);
CEmailTemplate emailTemplate(m_InputContext);
sAction.MakeLower();
if (sAction.CompareText("removeemail"))
{
sNextAction = "default";
m_sViewType = "removeemail";
m_iViewTypeID = m_InputContext.GetParamInt("emailtemplateid");
if ( iModClassId == 0 || sTemplateName.IsEmpty() )
sStatus = sTemplateName + " not removed";
else if ( emailTemplate.RemoveEmailTemplate(iModClassId, sTemplateName) )
sStatus = sTemplateName + " has been removed";
}
if (sAction.CompareText("editemail"))
{
sStatus = sTemplateName + " being edited";
sNextAction = "editemail";
m_sViewType = "editemail";
m_iViewTypeID = m_InputContext.GetParamInt("emailtemplateid");
}
if (sAction.CompareText("editinsert"))
{
sStatus = sInsertName + " being edited";
sNextAction = "editinsert";
m_sViewType = "editinsert";
m_iSiteID = m_iViewID;
m_iViewTypeID = m_InputContext.GetParamInt("insertid");
}
if (sAction.CompareText("removeinsert"))
{
sStatus = sInsertName + " removed";
sNextAction = "removeinsert";
m_sViewType = "removeinsert";
m_iViewTypeID = m_InputContext.GetParamInt("insertid");
if (m_sViewObject.CompareText("site"))
{
m_emailInserts.RemoveSiteEmailInsert(m_iViewID, sInsertName);
}
else
{
m_emailInserts.RemoveModClassEmailInsert(m_iViewID, sInsertName);
}
}
}
if (m_InputContext.ParamExists("createnewemail"))
{
sStatus = "Creating new email template";
sNextAction = "createnewemail";
m_sViewType = "createnewemail";
if (m_sViewObject.CompareText("class"))
{
m_iViewTypeID = m_iViewID;
}
else
{
m_iViewTypeID = m_iSavedClassID;
}
}
if (m_InputContext.ParamExists("saveandreturnhome"))
{
sNextAction = "default";
//save the email and return back
m_InputContext.GetParamString("action", sAction);
if (sAction.CompareText("save"))
{
bResult = bResult && SaveEmail();
}
else
{
bResult = bResult && SaveEmail(false);
}
m_sViewType = "default";
m_iViewTypeID = 0;
}
if (m_InputContext.ParamExists("saveandcreatenew"))
{
sNextAction = "createnewemail";
m_InputContext.GetParamString("action", sAction);
if (sAction.CompareText("save"))
{
bResult = bResult && SaveEmail();
}
else
{
bResult = bResult && SaveEmail(false);
}
m_sViewType = "createnewemail";
m_iViewTypeID = m_iViewID;
}
if (m_InputContext.ParamExists("insertsaveandreturnhome"))
{
sNextAction = "default";
bResult = bResult && CreateEmailInsert();
m_sViewType = "default";
}
if (m_InputContext.ParamExists("insertsaveandcreatenew"))
{
sNextAction = "createinsert";
m_sViewType = "createinsert";
bResult = bResult && CreateEmailInsert();
if (m_sViewType.CompareText("class"))
{
m_iClassID = m_iViewTypeID;
}
else
{
m_iSiteID = m_iViewTypeID;
}
}
if (m_InputContext.ParamExists("insertcreate"))
{
sNextAction = "createinsert";
if (m_sViewType.CompareText("class"))
{
m_iClassID = m_iViewTypeID;
}
else
{
m_iSiteID = m_iViewTypeID;
}
m_sViewType = "createinsert";
}
pPage->AddInside("H2G2", "<MOD-EMAIL-PAGE PAGE='" + sNextAction + "'></MOD-EMAIL-PAGE>");
pPage->AddInside("H2G2/MOD-EMAIL-PAGE", "<SELECTED-TEMPLATE>" + sTemplateName + "</SELECTED-TEMPLATE>");
pPage->AddInside("H2G2/MOD-EMAIL-PAGE", "<SELECTED-INSERT>" + sInsertName + "</SELECTED-INSERT>");
pPage->AddInside("H2G2/MOD-EMAIL-PAGE", "<PAGE-STATUS>" + sStatus + "</PAGE-STATUS>");
CTDVString sModClass = "<SELECTED-MOD-CLASS>";
sModClass << iModClassId << "</SELECTED-MOD-CLASS>";
pPage->AddInside("H2G2/MOD-EMAIL-PAGE", sModClass);
pPage->AddInside("H2G2/MOD-EMAIL-PAGE", "<SELECTED-SITE>" + sSelectedSite + "</SELECTED-SITE>");
CTDVString sEmailTemplates;
emailTemplates.GetAsString(sEmailTemplates);
pPage->AddInside("H2G2", sEmailTemplates);
CTDVString sEmailInserts;
m_emailInserts.GetAsString(sEmailInserts);
m_emailInserts.GetUpdatedModViewParams(m_sViewType, m_iViewTypeID);
pPage->AddInside("H2G2", sEmailInserts);
CTDVString sModView;
GetModeratorView(sModView);
pPage->AddInside("H2G2", sModView);
CTDVString sClassXML;
BuildModerationClassesList(sClassXML);
pPage->AddInside("H2G2", sClassXML);
CTDVString sEmailInsertGroups;
GetEmailInsertGroups(sEmailInsertGroups);
pPage->AddInside("H2G2", sEmailInsertGroups);
CTDVString sInsertTypes;
sInsertTypes = "<INSERT-TYPES>";
sInsertTypes += "<TYPE>inserted_text</TYPE>";
sInsertTypes += "<TYPE>content_type</TYPE>";
sInsertTypes += "<TYPE>add_content_method</TYPE>";
sInsertTypes += "<TYPE>content_url</TYPE>";
sInsertTypes += "<TYPE>content_subject</TYPE>";
sInsertTypes += "<TYPE>content_text</TYPE>";
sInsertTypes += "<TYPE>reference_number</TYPE>";
sInsertTypes += "<TYPE>nickname</TYPE>";
sInsertTypes += "<TYPE>userid</TYPE>";
sInsertTypes += "</INSERT-TYPES>";
pPage->AddInside("H2G2", sInsertTypes);
if (!bResult)
{
CTDVString sErrMsg;
GetLastErrorAsXMLString(sErrMsg);
pPage->AddInside("H2G2", sErrMsg);
}
return true;
}
/*********************************************************************************
bool CModerationEmailManagementBuilder::SaveEmail(void)
Author: David Williams
Created: 11/01/2005
Inputs: -
Outputs: -
Returns: -
Purpose: -
*********************************************************************************/
bool CModerationEmailManagementBuilder::SaveEmail(bool bSave)
{
bool bResult = false;
CTDVString sName = "";
CTDVString sSubject = "";
CTDVString sBody = "";
m_InputContext.GetParamString("name", sName);
m_InputContext.GetParamString("subject", sSubject);
m_InputContext.GetParamString("body", sBody);
CXMLObject::EscapeAllXML(&sName);
CXMLObject::EscapeAllXML(&sSubject);
CXMLObject::EscapeAllXML(&sBody);
int iModClassID = m_InputContext.GetParamInt("modclassid");
CEmailTemplate emailTemplate(m_InputContext);
if (bSave)
{
bResult = emailTemplate.AddNewEmailTemplate(iModClassID, sName, sSubject, sBody);
}
else
{
bResult = emailTemplate.UpdateEmailTemplate(iModClassID, sName, sSubject, sBody);
}
return bResult;
}
/*********************************************************************************
bool CModerationEmailManagementBuilder::BuildModerationClassesList(CTDVString& sClassXML)
Author: David Williams
Created: 11/01/2005
Inputs: -
Outputs: -
Returns: -
Purpose: -
*********************************************************************************/
bool CModerationEmailManagementBuilder::BuildModerationClassesList(CTDVString& sClassXML)
{
CModerationClasses modClasses(m_InputContext);
modClasses.GetModerationClasses();
modClasses.GetAsString(sClassXML);
return true;
}
/*********************************************************************************
bool CModerationEmailManagementBuilder::BuildSitesList(CTDVString& sSiteXML)
Author: David Williams
Created: 11/01/2005
Inputs: -
Outputs: -
Returns: -
Purpose: -
*********************************************************************************/
bool CModerationEmailManagementBuilder::BuildSitesList(CTDVString& sSiteXML)
{
bool bSaveClassID = false;
if (m_sViewObject.CompareText("site"))
{
bSaveClassID = true;
}
CBasicSiteList sitelist(m_InputContext);
if ( sitelist.PopulateList() )
{
if ( bSaveClassID )
{
//Get site ModClassId
CSite* pSite = sitelist.GetSite(m_iViewID);
if ( pSite )
m_iSavedClassID = pSite->GetModerationClassId();
}
sSiteXML = sitelist.GetAsXML2();
}
else
{
SetDNALastError("CModerationEmailManagementBuilder::BuildSitesList","BuildSitesList","Unable to get sites list.");
return false;
}
return true;
}
/*********************************************************************************
bool CModerationEmailManagementBuilder::GetModeratorView(CTDVString& sModView)
Author: David Williams
Created: 21/01/2005
Inputs: -
Outputs: -
Returns: -
Purpose: Indicates to the skin the current mode to display
viewtype viewid displayed
-------- ------ -----------
default 0 default view
createnewemail id of class form for creation of new email template
createinsert id of site form for creation of new insert
editemail id of email form for editing email template
editinsert id of insert form for editing email insert
removeemail id of email confirmation dialog
removeinsert id of insert confirmation dialog
*********************************************************************************/
bool CModerationEmailManagementBuilder::GetModeratorView(CTDVString& sModView)
{
CDBXMLBuilder xml;
xml.Initialise(&sModView);
xml.OpenTag("MODERATOR-VIEW",true);
xml.AddAttribute("VIEWTYPE", m_sViewType);
xml.AddIntAttribute("VIEWID", m_iViewTypeID, false);
xml.AddIntAttribute("SITEID", m_iSiteID, false);
xml.AddIntAttribute("CLASSID", m_iClassID, true);
xml.CloseTag("MODERATOR-VIEW");
return true;
}
/*********************************************************************************
bool CModerationEmailManagementBuilder::GetModeratorViewParameters()
Author: David Williams
Created: 21/01/2005
Inputs: -
Outputs: -
Returns: -
Purpose: -
*********************************************************************************/
bool CModerationEmailManagementBuilder::GetModeratorViewParameters()
{
if (!m_InputContext.GetParamString("view", m_sViewObject))
{
m_sViewObject = "all";
}
m_iViewID = m_InputContext.GetParamInt("viewid");
m_InputContext.GetParamString("accessobject", m_sAccessObject);
m_iAccessID = 0;
if (m_sAccessObject.FindText("class") == 0)
{
m_iAccessID = atoi(m_sAccessObject.Mid(5));
m_sAccessObject = "class";
}
else if (m_sAccessObject.FindText("site") == 0)
{
m_iAccessID = atoi(m_sAccessObject.Mid(4));
m_sAccessObject = "site";
}
else
{
m_sAccessObject.Empty();
}
return true;
}
/*********************************************************************************
bool CModerationEmailManagementBuilder::CreateEmailInsert()
Author: David Williams
Created: 31/01/2005
Inputs: -
Outputs: -
Returns: -
Purpose: -
*********************************************************************************/
bool CModerationEmailManagementBuilder::CreateEmailInsert()
{
bool bResult = true;
CTDVString sInsertName;
CTDVString sInsertGroup;
CTDVString sNewInsertGroup;
CTDVString sClassInsertText;
CTDVString sSiteInsertText;
CTDVString sInsertText = "";
CTDVString sDuplicateToClass;
CTDVString sState;
CTDVString sSiteID;
CTDVString sReasonDescription = "";
m_InputContext.GetParamString("InsertName", sInsertName);
m_InputContext.GetParamString("InsertGroup", sInsertGroup);
m_InputContext.GetParamString("NewInsertGroup", sNewInsertGroup);
m_InputContext.GetParamString("ClassInsertText", sClassInsertText);
m_InputContext.GetParamString("SiteInsertText", sSiteInsertText);
m_InputContext.GetParamString("DuplicateToClass", sDuplicateToClass);
m_InputContext.GetParamString("ReasonDescription", sReasonDescription);
m_InputContext.GetParamString("state", sState);
CXMLObject::EscapeAllXML(&sInsertName);
CXMLObject::EscapeAllXML(&sInsertGroup);
CXMLObject::EscapeAllXML(&sNewInsertGroup);
CXMLObject::EscapeAllXML(&sClassInsertText);
CXMLObject::EscapeAllXML(&sSiteInsertText);
CTDVString sGroup = sInsertGroup;
if (sInsertGroup.GetLength() == 0 &&
sNewInsertGroup.GetLength() != 0)
{
sGroup = sNewInsertGroup;
}
if (sDuplicateToClass.CompareText("on"))
{
int iModClassID = m_InputContext.GetParamInt("modclassid");
if (sState.CompareText("create"))
{
bResult = m_emailInserts.AddModClassEmailInsert(m_iViewID, sInsertName, sGroup, sClassInsertText, sReasonDescription);
}
else
{
bResult = m_emailInserts.UpdateModClassEmailInsert(iModClassID, sInsertName, sGroup, sClassInsertText, sReasonDescription);
}
}
else
{
int iSite = m_InputContext.GetParamInt("siteid");
if (sState.CompareText("create"))
{
bResult = m_emailInserts.AddSiteEmailInsert(m_iViewID, sInsertName, sGroup, sSiteInsertText, sReasonDescription);
}
else
{
bResult = m_emailInserts.UpdateSiteEmailInsert(iSite, sInsertName, sGroup, sSiteInsertText, sReasonDescription);
}
}
if (!bResult)
{
CTDVString sErrMsg;
CTDVString sErrCode;
m_emailInserts.GetLastErrorMessage(sErrMsg);
sErrCode = m_emailInserts.GetLastErrorCode();
SetDNALastError("CreateEmailInsert", sErrCode, sErrMsg);
}
return bResult;
}
/*********************************************************************************
bool CModerationEmailManagementBuilder::UpdateEmailInsert()
Author: David Williams
Created: 31/01/2005
Inputs: -
Outputs: -
Returns: -
Purpose: -
*********************************************************************************/
bool CModerationEmailManagementBuilder::UpdateEmailInsert()
{
bool bResult = true;
CTDVString sInsertName;
CTDVString sInsertGroup;
CTDVString sNewInsertGroup;
CTDVString sClassInsertText;
CTDVString sSiteInsertText;
CTDVString sInsertText = "";
CTDVString sDuplicateToClass;
CTDVString sState;
CTDVString sReasonDescription = "";
m_InputContext.GetParamString("InsertName", sInsertName);
m_InputContext.GetParamString("InsertGroup", sInsertGroup);
m_InputContext.GetParamString("NewInsertGroup", sNewInsertGroup);
m_InputContext.GetParamString("ClassInsertText", sClassInsertText);
m_InputContext.GetParamString("SiteInsertText", sSiteInsertText);
m_InputContext.GetParamString("DuplicateToClass", sDuplicateToClass);
m_InputContext.GetParamString("ReasonDescription", sReasonDescription);
m_InputContext.GetParamString("state", sState);
if (m_sViewObject.CompareText("class"))
{
//bResult = m_emailInserts.UpdateModClassEmailInsert(sInsertName, sInsertGroup, sInsertText);
}
else if (m_sViewObject.CompareText("site"))
{
bResult = m_emailInserts.UpdateSiteEmailInsert(m_iViewID, sInsertName, sInsertGroup, sInsertText, sReasonDescription);
}
else
{
bResult = SetDNALastError("UpdateEmailInsert", "InvalidOption", "Option other than class or site for view type specified.");
}
return bResult;
}
bool CModerationEmailManagementBuilder::GetEmailInsertGroups(CTDVString& sEmailInsertGroupsXML)
{
CStoredProcedure SP;
m_InputContext.InitialiseStoredProcedureObject(SP);
SP.GetEmailInsertGroups();
CDBXMLBuilder xml;
xml.Initialise(&sEmailInsertGroupsXML, &SP);
xml.OpenTag("EMAIL-INSERT-GROUPS");
while (!SP.IsEOF())
{
xml.DBAddTag("InsertGroup", "GROUP");
SP.MoveNext();
}
xml.CloseTag("EMAIL-INSERT-GROUPS");
return true;
}
| [
"VP-DEV-DNA-1\\NevesM31"
] | VP-DEV-DNA-1\NevesM31 |
ed781e285ddc82fc67a767126906be367ec892a1 | bbdfd57f4e992324d6e41fc0de53b4e6fa6470ce | /src/Analysis.h | a58ec4f853eeffee4f9a7e4f71d93f21170c4399 | [] | no_license | kdipetri/BNL_AC_LGADs | c06aa5af9af5e072de864d28d387c2fcc572c079 | 65d40f50d5a21e7cd62e77eb8fe5a3b2d89db0b9 | refs/heads/master | 2022-07-08T23:49:32.577877 | 2020-05-13T16:23:55 | 2020-05-13T16:23:55 | 255,373,064 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,391 | h | //////////////////////////////////////////////////////////
// This class has been automatically generated on
// Wed Apr 1 21:41:55 2020 by ROOT version 6.12/06
// from TTree pulse/Digitized waveforms
// found on file: run_scope27264_converted.root
//////////////////////////////////////////////////////////
#ifndef Analysis_h
#define Analysis_h
#include <TROOT.h>
#include <TChain.h>
#include <TFile.h>
#include "vector"
#include "PlotHelper.h"
// Header file for the classes stored in the TTree if any.
PlotHelper plotter("");//set up the plotter
TCanvas *c1 = new TCanvas("c1","c1",800,800);
float xmin = 20.3;
float xmax = 20.8;
//float xmin = 19.8;
//float xmax = 21.0;
float ymin = 22.8;
float ymax = 24.2;
int dut = 12;
int thresh = 110;
class Analysis {
public :
TTree *fChain; //!pointer to the analyzed TTree or TChain
Int_t fCurrent; //!current Tree number in a TChain
// Fixed size dimensions of array or collections stored in the TTree if any.
// Declaration of leaf types
UInt_t i_evt;
Float_t channel[4][1600];
Float_t time[1][1600];
Float_t baseline[4];
Float_t baseline_RMS[4];
Float_t noise[4];
Float_t amp[4];
Float_t t_peak[4];
Float_t integral[4];
Float_t intfull[4];
Float_t risetime[4];
Float_t decaytime[4];
Float_t LP2_5[4];
Float_t LP2_10[4];
Float_t LP2_15[4];
Float_t LP2_20[4];
Float_t LP2_25[4];
Float_t LP2_30[4];
Float_t LP2_35[4];
Float_t LP2_40[4];
Float_t LP2_50[4];
Float_t LP2_60[4];
Float_t LP2_30mV[4];
Float_t gaus_mean[4];
Float_t gaus_sigma[4];
Float_t gaus_chi2[4];
Float_t xIntercept;
Float_t yIntercept;
Float_t xResidBack;
Float_t yResidBack;
Float_t xSlope;
Float_t ySlope;
Float_t x_dut[13];
Float_t y_dut[13];
Float_t chi2;
Int_t ntracks;
Int_t nplanes;
Int_t npix;
Int_t nback;
// List of branches
TBranch *b_i_evt; //!
TBranch *b_channel; //!
TBranch *b_time; //!
TBranch *b_baseline; //!
TBranch *b_baseline_RMS; //!
TBranch *b_noise; //!
TBranch *b_amp; //!
TBranch *b_t_peak; //!
TBranch *b_integral; //!
TBranch *b_intfull; //!
TBranch *b_risetime; //!
TBranch *b_decaytime; //!
TBranch *b_LP2_5; //!
TBranch *b_LP2_10; //!
TBranch *b_LP2_15; //!
TBranch *b_LP2_20; //!
TBranch *b_LP2_25; //!
TBranch *b_LP2_30; //!
TBranch *b_LP2_35; //!
TBranch *b_LP2_40; //!
TBranch *b_LP2_50; //!
TBranch *b_LP2_60; //!
TBranch *b_LP2_30mV; //!
TBranch *b_gaus_mean; //!
TBranch *b_gaus_sigma; //!
TBranch *b_gaus_chi2; //!
TBranch *b_xIntercept; //!
TBranch *b_yIntercept; //!
TBranch *b_xResidBack; //!
TBranch *b_yResidBack; //!
TBranch *b_xSlope; //!
TBranch *b_ySlope; //!
TBranch *b_x_dut; //!
TBranch *b_y_dut; //!
TBranch *b_chi2; //!
TBranch *b_ntracks; //!
TBranch *b_nplanes; //!
TBranch *b_npix; //!
TBranch *b_nback; //!
Analysis(TTree *tree=0);
virtual ~Analysis();
virtual Int_t Cut(Long64_t entry);
virtual Int_t GetEntry(Long64_t entry);
virtual Long64_t LoadTree(Long64_t entry);
virtual void Init(TTree *tree);
virtual void Loop(std::string cfg);
virtual Bool_t Notify();
virtual void Show(Long64_t entry = -1);
virtual int n_hits();
virtual void charge_sharing(std::string cfg, int ch1,int ch2,int ch3);
virtual void xpos_lookup( std::string cfg, int ch1, int ch2, int ch3);
virtual void xpos_weight( std::string cfg, int ch1, int ch2, int ch3);
virtual void xpos_single( std::string cfg, int ch1, int ch2, int ch3);
virtual void time_res( std::string cfg, int ch1, int ch2, int ch3);
virtual void make_t0corr( std::string cfg, int ch);
virtual void makeProfiles();
virtual void charge_ratio(std::string cat, int ch1, int ch2);
virtual void charge_fraction(std::string cat, int ch1, int ch2, int ch3);
};
#endif
#ifdef Analysis_cxx
Analysis::Analysis(TTree *tree) : fChain(0)
{
// if parameter tree is not specified (or zero), connect the file
// used to generate this class and read the Tree.
if (tree == 0) {
TFile *f = (TFile*)gROOT->GetListOfFiles()->FindObject("run_scope27264_converted.root");
if (!f || !f->IsOpen()) {
f = new TFile("run_scope27264_converted.root");
}
f->GetObject("pulse",tree);
}
Init(tree);
}
Analysis::~Analysis()
{
if (!fChain) return;
delete fChain->GetCurrentFile();
}
Int_t Analysis::GetEntry(Long64_t entry)
{
// Read contents of entry.
if (!fChain) return 0;
return fChain->GetEntry(entry);
}
Long64_t Analysis::LoadTree(Long64_t entry)
{
// Set the environment to read one entry
if (!fChain) return -5;
Long64_t centry = fChain->LoadTree(entry);
if (centry < 0) return centry;
if (fChain->GetTreeNumber() != fCurrent) {
fCurrent = fChain->GetTreeNumber();
Notify();
}
return centry;
}
void Analysis::Init(TTree *tree)
{
// The Init() function is called when the selector needs to initialize
// a new tree or chain. Typically here the branch addresses and branch
// pointers of the tree will be set.
// It is normally not necessary to make changes to the generated
// code, but the routine can be extended by the user if needed.
// Init() will be called many times when running on PROOF
// (once per file to be processed).
// Set branch addresses and branch pointers
if (!tree) return;
fChain = tree;
fCurrent = -1;
fChain->SetMakeClass(1);
fChain->SetBranchAddress("i_evt", &i_evt, &b_i_evt);
fChain->SetBranchAddress("channel", channel, &b_channel);
fChain->SetBranchAddress("time", time, &b_time);
fChain->SetBranchAddress("baseline", baseline, &b_baseline);
fChain->SetBranchAddress("baseline_RMS", baseline_RMS, &b_baseline_RMS);
fChain->SetBranchAddress("noise", noise, &b_noise);
fChain->SetBranchAddress("amp", amp, &b_amp);
fChain->SetBranchAddress("t_peak", t_peak, &b_t_peak);
fChain->SetBranchAddress("integral", integral, &b_integral);
fChain->SetBranchAddress("intfull", intfull, &b_intfull);
fChain->SetBranchAddress("risetime", risetime, &b_risetime);
fChain->SetBranchAddress("decaytime", decaytime, &b_decaytime);
fChain->SetBranchAddress("LP2_5", LP2_5, &b_LP2_5);
fChain->SetBranchAddress("LP2_10", LP2_10, &b_LP2_10);
fChain->SetBranchAddress("LP2_15", LP2_15, &b_LP2_15);
fChain->SetBranchAddress("LP2_20", LP2_20, &b_LP2_20);
fChain->SetBranchAddress("LP2_25", LP2_25, &b_LP2_25);
fChain->SetBranchAddress("LP2_30", LP2_30, &b_LP2_30);
fChain->SetBranchAddress("LP2_35", LP2_35, &b_LP2_35);
fChain->SetBranchAddress("LP2_40", LP2_40, &b_LP2_40);
fChain->SetBranchAddress("LP2_50", LP2_50, &b_LP2_50);
fChain->SetBranchAddress("LP2_60", LP2_60, &b_LP2_60);
fChain->SetBranchAddress("LP2_30mV", LP2_30mV, &b_LP2_30mV);
fChain->SetBranchAddress("gaus_mean", gaus_mean, &b_gaus_mean);
fChain->SetBranchAddress("gaus_sigma", gaus_sigma, &b_gaus_sigma);
fChain->SetBranchAddress("gaus_chi2", gaus_chi2, &b_gaus_chi2);
fChain->SetBranchAddress("xIntercept", &xIntercept, &b_xIntercept);
fChain->SetBranchAddress("yIntercept", &yIntercept, &b_yIntercept);
fChain->SetBranchAddress("xResidBack", &xResidBack, &b_xResidBack);
fChain->SetBranchAddress("yResidBack", &yResidBack, &b_yResidBack);
fChain->SetBranchAddress("xSlope", &xSlope, &b_xSlope);
fChain->SetBranchAddress("ySlope", &ySlope, &b_ySlope);
fChain->SetBranchAddress("x_dut", x_dut, &b_x_dut);
fChain->SetBranchAddress("y_dut", y_dut, &b_y_dut);
fChain->SetBranchAddress("chi2", &chi2, &b_chi2);
fChain->SetBranchAddress("ntracks", &ntracks, &b_ntracks);
fChain->SetBranchAddress("nplanes", &nplanes, &b_nplanes);
fChain->SetBranchAddress("npix", &npix, &b_npix);
fChain->SetBranchAddress("nback", &nback, &b_nback);
Notify();
}
Bool_t Analysis::Notify()
{
// The Notify() function is called when a new file is opened. This
// can be either for a new TTree in a TChain or when when a new TTree
// is started when using PROOF. It is normally not necessary to make changes
// to the generated code, but the routine can be extended by the
// user if needed. The return value is currently not used.
return kTRUE;
}
void Analysis::Show(Long64_t entry)
{
// Print contents of entry.
// If entry is not specified, print current entry
if (!fChain) return;
fChain->Show(entry);
}
Int_t Analysis::Cut(Long64_t entry)
{
// This function may be called from Loop.
// returns 1 if entry is accepted.
// returns -1 otherwise.
return 1;
}
#endif // #ifdef Analysis_cxx
| [
"[email protected]"
] | |
5342def28ce0c966a56c027cc6e5823b81490902 | 5ee7b59b955ebde297f0dd924382a96a79771681 | /appplnr/PlnrQTpo1NArray.h | 54a365a978181a14ff83f4ac1a1133a4fce1bd9a | [] | no_license | epsitech/planar | a3b22468e6718342218143538a93e7af50debee0 | e97374190feaf229dac4ec941e19f6661150e400 | refs/heads/master | 2021-01-21T04:25:32.542626 | 2016-08-07T19:20:49 | 2016-08-07T19:20:49 | 48,572,177 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 976 | h | /**
* \file PlnrQTpo1NArray.h
* app access code for table TblPlnrQTpo1NArray (declarations)
* \author Alexander Wirthmueller
* \date created: 4 Dec 2015
* \date modified: 4 Dec 2015
*/
#ifndef PLNRQTPO1NARRAY_H
#define PLNRQTPO1NARRAY_H
#include <dartcore/Xmlio.h>
using namespace Xmlio;
/**
* PlnrQTpo1NArray
*/
class PlnrQTpo1NArray {
public:
PlnrQTpo1NArray(const uint jnum = 0, const string stubRef = "");
public:
uint jnum;
string stubRef;
public:
bool readXML(xmlXPathContext* docctx, string basexpath = "", bool addbasetag = false);
};
/**
* ListPlnrQTpo1NArray
*/
class ListPlnrQTpo1NArray {
public:
ListPlnrQTpo1NArray();
ListPlnrQTpo1NArray(const ListPlnrQTpo1NArray& src);
ListPlnrQTpo1NArray& operator=(const ListPlnrQTpo1NArray& src);
~ListPlnrQTpo1NArray();
void clear();
public:
vector<PlnrQTpo1NArray*> nodes;
public:
bool readXML(xmlXPathContext* docctx, string basexpath = "", bool addbasetag = false);
};
#endif
| [
"[email protected]"
] | |
6351a787ec5786906c59f00594ca82724ecd5102 | 09bb73e19075f5023dfba3b6b08a43c2482f0983 | /source/Lib/TLibEncoder/TEncBinCoderV2VwLB.h | 15547a4d94e97896288777171b1f1f192c50c1cc | [] | no_license | xuguangxin/hevc | 816e6eb1d23c058de44cd0043f4b697a6d8bc7ff | e6c72ec98f4db46ab5568742513b8daca5c83727 | refs/heads/master | 2020-06-02T11:23:13.735653 | 2010-09-27T05:12:41 | 2010-09-27T05:12:41 | 35,011,609 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,055 | h | /*! ====================================================================================================================
* \file
TEncBinCoderV2VwLB.h
* \brief
Copyright information.
* \par Copyright statements
HEVC (JCTVC cfp)
This software, including its corresponding source code, object code and executable, may only be used for
(1) research purposes or (2) for evaluation for standardisation purposes within the joint collaborative team on
video coding for HEVC , provided that this copyright notice and this corresponding notice appear in all copies,
and that the name of Research in Motion Limited not be used in advertising or publicity without specific, written
prior permission. This software, as defined above, is provided as a proof-of-concept and for demonstration
purposes only; there is no representation about the suitability of this software, as defined above, for any purpose.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
TRADEMARKS, Product and company names mentioned herein may be the trademarks of their respective owners.
Any rights not expressly granted herein are reserved.
Copyright (C) 2010 by Research in Motion Limited, Canada
All rights reserved.
* \par Full Contact Information
Standards & Licensing Department ([email protected])
Research in Motion
122 West John Carpenter Parkway
Irving, TX 75039, USA
* ====================================================================================================================
*/
#ifndef __TENCV2V__
#define __TENCV2V__
#include "TEncBinCoder.h"
#include "TEncV2VTrees.h"
#include <cstdlib>
#include <cstring>
class TEncClearBit : public TEncBinIf {
public:
virtual Void init ( TComBitIf* pcTComBitIf ) { m_pcBitIf = pcTComBitIf; }
virtual Void uninit () {}
virtual Void start () {}
virtual Void finish () {}
virtual Void copyState ( TEncBinIf* pcTEncBinIf ) { assert(0); }
virtual Void resetBits () { assert(0); }
virtual UInt getNumWrittenBits () { assert(0); return 0; }
Void setBalancedCPUs( UInt ui ) { m_uiBalancedCPUs = ui; }
UInt getBalancedCPUs() { return m_uiBalancedCPUs; }
protected:
virtual Void encodeBin ( UInt uiSymbol, ContextModel& rcSCModel ) {
m_pcBitIf->write( uiSymbol, 1 );
}
virtual Void encodeBinTrm ( UInt uiBit ) {
m_pcBitIf->write( uiBit , 1 );
}
virtual Void encodeBinEP ( UInt uiSymbol ) {
m_pcBitIf->write( uiSymbol, 1 );
}
protected:
TComBitIf* m_pcBitIf;
private:
UInt m_uiBalancedCPUs;
};
const int BUFFER_SIZE = 5000000;
const int TEMP_SIZE = 5000000;
typedef struct {
UInt code, next;
} parallel_buffer;
class TEncClearBuffer : public TEncClearBit {
protected:
parallel_buffer *buffer;
UInt buffer_tail, code_pos[StateCount], bit_pos[StateCount];
UChar *temp_space;
UInt offset;
private:
bool sourceSelectionDone;
UInt symbolCount[StateCount], LPSCount[StateCount];
void init ();
void storeBit(char bit, int state);
public:
virtual Void encodeBin(UInt uiSymbol, ContextModel& rcSCModel);
virtual Void encodeBinTrm ( UInt bit ) {
if (!sourceSelectionDone) { groupStates(); sourceSelectionDone = true; }
storeBit(bit, mergedStatesMapping[62]);
}
virtual Void encodeBinEP ( UInt bit ) {
if (!sourceSelectionDone) { groupStates(); sourceSelectionDone = true; }
storeBit(bit, mergedStatesMapping[0]);
}
virtual Void finish();
protected:
void myPutByte(UChar v) { m_pcBitIf->write( v, 8 ); }
virtual UInt addLoadBalancingHeader() { return 0; }
virtual void groupStates() { }
UInt putPrefCode(UInt v);
UInt getPrefCost(UInt v);
UInt mergedStateCount;
bool lastStateOfGroup[StateCount];
bool selectedTree[TreeCount];
UInt mergedStatesMapping[64];
UInt mergedTree[StateCount];
private:
virtual UInt encode_seq(int tree);
public:
TEncClearBuffer() {
buffer = new parallel_buffer[BUFFER_SIZE];
temp_space = new UChar[TEMP_SIZE];
init();
}
virtual ~TEncClearBuffer() {
delete [] temp_space;
delete [] buffer;
}
Void setState ( UInt* pui ) { memcpy( m_uiState, pui, sizeof(UInt) * StateCount ); }
Void setpState( UInt* pui ) { memcpy( &m_uipState[0][0], pui, sizeof(UInt) * StateCount * 2 ); }
protected:
UInt m_uiState[StateCount];
UInt m_uipState[StateCount][2];
};
class TEncV2V : public TEncClearBuffer {
UInt bitsUsed, codeBuffer;
UInt vlc_pos[StateCount];
UChar *LB_temp_space;
UInt getBestTree(UInt totalCount, UInt LPSCount);
double getTotalCost(UInt tree, UInt totalCount, UInt LPSCount);
void encode_bit(unsigned short state, UChar symbol);
virtual UInt encode_seq(int tree);
virtual UInt addLoadBalancingHeader() {
UInt res = 0;
UInt cpus = getBalancedCPUs();
for (int k = 1; k < cpus; ++k)
res += putPrefCode(LB_temp_space[k * offset / cpus]);
return res;
}
virtual void groupStates();
public:
TEncV2V() { LB_temp_space = new UChar[TEMP_SIZE]; }
~TEncV2V() { delete [] LB_temp_space; }
};
#endif
| [
"davidf@ce97f6c2-8f86-0410-b44d-af84b13ec34f"
] | davidf@ce97f6c2-8f86-0410-b44d-af84b13ec34f |
23c939a8cc0977f31cde5f9afc85e80cd834f680 | 63ebcf1891ed64d114f859f81e7444eb00e499bb | /src/engine/graphics.h | 8525f8f6d7ce8c865d0bcee84b99b912aaa72753 | [] | no_license | ikutoo/MG1906 | a289c02e65afe7ededb0586b2257c1ec04f469e4 | bc4905375474cf7cb2c164b6eb9524bc06d8a9af | refs/heads/master | 2020-06-04T08:54:17.585741 | 2019-08-10T12:32:30 | 2019-08-10T12:32:30 | 191,952,283 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,668 | h | #pragma once
#include <DXLib/DxLib.h>
#include "node.h"
#include "math.h"
namespace DxEngine
{
class CBox2D : public CNode
{
public:
CBox2D(recti vRect, int vColor = 0, bool vFill = true) : m_Rect(vRect), m_Color(vColor), m_Fill(vFill) {}
virtual void drawV() override;
private:
recti m_Rect = {};
int m_Color = 0;
bool m_Fill = true;
};
class CLine2D : public CNode
{
public:
CLine2D(vec2i vPointA, vec2i vPointB, int vColor = 0) : m_PointA(vPointA), m_PointB(vPointB), m_Color(vColor) {}
virtual void drawV() override;
private:
vec2i m_PointA = {}, m_PointB = {};
int m_Color = 0;
};
class CBillboard3D : public CNode
{
public:
CBillboard3D(VECTOR vPos, float vSize, float vAngle, const std::string& vImageFile);
~CBillboard3D();
virtual void drawV() override;
void setAngle(float vAngle) { m_Angle = vAngle; }
private:
VECTOR m_Position = {};
float m_Size = {};
float m_Angle = {};
int m_ImageHandle = -1;
std::string m_ImageFile = {};
};
class CPlane : public CNode
{
public:
CPlane(FLOAT3 vPos, FLOAT3 vNormal, FLOAT2 vSize, float vAngle, const std::string& vImageFile, COLOR_U8 vColor = { 255, 255, 255, 255 });
~CPlane();
virtual void drawV() override;
void setAngle(float vAngle) { m_Angle = vAngle; }
float getAngle() const { return m_Angle; }
void setColor(COLOR_U8 vColor) { m_Color = vColor; }
COLOR_U8 getColor() const { return m_Color; }
private:
VERTEX_3D m_Vertices[6] = {};
COLOR_U8 m_Color = {};
FLOAT3 m_Position = {};
FLOAT3 m_Normal = {};
FLOAT2 m_Size = {};
float m_Angle = {};
int m_ImageHandle = -1;
std::string m_ImageFile = {};
};
} | [
"[email protected]"
] | |
9d2a73bad3c7467605ef2d3155f7e59669e1164a | b24facc805c26cfe8490da50322b3bb4ede0e68a | /VS-Git/stdafx.cpp | d56a5c7e20c276704a7d37c7618e37acdb26ce29 | [] | no_license | wuzhipeng2014/VSproject | dd268c5b4895792ea2a47e6bae84f2e477d84b16 | 948c7b65f60ac87bad7e753c45e0e131db932208 | refs/heads/master | 2020-04-06T03:55:43.479883 | 2015-01-13T03:34:52 | 2015-01-13T03:34:52 | 29,170,762 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 259 | cpp | // stdafx.cpp : 只包括标准包含文件的源文件
// VS-Git.pch 将作为预编译头
// stdafx.obj 将包含预编译类型信息
#include "stdafx.h"
// TODO: 在 STDAFX.H 中
// 引用任何所需的附加头文件,而不是在此文件中引用
| [
"[email protected]"
] | |
417bdeef6d03db2dbcbc2978a4a133de0a37479a | cbbc86a0466ece98f0d3dd8b1ae5508c938e029c | /src/GraphGeneration/FileData.hpp | 963c9f4b6d90f4f443e50f11fa27607f831f459b | [] | no_license | GuillaumeBchd/RelativeNeighborhoodGraph | 118aa01ec70e353aef5107686aead3140199ec6a | aaaed0e3c1988ae330ae790f412bd5263d398318 | refs/heads/master | 2020-09-11T05:02:54.015697 | 2020-01-06T10:47:41 | 2020-01-06T10:47:41 | 221,946,752 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,629 | hpp | //
// FileData.hpp
// RelativeNeighborhoodGraph
//
// Created by GuillaumeBouchard ColinTroisemaine on 15/11/2019.
// Copyright © 2019 GuillaumeBouchard ColinTroisemaine. All rights reserved.
//
#ifndef FileData_hpp
#define FileData_hpp
#include <stdio.h>
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include "Exception.hpp"
/**
*\name FileData
*\brief Class that corresponds to a file of data used to generate the graph.
*This class needs to take two files as input and a separation character.
*The first file is the data file, it contains all the data which will be used to create the nodes of our graph.
*The second file is a small configuration file which contains a simple line to set if a column is a class attribute or not.
*/
class FileData{
//Attributes
private:
char separationCharacter;
std::vector<std::vector<std::string>> matrixOfString;
//We use an int code that specifies if the column is a class attribute of the graph
//0 Non-class attribute
//1 Class attribute not used to build the graph
//2 Class attribute used to build the graph
std::vector<int> isColumnAClass;
unsigned int numberOfRows;
unsigned int numberOfColumns;
//Constructors & Destructors
public:
/**
*\brief Default constructor for the class FileData
*/
FileData();
/**
*\brief FileData's constructor that takes the paths of two files and the separation character in those files. It is recommended to use this constructor.
*\arg filenameOfGraph path to the file containing the data used to create the graph
*\arg filenameForIsColumnAClass path to the file containing the information whether the column is a class attribute or not
*\arg sep separation character in the two files
*/
FileData(std::string filenameOfGraph, std::string filenameForIsColumnAClass, char sep);
//Methods
public:
char getSeparationCharacter(){return separationCharacter;}
unsigned int getNumberOfRows(){return numberOfRows;}
unsigned int getNumberOfColumns(){return numberOfColumns;}
/**
*\brief Getter that return the number of columns that are non class.
*/
unsigned int getNumberOfColumnsNonClass();
//A column can be both a class attribute and used to generate the graph
/**
*\brief Return true if the column given is a class attribute.
*/
bool isColumnAClassAttribute(unsigned int column);
/**
*\brief Return true if the column given is use to generate the graph.
*/
bool isColumnUsedToGenerateTheGraph(unsigned int column);
std::string getString(unsigned int row, unsigned int column){return matrixOfString[row][column];}
/**
*\brief Print the vector of int and the matrix of string
*/
void print();
/**
*\brief Print the matrix of string which is equal to the first file's content.
*/
void printMatrix();
/**
*\brief Print the vector of int which indequates whether the column is a class attribute or not. It is also equal to the second file's content.
*/
void printIsColumnAClassAttribute();
private:
/**
*\brief Method that add a row to the matrix of string from a string given.
*\arg line string which contains the matrix's row.
*/
void addRowOfMatrixFromLine(const std::string & line);
/**
*\brief Cut a string using the separation character to turn it into a vector of strings.
*/
std::string cutStringAfterSperationCharacter(std::string stringToCut);
/**
*\brief Remove the string's part before the the separation character's first occurence.
*/
std::string getFirstElementOfString(std::string stringToSearch);
/**
*\brief Return the first substring before the the separation character's first occurence.
*/
std::vector<std::string> cutStringOnSeparationCharacter(std::string stringToCut);
/**
*\brief Return the number of the separation character's occurence.
*/
unsigned int findNumberOfSeparationCharacter(std::string stringToSearch);
/**
*\brief Setter for the vector of int which indicates whether a column is a class attribute or not from a string.
*/
void setIsColumAClassWithString(std::string line);
/**
*\brief Setter that fill the vector of int with zeros.
*/
void setIsColumAClassToZero();
/**
*\brief Check if the size of the vector of int is the same as the number of columns of the matrix of string.
*/
void checkSize();
};
#endif /* FileData_hpp */
| [
"[email protected]"
] | |
673ef75b5ecc210a996773c8e69621669a8825e9 | 4d4b02b01a1e29650c8fd8dc1e962c10a6d3dbab | /nuclearSurface/imageComponentArray.cc | 1a59e426a802499049be7764817600900ee65c85 | [] | no_license | jwillbold/nuclearShape | 6349e6022585430baa64fa39a03992d11743179c | 08c59e0f5739c1604bb29b386cc31b163e137826 | refs/heads/master | 2020-04-26T09:12:23.557328 | 2009-07-30T04:22:18 | 2009-07-30T04:22:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 29,930 | cc | //
// imageComponentArray.cc
// lsmModeler
//
// Created by Robert Snapp on 2007-02-06.
// Copyright (c) 2007 Robert R. Snapp. All rights reserved.
//
#include "imageHistogram.h"
#include "nuclearSurface.h"
#include "imageComponentArray.h"
#include "grayImage3d.h"
#include "env.h"
#include "lsmVoxelImage.h"
#include "ntuple.h"
#include "convexhull.h"
#include <algorithm>
#include <stdexcept>
#include <set>
using namespace std;
// An STL pair<int,int> data structure is used to store a label in the first component,
// and its frequency in the second. Later we will need to sort the labels according to
// frequency; hence the following boolean function.
bool greaterFrequency(pair<int,int> lhs, pair<int,int> rhs) {
return lhs.second > rhs.second;
}
// A component is defined as a group of adjacent voxels that all contain intensities that are
// greater than or equal to a given threshold. The following function, assigns a unique
// integer label to each component. After calling labelComponents, the output grayImage3d
// labels can be scanned to identify the number of components, and the size of each, that
// lie above a given threshold. If threshold = 0, then an adaptive threshold is computed.
// voxels below threshold are labeled with a 0; those above with a positive integer, such
// that each contiguous set of voxels (assuming a 26 point topology)
// TODO revise the adaptive threshold procedure.
// TODO paramaterize the topology to include 18 and 6 point topologies.
// computeComponents assigns a label to each voxel in the indicated three-dimensional binary
// image, such that voxels that are adjacent to one another (assuming a 26 point topology)
// are assigned a common label for that component, and the labels for each component are unique.
// This is a generalization of the operation described as "pixel labeling"
// Anil Jain's, <i>Fundamentals of Digital Image Processing</i>, Prentice-Hall, p. 409. 1989;
// and in Horn's <i>Robot Vision</i>. During the first pass, equivalence classes of labels are
// maintained in the vector parent, following an algorithm described in Knuth's <i>Art of Computer Programming</i>,
// Vol. 1, Second Edition, 1973, p. 353, attributed to M. J. Fischer and B. A. Galler.
void ImageComponentArray::computeComponents(const binaryImage3d &input) {
if (debug) {
cerr << "ImageComponentArray::computeComponents(...)" << endl;
}
// Initialization
ulong nextLabel = 1; // Start from 1 as 0 represents the background.
ulong rows = input.rows();
ulong cols = input.cols();
ulong lays = input.layers();
float dx = input.getDX();
float dy = input.getDY();
float dz = input.getDZ();
d_labels.setRows(rows);
d_labels.setCols(cols);
d_labels.setLayers(lays);
d_labels.setDX(dx);
d_labels.setDY(dy);
d_labels.setDZ(dz);
if (verbosity > 1) {
std::cerr << "Set voxel dimensions to (dx, dy, dz) = ("
<< d_labels.getDX() << ", "
<< d_labels.getDY() << ", "
<< d_labels.getDZ() << ")" << std::endl;
}
d_labels.resize();
// For maintaining equivalence classes of labels. We create a graph of 1000 disjoint nodes.
// (New nodes will be added as needed.) Each node is either a root node of a tree or is a successor
// in a tree. Using the vector<int> parent, we maintain this equivalence graph, as parent[n]
// returns the parent of node n, i.e., node n is a successor of node parent[n]. Note that if
// node n is a root node, then parent[n] equals nil.
int const nil = -1; // since vectors are zero-indexed.
vector<int> parent(1000, nil);
if (verbosity > 1) {
cerr << "First pass within computeComponents" << endl;
}
// First pass
for(int l = 0; l < static_cast<int>(lays); l++) {
if (verbosity > 1) {
cerr << "L";
}
for(int i = 0; i < static_cast<int>(rows); i++) {
for(int j = 0; j < static_cast<int>(cols); j++) {
if(input.getVoxelClip(i, j, l)) {
// For each active binary voxel, check if a positive label has been assigned to a previously
// visited neighbor (assuming the 26-point topology). In general, this includes nine pixels
// in the previous layer, three pixels in the previous row of the current layer, and the single
// pixel in the previous column of the current row. However, the limits of the following for loops
// take all special cases into account.
for(int ll = max<int>(0, l-1); ll <= l; ll++)
for(int ii = max<int>(0, i-1); ii < min<int>(rows, i + l - ll + 1); ii++)
for(int jj = max<int>(0, j-1); jj < min<int>(cols, ((ll < l || ii < i) ? j + 2 : j)); jj++) {
// read the label of the neighboring voxel
int neighbor = d_labels.getVoxel(ii, jj, ll);
if (neighbor > 0) {
// A positive value indicates that the neighboring pixel is active, and has been assigned
// to the corresponding component.
int center = d_labels.getVoxel(i, j, l);
if (center == 0) {
// A zero value indicates that the current voxel has not yet been assigned to a component.
// Thus, we assign it to the same component as its neighbor.
d_labels.setVoxel(i, j, l, static_cast<ulong>(neighbor));
} else if (neighbor != center) {
// A different positive value indicates that this voxel unites two components that were
// previously assumed to be disjoint. We merge the two components by placing their labels
// in a common equivalence class. (See Knuth, vol. 1).
while(parent[center] != nil) {
center = parent[center];
}
while(parent[neighbor] != nil) {
neighbor = parent[neighbor];
}
if(center != neighbor) {
parent[neighbor] = center;
}
}
}
}
if (d_labels.getVoxel(i, j, l) == 0) {
// No upper-left neighboring pixels are set. Select a new component label.
d_labels.setVoxel(i, j, l, static_cast<GLint>(nextLabel++));
if (nextLabel >= parent.size()) {
// If necessary, enlarge the equivalence graph, parent.
parent.resize(2*nextLabel, nil);
}
}
}
}
}
}
if (verbosity > 1) {
cerr << endl
<< nextLabel - 1 << " labels generated."
<< endl;
}
// Consolidate the equivalence graph: replace the value of parent[n] with the index of the
// root node of the tree that contains node n.
for(ulong i = 1; i < nextLabel; ++i) {
if(parent[i] != nil) {
// If i is not a root node:
int rootNode;
while((rootNode = parent[parent[i]]) != nil) {
parent[i] = rootNode;
}
}
}
if (verbosity > 1) {
cerr << "\nSecond pass." << endl;
}
// Second pass: Replace each label with that of its root node.
for(ulong l = 0; l < lays; l++) {
if (verbosity > 1) {
cerr << "L";
}
for(ulong i = 0; i < rows; i++)
for(ulong j = 0; j < cols; j++) {
ulong k = d_labels.getVoxel(i, j, l);
int v = parent[k];
if (v != nil) {
d_labels.setVoxel(i, j, l, static_cast<ulong>(v));
}
}
}
if (verbosity > 1) {
cerr << "\nRank the positively labeled components." << endl;
}
// Rank the positively labeled components by frequency.
d_labelCount.resize(nextLabel);
for(ulong k = 0; k < nextLabel; k++) {
d_labelCount[k].first = k;
}
for (ulong l = 0; l < lays; l++)
for (ulong i = 0; i < rows; i++)
for (ulong j = 0; j < cols; j++) {
ulong k = d_labels.getVoxel(i, j, l);
if (k > 0) d_labelCount[k].second++; // Ignore 0, which represents the background
}
std::sort(d_labelCount.begin(), d_labelCount.end(), greaterFrequency);
if (verbosity > 1) {
ulong const maxLabelsShown = 25;
for(ulong i = 0; i < min(maxLabelsShown, nextLabel); i++) {
cerr << d_labelCount[i].second << ", ";
}
cerr << endl;
}
//////
// Compute the number of distinct labels in use.
int count = 0;
for(ulong i = 0; i < d_labelCount.size(); i++) {
if (d_labelCount[i].second > 0) {
count++;
} else {
break;
}
}
// Convert the labels so that they assume the sequence 1, 2, 3, ..., with 1 identifying
// the largest componet, 2 the second largest, etc., and 0 denotes the background. The
// element key[i] will provide the value of the new label for what was formerly known as i.
vector<int> key(d_labelCount.size() + 1, -1); // -1 denotes "undefinded."
key[0] = 0; // background label.
for(int i = 0; i < count; i++) {
key[d_labelCount[i].first] = i+1;
d_labelCount[i].first = i+1;
}
// Assign a new label to each voxel, using the new scheme. Note that only the first count
// elements of key have a value other than -1.
for (ulong l = 0; l < d_labels.layers(); l++) {
for (ulong i = 0; i < d_labels.rows(); i++) {
for (ulong j = 0; j < d_labels.cols(); j++) {
int k = d_labels.getVoxel(i, j, l);
int y = key[k];
if (y == -1) {
cerr << "computeComponents(...): "
<< "Something's wrong in file " << __FILE__ << ", line " << __LINE__ << endl
<< "The sorted vector components appears to be corrupt." << endl;
abort();
}
d_labels.setVoxel(i, j, l, y);
}
}
d_labelCount.resize(count);
}
}
#ifdef COMMENT
void ImageComponentArray::computeComponents(const grayImage3d<GLubyte> &input) {
if (debug) {
cerr << "ImageComponentArray::computeComponents(...)" << endl;
}
// Initialization
ulong nextLabel = 1; // Start from 1 as 0 represents the background.
ulong rows = input.rows();
ulong cols = input.cols();
ulong lays = input.layers();
float dx = input.getDX();
float dy = input.getDY();
float dz = input.getDZ();
d_labels.setRows(rows);
d_labels.setCols(cols);
d_labels.setLayers(lays);
d_labels.setDX(dx);
d_labels.setDY(dy);
d_labels.setDZ(dz);
if (verbosity > 1) {
std::cerr << "Set voxel dimensions to (dx, dy, dz) = ("
<< d_labels.getDX() << ", "
<< d_labels.getDY() << ", "
<< d_labels.getDZ() << ")" << std::endl;
}
d_labels.resize();
// For maintaining equivalence classes of labels. We create a graph of 1000 disjoint nodes.
// (New nodes will be added as needed.) Each node is either a root node of a tree or is a successor
// in a tree. Using the vector<int> parent, we maintain this equivalence graph, as parent[n]
// returns the parent of node n, i.e., node n is a successor of node parent[n]. Note that if
// node n is a root node, then parent[n] equals nil.
int const nil = -1; // since vectors are zero-indexed.
vector<int> parent(1000, nil);
if (verbosity > 1) {
cerr << "First pass within computeComponents" << endl;
}
// First pass
for(int l = 0; l < static_cast<int>(lays); l++) {
if (verbosity > 1) {
cerr << "L";
}
for(int i = 0; i < static_cast<int>(rows); i++) {
for(int j = 0; j < static_cast<int>(cols); j++) {
if(input.getVoxelClip(i, j, l)) {
// For each active binary voxel, check if a positive label has been assigned to a previously
// visited neighbor (assuming the 26-point topology). In general, this includes nine pixels
// in the previous layer, three pixels in the previous row of the current layer, and the single
// pixel in the previous column of the current row. However, the limits of the following for loops
// take all special cases into account.
for(int ll = max<int>(0, l-1); ll <= l; ll++)
for(int ii = max<int>(0, i-1); ii < min<int>(rows, i + l - ll + 1); ii++)
for(int jj = max<int>(0, j-1); jj < min<int>(cols, ((ll < l || ii < i) ? j + 2 : j)); jj++) {
// read the label of the neighboring voxel
int neighbor = d_labels.getVoxel(ii, jj, ll);
if (neighbor > 0) {
// A positive value indicates that the neighboring pixel is active, and has been assigned
// to the corresponding component.
int center = d_labels.getVoxel(i, j, l);
if (center == 0) {
// A zero value indicates that the current voxel has not yet been assigned to a component.
// Thus, we assign it to the same component as its neighbor.
d_labels.setVoxel(i, j, l, static_cast<ulong>(neighbor));
} else if (neighbor != center) {
// A different positive value indicates that this voxel unites two components that were
// previously assumed to be disjoint. We merge the two components by placing their labels
// in a common equivalence class. (See Knuth, vol. 1).
while(parent[center] != nil) {
center = parent[center];
}
while(parent[neighbor] != nil) {
neighbor = parent[neighbor];
}
if(center != neighbor) {
parent[neighbor] = center;
}
}
}
}
if (d_labels.getVoxel(i, j, l) == 0) {
// No upper-left neighboring pixels are set. Select a new component label.
d_labels.setVoxel(i, j, l, static_cast<GLint>(nextLabel++));
if (nextLabel >= parent.size()) {
// If necessary, enlarge the equivalence graph, parent.
parent.resize(2*nextLabel, nil);
}
}
}
}
}
}
if (verbosity > 1) {
cerr << endl
<< nextLabel << " labels generated."
<< endl;
}
// Consolidate the equivalence graph: replace the value of parent[n] with the index of the
// root node of the tree that contains node n.
for(ulong i = 1; i < min(nextLabel, parent.size()); ++i) {
if(parent[i] != nil) {
// If i is not a root node:
int rootNode;
while((rootNode = parent[parent[i]]) != nil) {
parent[i] = rootNode;
}
}
}
if (verbosity > 1) {
cerr << "\nSecond pass." << endl;
}
// Second pass: Replace each label with that of its root node.
for(ulong l = 0; l < lays; l++) {
if (verbosity > 1) {
cerr << "L";
}
for(ulong i = 0; i < rows; i++)
for(ulong j = 0; j < cols; j++) {
ulong k = d_labels.getVoxel(i, j, l);
int v = parent[k];
if (v != nil) {
d_labels.setVoxel(i, j, l, static_cast<ulong>(v));
}
}
}
if (verbosity > 1) {
cerr << "\nRank the positively labeled components." << endl;
}
// Rank the positively labeled components by frequency.
d_labelCount.resize(nextLabel);
for(ulong k = 0; k < nextLabel; k++) {
d_labelCount[k].first = k;
}
for (ulong l = 0; l < lays; l++)
for (ulong i = 0; i < rows; i++)
for (ulong j = 0; j < cols; j++) {
ulong k = d_labels.getVoxel(i, j, l);
if (k > 0) d_labelCount[k].second += 1; // Ignore 0, which represents the background
}
std::sort(d_labelCount.begin(), d_labelCount.end(), greaterFrequency);
if (debug) {
ulong const maxLabelsShown = 25;
for(ulong i = 0; i < min(maxLabelsShown, nextLabel); i++) {
cerr << d_labelCount[i].second << ", ";
}
}
if (debug) cerr << "done!" << endl;
}
#endif
#ifdef COMMENT
// The following constructor, ImageComponentArray(...),
// creates an image component array directly from the indicated channel of an lsm image.
// All voxels with intensities greater than or equal to the specified threshold will
// be classified as being active. The domain (or field of view) of the voxel volume
// can be restricted by specifing an appropriate subvolume.
ImageComponentArray::ImageComponentArray(const lsmVoxelImage &input,
ulong channel,
Subvolume &subvol,
GLubyte threshold) {
if (debug) {
cerr << "ImageComponentArray(...):" << endl;
}
ulong nextLabel = 1;
uint32 rows = subvol.height; // input.rows();
uint32 cols = subvol.width; // input.cols();
uint32 layers = subvol.depth; // input.layers();
float dx = input.getDX();
float dy = input.getDY();
float dz = input.getDZ();
if (threshold == 0) {
// select a threshold using the following adaptive algorithm
ImageHistogram h(1);
h.processImage(input, channel);
threshold = static_cast<ulong>(h.getMean() + 1.5*h.getSDev());
}
if(debug){
cerr << "rows = " << rows << endl
<< "cols = " << cols << endl
<< "layers = " << layers << endl
<< "dx = " << dx << " meters" << endl
<< "dy = " << dy << " meters" << endl
<< "dz = " << dz << " meters" << endl
<<"actual threshold = " << threshold << endl;
}
d_labels.setDX(dx);
d_labels.setDY(dy);
d_labels.setDZ(dz);
d_labels.setRows(rows);
d_labels.setCols(cols);
d_labels.setLayers(layers);
d_labels.resize();
int const root = -1;
vector<int> parent(1000, root);
for(int l = 0; l < static_cast<int>(layers); l++) {
if (debug) cerr << "!"; // poor man's progress bar.
int lImage = l + subvol.layer;
for(int i = 0; i < static_cast<int>(rows); i++) {
int iImage = i + subvol.row;
if (debug && i % 128 == 0) cerr << "."; // poor man's progress bar.
for(int j = 0; j < static_cast<int>(cols); j++) {
int jImage = j + subvol.col;
if (input.getVoxelClip(iImage, jImage, lImage, channel) >= threshold) {
// Assign a label to the current voxel that matches the label of any contiguous
// neighbors, assuming a 26-point topology, of which at most 9 + 3 + 1 = 13
// adjacent neighbors have been examined.
for(int ll = max(0, l-1); ll <= l; ll++)
for (int ii = max<int>(0, i-1); ii < min<int>(rows, i + l - ll + 1); ii++)
for (int jj = max<int>(0, j-1); jj < min<int>(cols, ((ll < l || ii < i) ? j + 2 : j)); jj++) {
int neighbor = d_labels.getVoxel(ii, jj, ll);
if (neighbor > 0) {
int center = d_labels.getVoxel(i, j, l);
if (center == 0) {
d_labels.setVoxel(i, j, l, static_cast<ulong>(neighbor));
} else if (neighbor != center) {
int maxValue = max<int>(neighbor, center);
if (maxValue >= static_cast<int>(parent.size())) {
parent.resize(2*maxValue, root);
}
while(parent[center] != root) {
center = parent[center];
}
while(parent[neighbor] != root) {
neighbor = parent[neighbor];
}
if(center != neighbor) {
parent[neighbor] = center;
}
}
}
}
if (d_labels.getVoxel(i, j, l) == 0) {
// no upper-left neighboring pixels are set. Select a new component label.
d_labels.setVoxel(i, j, l, static_cast<GLint>(nextLabel++));
}
}
}
}
}
if (debug) cerr << nextLabel << " labels generated, ";
// Make the equivalence graph shallow.
for(ulong i = 1; i < min(nextLabel, parent.size()); ++i) {
if(parent[i] != root) {
int gramps;
while((gramps = parent[parent[i]]) != root) {
parent[i] = gramps;
}
}
}
for(ulong l = 0; l < layers; l++)
for(ulong i = 0; i < rows; i++)
for(ulong j = 0; j < cols; j++) {
ulong k = d_labels.getVoxel(i, j, l);
int v = parent[k];
if (v != root) {
d_labels.setVoxel(i, j, l, v);
}
}
// Order the positively labeled components, according to their prominence.
d_labelCount.resize(nextLabel);
for(ulong k = 0; k < nextLabel; k++) {
d_labelCount[k].first = k;
}
for (ulong l = 0; l < layers; l++)
for (ulong i = 0; i < rows; i++)
for (ulong j = 0; j < cols; j++) {
ulong k = d_labels.getVoxel(i, j, l);
if (k > 0) d_labelCount[k].second += 1;
}
std::sort(d_labelCount.begin(), d_labelCount.end(), greaterFrequency);
if (debug) {
ulong const maxLabelsShown = 25;
for(ulong i = 0; i < min(maxLabelsShown, nextLabel); i++) {
cerr << d_labelCount[i].second << ", ";
}
}
if (debug) cerr << "done!" << endl;
}
#endif
// This version of pushComponentVoxels pushes only the coordinates of the voxel centers onto
// the vector container.
void ImageComponentArray::pushComponentVoxels(int rank, std::vector<ntuple<int, 3> > &points) {
if (rank < 0 || rank > static_cast<int>(d_labelCount.size()))
throw std::out_of_range("pushComponentVoxels: bad value for rank.");
ulong label = d_labelCount[rank].first;
for(ulong l = 0; l < d_labels.layers(); ++l)
for(ulong i = 0; i < d_labels.rows(); ++i)
for(ulong j = 0; j < d_labels.cols(); ++j) {
if (d_labels.getVoxel(i, j, l) == label) {
points.push_back(ntuple<int, 3>(static_cast<int>(i),
static_cast<int>(j),
static_cast<int>(l)));
}
}
return;
}
#ifdef COMMENT
// This version of pushComponentVoxels inserts the coordinates of the eight vertices that
// delimit each active voxel onto the vector points.
void ImageComponentArray::pushComponentVoxels(int rank, std::vector<ntuple<int, 3> > &points) {
if (rank < 0 || rank > static_cast<int>(d_labelCount.size()))
throw std::out_of_range("pushComponentVoxels: bad value for rank.");
ulong label = d_labelCount[rank].first;
for(ulong l = 0; l < d_labels.layers(); ++l)
for(ulong i = 0; i < d_labels.rows(); ++i)
for(ulong j = 0; j < d_labels.cols(); ++j) {
if (d_labels.getVoxel(i, j, l) == label) {
for(ulong ll = l; ll <= l + 1; ll++) {
for(ulong ii = i; ii <= i + 1; ii++) {
for(ulong jj = j; jj <= j + 1; jj++) {
points.push_back(ntuple<int, 3>(static_cast<int>(ii),
static_cast<int>(jj),
static_cast<int>(ll)));
}
}
}
}
}
return;
}
#endif
void ImageComponentArray::pushComponentShell(ulong rank, std::vector<ntuple<int, 3> > &points) {
if (rank > d_labelCount.size()) {
throw std::out_of_range("pushComponentShell: bad value for rank.");
}
ulong layers = d_labels.layers();
ulong rows = d_labels.rows();
ulong cols = d_labels.cols();
ulong label = d_labelCount[rank].first;
for(int l = 0; l < static_cast<int>(layers); ++l)
for(int i = 0; i < static_cast<int>(rows); ++i)
for(int j = 0; j < static_cast<int>(cols); ++j) {
if (d_labels.getVoxel(i, j, l) == label) {
// Examine the 26 possible neighbors of voxel (i, j, l)
bool isShellVoxel = false;
for (int ll = max(0, l - 1); ll < min(static_cast<int>(layers), l + 1); ll++)
for (int ii = max(0, i - 1); ii < min(static_cast<int>(rows), i + 1); ii++)
for (int jj = max(0, j - 1); jj < min(static_cast<int>(cols), j + 1); jj++) {
if (d_labels.getVoxel(ii, jj, ll) != label) {
isShellVoxel = true;
break;
}
}
if (isShellVoxel) {
for(int ll = l; ll <= l + 1; ll++) {
for(int ii = i; ii <= i + 1; ii++) {
for(int jj = j; jj <= j + 1; jj++) {
points.push_back(ntuple<int, 3>(static_cast<int>(ii),
static_cast<int>(jj),
static_cast<int>(ll)));
}
}
}
}
}
}
return;
}
void ImageComponentArray::renderVoxel(int i, int j, int l) {
float dx = d_labels.getDX();
float dy = d_labels.getDY();
float dz = d_labels.getDZ();
float x[2], y[2], z[2];
for(int ii = 0; ii < 2; ii++) {
x[ii] = (i + ii - 0.5)*dx;
y[ii] = (j + ii - 0.5)*dy;
z[ii] = (l + ii - 0.5)*dz;
}
glBegin(GL_QUADS);
glNormal3f(0, 0, -1.);
glVertex3f(x[0], y[0], z[0]);
glVertex3f(x[0], y[1], z[0]);
glVertex3f(x[1], y[1], z[0]);
glVertex3f(x[1], y[0], z[0]);
glNormal3f(0, -1., 0);
glVertex3f(x[0], y[0], z[0]);
glVertex3f(x[1], y[0], z[0]);
glVertex3f(x[1], y[0], z[1]);
glVertex3f(x[0], y[0], z[1]);
glNormal3f(-1., 0., 0.);
glVertex3f(x[0], y[0], z[0]);
glVertex3f(x[0], y[0], z[1]);
glVertex3f(x[0], y[1], z[1]);
glVertex3f(x[0], y[1], z[0]);
glNormal3f(0., 0., 1.);
glVertex3f(x[0], y[0], z[1]);
glVertex3f(x[1], y[0], z[1]);
glVertex3f(x[1], y[1], z[1]);
glVertex3f(x[0], y[1], z[1]);
glNormal3f(0., 1., 0.);
glVertex3f(x[0], y[1], z[0]);
glVertex3f(x[0], y[1], z[1]);
glVertex3f(x[1], y[1], z[1]);
glVertex3f(x[1], y[1], z[0]);
glNormal3f(1., 0., 0.);
glVertex3f(x[1], y[0], z[0]);
glVertex3f(x[1], y[1], z[0]);
glVertex3f(x[1], y[1], z[1]);
glVertex3f(x[1], y[0], z[1]);
glEnd();
}
void ImageComponentArray::displayComponent(int component) {
if (debug) cerr << "displayComponent(" << component << ")... ";
ulong targetLabel = d_labelCount[component].first;
ulong voxelCount = 0;
for(ulong l = 0; l < d_labels.layers(); l++)
for(ulong i = 0; i < d_labels.rows(); i++)
for(ulong j = 0; j < d_labels.cols(); j++) {
if (targetLabel == d_labels.getVoxel(i, j, l)) {
renderVoxel(i, j, l);
voxelCount++;
}
}
if (debug) cerr << voxelCount << " voxels rendered ... done!" << endl;
return;
}
void ImageComponentArray::displayLayer(ulong l) {
d_colors.rgbPixels(l);
}
double ImageComponentArray::volume(ulong component) const {
double totalVol = 0;
double voxelVol = d_labels.getDX()*d_labels.getDY()*d_labels.getDZ();
ulong layers = d_labels.layers();
ulong rows = d_labels.rows();
ulong cols = d_labels.cols();
ulong targetLabel = d_labelCount[component].first;
for(int l = 0; l < static_cast<int>(layers); l++)
for(int i = 0; i < static_cast<int>(rows); i++)
for(int j = 0; j < static_cast<int>(cols); j++) {
if (d_labels.getVoxelClip(i, j, l) == targetLabel) {
int totalNeighbors = 0;
int likeNeighbors = 0;
for(int ll = max<int>(0, l-1); ll < min<int>(static_cast<int>(layers), l+2); ll++)
for(int ii = max<int>(0, i-1); ii < min<int>(static_cast<int>(rows), i+2); ii++)
for(int jj = max<int>(0, j-1); jj < min<int>(static_cast<int>(cols), j+2); jj++) {
totalNeighbors++;
if (d_labels.getVoxelClip(ii, jj, ll) == targetLabel)
likeNeighbors++;
}
totalVol += (1 + static_cast<double>(likeNeighbors))/(1 + static_cast<double>(totalNeighbors));
}
}
return totalVol*voxelVol;
}
ulong ImageComponentArray::boundaryVoxelCount(int component) const {
ulong boundaryVoxels = 0;
ulong layers = d_labels.layers();
ulong rows = d_labels.rows();
ulong cols = d_labels.cols();
ulong targetLabel = d_labelCount[component].first;
for(int l = 0; l < static_cast<int>(layers); l++)
for(int i = 0; i < static_cast<int>(rows); i++)
for(int j = 0; j < static_cast<int>(cols); j++) {
if (d_labels.getVoxelClip(i, j, l) == targetLabel) {
bool isBoundaryVoxel = false;
for(int ll = max<int>(0, l-1); ll < min<int>(static_cast<int>(layers), l+2); ll++)
for(int ii = max<int>(0, i-1); ii < min<int>(static_cast<int>(rows), i+2); ii++)
for(int jj = max<int>(0, j-1); jj < min<int>(static_cast<int>(cols), j+2); jj++) {
if (d_labels.getVoxelClip(ii, jj, ll) != targetLabel)
isBoundaryVoxel = true;
}
if (isBoundaryVoxel) boundaryVoxels++;
}
}
return boundaryVoxels;
}
void ImageComponentArray::computeConvexHull(ulong i, ConvexHull<int> &c, HullType mode) {
vector<ntuple<int,3> > v;
if (verbosity > 1) {
cerr << "computeConvexHull: Component " << i
<< " uses integer label " << d_labelCount[i].first
<< ", and should have " << d_labelCount[i].second << " voxels." << endl;
}
switch (mode) {
case VOXEL_CENTERS:
pushComponentVoxels(i, v);
break;
case VOXEL_CORNERS:
pushComponentShell(i, v);
break;
}
if (verbosity > 2) {
cout << "Creating a convex hull from " << v.size() << " points." << endl;
}
c.compute(v);
return;
}
GLubyte pkRGB(int r, int g, int b) {
return static_cast<GLubyte>(((((r & 7) << 3) | (g & 7)) << 3) | (b & 3));
}
void ImageComponentArray::makeColorLabels(size_t nLabels) {
vector<GLubyte> table(max(nLabels, static_cast<size_t>(8)) + 1, 0xff);
table[0] = 0; // black
table[1] = pkRGB(7,0,0); // red
table[2] = pkRGB(5,4,0); // orange
table[3] = pkRGB(7,7,0); // yellow
table[4] = pkRGB(1,7,2); // green
table[5] = pkRGB(1,1,3); // blue
table[6] = pkRGB(0,1,2); // magenta
table[7] = pkRGB(5,2,3); // magenta
table[8] = pkRGB(3,0,3); // magenta
ulong rows = d_labels.rows();
ulong cols = d_labels.cols();
ulong layers = d_labels.layers();
d_colors.setRows(rows);
d_colors.setCols(cols);
d_colors.setLayers(layers);
d_colors.resize();
for(ulong l = 0; l < layers; l++) {
for(ulong i = 0; i < rows; i++) {
for(ulong j = 0; j < cols; j++) {
ulong x = d_labels.getVoxel(i, j, l);
d_colors.setVoxel(i, j, l, table[x]);
}
}
}
}
| [
"[email protected]"
] | |
d8a61e0ea216d192f9e8ee54b85c60c064e0c32f | 5565cbbc41627d1a8edd03e058e0884ceb91dc68 | /leetcode/demo.cpp | d2db034e5be89914f03b96e5300480ddcb11413b | [] | no_license | SYeShare/Learning | 3c722216c4dc97751f9ecba5c86f335837b8283c | ea36e3d757922a87ba7695fad02bbbc75b357fef | refs/heads/master | 2021-06-22T07:40:43.959070 | 2020-12-14T14:37:36 | 2020-12-14T14:37:36 | 156,408,291 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 56 | cpp | //new test
#include "origin.hpp"
class Solution_DFS
{
}; | [
"[email protected]"
] | |
71523cb0447e6864a0590b7f119db1b45b683cc6 | a4737f0c8d483afbaeb933392b699b58e7703b03 | /C++/Teach Yourself C++/1. An Overview of C++/pg23Examples.cpp | a3228d84a56d5de1247133d76b11c3d9da33c611 | [] | no_license | abhirathmahipal/Practice | b3acb3a587e4c331cc95cb846fe3609b989c4562 | cd2d08b941cd87be3ce6b4588a2507e6639e5561 | refs/heads/master | 2022-12-20T00:47:47.029396 | 2019-10-02T05:20:31 | 2019-10-02T05:20:31 | 49,846,648 | 2 | 0 | null | 2022-12-10T04:19:44 | 2016-01-18T02:20:26 | JavaScript | UTF-8 | C++ | false | false | 363 | cpp | #include <iostream>
using namespace std;
class myClass {
// private to my class
int a;
public:
void set_a(int num);
int get_a();
};
void myClass:: set_a(int num)
{
a = num;
}
int myClass:: get_a()
{
return a;
}
int main()
{
myClass ob1, ob2;
ob1.set_a(10);
ob2.set_a(99);
cout << ob1.get_a() << "\n";
cout << ob2.get_a() << "\n";
return 0;
}
| [
"[email protected]"
] | |
ed728db8a49683b4f8ccfe7d590fd541bc4f55ac | 0aab048feb1da0ada37ccecab1b0d02b08a52d35 | /test/Core/Physics/PlayerPhysics.h | 4ee76cb8274241972cce1e73dc039049e15f4cd5 | [] | no_license | luckyycode/nanocat-2014 | 94774892336d5d88f7ec35447bbe11e4d2f481f0 | 1fb7e3d6b34506766a101763e739317dee72d0e9 | refs/heads/master | 2020-03-31T05:22:30.388621 | 2018-10-07T13:41:40 | 2018-10-07T13:41:40 | 151,943,607 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,391 | h | //
// * *
// __ *
// ,db' * *
// ,d8/ * * *
// 888
// `db\ * *
// `o`_ **
// * * * _ *
// * / )
// * /\__/\ * ( ( *
// ,-.,-.,) (.,-.,-.,-.) ).,-.,-.
// | @| ={ }= | @| / / | @|o |
// _j__j__j_) `-------/ /__j__j__j_
// ________( /___________
// | | @| \ || o|O | @|
// |o | |,'\ , ,'"| | | | hjw
// vV\|/vV|`-'\ ,---\ | \Vv\hjwVv\//v
// _) ) `. \ /
// (__/ ) )
// _ _ _ _
// | \ | | ___ | | __ ___ ___ _ __ __ _ (_) _ __ ___
// | \| | / _ \| |/ // _ \ / _ \| '_ \ / _` || || '_ \ / _ \
// | |\ || __/| <| (_) | | __/| | | || (_| || || | | || __/
// |_| \_| \___||_|\_\\___/ \___||_| |_| \__, ||_||_| |_| \___|
// |___/
// PlayerPhysics.hpp
// Neko engine
//
// Created by Kawaii Neko on 10/13/15.
// Copyright © 2015 Neko Vision. All rights reserved.
//
#ifndef PlayerPhysics_hpp
#define PlayerPhysics_hpp
#include "../../Math/BoundingBox.h"
#include "../../Math/BoundingSphere.h"
#include "../../World/Quadtree/Quadtree.h" // World ground nodes.
#include "../../Core/Core.h"
namespace Neko {
/**
* Object owner type.
*/
enum class EObjectWorldType : int32_t {
ServerWorld = 0,
ClientWorld
};
class CQuadtreeNode;
/// Physical object.
class CPhysicsObject
{
public:
// Object flags.
const static int32_t PHYS_CHARACTER = 0x1;
const static int32_t PHYS_NONMOVABLE = 0x2; // A static world object.
const static int32_t PHYS_MOVABLE = 0x4; // A movable object but not a character!
// Physics object flags.
const static int32_t PHYS_APPLYGRAVITY = 0x1; // Do do we need to apply the gravity force on the object?
CPhysicsObject();
virtual ~CPhysicsObject();
/**
* Set object position.
*
* @param newPos A new position to set.
*/
inline void SetObjectPos( const Vec3 & newPos ) { m_vPosition = newPos; }
/**
* Get object position.
*/
inline Vec3 GetObjectPos() { return m_vPosition; }
/**
* Set object velocity.
*
* @param newVel A new position to set.
*/
inline void SetVelocity( const Vec3 & newVel ) { m_vVelocity = newVel; }
/**
* Get object velocity.
*/
inline Vec3 & GetVelocity() { return m_vVelocity; }
/**
* Set object acceleration vector.
*
* @param newAccel A new acceleration to set.
*/
inline void SetAcceleration( const Vec3 & newAccel ) { m_vAcceleration = newAccel; }
/**
* Get object acceleration.
*/
inline Vec3 & GetAcceleration() { return m_vAcceleration; }
/**
* Set object default acceleration vector.
*
* @param newAccel A new default acceleration to set.
*/
inline void SetDefaultAcceleration( const Vec3 & newAccel ) { m_vDefaultAcceleration = newAccel; }
/**
* Get object default acceleration.
*/
inline void ResetAcceleration() { m_vAcceleration = m_vDefaultAcceleration; }
/**
* Set object radius.
*
* @param newRadius A new radius value.
*/
inline void SetRadius( const float & newRadius ) { m_fRadius = newRadius; }
/**
* Get object radius.
*/
inline const float & GetRadius() const { return m_fRadius; }
/**
* Set object mass.
*
* @param newMass A new mass value.
*/
inline void SetMass( const float & newMass ) { m_fMass = newMass; }
/**
* Get object mass.
*/
inline const float & GetMass() const { return m_fMass; }
/**
* Is object on the ground?
*/
inline bool IsOnGround() { return m_bCollided; }
/**
* Set a corresponding value.
*/
inline void SetOnGround( bool value ) { m_bCollided = value; }
/**
* Get object flag property.
*/
inline int32_t GetObjectFlags() const { return objectFlags; }
/**
* Set object flag property.
*
* @param flag An option to set.
*/
inline void SetObjectFlag( int32_t flag ) { objectFlags |= flag; }
/**
* Get object's physics flag property.
*/
inline int32_t GetObjectPhysFlags() const { return physicsFlags; }
/**
* Set object's physics flag property.
*
* @param flag An option to set.
*/
inline void SetObjectPhysFlag( int32_t flag ) { physicsFlags |= flag; }
/**
* Set object state to be standing on the node.
*
* @param node A quadtree world node.
*/
inline void StandingOn( const CQuadtreeNode * node ) { m_pNode = node; }
/**
* Get where object is currently standing.
*/
inline const CQuadtreeNode * GetStandingOn() const { return m_pNode; }
/**
* Set bounding box dimension.
*
* @param min Minimum point.
* @param max Maximum point.
*/
inline void SetDimensions( const Vec3 & min, const Vec3 & max ) {
m_bBox = SBoundingBox( min, max );
}
/**
* Get object's bounding box.
*/
inline SBoundingBox * GetBoundingBox() { return &m_bBox; }
/**
* Set bounding box position.
*
* @param newPos A corresponding value.
*/
inline void SetBBoxOrigin( const Vec3 & newPos ) {
m_bBox.Translate( newPos );
}
/**
* Set object scale.
*
* @param newScale A new scale value to set.
*/
inline void SetScale( const Vec3 & newScale ) { m_vScale = newScale; }
/**
* Get object's scale.
*/
inline const Vec3 & GetScale() const { return m_vScale; }
/**
* Set object rotation.
*
* @param newRotation A new rotation value to set.
*/
inline void SetRotation( const Vec3 & newRotation ) { m_vRotation = newRotation; }
/**
* Get object's rotation.
*/
inline const Vec3 & GetRotation() const { return m_vRotation; }
public:
// private:
//! Bounding box.
SBoundingBox m_bBox;
BoundingSphere m_pbSphere;
//! Object position.
Vec3 m_vPosition;
//! Velocity.
Vec3 m_vVelocity;
Vec3 m_vConstVelocity;
//! Acceleration vector.
Vec3 m_vAcceleration;
Vec3 m_vDefaultAcceleration;
//! Object scale.
Vec3 m_vScale;
//! Object rotation.
Vec3 m_vRotation;
//! Object friction.
float m_fFriction;
//! Object radius.
float m_fRadius;
//! Object mass.
float m_fMass;
//! Has collided?
bool m_bCollided;
//! Object flag options.
int32_t objectFlags;
//! Object's physics flags.
int32_t physicsFlags;
//! Object world type.
EObjectWorldType m_worldType;
//! World node.
const CQuadtreeNode *m_pNode;
//! Object standing on.
CPhysicsObject *m_pStandingOn;
};
/// Motion.
struct SMotionInfo
{
Vec3 m_vForce;
Vec3 m_vUnitForce;
float m_fSlideRatio;
float m_fForceMag;
/**
* Constructor.
*/
SMotionInfo() {
Vec3 force( 0.0f, -2.0f, 0.0f );
// Set the gravity value.
SetForce( &force );
m_fSlideRatio = -0.7071f;
}
/**
* Set motion force.
*
* @param pForce Force value to set.
*/
inline void SetForce( const Vec3 * pForce )
{
m_vForce = *pForce;
m_fForceMag = m_vForce.Length();
// Check if we can set the force.
if( m_fForceMag > 0.00001f ) {
m_vUnitForce = m_vForce;
m_vUnitForce = m_vUnitForce / m_fForceMag;
} else {
m_vUnitForce.MakeNull();
}
}
};
/**
* Player movement information.
*/
struct SMoveInfo
{
CPhysicsObject * m_pObject;
float m_fDeltaTime;
Vec3 m_vDisplacement;
};
/**
* A small struct to store object physics values.
*/
struct SContainerPhysics
{
Vec3 m_vVelocity;
Vec3 m_vAcceleration;
CPhysicsObject * m_pHandle;
};
/**
* Ray cast hit test information.
*/
struct SRaycastInfo
{
Vec3 m_vDirection;
Vec3 m_vOrigin;
Vec3 m_vHitOrigin;
int32_t m_bCollided;
float m_fDistance;
float m_fMaxDistance;
CPhysicsObject * m_pObject; //! Can be NEKO_NULL.
CQuadtreeNode * m_pGroundNode; //! World ground node. Can be NEKO_NULL.
SRaycastInfo() {
m_pGroundNode = NEKO_NULL;
m_pObject = NEKO_NULL;
}
};
/// World physics.
class CWorldPhysics
{
NEKO_NONCOPYABLE( CWorldPhysics );
public:
/**
* Constructor.
*/
CWorldPhysics();
/**
* Destructor.
*/
~CWorldPhysics();
/**
* Update physics.
*/
void Update();
/**
* Update ground nodes with its objects.
*/
void UpdateWorldNode( CQuadtreeNode * node, CPhysicsObject * hObject );
/**
* Update movement.
*/
void UpdateMovement( CPhysicsObject * pObject, const float time );
/**
* Check world object collision.
*
* @param node Quadtree node.
* @param hObject An object.
*/
int32_t CheckWorldCollision( CQuadtreeNode * node, CPhysicsObject * hObject );
/**
* Check ray hit intersection.
*/
int32_t RayHitIntersection( SRaycastInfo * raycastInfo, bool touchObjects = false );
/**
* Check world ground ray hit intersection.
*/
int32_t RayHitGroundIntersection( SRaycastInfo * raycastInfo );
/**
* Check object collision.
*
* @param node A quadtree node.
* @param hObject A quadtree chunk objects.
*/
int32_t CheckObjectCollision( CQuadtreeNode * node, CPhysicsObject * hObject );
/**
* Calculate collision information.
*/
bool CalculateCollisionInfo( CPhysicsObject * pObject, Vec3 * pObjectVel, Vec3 * pStopPlane, Vec3 * pVelocityAdd, Vec3 * pForce );
/**
* Retrieve collision offset.
*
* @param vNormal Polygon normal direction.
*/
static Vec3 GetCollisionOffset( Vec3 &vNormal, float radius, float distance );
};
extern CWorldPhysics * g_pWorldPhysics;
/// Player ( character ) physics.
class CPlayerPhysics
{
NEKO_NONCOPYABLE( CPlayerPhysics );
public:
/**
* Constructor.
*/
CPlayerPhysics();
/**
* Destructor.
*/
~CPlayerPhysics();
};
}
#endif /* PlayerPhysics_hpp */
| [
"[email protected]"
] | |
95d53519ed6d62dfc8e42fb2df1e64c9ae65dd6e | 38c10c01007624cd2056884f25e0d6ab85442194 | /third_party/WebKit/Source/core/css/SelectorChecker.cpp | 4cefe5e5155a7e46d3db8f2a29953039a0d05a31 | [
"BSD-3-Clause",
"LGPL-2.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-only",
"GPL-1.0-or-later",
"GPL-2.0-only",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-other-copyleft",
"MIT",
"Apache-2.0"
] | permissive | zenoalbisser/chromium | 6ecf37b6c030c84f1b26282bc4ef95769c62a9b2 | e71f21b9b4b9b839f5093301974a45545dad2691 | refs/heads/master | 2022-12-25T14:23:18.568575 | 2016-07-14T21:49:52 | 2016-07-23T08:02:51 | 63,980,627 | 0 | 2 | BSD-3-Clause | 2022-12-12T12:43:41 | 2016-07-22T20:14:04 | null | UTF-8 | C++ | false | false | 51,801 | cpp | /*
* Copyright (C) 1999 Lars Knoll ([email protected])
* (C) 2004-2005 Allan Sandfeld Jensen ([email protected])
* Copyright (C) 2006, 2007 Nicholas Shanks ([email protected])
* Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 Apple Inc. All rights reserved.
* Copyright (C) 2007 Alexey Proskuryakov <[email protected]>
* Copyright (C) 2007, 2008 Eric Seidel <[email protected]>
* Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
* Copyright (c) 2011, Code Aurora Forum. All rights reserved.
* Copyright (C) Research In Motion Limited 2011. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "config.h"
#include "core/css/SelectorChecker.h"
#include "core/HTMLNames.h"
#include "core/css/CSSSelectorList.h"
#include "core/dom/Document.h"
#include "core/dom/Element.h"
#include "core/dom/ElementTraversal.h"
#include "core/dom/Fullscreen.h"
#include "core/dom/NodeComputedStyle.h"
#include "core/dom/NthIndexCache.h"
#include "core/dom/StyleEngine.h"
#include "core/dom/Text.h"
#include "core/dom/shadow/ComposedTreeTraversal.h"
#include "core/dom/shadow/InsertionPoint.h"
#include "core/dom/shadow/ShadowRoot.h"
#include "core/editing/FrameSelection.h"
#include "core/frame/LocalFrame.h"
#include "core/html/HTMLDocument.h"
#include "core/html/HTMLFrameElementBase.h"
#include "core/html/HTMLInputElement.h"
#include "core/html/HTMLOptionElement.h"
#include "core/html/HTMLSelectElement.h"
#include "core/html/parser/HTMLParserIdioms.h"
#include "core/html/track/vtt/VTTElement.h"
#include "core/inspector/InspectorInstrumentation.h"
#include "core/layout/LayoutObject.h"
#include "core/layout/LayoutScrollbar.h"
#include "core/page/FocusController.h"
#include "core/page/Page.h"
#include "core/style/ComputedStyle.h"
#include "platform/scroll/ScrollableArea.h"
#include "platform/scroll/ScrollbarTheme.h"
namespace blink {
using namespace HTMLNames;
SelectorChecker::SelectorChecker(Mode mode)
: m_mode(mode)
{
}
static bool isFrameFocused(const Element& element)
{
return element.document().frame() && element.document().frame()->selection().isFocusedAndActive();
}
static bool matchesSpatialNavigationFocusPseudoClass(const Element& element)
{
return isHTMLOptionElement(element) && toHTMLOptionElement(element).spatialNavigationFocused() && isFrameFocused(element);
}
static bool matchesListBoxPseudoClass(const Element& element)
{
return isHTMLSelectElement(element) && !toHTMLSelectElement(element).usesMenuList();
}
static bool matchesTagName(const Element& element, const QualifiedName& tagQName)
{
if (tagQName == anyQName())
return true;
const AtomicString& localName = tagQName.localName();
if (localName != starAtom && localName != element.localName()) {
if (element.isHTMLElement() || !element.document().isHTMLDocument())
return false;
// Non-html elements in html documents are normalized to their camel-cased
// version during parsing if applicable. Yet, type selectors are lower-cased
// for selectors in html documents. Compare the upper case converted names
// instead to allow matching SVG elements like foreignObject.
if (element.tagQName().localNameUpper() != tagQName.localNameUpper())
return false;
}
const AtomicString& namespaceURI = tagQName.namespaceURI();
return namespaceURI == starAtom || namespaceURI == element.namespaceURI();
}
static Element* parentElement(const SelectorChecker::SelectorCheckingContext& context)
{
// - If context.scope is a shadow root, we should walk up to its shadow host.
// - If context.scope is some element in some shadow tree and querySelector initialized the context,
// e.g. shadowRoot.querySelector(':host *'),
// (a) context.element has the same treescope as context.scope, need to walk up to its shadow host.
// (b) Otherwise, should not walk up from a shadow root to a shadow host.
if (context.scope && (context.scope == context.element->containingShadowRoot() || context.scope->treeScope() == context.element->treeScope()))
return context.element->parentOrShadowHostElement();
return context.element->parentElement();
}
static bool scopeContainsLastMatchedElement(const SelectorChecker::SelectorCheckingContext& context)
{
// If this context isn't scoped, skip checking.
if (!context.scope)
return true;
if (context.scope->treeScope() == context.element->treeScope())
return true;
// Because Blink treats a shadow host's TreeScope as a separate one from its descendent shadow roots,
// if the last matched element is a shadow host, the condition above isn't met, even though it
// should be.
return context.element == context.scope->shadowHost() && (!context.previousElement || context.previousElement->isInDescendantTreeOf(context.element));
}
static inline bool nextSelectorExceedsScope(const SelectorChecker::SelectorCheckingContext& context)
{
if (context.scope && context.scope->isInShadowTree())
return context.element == context.scope->shadowHost();
return false;
}
static bool shouldMatchHoverOrActive(const SelectorChecker::SelectorCheckingContext& context)
{
// If we're in quirks mode, then :hover and :active should never match anchors with no
// href and *:hover and *:active should not match anything. This is specified in
// https://quirks.spec.whatwg.org/#the-:active-and-:hover-quirk
if (!context.element->document().inQuirksMode())
return true;
if (context.isSubSelector)
return true;
if (context.selector->relation() == CSSSelector::SubSelector && context.selector->tagHistory())
return true;
return context.element->isLink();
}
static bool isFirstChild(Element& element)
{
return !ElementTraversal::previousSibling(element);
}
static bool isLastChild(Element& element)
{
return !ElementTraversal::nextSibling(element);
}
static bool isFirstOfType(Element& element, const QualifiedName& type)
{
return !ElementTraversal::previousSibling(element, HasTagName(type));
}
static bool isLastOfType(Element& element, const QualifiedName& type)
{
return !ElementTraversal::nextSibling(element, HasTagName(type));
}
static int nthChildIndex(Element& element)
{
if (NthIndexCache* nthIndexCache = element.document().nthIndexCache())
return nthIndexCache->nthChildIndex(element);
int index = 1;
for (const Element* sibling = ElementTraversal::previousSibling(element); sibling; sibling = ElementTraversal::previousSibling(*sibling))
index++;
return index;
}
static int nthOfTypeIndex(Element& element, const QualifiedName& type)
{
if (NthIndexCache* nthIndexCache = element.document().nthIndexCache())
return nthIndexCache->nthChildIndexOfType(element, type);
int index = 1;
for (const Element* sibling = ElementTraversal::previousSibling(element, HasTagName(type)); sibling; sibling = ElementTraversal::previousSibling(*sibling, HasTagName(type)))
++index;
return index;
}
static int nthLastChildIndex(Element& element)
{
if (NthIndexCache* nthIndexCache = element.document().nthIndexCache())
return nthIndexCache->nthLastChildIndex(element);
int index = 1;
for (const Element* sibling = ElementTraversal::nextSibling(element); sibling; sibling = ElementTraversal::nextSibling(*sibling))
++index;
return index;
}
static int nthLastOfTypeIndex(Element& element, const QualifiedName& type)
{
if (NthIndexCache* nthIndexCache = element.document().nthIndexCache())
return nthIndexCache->nthLastChildIndexOfType(element, type);
int index = 1;
for (const Element* sibling = ElementTraversal::nextSibling(element, HasTagName(type)); sibling; sibling = ElementTraversal::nextSibling(*sibling, HasTagName(type)))
++index;
return index;
}
bool SelectorChecker::match(const SelectorCheckingContext& context, MatchResult& result) const
{
ASSERT(context.selector);
return matchSelector(context, result) == SelectorMatches;
}
bool SelectorChecker::match(const SelectorCheckingContext& context) const
{
MatchResult ignoreResult;
return match(context, ignoreResult);
}
// Recursive check of selectors and combinators
// It can return 4 different values:
// * SelectorMatches - the selector matches the element e
// * SelectorFailsLocally - the selector fails for the element e
// * SelectorFailsAllSiblings - the selector fails for e and any sibling of e
// * SelectorFailsCompletely - the selector fails for e and any sibling or ancestor of e
SelectorChecker::Match SelectorChecker::matchSelector(const SelectorCheckingContext& context, MatchResult& result) const
{
MatchResult subResult;
if (!checkOne(context, subResult))
return SelectorFailsLocally;
if (subResult.dynamicPseudo != NOPSEUDO)
result.dynamicPseudo = subResult.dynamicPseudo;
if (context.selector->isLastInTagHistory()) {
if (scopeContainsLastMatchedElement(context)) {
result.specificity += subResult.specificity;
return SelectorMatches;
}
return SelectorFailsLocally;
}
Match match;
if (context.selector->relation() != CSSSelector::SubSelector) {
if (nextSelectorExceedsScope(context))
return SelectorFailsCompletely;
if (context.pseudoId != NOPSEUDO && context.pseudoId != result.dynamicPseudo)
return SelectorFailsCompletely;
TemporaryChange<PseudoId> dynamicPseudoScope(result.dynamicPseudo, NOPSEUDO);
match = matchForRelation(context, result);
} else {
match = matchForSubSelector(context, result);
}
if (match == SelectorMatches)
result.specificity += subResult.specificity;
return match;
}
static inline SelectorChecker::SelectorCheckingContext prepareNextContextForRelation(const SelectorChecker::SelectorCheckingContext& context)
{
SelectorChecker::SelectorCheckingContext nextContext(context);
ASSERT(context.selector->tagHistory());
nextContext.selector = context.selector->tagHistory();
return nextContext;
}
SelectorChecker::Match SelectorChecker::matchForSubSelector(const SelectorCheckingContext& context, MatchResult& result) const
{
SelectorCheckingContext nextContext = prepareNextContextForRelation(context);
PseudoId dynamicPseudo = result.dynamicPseudo;
// a selector is invalid if something follows a pseudo-element
// We make an exception for scrollbar pseudo elements and allow a set of pseudo classes (but nothing else)
// to follow the pseudo elements.
nextContext.hasScrollbarPseudo = dynamicPseudo != NOPSEUDO && (context.scrollbar || dynamicPseudo == SCROLLBAR_CORNER || dynamicPseudo == RESIZER);
nextContext.hasSelectionPseudo = dynamicPseudo == SELECTION;
if ((context.inRightmostCompound || m_mode == CollectingCSSRules || m_mode == CollectingStyleRules || m_mode == QueryingRules) && dynamicPseudo != NOPSEUDO
&& !nextContext.hasSelectionPseudo
&& !(nextContext.hasScrollbarPseudo && nextContext.selector->match() == CSSSelector::PseudoClass))
return SelectorFailsCompletely;
nextContext.isSubSelector = true;
return matchSelector(nextContext, result);
}
static inline bool isV0ShadowRoot(const Node* node)
{
return node && node->isShadowRoot() && toShadowRoot(node)->type() == ShadowRootType::V0;
}
SelectorChecker::Match SelectorChecker::matchForPseudoShadow(const SelectorCheckingContext& context, const ContainerNode* node, MatchResult& result) const
{
if (!isV0ShadowRoot(node))
return SelectorFailsCompletely;
if (!context.previousElement)
return SelectorFailsCompletely;
return matchSelector(context, result);
}
static inline Element* parentOrV0ShadowHostElement(const Element& element)
{
if (element.parentNode() && element.parentNode()->isShadowRoot()) {
if (toShadowRoot(element.parentNode())->type() != ShadowRootType::V0)
return nullptr;
}
return element.parentOrShadowHostElement();
}
SelectorChecker::Match SelectorChecker::matchForRelation(const SelectorCheckingContext& context, MatchResult& result) const
{
SelectorCheckingContext nextContext = prepareNextContextForRelation(context);
nextContext.previousElement = context.element;
CSSSelector::Relation relation = context.selector->relation();
// Disable :visited matching when we see the first link or try to match anything else than an ancestors.
if (!context.isSubSelector && (context.element->isLink() || (relation != CSSSelector::Descendant && relation != CSSSelector::Child)))
nextContext.visitedMatchType = VisitedMatchDisabled;
nextContext.pseudoId = NOPSEUDO;
switch (relation) {
case CSSSelector::Descendant:
if (context.selector->relationIsAffectedByPseudoContent()) {
for (Element* element = context.element; element; element = element->parentElement()) {
if (matchForShadowDistributed(nextContext, *element, result) == SelectorMatches)
return SelectorMatches;
}
return SelectorFailsCompletely;
}
nextContext.isSubSelector = false;
nextContext.inRightmostCompound = false;
if (nextContext.selector->pseudoType() == CSSSelector::PseudoShadow)
return matchForPseudoShadow(nextContext, context.element->containingShadowRoot(), result);
for (nextContext.element = parentElement(context); nextContext.element; nextContext.element = parentElement(nextContext)) {
Match match = matchSelector(nextContext, result);
if (match == SelectorMatches || match == SelectorFailsCompletely)
return match;
if (nextSelectorExceedsScope(nextContext))
return SelectorFailsCompletely;
}
return SelectorFailsCompletely;
case CSSSelector::Child:
{
if (context.selector->relationIsAffectedByPseudoContent())
return matchForShadowDistributed(nextContext, *context.element, result);
nextContext.isSubSelector = false;
nextContext.inRightmostCompound = false;
if (nextContext.selector->pseudoType() == CSSSelector::PseudoShadow)
return matchForPseudoShadow(nextContext, context.element->parentNode(), result);
nextContext.element = parentElement(context);
if (!nextContext.element)
return SelectorFailsCompletely;
return matchSelector(nextContext, result);
}
case CSSSelector::DirectAdjacent:
// Shadow roots can't have sibling elements
if (nextContext.selector->pseudoType() == CSSSelector::PseudoShadow)
return SelectorFailsCompletely;
if (m_mode == ResolvingStyle) {
if (ContainerNode* parent = context.element->parentElementOrShadowRoot())
parent->setChildrenAffectedByDirectAdjacentRules();
}
nextContext.element = ElementTraversal::previousSibling(*context.element);
if (!nextContext.element)
return SelectorFailsAllSiblings;
nextContext.isSubSelector = false;
nextContext.inRightmostCompound = false;
return matchSelector(nextContext, result);
case CSSSelector::IndirectAdjacent:
// Shadow roots can't have sibling elements
if (nextContext.selector->pseudoType() == CSSSelector::PseudoShadow)
return SelectorFailsCompletely;
if (m_mode == ResolvingStyle) {
if (ContainerNode* parent = context.element->parentElementOrShadowRoot())
parent->setChildrenAffectedByIndirectAdjacentRules();
}
nextContext.element = ElementTraversal::previousSibling(*context.element);
nextContext.isSubSelector = false;
nextContext.inRightmostCompound = false;
for (; nextContext.element; nextContext.element = ElementTraversal::previousSibling(*nextContext.element)) {
Match match = matchSelector(nextContext, result);
if (match == SelectorMatches || match == SelectorFailsAllSiblings || match == SelectorFailsCompletely)
return match;
}
return SelectorFailsAllSiblings;
case CSSSelector::ShadowPseudo:
{
if (!context.isUARule && context.selector->pseudoType() == CSSSelector::PseudoShadow)
UseCounter::countDeprecation(context.element->document(), UseCounter::CSSSelectorPseudoShadow);
// If we're in the same tree-scope as the scoping element, then following a shadow descendant combinator would escape that and thus the scope.
if (context.scope && context.scope->shadowHost() && context.scope->shadowHost()->treeScope() == context.element->treeScope())
return SelectorFailsCompletely;
Element* shadowHost = context.element->shadowHost();
if (!shadowHost)
return SelectorFailsCompletely;
nextContext.element = shadowHost;
nextContext.isSubSelector = false;
nextContext.inRightmostCompound = false;
return matchSelector(nextContext, result);
}
case CSSSelector::ShadowDeep:
{
if (!context.isUARule)
UseCounter::countDeprecation(context.element->document(), UseCounter::CSSDeepCombinator);
if (ShadowRoot* root = context.element->containingShadowRoot()) {
if (root->type() == ShadowRootType::UserAgent)
return SelectorFailsCompletely;
}
if (context.selector->relationIsAffectedByPseudoContent()) {
// TODO(kochi): closed mode tree should be handled as well for ::content.
for (Element* element = context.element; element; element = element->parentOrShadowHostElement()) {
if (matchForShadowDistributed(nextContext, *element, result) == SelectorMatches)
return SelectorMatches;
}
return SelectorFailsCompletely;
}
nextContext.isSubSelector = false;
nextContext.inRightmostCompound = false;
for (nextContext.element = parentOrV0ShadowHostElement(*context.element); nextContext.element; nextContext.element = parentOrV0ShadowHostElement(*nextContext.element)) {
Match match = matchSelector(nextContext, result);
if (match == SelectorMatches || match == SelectorFailsCompletely)
return match;
if (nextSelectorExceedsScope(nextContext))
return SelectorFailsCompletely;
}
return SelectorFailsCompletely;
}
case CSSSelector::SubSelector:
ASSERT_NOT_REACHED();
}
ASSERT_NOT_REACHED();
return SelectorFailsCompletely;
}
SelectorChecker::Match SelectorChecker::matchForShadowDistributed(const SelectorCheckingContext& context, const Element& element, MatchResult& result) const
{
WillBeHeapVector<RawPtrWillBeMember<InsertionPoint>, 8> insertionPoints;
collectDestinationInsertionPoints(element, insertionPoints);
SelectorCheckingContext nextContext(context);
nextContext.isSubSelector = false;
nextContext.inRightmostCompound = false;
for (const auto& insertionPoint : insertionPoints) {
nextContext.element = insertionPoint;
// TODO(esprehn): Why does SharingRules have a special case?
if (m_mode == SharingRules)
nextContext.scope = insertionPoint->containingShadowRoot();
if (match(nextContext, result))
return SelectorMatches;
}
return SelectorFailsLocally;
}
template<typename CharType>
static inline bool containsHTMLSpaceTemplate(const CharType* string, unsigned length)
{
for (unsigned i = 0; i < length; ++i) {
if (isHTMLSpace<CharType>(string[i]))
return true;
}
return false;
}
static inline bool containsHTMLSpace(const AtomicString& string)
{
if (LIKELY(string.is8Bit()))
return containsHTMLSpaceTemplate<LChar>(string.characters8(), string.length());
return containsHTMLSpaceTemplate<UChar>(string.characters16(), string.length());
}
static bool attributeValueMatches(const Attribute& attributeItem, CSSSelector::Match match, const AtomicString& selectorValue, TextCaseSensitivity caseSensitivity)
{
// TODO(esprehn): How do we get here with a null value?
const AtomicString& value = attributeItem.value();
if (value.isNull())
return false;
switch (match) {
case CSSSelector::AttributeExact:
if (caseSensitivity == TextCaseSensitive)
return selectorValue == value;
return equalIgnoringCase(selectorValue, value);
case CSSSelector::AttributeSet:
return true;
case CSSSelector::AttributeList:
{
// Ignore empty selectors or selectors containing HTML spaces
if (selectorValue.isEmpty() || containsHTMLSpace(selectorValue))
return false;
unsigned startSearchAt = 0;
while (true) {
size_t foundPos = value.find(selectorValue, startSearchAt, caseSensitivity);
if (foundPos == kNotFound)
return false;
if (!foundPos || isHTMLSpace<UChar>(value[foundPos - 1])) {
unsigned endStr = foundPos + selectorValue.length();
if (endStr == value.length() || isHTMLSpace<UChar>(value[endStr]))
break; // We found a match.
}
// No match. Keep looking.
startSearchAt = foundPos + 1;
}
return true;
}
case CSSSelector::AttributeContain:
if (selectorValue.isEmpty())
return false;
return value.contains(selectorValue, caseSensitivity);
case CSSSelector::AttributeBegin:
if (selectorValue.isEmpty())
return false;
return value.startsWith(selectorValue, caseSensitivity);
case CSSSelector::AttributeEnd:
if (selectorValue.isEmpty())
return false;
return value.endsWith(selectorValue, caseSensitivity);
case CSSSelector::AttributeHyphen:
if (value.length() < selectorValue.length())
return false;
if (!value.startsWith(selectorValue, caseSensitivity))
return false;
// It they start the same, check for exact match or following '-':
if (value.length() != selectorValue.length() && value[selectorValue.length()] != '-')
return false;
return true;
default:
break;
}
ASSERT_NOT_REACHED();
return true;
}
static bool anyAttributeMatches(Element& element, CSSSelector::Match match, const CSSSelector& selector)
{
const QualifiedName& selectorAttr = selector.attribute();
ASSERT(selectorAttr.localName() != starAtom); // Should not be possible from the CSS grammar.
// Synchronize the attribute in case it is lazy-computed.
// Currently all lazy properties have a null namespace, so only pass localName().
element.synchronizeAttribute(selectorAttr.localName());
const AtomicString& selectorValue = selector.value();
TextCaseSensitivity caseSensitivity = (selector.attributeMatchType() == CSSSelector::CaseInsensitive) ? TextCaseInsensitive : TextCaseSensitive;
AttributeCollection attributes = element.attributesWithoutUpdate();
for (const auto& attributeItem: attributes) {
if (!attributeItem.matches(selectorAttr))
continue;
if (attributeValueMatches(attributeItem, match, selectorValue, caseSensitivity))
return true;
if (caseSensitivity == TextCaseInsensitive) {
if (selectorAttr.namespaceURI() != starAtom)
return false;
continue;
}
// Legacy dictates that values of some attributes should be compared in
// a case-insensitive manner regardless of whether the case insensitive
// flag is set or not.
bool legacyCaseInsensitive = element.document().isHTMLDocument() && !HTMLDocument::isCaseSensitiveAttribute(selectorAttr);
// If case-insensitive, re-check, and count if result differs.
// See http://code.google.com/p/chromium/issues/detail?id=327060
if (legacyCaseInsensitive && attributeValueMatches(attributeItem, match, selectorValue, TextCaseInsensitive)) {
UseCounter::count(element.document(), UseCounter::CaseInsensitiveAttrSelectorMatch);
return true;
}
if (selectorAttr.namespaceURI() != starAtom)
return false;
}
return false;
}
bool SelectorChecker::checkOne(const SelectorCheckingContext& context, MatchResult& result) const
{
ASSERT(context.element);
Element& element = *context.element;
ASSERT(context.selector);
const CSSSelector& selector = *context.selector;
// Only :host and :host-context() should match the host: http://drafts.csswg.org/css-scoping/#host-element
if (context.scope && context.scope->shadowHost() == element && (!selector.isHostPseudoClass()
&& !context.treatShadowHostAsNormalScope
&& selector.match() != CSSSelector::PseudoElement))
return false;
switch (selector.match()) {
case CSSSelector::Tag:
return matchesTagName(element, selector.tagQName());
case CSSSelector::Class:
return element.hasClass() && element.classNames().contains(selector.value());
case CSSSelector::Id:
return element.hasID() && element.idForStyleResolution() == selector.value();
// Attribute selectors
case CSSSelector::AttributeExact:
case CSSSelector::AttributeSet:
case CSSSelector::AttributeHyphen:
case CSSSelector::AttributeList:
case CSSSelector::AttributeContain:
case CSSSelector::AttributeBegin:
case CSSSelector::AttributeEnd:
return anyAttributeMatches(element, selector.match(), selector);
case CSSSelector::PseudoClass:
return checkPseudoClass(context, result);
case CSSSelector::PseudoElement:
return checkPseudoElement(context, result);
case CSSSelector::PagePseudoClass:
// FIXME: what?
return true;
case CSSSelector::Unknown:
// FIXME: what?
return true;
}
ASSERT_NOT_REACHED();
return true;
}
bool SelectorChecker::checkPseudoNot(const SelectorCheckingContext& context, MatchResult& result) const
{
const CSSSelector& selector = *context.selector;
SelectorCheckingContext subContext(context);
subContext.isSubSelector = true;
ASSERT(selector.selectorList());
for (subContext.selector = selector.selectorList()->first(); subContext.selector; subContext.selector = subContext.selector->tagHistory()) {
// :not cannot nest. I don't really know why this is a
// restriction in CSS3, but it is, so let's honor it.
// the parser enforces that this never occurs
ASSERT(subContext.selector->pseudoType() != CSSSelector::PseudoNot);
// We select between :visited and :link when applying. We don't know which one applied (or not) yet.
if (subContext.selector->pseudoType() == CSSSelector::PseudoVisited || (subContext.selector->pseudoType() == CSSSelector::PseudoLink && subContext.visitedMatchType == VisitedMatchEnabled))
return true;
// context.scope is not available if m_mode == SharingRules.
// We cannot determine whether :host or :scope matches a given element or not.
if (m_mode == SharingRules && (subContext.selector->isHostPseudoClass() || subContext.selector->pseudoType() == CSSSelector::PseudoScope))
return true;
if (!checkOne(subContext, result))
return true;
}
return false;
}
bool SelectorChecker::checkPseudoClass(const SelectorCheckingContext& context, MatchResult& result) const
{
Element& element = *context.element;
const CSSSelector& selector = *context.selector;
if (context.hasScrollbarPseudo) {
// CSS scrollbars match a specific subset of pseudo classes, and they have specialized rules for each
// (since there are no elements involved).
return checkScrollbarPseudoClass(context, result);
}
switch (selector.pseudoType()) {
case CSSSelector::PseudoNot:
return checkPseudoNot(context, result);
case CSSSelector::PseudoEmpty:
{
bool result = true;
for (Node* n = element.firstChild(); n; n = n->nextSibling()) {
if (n->isElementNode()) {
result = false;
break;
}
if (n->isTextNode()) {
Text* textNode = toText(n);
if (!textNode->data().isEmpty()) {
result = false;
break;
}
}
}
if (m_mode == ResolvingStyle) {
element.setStyleAffectedByEmpty();
if (context.inRightmostCompound)
context.elementStyle->setEmptyState(result);
else if (element.computedStyle() && (element.document().styleEngine().usesSiblingRules() || element.computedStyle()->unique()))
element.mutableComputedStyle()->setEmptyState(result);
}
return result;
}
case CSSSelector::PseudoFirstChild:
if (ContainerNode* parent = element.parentElementOrDocumentFragment()) {
if (m_mode == ResolvingStyle) {
parent->setChildrenAffectedByFirstChildRules();
element.setAffectedByFirstChildRules();
}
return isFirstChild(element);
}
break;
case CSSSelector::PseudoFirstOfType:
if (ContainerNode* parent = element.parentElementOrDocumentFragment()) {
if (m_mode == ResolvingStyle)
parent->setChildrenAffectedByForwardPositionalRules();
return isFirstOfType(element, element.tagQName());
}
break;
case CSSSelector::PseudoLastChild:
if (ContainerNode* parent = element.parentElementOrDocumentFragment()) {
if (m_mode == ResolvingStyle) {
parent->setChildrenAffectedByLastChildRules();
element.setAffectedByLastChildRules();
}
if (!parent->isFinishedParsingChildren())
return false;
return isLastChild(element);
}
break;
case CSSSelector::PseudoLastOfType:
if (ContainerNode* parent = element.parentElementOrDocumentFragment()) {
if (m_mode == ResolvingStyle)
parent->setChildrenAffectedByBackwardPositionalRules();
if (!parent->isFinishedParsingChildren())
return false;
return isLastOfType(element, element.tagQName());
}
break;
case CSSSelector::PseudoOnlyChild:
if (ContainerNode* parent = element.parentElementOrDocumentFragment()) {
if (m_mode == ResolvingStyle) {
parent->setChildrenAffectedByFirstChildRules();
parent->setChildrenAffectedByLastChildRules();
element.setAffectedByFirstChildRules();
element.setAffectedByLastChildRules();
}
if (!parent->isFinishedParsingChildren())
return false;
return isFirstChild(element) && isLastChild(element);
}
break;
case CSSSelector::PseudoOnlyOfType:
// FIXME: This selector is very slow.
if (ContainerNode* parent = element.parentElementOrDocumentFragment()) {
if (m_mode == ResolvingStyle) {
parent->setChildrenAffectedByForwardPositionalRules();
parent->setChildrenAffectedByBackwardPositionalRules();
}
if (!parent->isFinishedParsingChildren())
return false;
return isFirstOfType(element, element.tagQName()) && isLastOfType(element, element.tagQName());
}
break;
case CSSSelector::PseudoPlaceholderShown:
if (isHTMLTextFormControlElement(element))
return toHTMLTextFormControlElement(element).isPlaceholderVisible();
break;
case CSSSelector::PseudoNthChild:
if (ContainerNode* parent = element.parentElementOrDocumentFragment()) {
if (m_mode == ResolvingStyle)
parent->setChildrenAffectedByForwardPositionalRules();
return selector.matchNth(nthChildIndex(element));
}
break;
case CSSSelector::PseudoNthOfType:
if (ContainerNode* parent = element.parentElementOrDocumentFragment()) {
if (m_mode == ResolvingStyle)
parent->setChildrenAffectedByForwardPositionalRules();
return selector.matchNth(nthOfTypeIndex(element, element.tagQName()));
}
break;
case CSSSelector::PseudoNthLastChild:
if (ContainerNode* parent = element.parentElementOrDocumentFragment()) {
if (m_mode == ResolvingStyle)
parent->setChildrenAffectedByBackwardPositionalRules();
if (!parent->isFinishedParsingChildren())
return false;
return selector.matchNth(nthLastChildIndex(element));
}
break;
case CSSSelector::PseudoNthLastOfType:
if (ContainerNode* parent = element.parentElementOrDocumentFragment()) {
if (m_mode == ResolvingStyle)
parent->setChildrenAffectedByBackwardPositionalRules();
if (!parent->isFinishedParsingChildren())
return false;
return selector.matchNth(nthLastOfTypeIndex(element, element.tagQName()));
}
break;
case CSSSelector::PseudoTarget:
return element == element.document().cssTarget();
case CSSSelector::PseudoAny:
{
SelectorCheckingContext subContext(context);
subContext.isSubSelector = true;
ASSERT(selector.selectorList());
for (subContext.selector = selector.selectorList()->first(); subContext.selector; subContext.selector = CSSSelectorList::next(*subContext.selector)) {
if (match(subContext))
return true;
}
}
break;
case CSSSelector::PseudoAutofill:
return element.isFormControlElement() && toHTMLFormControlElement(element).isAutofilled();
case CSSSelector::PseudoAnyLink:
case CSSSelector::PseudoLink:
return element.isLink();
case CSSSelector::PseudoVisited:
return element.isLink() && context.visitedMatchType == VisitedMatchEnabled;
case CSSSelector::PseudoDrag:
if (m_mode == ResolvingStyle) {
if (context.inRightmostCompound)
context.elementStyle->setAffectedByDrag();
else
element.setChildrenOrSiblingsAffectedByDrag();
}
return element.layoutObject() && element.layoutObject()->isDragging();
case CSSSelector::PseudoFocus:
if (m_mode == ResolvingStyle) {
if (context.inRightmostCompound)
context.elementStyle->setAffectedByFocus();
else
element.setChildrenOrSiblingsAffectedByFocus();
}
return matchesFocusPseudoClass(element);
case CSSSelector::PseudoHover:
if (m_mode == ResolvingStyle) {
if (context.inRightmostCompound)
context.elementStyle->setAffectedByHover();
else
element.setChildrenOrSiblingsAffectedByHover();
}
if (!shouldMatchHoverOrActive(context))
return false;
if (InspectorInstrumentation::forcePseudoState(&element, CSSSelector::PseudoHover))
return true;
return element.hovered();
case CSSSelector::PseudoActive:
if (m_mode == ResolvingStyle) {
if (context.inRightmostCompound)
context.elementStyle->setAffectedByActive();
else
element.setChildrenOrSiblingsAffectedByActive();
}
if (!shouldMatchHoverOrActive(context))
return false;
if (InspectorInstrumentation::forcePseudoState(&element, CSSSelector::PseudoActive))
return true;
return element.active();
case CSSSelector::PseudoEnabled:
if (element.isFormControlElement() || isHTMLOptionElement(element) || isHTMLOptGroupElement(element))
return !element.isDisabledFormControl();
if (isHTMLAnchorElement(element) || isHTMLAreaElement(element))
return element.isLink();
break;
case CSSSelector::PseudoFullPageMedia:
return element.document().isMediaDocument();
case CSSSelector::PseudoDefault:
return element.isDefaultButtonForForm();
case CSSSelector::PseudoDisabled:
// TODO(esprehn): Why not just always return isDisabledFormControl()?
// Can it be true for elements not in the list below?
if (element.isFormControlElement() || isHTMLOptionElement(element) || isHTMLOptGroupElement(element))
return element.isDisabledFormControl();
break;
case CSSSelector::PseudoReadOnly:
return element.matchesReadOnlyPseudoClass();
case CSSSelector::PseudoReadWrite:
return element.matchesReadWritePseudoClass();
case CSSSelector::PseudoOptional:
return element.isOptionalFormControl();
case CSSSelector::PseudoRequired:
return element.isRequiredFormControl();
case CSSSelector::PseudoValid:
if (m_mode == ResolvingStyle)
element.document().setContainsValidityStyleRules();
return element.matchesValidityPseudoClasses() && element.isValidElement();
case CSSSelector::PseudoInvalid:
if (m_mode == ResolvingStyle)
element.document().setContainsValidityStyleRules();
return element.matchesValidityPseudoClasses() && !element.isValidElement();
case CSSSelector::PseudoChecked:
{
if (isHTMLInputElement(element)) {
HTMLInputElement& inputElement = toHTMLInputElement(element);
// Even though WinIE allows checked and indeterminate to
// co-exist, the CSS selector spec says that you can't be
// both checked and indeterminate. We will behave like WinIE
// behind the scenes and just obey the CSS spec here in the
// test for matching the pseudo.
if (inputElement.shouldAppearChecked() && !inputElement.shouldAppearIndeterminate())
return true;
} else if (isHTMLOptionElement(element) && toHTMLOptionElement(element).selected()) {
return true;
}
break;
}
case CSSSelector::PseudoIndeterminate:
return element.shouldAppearIndeterminate();
case CSSSelector::PseudoRoot:
return element == element.document().documentElement();
case CSSSelector::PseudoLang:
{
AtomicString value;
if (element.isVTTElement())
value = toVTTElement(element).language();
else
value = element.computeInheritedLanguage();
const AtomicString& argument = selector.argument();
if (value.isEmpty() || !startsWithIgnoringASCIICase(value, argument))
break;
if (value.length() != argument.length() && value[argument.length()] != '-')
break;
return true;
}
case CSSSelector::PseudoFullScreen:
// While a Document is in the fullscreen state, and the document's current fullscreen
// element is an element in the document, the 'full-screen' pseudoclass applies to
// that element. Also, an <iframe>, <object> or <embed> element whose child browsing
// context's Document is in the fullscreen state has the 'full-screen' pseudoclass applied.
if (isHTMLFrameElementBase(element) && element.containsFullScreenElement())
return true;
return Fullscreen::isActiveFullScreenElement(element);
case CSSSelector::PseudoFullScreenAncestor:
return element.containsFullScreenElement();
case CSSSelector::PseudoInRange:
if (m_mode == ResolvingStyle)
element.document().setContainsValidityStyleRules();
return element.isInRange();
case CSSSelector::PseudoOutOfRange:
if (m_mode == ResolvingStyle)
element.document().setContainsValidityStyleRules();
return element.isOutOfRange();
case CSSSelector::PseudoFutureCue:
return element.isVTTElement() && !toVTTElement(element).isPastNode();
case CSSSelector::PseudoPastCue:
return element.isVTTElement() && toVTTElement(element).isPastNode();
case CSSSelector::PseudoScope:
if (m_mode == SharingRules)
return true;
if (context.scope == element.document())
return element == element.document().documentElement();
return context.scope == element;
case CSSSelector::PseudoUnresolved:
return element.isUnresolvedCustomElement();
case CSSSelector::PseudoHost:
case CSSSelector::PseudoHostContext:
return checkPseudoHost(context, result);
case CSSSelector::PseudoSpatialNavigationFocus:
return context.isUARule && matchesSpatialNavigationFocusPseudoClass(element);
case CSSSelector::PseudoListBox:
return context.isUARule && matchesListBoxPseudoClass(element);
case CSSSelector::PseudoWindowInactive:
if (!context.hasSelectionPseudo)
return false;
return !element.document().page()->focusController().isActive();
case CSSSelector::PseudoHorizontal:
case CSSSelector::PseudoVertical:
case CSSSelector::PseudoDecrement:
case CSSSelector::PseudoIncrement:
case CSSSelector::PseudoStart:
case CSSSelector::PseudoEnd:
case CSSSelector::PseudoDoubleButton:
case CSSSelector::PseudoSingleButton:
case CSSSelector::PseudoNoButton:
case CSSSelector::PseudoCornerPresent:
return false;
case CSSSelector::PseudoUnknown:
default:
ASSERT_NOT_REACHED();
break;
}
return false;
}
bool SelectorChecker::checkPseudoElement(const SelectorCheckingContext& context, MatchResult& result) const
{
const CSSSelector& selector = *context.selector;
Element& element = *context.element;
switch (selector.pseudoType()) {
case CSSSelector::PseudoCue:
{
SelectorCheckingContext subContext(context);
subContext.isSubSelector = true;
subContext.scope = nullptr;
subContext.treatShadowHostAsNormalScope = false;
for (subContext.selector = selector.selectorList()->first(); subContext.selector; subContext.selector = CSSSelectorList::next(*subContext.selector)) {
if (match(subContext))
return true;
}
return false;
}
case CSSSelector::PseudoWebKitCustomElement:
{
if (ShadowRoot* root = element.containingShadowRoot())
return root->type() == ShadowRootType::UserAgent && element.shadowPseudoId() == selector.value();
return false;
}
case CSSSelector::PseudoContent:
return element.isInShadowTree() && element.isInsertionPoint();
case CSSSelector::PseudoShadow:
return element.isInShadowTree() && context.previousElement;
default:
break;
}
if (!context.inRightmostCompound && m_mode == ResolvingStyle)
return false;
if (m_mode == QueryingRules)
return false;
PseudoId pseudoId = CSSSelector::pseudoId(selector.pseudoType());
if (pseudoId != NOPSEUDO && m_mode != SharingRules)
result.dynamicPseudo = pseudoId;
// ::before, ::after, etc.
return true;
}
bool SelectorChecker::checkPseudoHost(const SelectorCheckingContext& context, MatchResult& result) const
{
const CSSSelector& selector = *context.selector;
Element& element = *context.element;
if (m_mode == SharingRules)
return true;
// :host only matches a shadow host when :host is in a shadow tree of the shadow host.
const ContainerNode* shadowHost = context.scope->shadowHost();
if (!shadowHost || shadowHost != element)
return false;
ASSERT(element.shadow());
// For empty parameter case, i.e. just :host or :host().
if (!selector.selectorList()) // Use *'s specificity. So just 0.
return true;
SelectorCheckingContext subContext(context);
subContext.isSubSelector = true;
bool matched = false;
unsigned maxSpecificity = 0;
// If one of simple selectors matches an element, returns SelectorMatches. Just "OR".
for (subContext.selector = selector.selectorList()->first(); subContext.selector; subContext.selector = CSSSelectorList::next(*subContext.selector)) {
subContext.treatShadowHostAsNormalScope = true;
subContext.scope = context.scope;
// Use ComposedTreeTraversal to traverse a composed ancestor list of a given element.
Element* nextElement = &element;
SelectorCheckingContext hostContext(subContext);
do {
MatchResult subResult;
hostContext.element = nextElement;
if (match(hostContext, subResult)) {
matched = true;
// Consider div:host(div:host(div:host(div:host...))).
maxSpecificity = std::max(maxSpecificity, hostContext.selector->specificity() + subResult.specificity);
break;
}
hostContext.treatShadowHostAsNormalScope = false;
hostContext.scope = nullptr;
if (selector.pseudoType() == CSSSelector::PseudoHost)
break;
hostContext.inRightmostCompound = false;
nextElement = ComposedTreeTraversal::parentElement(*nextElement);
} while (nextElement);
}
if (matched) {
result.specificity += maxSpecificity;
return true;
}
// FIXME: this was a fallthrough condition.
return false;
}
bool SelectorChecker::checkScrollbarPseudoClass(const SelectorCheckingContext& context, MatchResult& result) const
{
const CSSSelector& selector = *context.selector;
LayoutScrollbar* scrollbar = context.scrollbar;
ScrollbarPart part = context.scrollbarPart;
if (selector.pseudoType() == CSSSelector::PseudoNot)
return checkPseudoNot(context, result);
// FIXME: This is a temporary hack for resizers and scrollbar corners. Eventually :window-inactive should become a real
// pseudo class and just apply to everything.
if (selector.pseudoType() == CSSSelector::PseudoWindowInactive)
return !context.element->document().page()->focusController().isActive();
if (!scrollbar)
return false;
switch (selector.pseudoType()) {
case CSSSelector::PseudoEnabled:
return scrollbar->enabled();
case CSSSelector::PseudoDisabled:
return !scrollbar->enabled();
case CSSSelector::PseudoHover:
{
ScrollbarPart hoveredPart = scrollbar->hoveredPart();
if (part == ScrollbarBGPart)
return hoveredPart != NoPart;
if (part == TrackBGPart)
return hoveredPart == BackTrackPart || hoveredPart == ForwardTrackPart || hoveredPart == ThumbPart;
return part == hoveredPart;
}
case CSSSelector::PseudoActive:
{
ScrollbarPart pressedPart = scrollbar->pressedPart();
if (part == ScrollbarBGPart)
return pressedPart != NoPart;
if (part == TrackBGPart)
return pressedPart == BackTrackPart || pressedPart == ForwardTrackPart || pressedPart == ThumbPart;
return part == pressedPart;
}
case CSSSelector::PseudoHorizontal:
return scrollbar->orientation() == HorizontalScrollbar;
case CSSSelector::PseudoVertical:
return scrollbar->orientation() == VerticalScrollbar;
case CSSSelector::PseudoDecrement:
return part == BackButtonStartPart || part == BackButtonEndPart || part == BackTrackPart;
case CSSSelector::PseudoIncrement:
return part == ForwardButtonStartPart || part == ForwardButtonEndPart || part == ForwardTrackPart;
case CSSSelector::PseudoStart:
return part == BackButtonStartPart || part == ForwardButtonStartPart || part == BackTrackPart;
case CSSSelector::PseudoEnd:
return part == BackButtonEndPart || part == ForwardButtonEndPart || part == ForwardTrackPart;
case CSSSelector::PseudoDoubleButton:
{
ScrollbarButtonsPlacement buttonsPlacement = scrollbar->theme()->buttonsPlacement();
if (part == BackButtonStartPart || part == ForwardButtonStartPart || part == BackTrackPart)
return buttonsPlacement == ScrollbarButtonsPlacementDoubleStart || buttonsPlacement == ScrollbarButtonsPlacementDoubleBoth;
if (part == BackButtonEndPart || part == ForwardButtonEndPart || part == ForwardTrackPart)
return buttonsPlacement == ScrollbarButtonsPlacementDoubleEnd || buttonsPlacement == ScrollbarButtonsPlacementDoubleBoth;
return false;
}
case CSSSelector::PseudoSingleButton:
{
ScrollbarButtonsPlacement buttonsPlacement = scrollbar->theme()->buttonsPlacement();
if (part == BackButtonStartPart || part == ForwardButtonEndPart || part == BackTrackPart || part == ForwardTrackPart)
return buttonsPlacement == ScrollbarButtonsPlacementSingle;
return false;
}
case CSSSelector::PseudoNoButton:
{
ScrollbarButtonsPlacement buttonsPlacement = scrollbar->theme()->buttonsPlacement();
if (part == BackTrackPart)
return buttonsPlacement == ScrollbarButtonsPlacementNone || buttonsPlacement == ScrollbarButtonsPlacementDoubleEnd;
if (part == ForwardTrackPart)
return buttonsPlacement == ScrollbarButtonsPlacementNone || buttonsPlacement == ScrollbarButtonsPlacementDoubleStart;
return false;
}
case CSSSelector::PseudoCornerPresent:
return scrollbar->scrollableArea() && scrollbar->scrollableArea()->isScrollCornerVisible();
default:
return false;
}
}
bool SelectorChecker::matchesFocusPseudoClass(const Element& element)
{
if (InspectorInstrumentation::forcePseudoState(const_cast<Element*>(&element), CSSSelector::PseudoFocus))
return true;
return element.focused() && isFrameFocused(element);
}
}
| [
"[email protected]"
] | |
5b78c1b7c3425b52c9314083ec8a937a47ae0c81 | 2748d0af8c89e0975bdfde2a24b5e567bfcac0ab | /communication/test2_server/include/test2_server.h | 2939b80291d0dc095301bb165549af3a5e545c9e | [] | no_license | shenglixu/golems | 184384574958112690719c9295e9c08b75ccb093 | ae516ce6d70cfd07e8806f243686536ca42d662d | refs/heads/master | 2021-01-22T21:37:32.705276 | 2016-11-14T23:44:29 | 2016-11-14T23:44:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,322 | h | #pragma once
#include <QMainWindow>
#include <QBluetoothHostInfo>
#include <QBluetoothLocalDevice>
#include <QBluetoothServiceDiscoveryAgent>
#include <QBluetoothTransferRequest>
#include <QBluetoothTransferReply>
#include <QFile>
#include <QTimer>
#include <unistd.h>
#include <sns.h>
#include <ach.h>
#include "server_unit.h"
#include <communication/msgs/server_msgs.h>
#include "test2_fsa.h"
enum OPTIONS_MSG {
NOTHING=0,
DEBUG = 1,
CLIENT_NEWS=2,
CLIENT_CMD=3,
SERVER_COMMAND=4,
SERVER_NOTIFICATION=5,
ERROR=6,
INFO = 7
};
namespace Ui {
class Test2_Server;
}
/**
* @class Test2_Server
*/
class Test2_Server : public QMainWindow
{
Q_OBJECT
public:
explicit Test2_Server(QWidget *parent = 0);
~Test2_Server();
void showMsg( const QString &_msg, int _option = NOTHING );
void do_action( int _action );
void poll_chan();
void poll_fsa();
void reset_server();
void showStateName();
void notify_client( int _typeNotification );
void goBack();
signals:
void sendMsg_signal( const QString &_msg );
void rcvMsg_signal( const QString &_msg );
public slots:
void dbgMsg_slot( const QString &_msg );
private slots:
void sendMsg_slot();
void rcvMsg_slot( const QString &_sender, const QString &_msg );
void clientConnected_slot( const QString &_name );
void clientDisconnected_slot( const QString &_name );
void stopComm_slot();
void setAch_slot();
void poll();
void OB_discovered_slot( QBluetoothServiceInfo );
void OB_finishedTransfer_slot( QBluetoothTransferReply*);
private:
Ui::Test2_Server *ui;
server_unit* mServer;
QString mLocalName;
QBluetoothLocalDevice* mLocalAdapter;
QTimer* mTimer;
// For pushing image
QBluetoothServiceDiscoveryAgent* mDiscoveryAgent;
QBluetoothServiceInfo mService_OBB;
QFile* mFile_OBB;
QBluetoothTransferReply* mReply_OBB;
QBluetoothTransferManager mMgr;
Test2_FSA mFsa;
bool mMsg_received_flag;
int mMsg_source; int mMsg_type;
int mPx, mPy;
std::string mImage_filename;
std::string mImage_fullname;
// Communication between processes
bool mAchComm_ready_flag;
ach_channel_t mServer2See_chan;
ach_channel_t mSee2Server_chan;
ach_channel_t mServer2Plan_chan;
ach_channel_t mPlan2Server_chan;
};
| [
"[email protected]"
] | |
11f77a29c82e8c18429160689175dc34e8c8298b | 31479133dc7eb82475eefb33fd5063e36d3b814d | /9-4/stdafx.cpp | db6900d71b6674e094b2483211b9b6b8610f0891 | [] | no_license | scnb/Cpp-Primer-Plus-Exercise | 005baf53b9c142d7366f6d2398de9b2c599e41f5 | 72002bf0181caf5287719cd0c27b349f2fd87663 | refs/heads/master | 2021-08-14T11:45:07.272413 | 2017-11-15T15:19:32 | 2017-11-15T15:19:32 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 254 | cpp | // stdafx.cpp : 只包括标准包含文件的源文件
// 9-4.pch 将作为预编译头
// stdafx.obj 将包含预编译类型信息
#include "stdafx.h"
// TODO: 在 STDAFX.H 中引用任何所需的附加头文件,
//而不是在此文件中引用
| [
"[email protected]"
] | |
1402c7c85b2ae4854d7469a26f6e6792044baf7e | ae1973a399f4b26ed1a854e9725307fd5ef8cdbe | /src/master/player.hpp | 47ec3564c89c90bc83a3ccf66d70d96bcb73c6ad | [] | no_license | mmpg/engine | 2c4bcb6e4bc73be28f3017126e79eb9dce711e1b | 2d4d769f95c59280a1e04e4d51ceff24c5137573 | refs/heads/master | 2021-01-10T06:05:35.747507 | 2016-01-03T02:44:08 | 2016-01-03T02:44:08 | 44,712,944 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 527 | hpp | #pragma once
#include <string>
namespace mmpg {
class Player {
public:
Player(unsigned int id, std::string email);
~Player();
void Build();
void Start();
void Stop();
void Update(const std::string& code);
void Recover();
unsigned int id() const;
const std::string& key() const;
const std::string& email() const;
std::string path() const;
bool is_built() const;
bool is_alive() const;
private:
unsigned int id_;
std::string key_;
std::string email_;
bool is_built_;
pid_t pid_;
};
}
| [
"[email protected]"
] | |
18738ba272209c47f694e715fd6a57023baf5229 | 52713bf9e6ff2ffee93ce6aa776ce0b5d9975af0 | /qrc_a.cpp | 62cfa2d040491a9a7ce55dd59a9ec98fc29dbf93 | [] | no_license | svetlanahanina/ball_game | d76c96f02e9b9048b868a6362a65d4bfeab6af8e | a93b8363ee507c29540d44792d129d786b033411 | refs/heads/master | 2021-05-05T11:12:17.083004 | 2018-01-20T08:56:35 | 2018-01-20T08:56:35 | 118,119,425 | 0 | 0 | null | 2018-01-19T11:52:23 | 2018-01-19T11:52:23 | null | UTF-8 | C++ | false | false | 36,652 | cpp | /****************************************************************************
** Resource object code
**
** Created by: The Resource Compiler for Qt version 4.8.6
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include <QtCore/qglobal.h>
static const unsigned char qt_resource_data[] = {
// /home/giorgi/4course/механика/ellipse2/resourse/aqua_ball.png
0x0,0x0,0x8,0x1,
0x89,
0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0,
0x0,0x0,0x20,0x0,0x0,0x0,0x20,0x8,0x6,0x0,0x0,0x0,0x73,0x7a,0x7a,0xf4,
0x0,0x0,0x0,0x6,0x62,0x4b,0x47,0x44,0x0,0xff,0x0,0xff,0x0,0xff,0xa0,0xbd,
0xa7,0x93,0x0,0x0,0x0,0x9,0x70,0x48,0x59,0x73,0x0,0x0,0xb,0x13,0x0,0x0,
0xb,0x13,0x1,0x0,0x9a,0x9c,0x18,0x0,0x0,0x0,0x7,0x74,0x49,0x4d,0x45,0x7,
0xe0,0xc,0x19,0xa,0x17,0x35,0x6c,0xd6,0x81,0x55,0x0,0x0,0x7,0x8e,0x49,0x44,
0x41,0x54,0x58,0xc3,0xa5,0x97,0x5d,0x6c,0x54,0x69,0x19,0xc7,0x7f,0xcf,0xfb,0xbe,
0xe7,0xcc,0x4c,0xa7,0x9d,0x2,0x9d,0x7e,0xc8,0x52,0xa0,0x40,0x4b,0xda,0x8a,0x2,
0xa,0x2e,0x21,0x1b,0xf7,0x23,0x41,0x51,0xaf,0x58,0xa3,0x1b,0x2f,0x30,0x2a,0x17,
0x7a,0xed,0x85,0xf7,0xe2,0x5e,0x7a,0xa7,0x6e,0x42,0xd6,0x98,0x90,0x18,0x37,0x46,
0xd7,0x18,0x49,0x70,0xd1,0xc5,0xd5,0x64,0xc3,0x2,0x59,0xed,0x5,0x50,0x5d,0xa1,
0xd0,0x42,0xa1,0x85,0xb6,0x7c,0xb4,0xa5,0x33,0xe7,0xe3,0x7d,0xbc,0x38,0x67,0xa6,
0xdd,0xc2,0xee,0xe2,0xee,0x4c,0x9e,0xbc,0x67,0xe6,0x9c,0x9c,0xff,0xef,0xfd,0x3f,
0xcf,0xfb,0x25,0x3c,0xd9,0xc7,0x0,0x83,0xc0,0x3e,0x60,0xf,0x30,0x88,0x98,0xaa,
0x88,0x29,0x2,0xa8,0xfa,0x1a,0xea,0x67,0x80,0x51,0xe0,0x3c,0x70,0x26,0xbf,0xf6,
0x1f,0xf5,0x62,0x79,0x82,0xfb,0x2f,0x0,0x87,0x30,0xf6,0x60,0xd0,0xba,0xae,0xb7,
0xb5,0xfa,0x94,0xad,0xf6,0xf4,0xd2,0xd1,0xd9,0x4d,0xb9,0xb5,0x15,0x80,0xc5,0x85,
0x5,0x66,0xef,0x4c,0x33,0x33,0x75,0x9d,0x85,0x99,0xc9,0x34,0x5e,0x98,0xbb,0x8e,
0x4f,0x4f,0x2,0xaf,0x3,0x6f,0x2,0xfa,0x71,0x0,0x6,0x80,0x23,0x62,0x83,0xc3,
0xa5,0x9e,0x6d,0xdd,0xc3,0xbb,0xf7,0xf1,0xfc,0x73,0xcf,0xf2,0x85,0x9d,0x43,0xf4,
0x6f,0xec,0x61,0x5d,0xa5,0x4c,0x21,0x74,0x0,0xd4,0xa3,0x84,0xb9,0x7,0x8b,0xfc,
0x77,0x62,0x8a,0xb3,0x23,0x97,0x38,0xfd,0xb7,0xb7,0xb8,0xf8,0xcf,0x33,0x2c,0x4d,
0x5d,0x9e,0xd6,0x34,0x3e,0xe,0xbc,0xa,0xbc,0xf7,0xff,0x0,0x1c,0x0,0x7e,0x58,
0xa8,0x6e,0x3a,0x30,0xb8,0xf7,0x59,0xbe,0xfe,0xe2,0x21,0xe,0xee,0xdf,0x49,0xdf,
0xfa,0x2a,0xc6,0x7c,0xb8,0x69,0xde,0x2b,0x57,0x6f,0xce,0x70,0xf2,0xed,0x11,0x7e,
0xf7,0xfb,0xd7,0x19,0x3d,0xf7,0x16,0xf5,0x99,0xf1,0x53,0xc0,0x4f,0x81,0x53,0xab,
0x9f,0xb7,0x8f,0x79,0xc7,0x8b,0xc0,0xd1,0x72,0xdf,0xae,0xfd,0x5f,0xfe,0xc6,0x77,
0xf8,0xfe,0xb7,0x5f,0xe2,0xc0,0xd3,0x3b,0x68,0x29,0x85,0xd4,0xe2,0x84,0xa5,0x28,
0x66,0x29,0x4a,0x3e,0x20,0x62,0x6a,0x71,0x42,0xa9,0x18,0x32,0xbc,0xa5,0x97,0x2d,
0x3,0xdb,0x89,0x8a,0x55,0xae,0x4f,0xcf,0x6e,0x8d,0xef,0x4d,0xed,0x0,0x1a,0x75,
0xf2,0x81,0x0,0x7,0x80,0xa3,0xad,0xdb,0xf7,0xed,0x3c,0xf8,0xcd,0xef,0xf2,0xd2,
0x57,0xbf,0xc8,0xa6,0x4f,0x75,0x50,0x8b,0x53,0x16,0xa3,0x98,0x87,0xf5,0x98,0x87,
0xf5,0x24,0x6f,0x1f,0x17,0xcb,0xf7,0x6a,0x51,0x42,0x7b,0x5b,0xb,0x1b,0x7b,0xd7,
0x13,0x95,0xbb,0x99,0xb8,0x3d,0xd7,0x13,0xcd,0xde,0x18,0x0,0xae,0x2,0x57,0x1e,
0x7,0x30,0x0,0x1c,0x6d,0xd9,0xfa,0xb9,0xfd,0x4f,0x7f,0xed,0x5b,0x7c,0xe5,0x99,
0xdd,0xac,0x6b,0x2f,0x53,0x4b,0x7c,0x26,0x1e,0x25,0x79,0xc4,0x2c,0xc6,0x9,0x8b,
0xd1,0xa3,0xf1,0xb0,0xbe,0xfc,0xdc,0x62,0x7e,0x6d,0xac,0xa1,0x63,0x5d,0x3b,0xf3,
0x6e,0x2d,0xd3,0x77,0xee,0xf4,0xc4,0x77,0x6f,0x75,0x3,0xe7,0x80,0x59,0x0,0xb7,
0xa2,0x16,0x8e,0x84,0xdd,0x7d,0x7,0xba,0x77,0x3f,0xcf,0xce,0xe1,0x7e,0x82,0x30,
0x64,0xee,0x61,0x1d,0x44,0x0,0x41,0x25,0x7f,0xec,0x7d,0xed,0x8a,0x8f,0xb2,0x5c,
0xec,0xaa,0x48,0xe3,0xb7,0x2a,0x41,0x18,0xb2,0x73,0xb8,0x9f,0xb1,0x1b,0xcf,0x33,
0xb9,0x30,0x77,0x20,0x9a,0xbe,0x7a,0x4,0xf8,0x11,0xa0,0xd,0x80,0x17,0xc4,0x85,
0x87,0x4b,0x3,0x7b,0xe9,0x1f,0x1a,0xa2,0xb3,0xa3,0xc2,0xdd,0x5a,0x84,0x89,0xd,
0x88,0x1,0x1,0x45,0x32,0x98,0x1c,0x40,0x1f,0x5b,0xcd,0xda,0x4,0x11,0xcd,0xaf,
0xd5,0xe3,0x53,0x4f,0x67,0x47,0x85,0xfe,0xa1,0x61,0xe6,0xa6,0x26,0x88,0x67,0x27,
0xf,0x6b,0x12,0x9d,0x2,0xfe,0xea,0xf2,0x49,0xe6,0x50,0x61,0xe3,0x50,0x77,0xb9,
0x7f,0x17,0x5d,0xd5,0x35,0xdc,0xaf,0x27,0xa8,0x11,0xc4,0x64,0x0,0x2a,0xcb,0xe2,
0x2a,0x79,0xd7,0x65,0x95,0x5,0x9a,0x21,0x2d,0xb,0x37,0x20,0x3c,0xea,0x15,0xf1,
0x9e,0xce,0x6a,0x3b,0xe5,0xfe,0x5d,0xd4,0x27,0xff,0xd3,0x5d,0x1b,0x1b,0x39,0x4,
0x9c,0x76,0xc0,0x20,0xd6,0x1d,0xc,0x37,0x7f,0x9a,0x52,0xa5,0x8d,0xa0,0x58,0xe0,
0x5e,0x94,0xa0,0xc6,0x80,0x51,0x10,0xf,0x22,0x2b,0x20,0x56,0xa4,0x63,0x75,0xe,
0xb4,0x1,0xa0,0xcd,0x16,0x55,0xf0,0x1e,0xf1,0x4a,0x58,0x2c,0x50,0xaa,0xb4,0x11,
0x6e,0xde,0x41,0x6d,0xfc,0xc2,0x41,0xd2,0x64,0xd0,0x1,0xfb,0xec,0x9a,0xae,0x5e,
0xb7,0x61,0x0,0x5b,0x28,0xb0,0xa4,0x50,0x8f,0x3d,0x6a,0x0,0xa3,0x19,0x88,0x8,
0x2a,0x6,0xc,0x28,0xba,0x22,0x15,0xab,0x1c,0x50,0xcd,0xfe,0xd6,0xac,0xc7,0xcd,
0x36,0x77,0xc0,0x2b,0xd8,0x42,0x1,0xb7,0xa1,0x1f,0xbb,0xa6,0xab,0x37,0x9d,0xbd,
0xb9,0xcf,0x1,0x7b,0x5c,0xd7,0x26,0x4b,0x65,0x2d,0xa9,0x73,0xcc,0x27,0x1e,0x41,
0xf2,0xf7,0x19,0x54,0x33,0x41,0x35,0x59,0xf,0xb5,0x29,0xae,0xcb,0x69,0x50,0x6d,
0x9a,0xd0,0x74,0xc0,0x37,0x40,0x32,0x71,0xf1,0x1e,0x4d,0x3c,0xa9,0x73,0x50,0x59,
0x87,0xeb,0xda,0x64,0xd3,0xd9,0x9b,0x7b,0x1c,0x30,0x68,0xaa,0xeb,0xd1,0x30,0xa4,
0x2e,0x86,0x7,0xa9,0x22,0xa2,0x34,0x52,0x9,0xa0,0x6,0xd4,0x93,0x3b,0x20,0x8f,
0xda,0xaf,0xb2,0x2,0x80,0xac,0xc7,0x79,0xf6,0xf0,0x79,0x16,0x53,0x45,0x53,0xa5,
0x6e,0xc,0x1a,0x6,0x98,0xea,0x53,0x0,0x83,0xe,0x63,0xab,0xb2,0xa6,0x13,0xef,
0x2,0x96,0x44,0xb8,0x9f,0x7a,0xac,0xb1,0xa8,0x2c,0xa7,0xb0,0xd1,0x73,0xc5,0xe4,
0xe2,0xb2,0x5c,0x8c,0x8d,0x72,0x68,0xd8,0xf,0x8,0xd2,0x2c,0xc6,0x6,0x88,0x78,
0x48,0x53,0x65,0x9,0x83,0x77,0x1,0xb2,0xa6,0xa,0xc6,0x56,0x1d,0xc6,0x14,0x29,
0x95,0xf1,0x81,0xa3,0x6e,0x2c,0x73,0x89,0xd2,0xe2,0x4,0x8f,0xa0,0x9a,0x89,0x66,
0xc2,0x79,0xbb,0xb2,0x20,0x9b,0x92,0x19,0xa5,0xa0,0xab,0x40,0x72,0x0,0x14,0x83,
0xf0,0x30,0xf1,0xd4,0x8d,0x41,0x2,0x7,0xa5,0x32,0x18,0x53,0x74,0x0,0x6a,0x2d,
0xde,0x39,0xd4,0x39,0xee,0x7b,0x88,0x15,0x2c,0x82,0x17,0x83,0x8a,0x41,0x8d,0xcd,
0x47,0x85,0xc1,0x18,0x41,0x44,0x30,0x22,0xef,0x93,0xf7,0xaa,0xa8,0x2a,0xd9,0x57,
0x72,0x17,0x40,0x24,0xfb,0xe5,0x3d,0x3c,0xf4,0xe0,0x9d,0xcb,0xc,0xb3,0xd9,0x24,
0xec,0xf0,0xbe,0xe6,0xd3,0x8,0x71,0xe,0x1f,0x4,0x24,0xc6,0x92,0xa8,0x10,0x60,
0x10,0x63,0xf1,0xc6,0x22,0xc6,0x62,0x8d,0x21,0xb0,0x82,0x33,0x6,0x27,0x60,0x45,
0x68,0x2c,0x8c,0x5e,0x33,0x80,0x58,0x21,0x11,0x4f,0x22,0x42,0x92,0x17,0xb2,0x51,
0xd0,0x54,0x89,0x55,0x48,0x8d,0xc5,0x4,0x1,0x6,0xf0,0x69,0x4,0xde,0xd7,0x1c,
0x3e,0x9d,0xf1,0xf3,0x73,0x19,0x40,0xee,0x42,0x64,0x2d,0x91,0x18,0x8c,0x58,0x2,
0x6b,0x29,0x5a,0x43,0xd1,0x1a,0xa,0xd6,0x10,0x18,0x21,0x10,0xc1,0x1a,0xc1,0x34,
0x96,0x60,0x20,0x55,0x25,0xf6,0x4a,0xec,0x85,0x7a,0xea,0xa9,0x41,0x16,0x1e,0xbc,
0x78,0xb0,0x16,0x13,0x68,0x73,0x8b,0xe4,0xe7,0xef,0x82,0x4f,0x67,0x1c,0x30,0xea,
0xef,0x4c,0x3e,0x23,0xd6,0xa2,0xce,0xe1,0x3,0x87,0x77,0x1,0x4,0xe,0xe7,0x32,
0xf1,0xb2,0xb3,0x94,0x72,0x88,0xd0,0xa,0x81,0x91,0x47,0x1c,0x68,0x0,0x44,0x5e,
0x9b,0xf7,0x41,0xf0,0xa,0xc9,0x8a,0xc9,0xda,0x28,0x78,0xef,0xf1,0x33,0x93,0x0,
0xa3,0xe,0x38,0xef,0x6f,0x8e,0x7d,0x4f,0x96,0xe6,0xad,0xb6,0x74,0x67,0x39,0xa,
0x1c,0x85,0xc0,0xd2,0x1a,0x58,0x5a,0x9d,0xa5,0xc5,0x19,0x5a,0x56,0xb9,0xe0,0x56,
0x1,0x24,0x39,0x40,0xdd,0x7b,0xa,0x49,0x6,0xe9,0x8c,0x60,0xd,0x88,0x8,0xf5,
0x15,0x1b,0x44,0xb9,0x3f,0x8b,0x9f,0xbc,0x92,0x2,0xe7,0x1d,0x70,0x46,0x6f,0xdf,
0xb8,0xee,0xaf,0x5d,0xda,0x4c,0xf7,0x7a,0x70,0x99,0x78,0x5b,0xe0,0x68,0xcb,0x21,
0xca,0xce,0xd0,0xe2,0xcc,0xb2,0xb,0x4d,0x0,0xc9,0x1,0x94,0x44,0xb3,0xde,0xd7,
0x53,0xcf,0x92,0x55,0xc2,0x24,0xc5,0x19,0x9f,0x15,0x2d,0x29,0xa0,0xd4,0x1a,0x85,
0x7a,0xed,0x12,0x7a,0xfb,0xc6,0x75,0xe0,0x8c,0x3,0x46,0x49,0xe2,0x93,0xfe,0xc2,
0x3b,0x3f,0x60,0xef,0x73,0x84,0xae,0x48,0xd9,0x59,0x5a,0x43,0x4b,0x5b,0x60,0x69,
0x73,0xcb,0x10,0x25,0x9b,0x45,0x68,0xd,0xc1,0x2a,0x7,0x62,0x55,0xa2,0xd4,0x53,
0x4b,0x3d,0x61,0xea,0x71,0x46,0x30,0x26,0x6d,0x4e,0x96,0x5e,0x95,0xd4,0x2b,0x71,
0x54,0x47,0x2f,0xbc,0x3,0x49,0x7c,0x12,0xf8,0xb7,0xcd,0x47,0x51,0x9d,0xd9,0xa9,
0x2f,0x99,0x9e,0x8d,0xad,0xe5,0xbe,0x81,0x4c,0x38,0x74,0x54,0x9a,0x91,0x39,0x52,
0xc9,0xa1,0x5a,0x3,0x4b,0x39,0xb0,0x94,0x3,0x43,0xc9,0x19,0xa,0x2e,0x87,0x32,
0x59,0x71,0x5a,0xc9,0x86,0x6a,0x63,0xc2,0xd2,0x7c,0x94,0xa4,0xa,0xd1,0xd9,0xd3,
0xe8,0x1b,0xaf,0x4d,0x93,0x26,0x2f,0x3,0x57,0x1a,0x3b,0xa2,0xab,0xa4,0x49,0x97,
0x59,0x9a,0xdf,0xdf,0xba,0x7d,0x7,0xed,0xeb,0x3a,0xa8,0x84,0x8e,0xb6,0x42,0x26,
0xda,0x0,0x69,0x6b,0xb8,0xd2,0x4c,0x8d,0xa5,0x94,0x17,0x6a,0x68,0xd,0xce,0x98,
0x6c,0x74,0x98,0xe5,0xa5,0x5b,0x81,0xd4,0x2b,0x5e,0x95,0xfa,0xe4,0x38,0xb5,0x3f,
0xfc,0x12,0x9d,0x9a,0x78,0x5,0x38,0xb6,0x7a,0x4b,0x36,0xae,0x77,0x6e,0x6d,0x77,
0x3e,0xdd,0xda,0xf1,0x99,0xcf,0x53,0x69,0x29,0xd1,0x16,0x3a,0xda,0xa,0x41,0xd6,
0x86,0x8e,0x4a,0xee,0x4c,0x6,0xe0,0xb2,0xb4,0x38,0x43,0xc1,0x5a,0x42,0x2b,0x58,
0x63,0xb2,0x9,0x2a,0x9f,0x2d,0xbd,0x64,0xa3,0x23,0x4d,0x3c,0xd1,0xc2,0x3c,0x33,
0xbf,0x3d,0x46,0xed,0xec,0xe9,0x53,0xc0,0xcb,0x8d,0x2d,0xd9,0x4a,0x80,0x59,0xe0,
0x76,0x7d,0x6c,0x74,0x87,0xc3,0xf7,0x74,0xf,0x7d,0x96,0xf6,0x96,0x96,0xcc,0x85,
0x42,0x90,0x39,0x10,0x58,0x2a,0x81,0x6d,0xa6,0xa2,0xe1,0x40,0xc1,0x1a,0x9c,0x35,
0xd9,0xd0,0x6b,0x8a,0xb,0xa9,0xcf,0xc4,0x6b,0xf3,0xf,0x18,0x7f,0xed,0x18,0x33,
0x27,0x7e,0x33,0x2,0xfc,0x38,0xdf,0x13,0x3e,0x76,0x57,0x7c,0x5,0x98,0x99,0x1f,
0x1d,0x19,0xd0,0xc5,0x7,0x3d,0x9d,0x1b,0xfb,0xa8,0x76,0x74,0x64,0x5,0x99,0x3b,
0x51,0x9,0x56,0xa4,0xc1,0x59,0x4a,0xce,0x10,0x58,0x93,0xdb,0x9e,0x8b,0x3,0x69,
0x92,0x92,0xc4,0x29,0x33,0x63,0x97,0xb9,0x74,0xfc,0x17,0x4c,0xfc,0xf1,0xd7,0x23,
0xc0,0x4f,0x80,0x13,0x1f,0x75,0x2e,0x18,0x5,0xae,0xde,0x7b,0xef,0x62,0xf7,0x83,
0xf1,0xcb,0x5b,0x8b,0x41,0xc0,0x86,0x4d,0x7d,0xb4,0x17,0xc2,0xe5,0xe2,0xc,0x2c,
0x15,0x97,0x3,0x58,0x83,0xcb,0xd7,0x7,0x45,0x48,0x53,0x4f,0x1c,0xa7,0x2c,0x2d,
0x2c,0x72,0xe1,0x8d,0x3f,0x71,0xfe,0x57,0x3f,0x63,0xe2,0xef,0x7f,0x3e,0x95,0xf7,
0xfc,0xc4,0x93,0x1c,0x4c,0x1a,0x4e,0x9c,0x9b,0xbf,0x75,0xa3,0x36,0x76,0xe6,0x1f,
0xdb,0xe6,0xae,0x5d,0x69,0xb5,0x3e,0xa1,0x73,0xed,0x5a,0x3a,0xca,0x65,0x2a,0xce,
0xe6,0x61,0x28,0x9a,0x6c,0xd1,0x49,0x53,0x4f,0x14,0xc5,0xdc,0xbe,0x79,0x93,0x77,
0xdf,0x3c,0xc5,0x5f,0x5e,0xfd,0x39,0x6f,0x1f,0x3f,0x36,0x7d,0x6f,0xe2,0xea,0x2b,
0x79,0xce,0xcf,0x7d,0xa2,0xc3,0x69,0x50,0x2c,0x1e,0xdc,0xb0,0x65,0x5b,0xef,0xf0,
0xce,0x5d,0x76,0x78,0x68,0x98,0x6d,0x7d,0x9b,0xe8,0x5a,0xbb,0x6,0x1,0xa6,0xef,
0xde,0xe3,0xf2,0xb5,0x71,0x2e,0x5d,0xbc,0xc8,0x85,0x91,0x7f,0xa5,0x37,0xc6,0x2e,
0x5f,0x8f,0x6b,0xb5,0x4f,0x7c,0x38,0xfd,0xd0,0xe3,0xb9,0xb,0x82,0x6a,0xe0,0x82,
0x22,0x40,0x9c,0xc4,0xb5,0x24,0x8e,0x3f,0xd6,0xf1,0xfc,0x7f,0x7e,0x35,0xc4,0x91,
0xec,0x59,0x86,0x7f,0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82,
// /home/giorgi/4course/механика/ellipse2/resourse/Soccer_ball.png
0x0,0x0,0x8,0x5a,
0x89,
0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0,
0x0,0x0,0x20,0x0,0x0,0x0,0x20,0x8,0x6,0x0,0x0,0x0,0x73,0x7a,0x7a,0xf4,
0x0,0x0,0x0,0x6,0x62,0x4b,0x47,0x44,0x0,0xff,0x0,0xff,0x0,0xff,0xa0,0xbd,
0xa7,0x93,0x0,0x0,0x0,0x9,0x70,0x48,0x59,0x73,0x0,0x0,0xd,0xd7,0x0,0x0,
0xd,0xd7,0x1,0x42,0x28,0x9b,0x78,0x0,0x0,0x0,0x7,0x74,0x49,0x4d,0x45,0x7,
0xe0,0xc,0x19,0xa,0x13,0xe,0xb9,0xb1,0xad,0x75,0x0,0x0,0x7,0xe7,0x49,0x44,
0x41,0x54,0x58,0xc3,0xad,0x57,0x6b,0x4c,0x54,0xdb,0x15,0xfe,0xce,0x99,0x33,0x4f,
0x87,0x39,0x8e,0x83,0x94,0x87,0x5c,0x11,0x11,0x8a,0x88,0xf,0xb8,0x5e,0x3,0xd8,
0xf2,0x32,0x42,0x4c,0x6c,0x7c,0x10,0xa2,0xc4,0xf8,0x4a,0x7c,0x1b,0x89,0xf5,0x87,
0x8d,0xd6,0xc4,0x96,0xa8,0x7f,0x8c,0x69,0xa3,0x69,0xd3,0xa6,0xc8,0xf,0xbd,0x19,
0x82,0x4,0x94,0x36,0x10,0x53,0x6f,0x50,0x89,0x20,0x2a,0xf,0xc5,0x11,0x42,0x47,
0x21,0x28,0x86,0xe7,0xc0,0xcc,0x30,0xc3,0xcc,0xe1,0x9c,0xb3,0xfa,0xa3,0x9d,0x13,
0x10,0x18,0xb9,0x37,0x77,0x25,0x3b,0xb3,0xcf,0x99,0x7d,0xd6,0xf7,0xed,0xb5,0xd7,
0x5e,0xdf,0xde,0xc,0x7e,0x82,0x59,0xad,0xd6,0x18,0x97,0xcb,0xf5,0x1b,0x59,0x96,
0x79,0x0,0x50,0xa9,0x54,0xe3,0x21,0x21,0x21,0xff,0xdc,0xbb,0x77,0x6f,0xef,0x8f,
0xf5,0xc5,0x2c,0x74,0xe0,0xc5,0x8b,0x17,0xff,0x6d,0x32,0x99,0x7e,0x99,0x91,0x91,
0xf1,0xb,0x86,0x61,0xd4,0x1a,0x8d,0x6,0x2c,0xcb,0x2,0x0,0x64,0x59,0x86,0xdf,
0xef,0x7,0x11,0x4d,0x35,0x36,0x36,0xe,0x98,0xcd,0xe6,0x1f,0x8e,0x1e,0x3d,0x7a,
0xe8,0x67,0x21,0xb0,0x7c,0xf9,0xf2,0xff,0x7c,0xfa,0xf4,0x29,0x2e,0x21,0x21,0x1,
0x55,0x55,0x55,0x30,0x18,0xc,0xd0,0x6a,0xb5,0xe0,0x38,0x6e,0x6,0x1,0x51,0x14,
0xe1,0xf7,0xfb,0xe1,0xf5,0x7a,0x51,0x57,0x57,0x87,0x94,0x94,0x14,0x5f,0x7b,0x7b,
0xfb,0x5f,0x8b,0x8b,0x8b,0x7f,0xfb,0x93,0x8,0x64,0x66,0x66,0xa6,0x3d,0x7b,0xf6,
0xec,0x99,0x56,0xab,0x65,0x34,0x1a,0xd,0xa2,0xa2,0xa2,0xd0,0xd0,0xd0,0x0,0x9d,
0x4e,0x7,0xb5,0x5a,0xd,0x86,0x61,0x66,0x10,0x20,0x22,0x48,0x92,0x84,0xa9,0xa9,
0x29,0xd4,0xd4,0xd4,0x20,0x35,0x35,0x15,0xe,0x87,0x3,0x43,0x43,0x43,0x7d,0x1e,
0x8f,0xe7,0xbb,0xa2,0xa2,0xa2,0xc1,0x5,0x13,0xd8,0xbc,0x79,0xf3,0x9f,0x9a,0x9a,
0x9a,0x8a,0x8d,0x46,0x23,0x38,0x8e,0x83,0x46,0xa3,0x41,0x4e,0x4e,0xe,0x76,0xec,
0xd8,0x1,0x96,0x65,0xe1,0xf1,0x78,0xc0,0xf3,0x3c,0x72,0x73,0x73,0x61,0x30,0x18,
0x30,0x31,0x31,0x81,0xab,0x57,0xaf,0xc2,0x66,0xb3,0x61,0x7c,0x7c,0x1c,0x92,0x24,
0xe1,0xdc,0xb9,0x73,0x48,0x4b,0x4b,0xc3,0xc8,0xc8,0x8,0xc6,0xc6,0xc6,0x84,0xee,
0xee,0xee,0xbd,0x47,0x8e,0x1c,0xa9,0xfa,0xea,0x9a,0x6c,0xda,0xb4,0xe9,0x9a,0x5a,
0xad,0x26,0xb3,0xd9,0x4c,0x16,0x8b,0x85,0xd2,0xd2,0xd2,0xe8,0xed,0xdb,0xb7,0x34,
0xdd,0x24,0x49,0xa2,0xe1,0xe1,0x61,0xaa,0xa8,0xa8,0xa0,0xf4,0xf4,0x74,0xd2,0xeb,
0xf5,0x4,0x60,0x46,0xd3,0xeb,0xf5,0x74,0xe3,0xc6,0xd,0x1a,0x1a,0x1a,0xa2,0xce,
0xce,0x4e,0xaa,0xaf,0xaf,0x17,0x6f,0xdf,0xbe,0xbd,0x25,0x28,0x78,0x56,0x56,0xd6,
0x16,0x95,0x4a,0xa5,0x80,0x17,0x14,0x14,0x90,0x20,0x8,0x34,0x9f,0x9,0x82,0x40,
0x66,0xb3,0x79,0x16,0x78,0xa0,0xa9,0xd5,0x6a,0x2a,0x2f,0x2f,0xa7,0x91,0x91,0x11,
0x7a,0xf7,0xee,0x1d,0x3d,0x79,0xf2,0xc4,0x67,0xb5,0x5a,0xa3,0xe7,0x25,0xc0,0x71,
0x9c,0xcc,0xf3,0x3c,0x59,0x2c,0x16,0xca,0xc8,0xc8,0x8,0xa,0x1e,0x88,0x44,0x6c,
0x6c,0xec,0xbc,0x4,0x0,0x10,0xcf,0xf3,0xd4,0xd5,0xd5,0x45,0x83,0x83,0x83,0xd4,
0xd6,0xd6,0x46,0xd5,0xd5,0xd5,0x33,0xb6,0x2a,0x1b,0xe8,0x9c,0x3f,0x7f,0xfe,0xd9,
0xfa,0xf5,0xeb,0x99,0xd,0x1b,0x36,0x60,0xf5,0xea,0xd5,0xb8,0x7f,0xff,0x3e,0xd4,
0x6a,0x75,0xd0,0x88,0xb1,0x2c,0x8b,0xa5,0x4b,0x97,0x6,0x1d,0xe3,0x74,0x3a,0xb1,
0x67,0xcf,0x1e,0xb8,0xdd,0x6e,0x2c,0x59,0xb2,0x4,0xa1,0xa1,0xa1,0xcb,0x6f,0xde,
0xbc,0x79,0x59,0x99,0x34,0x0,0x54,0x54,0x54,0xa8,0x22,0x22,0x22,0x52,0x8e,0x1d,
0x3b,0x86,0xf0,0xf0,0x70,0x3c,0x7c,0xf8,0x10,0x3c,0xcf,0x2f,0xa8,0x3e,0x2c,0x5b,
0xb6,0xc,0xcd,0xcd,0xcd,0x41,0xc7,0xc4,0xc5,0xc5,0xa1,0xbf,0xbf,0x1f,0xc3,0xc3,
0xc3,0x0,0x80,0x81,0x81,0x81,0x4b,0x0,0x2e,0x2b,0x4,0x6,0x7,0x7,0xff,0x10,
0x13,0x13,0xa3,0xb,0x9,0x9,0x81,0x46,0xa3,0x1,0x0,0x88,0xa2,0xf8,0xd5,0x8,
0x0,0x40,0x6c,0x6c,0x6c,0xd0,0xff,0xc3,0xc3,0xc3,0x51,0x5a,0x5a,0xa,0xad,0x56,
0xb,0x51,0x14,0xd1,0xda,0xda,0xa,0xab,0xd5,0xca,0xc6,0xc5,0xc5,0xbd,0xb2,0xdb,
0xed,0xdf,0xb2,0x0,0xe0,0x76,0xbb,0xf,0x9a,0x4c,0x26,0xe8,0xf5,0x7a,0xa8,0x54,
0x2a,0xe8,0xf5,0x7a,0xb8,0xdd,0xee,0xaf,0x82,0x3b,0x1c,0xe,0xac,0x5a,0xb5,0xa,
0x87,0xe,0x1d,0xc2,0x9a,0x35,0x6b,0x60,0x34,0x1a,0x67,0x2d,0xd1,0xa5,0x4b,0x97,
0xa0,0xd7,0xeb,0x95,0xe7,0xc4,0xc4,0x44,0xc4,0xc7,0xc7,0xe3,0xe3,0xc7,0x8f,0x29,
0xca,0xc0,0x86,0x86,0x6,0xa1,0xb7,0xb7,0x97,0xfc,0x7e,0x3f,0x11,0x11,0xd,0xe,
0xe,0x52,0x6d,0x6d,0x6d,0xd0,0x4,0x7c,0xff,0xfe,0x3d,0x55,0x57,0x57,0x2b,0xdf,
0x48,0x92,0x44,0x1e,0x8f,0x87,0x6e,0xdd,0xba,0x45,0x1b,0x37,0x6e,0x24,0x8d,0x46,
0x43,0xb9,0xb9,0xb9,0xe4,0xf7,0xfb,0x49,0x10,0x4,0xf2,0xf9,0x7c,0xe4,0xf5,0x7a,
0x69,0x7c,0x7c,0x9c,0x4a,0x4b,0x4b,0x49,0xa7,0xd3,0x11,0x0,0x70,0x56,0xab,0x35,
0x9a,0x88,0xd4,0x5a,0xad,0x56,0xa9,0x6c,0x16,0x8b,0x5,0x1e,0x8f,0x67,0xde,0x99,
0x77,0x76,0x76,0xe2,0xc3,0x87,0xf,0xd8,0xbe,0x7d,0x3b,0x54,0x2a,0x95,0x32,0x3b,
0x83,0xc1,0x80,0x53,0xa7,0x4e,0xe1,0xc4,0x89,0x13,0xe8,0xe8,0xe8,0x40,0x5f,0x5f,
0x1f,0x58,0x96,0x85,0x2c,0xcb,0x33,0xa2,0x92,0x99,0x99,0x9,0xb3,0xd9,0x8c,0x94,
0x94,0x94,0x54,0x56,0x10,0x84,0x3d,0x6a,0xb5,0x1a,0x2a,0x95,0xa,0xc,0xf3,0xbf,
0xc2,0x28,0x49,0x12,0xae,0x5f,0xbf,0x8e,0xd4,0xd4,0x54,0x1c,0x38,0x70,0x0,0x75,
0x75,0x75,0xf0,0xf9,0x7c,0x20,0x22,0x74,0x75,0x75,0xe1,0xc3,0x87,0xf,0xd8,0xb6,
0x6d,0x9b,0x2,0x3e,0xd7,0xee,0x48,0x4a,0x4a,0x82,0x28,0x8a,0x20,0x22,0x0,0x0,
0x11,0x29,0x7d,0x8d,0x46,0x83,0xe8,0xe8,0x68,0x8c,0x8e,0x8e,0xfe,0x91,0x93,0x65,
0x39,0x89,0x65,0x59,0xb0,0x2c,0xb,0x86,0x61,0x40,0x44,0x38,0x73,0xe6,0x8c,0x92,
0xd9,0xad,0xad,0xad,0xb8,0x73,0xe7,0xe,0x78,0x9e,0x47,0x7c,0x7c,0x3c,0x8e,0x1c,
0x39,0x82,0xc3,0x87,0xf,0x2b,0x64,0xe7,0x32,0x22,0x52,0xa2,0x29,0x8a,0x22,0x58,
0x96,0x55,0xc0,0x3,0x1a,0x12,0x11,0x11,0x81,0xfe,0xfe,0xfe,0x38,0x96,0x65,0x59,
0x7d,0x80,0x1d,0x11,0x61,0x62,0x62,0x2,0x56,0xab,0x75,0x96,0xc3,0xf1,0xf1,0x71,
0xbc,0x78,0xf1,0x2,0x6d,0x6d,0x6d,0x8a,0xf3,0x60,0x4,0x88,0x8,0x66,0xb3,0x19,
0xc3,0xc3,0xc3,0x33,0xa2,0x10,0xf8,0x5d,0xbc,0x78,0x31,0x78,0x9e,0xe7,0x38,0x95,
0x4a,0xe5,0x14,0x4,0x1,0x92,0x24,0x41,0x92,0x24,0x94,0x94,0x94,0xc0,0xe5,0x72,
0xcd,0xeb,0xbc,0xad,0xad,0x2d,0x28,0x78,0x40,0x19,0x89,0x8,0x89,0x89,0x89,0x78,
0xfd,0xfa,0x35,0x96,0x2e,0x5d,0xaa,0xbc,0xb,0x48,0xf7,0xda,0xb5,0x6b,0x91,0x97,
0x97,0x77,0x9b,0xed,0xec,0xec,0xbc,0x5d,0x57,0x57,0x87,0xa9,0xa9,0x29,0x88,0xa2,
0x88,0xa6,0xa6,0xa6,0xa0,0x0,0xbd,0xbd,0xbd,0x90,0x24,0x69,0xce,0x59,0x4f,0x7,
0x27,0x22,0x2c,0x5a,0xb4,0x8,0x93,0x93,0x93,0x33,0xd6,0x5f,0x96,0x65,0xd8,0xed,
0x76,0x84,0x86,0x86,0x82,0xe3,0xb8,0x5b,0xdc,0x95,0x2b,0x57,0x9e,0x67,0x65,0x65,
0x21,0x29,0x29,0x9,0x3c,0xcf,0xc3,0xeb,0xf5,0x6,0x25,0x30,0x3a,0x3a,0xa,0x97,
0xcb,0x5,0xb3,0xd9,0x3c,0x2b,0xb9,0xa6,0x83,0xcb,0xb2,0xc,0x59,0x96,0xf1,0xe0,
0xc1,0x3,0x24,0x26,0x26,0x22,0x32,0x32,0x12,0x44,0x4,0x51,0x14,0xd1,0xdb,0xdb,
0x8b,0x6f,0xbe,0xf9,0x46,0xc8,0xcb,0xcb,0x73,0xb2,0x0,0x60,0x32,0x99,0xa4,0xe4,
0xe4,0x64,0xa4,0xa7,0xa7,0xa3,0xb8,0xb8,0x38,0x68,0x82,0x9,0x82,0x80,0xbb,0x77,
0xef,0x2a,0x0,0x5f,0x2,0x6,0x9a,0x20,0x8,0xd8,0xb2,0x65,0xb,0xca,0xca,0xca,
0xb0,0x7a,0xf5,0x6a,0x64,0x64,0x64,0xe0,0xde,0xbd,0x7b,0x78,0xf5,0xea,0x15,0xa2,
0xa2,0xa2,0xd0,0xd2,0xd2,0xf2,0x49,0x11,0xa3,0xc2,0xc2,0xc2,0xa,0x97,0xcb,0x5,
0xaf,0xd7,0x8b,0xdd,0xbb,0x77,0x23,0x27,0x27,0x27,0x68,0x14,0x1e,0x3f,0x7e,0x8c,
0xa9,0xa9,0xa9,0x19,0x80,0xd3,0x67,0x2f,0x8a,0x22,0x76,0xee,0xdc,0x89,0x97,0x2f,
0x5f,0x2a,0xdb,0xfa,0xcd,0x9b,0x37,0x38,0x7b,0xf6,0x2c,0x3a,0x3a,0x3a,0xa0,0xd3,
0xe9,0x60,0x34,0x1a,0xff,0x32,0xc3,0xe9,0xd3,0xa7,0x4f,0x1d,0xef,0xde,0xbd,0x23,
0x87,0xc3,0x41,0x63,0x63,0x63,0x94,0x9c,0x9c,0x3c,0x4b,0x5a,0xd,0x6,0x3,0x15,
0x14,0x14,0x50,0x6d,0x6d,0x2d,0x55,0x56,0x56,0x52,0x4d,0x4d,0xd,0x8d,0x8c,0x8c,
0x90,0xcf,0xe7,0x23,0x9f,0xcf,0x47,0x93,0x93,0x93,0x64,0xb7,0xdb,0x69,0xdd,0xba,
0x75,0xb3,0xbe,0xe5,0x38,0x8e,0xc2,0xc2,0xc2,0xa8,0xb1,0xb1,0x91,0xea,0xeb,0xeb,
0x47,0x66,0xa8,0x21,0x0,0xd8,0x6c,0xb6,0xcb,0x6b,0xd6,0xac,0xf9,0xb3,0xc1,0x60,
0x80,0xd9,0x6c,0xc6,0xa3,0x47,0x8f,0x90,0x97,0x97,0x87,0xf6,0xf6,0x76,0xf0,0x3c,
0x8f,0xec,0xec,0x6c,0x5c,0xbb,0x76,0xd,0x31,0x31,0x31,0x4a,0xbd,0xf0,0x78,0x3c,
0x68,0x6e,0x6e,0x86,0xdf,0xef,0x7,0xc3,0x30,0xe8,0xe9,0xe9,0x41,0x49,0x49,0x9,
0xc6,0xc6,0xc6,0x66,0x45,0xcd,0x60,0x30,0x20,0x2c,0x2c,0xc,0x7e,0xbf,0x1f,0x36,
0x9b,0xed,0x77,0x73,0x86,0xb6,0xaa,0xaa,0xaa,0xaf,0xa5,0xa5,0x85,0xfa,0xfb,0xfb,
0xc9,0xe5,0x72,0x91,0xd3,0xe9,0xa4,0xb,0x17,0x2e,0xd0,0xd8,0xd8,0x18,0x79,0xbd,
0x5e,0xf2,0x7a,0xbd,0x34,0x39,0x39,0x49,0x93,0x93,0x93,0xca,0xb3,0xd7,0xeb,0x25,
0x8f,0xc7,0x43,0x6e,0xb7,0x9b,0x8a,0x8b,0x8b,0xe7,0x3c,0x94,0x18,0x8d,0x46,0xb2,
0x58,0x2c,0x74,0xfc,0xf8,0x71,0xaa,0xac,0xac,0x9c,0xfb,0x40,0xf2,0xff,0xaa,0x95,
0x3c,0x31,0x31,0xe1,0x1e,0x1d,0x1d,0x55,0xb4,0x20,0x35,0x35,0x15,0x1c,0xc7,0x29,
0xeb,0x3c,0x7d,0xcd,0xa7,0xf7,0x1,0xe0,0xe4,0xc9,0x93,0xb3,0xca,0xb3,0xd1,0x68,
0x84,0x56,0xab,0x5,0xcf,0xf3,0x28,0x2c,0x2c,0xf4,0xc9,0xb2,0xbc,0x6e,0x5e,0x2,
0x85,0x85,0x85,0xce,0xae,0xae,0xae,0x82,0x81,0x81,0x1,0x79,0x68,0x68,0x8,0x6e,
0xb7,0x1b,0xc,0xc3,0x28,0x3a,0xf0,0x65,0xa6,0x7f,0x49,0x22,0x2c,0x2c,0xc,0xa1,
0xa1,0xa1,0x81,0xe3,0x1d,0x4c,0x26,0x13,0xb4,0x5a,0x2d,0xb4,0x5a,0x2d,0x32,0x33,
0x33,0xd1,0xdf,0xdf,0x5f,0x50,0x58,0x58,0xe8,0xfc,0xea,0xb1,0xbc,0xac,0xac,0x6c,
0xe3,0x8a,0x15,0x2b,0x7e,0x30,0x18,0xc,0x21,0x3a,0x9d,0xe,0x76,0xbb,0x1d,0xd9,
0xd9,0xd9,0xf3,0x96,0xe0,0xe9,0x75,0x60,0xd7,0xae,0x5d,0x68,0x69,0x69,0x41,0x48,
0x48,0x8,0x2c,0x16,0xb,0xe2,0xe3,0xe3,0x51,0x54,0x54,0x24,0x4c,0x4c,0x4c,0xfc,
0x7a,0xff,0xfe,0xfd,0xcd,0xb,0xbe,0x98,0x94,0x97,0x97,0xaf,0xac,0xa9,0xa9,0xe9,
0xee,0xe9,0xe9,0x61,0xd5,0x6a,0x35,0xe,0x1e,0x3c,0x88,0xfc,0xfc,0x7c,0x4,0x94,
0x33,0xa0,0x7a,0x81,0xea,0x26,0xcb,0x32,0x3e,0x7f,0xfe,0xc,0x9b,0xcd,0x86,0xd8,
0xd8,0x58,0x70,0x1c,0x7,0xa7,0xd3,0x9,0x87,0xc3,0xd1,0x27,0x8,0xc2,0x8f,0xbb,
0x98,0x4c,0xb7,0x84,0x84,0x84,0xa7,0xef,0xdf,0xbf,0xff,0x95,0x5e,0xaf,0xc7,0xca,
0x95,0x2b,0x91,0x9f,0x9f,0x8f,0x7d,0xfb,0xf6,0xc1,0x60,0x30,0x28,0x2a,0x37,0x30,
0x30,0x0,0xbb,0xdd,0xe,0xa3,0xd1,0x88,0xe8,0xe8,0x68,0xb8,0x5c,0x2e,0xa8,0x54,
0xaa,0xc1,0x8e,0x8e,0x8e,0xdf,0x9f,0x3e,0x7d,0xfa,0x1f,0x3f,0xcb,0xe5,0x34,0x3e,
0x3e,0xfe,0x45,0x4f,0x4f,0xcf,0xb7,0x0,0x18,0x9d,0x4e,0x7,0x9e,0xe7,0x91,0x9c,
0x9c,0x8c,0xfc,0xfc,0x7c,0x98,0x4c,0x26,0x44,0x46,0x46,0x82,0x65,0x59,0xdf,0xf3,
0xe7,0xcf,0x87,0x78,0x9e,0xff,0xdb,0x99,0x33,0x67,0xae,0x2e,0xc4,0x2f,0xb7,0x50,
0x2,0xdd,0xdd,0xdd,0xdf,0x5,0xfa,0x5b,0xb7,0x6e,0x8d,0xed,0xeb,0xeb,0xfb,0xbb,
0xc9,0x64,0x32,0x33,0xc,0xf3,0x2f,0xaf,0xd7,0x3b,0xe8,0x74,0x3a,0xbf,0xff,0x32,
0xc1,0x16,0x62,0xff,0x5,0x68,0x74,0xd7,0x4f,0xb0,0x7d,0x4,0xf6,0x0,0x0,0x0,
0x0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82,
// /home/giorgi/4course/механика/ellipse2/resourse/basketball.png
0x0,0x0,0x9,0xa7,
0x89,
0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0,
0x0,0x0,0x20,0x0,0x0,0x0,0x20,0x8,0x6,0x0,0x0,0x0,0x73,0x7a,0x7a,0xf4,
0x0,0x0,0x0,0x6,0x62,0x4b,0x47,0x44,0x0,0xff,0x0,0xff,0x0,0xff,0xa0,0xbd,
0xa7,0x93,0x0,0x0,0x0,0x9,0x70,0x48,0x59,0x73,0x0,0x0,0xe,0xc4,0x0,0x0,
0xe,0xc4,0x1,0x95,0x2b,0xe,0x1b,0x0,0x0,0x0,0x7,0x74,0x49,0x4d,0x45,0x7,
0xe0,0xc,0x19,0xa,0x28,0x3,0xfb,0xb2,0x3e,0xf0,0x0,0x0,0x9,0x34,0x49,0x44,
0x41,0x54,0x58,0xc3,0xc5,0x97,0x5b,0x8c,0x9d,0x57,0x75,0xc7,0x7f,0x6b,0x5f,0xbe,
0xcb,0xb9,0xcf,0x19,0xcf,0xc4,0xf6,0x64,0x98,0x71,0xec,0x90,0x40,0x6e,0x36,0x21,
0x44,0x6d,0x20,0x49,0xdb,0xc8,0x10,0x10,0x9,0xf4,0xa5,0x45,0xa5,0x2,0x29,0x6a,
0x11,0xed,0x4b,0xab,0xd2,0x87,0x3e,0x14,0xde,0x88,0xf2,0xd2,0x56,0x95,0x7a,0x51,
0x90,0x8a,0x90,0x1a,0x51,0xb5,0x15,0x50,0x45,0xe1,0x1a,0x40,0x21,0x6,0x87,0x88,
0x49,0xa0,0x71,0x1c,0xdf,0x62,0x3b,0xbe,0xce,0x78,0xe6,0x78,0xe6,0xcc,0x9c,0xf3,
0x7d,0xe7,0xbb,0xec,0xbd,0x79,0x98,0x88,0x26,0x28,0xb4,0x94,0x46,0xea,0x7a,0xd9,
0x4f,0x4b,0xeb,0xa7,0xff,0x5e,0x6b,0xef,0xf5,0x87,0xff,0xe7,0x90,0xff,0x6d,0xc2,
0x57,0x1e,0xb8,0xa1,0xdd,0x54,0xb2,0xab,0x68,0xa4,0x3b,0xdb,0xd4,0x53,0x2a,0x2f,
0xa3,0xae,0x55,0xe3,0xdd,0x8b,0x8d,0xb5,0xfc,0x6a,0x79,0xe9,0xab,0xcf,0x47,0x2b,
0x9f,0x58,0x5a,0xaa,0xde,0x54,0x80,0xcf,0xdc,0x83,0xb9,0x7b,0xe7,0x4d,0xef,0x8a,
0xea,0xfa,0xe0,0x72,0xee,0xdf,0xd3,0x97,0x70,0x7d,0xdb,0x30,0x65,0x8c,0x8e,0x6c,
0xc3,0xaa,0x29,0xed,0xea,0x29,0xed,0x26,0xe2,0xaa,0xcb,0x45,0xda,0x78,0x76,0x3d,
0x34,0xbf,0x7d,0xb5,0x1f,0x3f,0xf9,0xce,0xcf,0x3e,0x7d,0xf9,0xff,0xc,0xf0,0xe5,
0x7,0x6f,0x79,0x4f,0x22,0xc5,0x47,0xaf,0xe4,0xf5,0x83,0xb3,0x12,0xae,0x69,0x52,
0xb3,0xa7,0x69,0xb8,0xe2,0x84,0xa5,0x3c,0xe6,0xd9,0x32,0xe2,0xae,0x9d,0x6d,0xe6,
0x54,0xce,0x60,0x92,0x53,0xc5,0xd,0x96,0xb3,0x50,0xee,0xee,0x37,0xe,0x9f,0xf1,
0xed,0x2f,0x3e,0x79,0xe6,0xec,0x63,0x4f,0x3d,0x75,0x74,0xf4,0xab,0x0,0xa8,0x7f,
0x7f,0xef,0xdb,0xff,0xa4,0xad,0xeb,0x3f,0x3c,0x57,0x94,0x37,0xf4,0xea,0x82,0x7d,
0xad,0x84,0x4b,0x65,0xc5,0x24,0xed,0xf2,0xf5,0x4d,0xb8,0xab,0x63,0x39,0xbf,0x31,
0xe4,0x87,0x63,0xe1,0xae,0xd9,0x94,0x2b,0xaa,0x81,0x37,0x31,0xf3,0x51,0x85,0x93,
0x40,0xd4,0xea,0x95,0x6d,0xd4,0x63,0x21,0xd6,0x7f,0xf7,0x7,0xff,0xf0,0xc4,0xd2,
0x2f,0xd,0xf0,0xf9,0x7,0x6f,0xeb,0xb5,0x8a,0xea,0x2f,0x2c,0xf5,0x9f,0x9f,0x1b,
0x6e,0x49,0x2a,0x9e,0xdd,0xdd,0x36,0x17,0x6d,0x87,0xc7,0xcf,0x5d,0x65,0x67,0xaf,
0x4f,0x3b,0x11,0x8e,0x2d,0xaf,0xf3,0xd6,0xa6,0x62,0xdd,0xb,0xd7,0xb5,0xd,0x77,
0x4e,0x9,0x8d,0xba,0xe0,0x2d,0xd,0xc7,0x70,0x52,0x32,0xdd,0x6b,0xa1,0x4d,0x42,
0x29,0xe6,0xa9,0xab,0x75,0xf1,0xd9,0x3,0x8f,0xbe,0xf8,0xcd,0xff,0x11,0xe0,0x1e,
0x30,0x9f,0xbc,0xff,0xc6,0x87,0x4d,0x5d,0x7d,0xea,0xec,0xe6,0x84,0xb4,0x9e,0xe0,
0xbb,0xd3,0x7c,0x63,0xe0,0xb8,0xa9,0x23,0xdc,0xd7,0xd7,0x7c,0xee,0xe5,0x31,0xef,
0xe8,0xc2,0x8c,0x38,0x4e,0x9b,0x36,0xef,0xef,0x96,0x34,0xeb,0x9c,0x86,0x14,0xc4,
0x56,0x13,0xa5,0x16,0x6d,0xa1,0xd9,0x8e,0x49,0x8c,0x22,0x94,0x9e,0x4c,0xc9,0xf,
0x86,0x75,0xf4,0x97,0xf3,0xff,0x78,0xe2,0x3b,0xaf,0xad,0xa7,0x7f,0x1e,0xe0,0x91,
0xf,0xde,0xf2,0x29,0xe3,0xdc,0xa7,0x4f,0x6d,0x8e,0xc5,0xd4,0x5,0xa6,0x3f,0x43,
0x3e,0xb5,0x83,0x85,0x7a,0xcc,0xd7,0xd6,0x3,0x65,0x96,0x31,0x16,0x45,0xd7,0x18,
0x3e,0xde,0xdd,0x62,0x87,0x2f,0x49,0xf3,0x4d,0xda,0x16,0x66,0x9a,0x9a,0x56,0xec,
0x91,0xd8,0xb0,0x2c,0x11,0x47,0x26,0x31,0x3f,0xda,0x10,0x8e,0x6c,0x6,0xce,0x16,
0x32,0x7f,0x72,0x1c,0x4d,0xa7,0xf1,0xcc,0xf,0x5e,0x58,0x5e,0x1b,0xbe,0xa1,0x2,
0x5f,0xfc,0xd0,0x6d,0x7,0x43,0x56,0x3d,0x9a,0x8d,0x37,0x17,0xae,0x64,0x19,0xdd,
0x46,0x83,0xa7,0x7d,0x8b,0x8b,0xc3,0x11,0xbf,0xdb,0xd,0x9c,0x2e,0x15,0xdf,0x1f,
0xc1,0xfb,0x7a,0x9e,0xfb,0xfb,0xc2,0x62,0xb1,0xc6,0xc8,0x6b,0xa6,0x3b,0x31,0x21,
0x56,0x5c,0xd4,0x29,0x27,0x26,0x30,0x52,0x96,0x44,0xe0,0x2d,0x1d,0xc5,0xce,0x36,
0xf4,0x4c,0x8d,0xd5,0x86,0x32,0x44,0x54,0x75,0x78,0x78,0xf6,0x6f,0x5e,0xfa,0x34,
0x50,0xbf,0xe,0xe0,0xf3,0x1f,0x5b,0x48,0x9a,0x83,0xd6,0xe7,0x7c,0x96,0x7d,0xf4,
0xc4,0x7a,0xc6,0xb4,0x54,0xec,0x6a,0xc5,0x4c,0xe2,0x94,0x6f,0xac,0x95,0xfc,0x64,
0x14,0x98,0x36,0x81,0xfb,0xfb,0x81,0xdf,0xd1,0x43,0xb4,0x38,0x82,0x28,0x26,0x71,
0xc4,0xb,0x24,0x9c,0xf,0x96,0xc8,0x28,0xae,0x4f,0x4a,0x6e,0x9d,0x56,0x34,0x13,
0x43,0x94,0xc6,0x88,0x11,0xbc,0xd1,0xac,0x54,0x4d,0x8a,0xca,0x73,0x6d,0x94,0x9f,
0x7f,0x39,0xf7,0x1f,0x7b,0xdb,0x5f,0x1f,0xff,0x2e,0x80,0xf9,0xd9,0x5d,0xac,0x76,
0xef,0xad,0xab,0xfc,0x83,0x6b,0x79,0x4e,0xe1,0xa,0x7a,0x26,0xa7,0xc8,0xc6,0x98,
0x2c,0xf0,0xdb,0xed,0x36,0xb7,0x5b,0xa1,0xa1,0xe0,0xe,0x5b,0x90,0xd7,0x9e,0xa0,
0x85,0xc3,0x99,0xe6,0xca,0xd8,0x33,0xdd,0xcc,0xf9,0x8d,0x5e,0xc9,0x42,0x37,0x41,
0xb5,0x52,0xb0,0x40,0x9c,0x32,0xee,0xee,0xe2,0xf9,0x21,0x94,0x12,0x33,0x28,0x2d,
0x2f,0x9c,0x5f,0xe7,0x8f,0xf7,0x9a,0xf9,0x59,0x9b,0x7f,0x18,0x78,0x1a,0xa8,0x7f,
0x6,0x60,0xc5,0x1d,0x54,0xc1,0x75,0x97,0x27,0x15,0x5d,0x3c,0x75,0xf0,0x68,0xf,
0x5a,0x2,0x7a,0x3c,0x64,0x7f,0x70,0x24,0x46,0xe1,0xcb,0x88,0xc3,0x23,0xcf,0xf9,
0x2c,0xd0,0x8f,0x3,0xf,0xcc,0x68,0x76,0x4f,0xc7,0x38,0xf1,0xb8,0xa,0x6a,0x9d,
0x72,0xc4,0xf7,0x39,0x3a,0x4c,0x28,0x64,0x37,0xaf,0xac,0xae,0xe3,0xab,0x82,0x1b,
0xe7,0xa6,0xc8,0xa3,0x8a,0xa5,0xcd,0x82,0xfb,0x66,0xec,0x7d,0x5f,0xff,0xa3,0x3,
0x8b,0xef,0xfb,0xfb,0xe7,0x4f,0x19,0x80,0x8f,0xdc,0xbe,0x6b,0xc7,0x30,0x2b,0xde,
0x6d,0xca,0x82,0xe0,0x3,0x5d,0xed,0x70,0xa2,0xb1,0x22,0x88,0x80,0xb,0x8e,0x60,
0xe0,0x54,0xae,0x78,0xf1,0x6a,0x49,0xa2,0x2,0xbf,0x3e,0x63,0xb8,0x65,0x36,0x25,
0x98,0xc0,0x86,0x69,0x21,0x71,0x93,0x7f,0x1d,0x75,0xa8,0x47,0xd3,0x9c,0x1b,0x55,
0xcc,0xcd,0x74,0xb8,0xbe,0xa1,0x98,0xf4,0xba,0xe4,0x95,0xe3,0xec,0x60,0x13,0x31,
0x9a,0xe7,0x6,0x15,0x77,0x4f,0xb3,0x67,0xb1,0xa3,0xe,0x0,0xdb,0x0,0x3b,0x24,
0x9a,0x2f,0x8a,0x7a,0xcf,0xe5,0x71,0x89,0xa9,0x2b,0x9c,0xf1,0x4,0x6b,0x9,0x46,
0x8,0xa,0xf2,0xa,0xe,0xad,0xd5,0x54,0x45,0xe0,0xe6,0x26,0xdc,0x33,0x6b,0x31,
0xcd,0x88,0x32,0x6d,0xf0,0x78,0xde,0x66,0x69,0x3d,0xe5,0x8e,0x99,0x16,0x17,0xb5,
0x66,0x65,0x2d,0x63,0x3a,0x8d,0x78,0x68,0x4f,0x8b,0xe0,0xb7,0x38,0xbc,0x32,0x44,
0x45,0x4d,0x96,0xd7,0xd6,0x78,0xc7,0x5c,0x8f,0x6e,0x73,0x7,0x9b,0xc5,0x66,0xd2,
0x56,0xfe,0x16,0xe0,0x4b,0x6,0x20,0x89,0xd8,0x55,0xfb,0xba,0x55,0x78,0xcf,0x35,
0xba,0xc4,0xa1,0x71,0x8,0x4a,0x69,0x4e,0x6d,0xe4,0x9c,0x9c,0x54,0xb4,0x14,0x1c,
0x9c,0x15,0x66,0x52,0xc3,0x46,0x80,0x46,0xe9,0x49,0x6d,0xc9,0xc0,0x2b,0x7e,0xf4,
0xca,0x2a,0x83,0x71,0xc5,0xcc,0x54,0x8b,0x71,0x19,0xe8,0x36,0x34,0x47,0x97,0xd7,
0x18,0x79,0x45,0x1c,0x37,0xb8,0x77,0x77,0x83,0x6a,0x61,0x91,0x45,0x6,0xcc,0xba,
0x21,0x1d,0x29,0x19,0x91,0xec,0xd9,0xb7,0x6f,0x9f,0x51,0x0,0xb1,0x55,0xfd,0xcb,
0x65,0x30,0x42,0x40,0xf0,0x78,0xa,0x8a,0x6a,0xc2,0x73,0x83,0x8c,0xa3,0x95,0x67,
0x4f,0x37,0xe2,0xbd,0x53,0x86,0x96,0x55,0x14,0xb5,0xa3,0xa,0xe0,0x9d,0x87,0x49,
0xc1,0x81,0xb6,0x10,0x9b,0x8,0xa7,0x22,0xce,0xe,0x32,0xa6,0x5a,0x2d,0x76,0xb4,
0x5a,0x7c,0xe9,0x5c,0xc6,0xc9,0x32,0xe6,0x9e,0x59,0xcb,0xcd,0x37,0xec,0xe3,0xd6,
0x8e,0x62,0x71,0xb2,0xc2,0x4c,0x98,0x10,0xe3,0x98,0x38,0xd7,0x3f,0x10,0x45,0x76,
0xbb,0x9,0xeb,0xa0,0x86,0x1e,0xd9,0x87,0xa6,0x76,0x60,0xad,0xf0,0xdc,0x46,0xcd,
0x44,0x6b,0x6e,0xea,0x68,0xe6,0xa4,0x66,0x58,0x3b,0x9c,0x31,0x18,0x5,0xb1,0x28,
0x74,0x5d,0x83,0x16,0x9a,0x55,0x46,0x33,0x36,0xdc,0x35,0x97,0x72,0x7c,0x23,0x63,
0x5e,0x65,0x7c,0x20,0xf1,0xb8,0x9d,0x3b,0xe8,0xcf,0x5f,0x47,0x35,0x5a,0x67,0xbc,
0xf2,0xa,0xb3,0x2b,0xc7,0x68,0xf8,0x82,0xe0,0x14,0x63,0x60,0xb5,0x46,0x8a,0x9e,
0x13,0x3,0x90,0x49,0xb4,0xa9,0xa5,0xf2,0x91,0xd4,0xba,0x26,0xf0,0xfd,0x15,0xcf,
0x8,0xb8,0x7b,0x46,0xe8,0xba,0x9a,0x32,0x38,0x94,0x81,0xdc,0x7b,0xa2,0x0,0x89,
0x15,0x5c,0x10,0xbc,0x57,0xd4,0x65,0xc1,0x6c,0xa3,0xc9,0xde,0xc9,0x6,0xfb,0x9b,
0x25,0x2d,0x36,0x69,0x6f,0x25,0x6c,0xcd,0x2d,0x50,0x2d,0xbf,0xcc,0xd4,0xe0,0x65,
0x9a,0x2e,0xa3,0xa1,0x3,0x21,0x78,0xb6,0xc4,0x70,0xb2,0x4c,0x18,0xe9,0x68,0xeb,
0x8a,0x1f,0x6f,0x8f,0x61,0x3f,0xe9,0x2d,0xdb,0x6a,0x92,0x51,0xeb,0xee,0xf1,0x4d,
0xa1,0x8,0x81,0x3b,0xa7,0x20,0xae,0x2b,0x8a,0x0,0x46,0x81,0x9,0x82,0xe,0x82,
0xf6,0x1,0xa9,0x4a,0x2,0x81,0x3a,0x8,0x5d,0x9d,0xf1,0xfb,0x9d,0x84,0x99,0x6c,
0x42,0xd7,0x7a,0x3a,0xd6,0x21,0xe3,0x9c,0xfe,0xc9,0xef,0xa1,0x27,0x39,0x51,0x64,
0x30,0x89,0x6,0xa5,0xf9,0xc9,0x96,0x66,0x35,0xc4,0xcc,0xf4,0x23,0xae,0x6b,0x94,
0xe7,0x9f,0x79,0xe6,0xc2,0x36,0x80,0xa9,0xae,0x5e,0x88,0x9d,0xbb,0x74,0x6c,0xe2,
0xbb,0x5b,0x5a,0xb3,0x7f,0xda,0xd3,0x20,0x50,0xf9,0x40,0xa4,0x3,0xce,0x83,0xb,
0x10,0x0,0xaf,0x14,0xb9,0xf7,0x58,0xad,0x29,0x11,0x92,0xba,0x62,0x2e,0x5b,0x25,
0x11,0x8d,0x11,0xc1,0xeb,0x80,0xaa,0x6a,0x24,0xd7,0x28,0x6d,0xc8,0xbd,0xe6,0xcc,
0xd0,0x31,0x70,0x60,0xad,0x65,0xff,0x74,0xc5,0x74,0x47,0x55,0x2f,0x8d,0xa2,0x97,
0x0,0x67,0x0,0x4e,0x8f,0x4e,0xad,0xec,0x65,0xe1,0xd9,0xd5,0x4a,0xbd,0x6d,0x3e,
0x8a,0x49,0xa9,0x70,0x3e,0x40,0x8,0xd4,0x1e,0x74,0x80,0xaa,0x4,0x65,0x3d,0xca,
0x8,0x5b,0xe,0x3c,0x9e,0x9e,0xf6,0x38,0x89,0xb0,0xde,0x61,0xac,0xa0,0x3,0x80,
0x65,0x52,0x7b,0xce,0xad,0x67,0x5c,0xc4,0x52,0xba,0x92,0xa9,0xb6,0xe6,0xb6,0x4e,
0x60,0xae,0xb5,0xfd,0x82,0x4e,0x32,0x2e,0xbf,0x72,0x39,0xff,0x31,0xe0,0xd,0xc0,
0xa3,0x4b,0x54,0x7f,0x7a,0x20,0x7e,0xd2,0x84,0xea,0x23,0x65,0x3e,0x89,0x68,0xc6,
0xa0,0xa,0x8,0x8e,0x20,0x80,0x2,0xe7,0xa0,0xe,0xc2,0xa4,0xf6,0x34,0xb5,0x26,
0xf8,0x40,0xd,0x5c,0x2d,0x6a,0x26,0x1e,0xc6,0x9b,0x5,0x9b,0x5,0x14,0x91,0x27,
0xa4,0x86,0x5e,0x2b,0xb0,0xd8,0xf4,0xec,0xf5,0x13,0x3a,0x51,0x44,0x28,0x2d,0x45,
0x51,0x62,0x6c,0xca,0xc6,0xc4,0x1f,0xfa,0xb3,0xa5,0x4b,0x27,0x5e,0xf7,0x17,0x9c,
0xaa,0xaa,0x6f,0xdd,0xde,0xb4,0x87,0x56,0x86,0xee,0x37,0xd7,0x8b,0x1a,0xa5,0x2,
0xa7,0x47,0xc2,0xb0,0x52,0x54,0xc1,0x43,0x8,0x44,0xe2,0x88,0x74,0x40,0x8b,0x80,
0x77,0x34,0xb5,0x10,0x2b,0x4f,0xd7,0xc0,0x5c,0xe4,0x59,0x68,0x59,0x16,0x7b,0x8a,
0x5e,0x43,0xd1,0x24,0x10,0xaa,0x2,0x31,0x81,0xaa,0xaa,0x8,0x71,0x4c,0x20,0xe0,
0xbd,0x1e,0x9e,0x1f,0xeb,0xc7,0x8f,0x1f,0x1f,0x8c,0x5e,0x7,0xf0,0xf8,0x91,0x33,
0x2b,0xef,0xbe,0x75,0xe1,0xb1,0xe9,0xa8,0xf1,0x6b,0x47,0xb2,0x3c,0x35,0xb5,0xa2,
0x6f,0x6a,0x16,0x1a,0x1,0x2d,0x1,0x5,0x88,0xf,0x34,0x34,0x44,0x46,0x68,0xa0,
0xe8,0xc6,0x8a,0x86,0x52,0xb4,0xc,0x4,0xe7,0x48,0x23,0x85,0x6,0xdc,0xa8,0xa0,
0x4c,0x34,0x2,0x18,0x23,0xf8,0x60,0xd0,0xa2,0xf0,0x41,0x58,0xcb,0xc2,0x7f,0xfc,
0xde,0x97,0xcf,0x7e,0x8d,0xed,0x96,0x7a,0xfd,0x42,0x72,0x76,0x65,0x78,0xf4,0x8e,
0x6b,0xfb,0xbb,0x36,0x8c,0x7d,0x67,0x53,0x17,0x5c,0x9b,0x4,0x1a,0x3a,0x60,0x55,
0xc0,0xa,0x98,0xb0,0xdd,0xf,0x3a,0x78,0x2c,0x60,0xd4,0x76,0x91,0xbc,0xe,0x78,
0x14,0x21,0x4,0x42,0x8,0x28,0xe5,0x70,0x4a,0x83,0xa,0x88,0x4,0x2a,0x89,0xf0,
0x5a,0x51,0x44,0xe9,0xd2,0xc9,0x22,0x7d,0xe4,0x6f,0x7f,0x78,0xf6,0xc4,0x1b,0x6e,
0x44,0x57,0xc1,0xbd,0x6b,0xaa,0x7d,0xb2,0x8c,0xed,0xbc,0xf2,0xee,0xc6,0x95,0x71,
0x85,0xf,0xd0,0x34,0x2,0x2a,0xc0,0xab,0xd8,0x5a,0x20,0x88,0x50,0x56,0x8e,0x48,
0xb,0x65,0x0,0xab,0x4,0xef,0x3c,0xda,0xb,0x88,0x90,0x6e,0xcf,0xc,0x12,0xc7,
0x10,0x27,0x64,0x3a,0xba,0x70,0xa1,0xb6,0x8f,0xfc,0xd6,0x63,0x2f,0x3e,0x1,0xf8,
0x5f,0xb8,0x92,0x1d,0x5a,0xdb,0x1a,0x2c,0xf4,0xd3,0x33,0xb,0xd6,0x5e,0x13,0x7,
0x75,0xc3,0x66,0x5,0x93,0x3a,0xd0,0x8d,0x5,0x25,0xff,0x95,0xa1,0x4,0x6a,0x1,
0xef,0xc1,0xd5,0x10,0x2,0x58,0x11,0xac,0xf1,0x34,0x13,0x85,0x8d,0xd,0x5,0x1a,
0x74,0x44,0x21,0x72,0xe6,0x4a,0xad,0xfe,0xea,0xde,0x7f,0x3b,0xfd,0x5,0xa0,0xfc,
0x6f,0x77,0x42,0x80,0x63,0xab,0xe3,0x8b,0x77,0x4e,0xf7,0xff,0xb3,0xa5,0x43,0xda,
0x35,0xea,0xe6,0x81,0x13,0x3d,0xa8,0x3c,0xa5,0x17,0x1a,0x1a,0xac,0xe,0x4,0x81,
0xda,0x6f,0xb,0x63,0x45,0x50,0x4,0xe4,0x55,0x65,0xbc,0x80,0xd5,0x6,0xaf,0x23,
0xb6,0x82,0x39,0x74,0x6e,0x12,0x1e,0xb9,0xff,0xab,0x97,0xfe,0x19,0x28,0x7e,0xbe,
0x96,0xfe,0x45,0xa6,0xe0,0xf0,0xea,0x70,0xb5,0xf2,0xc9,0x77,0x17,0xba,0xfa,0xca,
0x94,0x8d,0xfa,0x56,0xf4,0xee,0x4d,0x2f,0x32,0x74,0x30,0xa8,0x3,0x88,0x60,0x95,
0xd0,0xb0,0x1a,0xa3,0x5,0x63,0x2d,0x69,0x12,0xa3,0x94,0x66,0x64,0x52,0x6,0x4e,
0x5f,0x58,0xf3,0xf6,0xb,0xc7,0x72,0xf3,0xf0,0x43,0xdf,0x5b,0xfe,0xe,0x50,0xfd,
0xaa,0xd6,0x4c,0x3d,0xb4,0xb7,0x73,0xdd,0x8c,0xd,0xf,0x88,0x52,0x7,0x8d,0xb0,
0x7f,0xa3,0xac,0xfb,0x4e,0xc4,0x88,0xf2,0x62,0x55,0xa0,0x69,0x14,0xa9,0xb1,0xae,
0x95,0x26,0x23,0x71,0xf5,0xa9,0x75,0x2f,0x4f,0x1d,0xdb,0xc8,0x9e,0xf8,0x97,0x13,
0xe3,0x67,0x80,0xec,0xcd,0x32,0xa7,0xea,0xc1,0x85,0x6e,0x67,0x67,0x54,0xbe,0x35,
0xc1,0xdc,0x18,0xeb,0x74,0x4f,0x9c,0x30,0x13,0xa8,0x4d,0xe9,0xfc,0x46,0xe9,0xf4,
0xf9,0xc2,0xaa,0x93,0x45,0xa9,0x8f,0xff,0xd3,0x4b,0xcb,0xcb,0x6f,0x24,0xf7,0x9b,
0xe2,0x8e,0x5f,0x93,0xa7,0x5e,0x3d,0xe5,0xd5,0xe1,0xf0,0xaf,0xed,0xee,0x5f,0x36,
0x7e,0xa,0x9e,0x8c,0x69,0xed,0x4e,0x6,0x81,0x9,0x0,0x0,0x0,0x0,0x49,0x45,
0x4e,0x44,0xae,0x42,0x60,0x82,
};
static const unsigned char qt_resource_name[] = {
// resourse
0x0,0x8,
0xc,0xa6,0xc6,0x95,
0x0,0x72,
0x0,0x65,0x0,0x73,0x0,0x6f,0x0,0x75,0x0,0x72,0x0,0x73,0x0,0x65,
// aqua_ball.png
0x0,0xd,
0x9,0x39,0xbd,0xe7,
0x0,0x61,
0x0,0x71,0x0,0x75,0x0,0x61,0x0,0x5f,0x0,0x62,0x0,0x61,0x0,0x6c,0x0,0x6c,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67,
// Soccer_ball.png
0x0,0xf,
0x7,0x16,0xb5,0x27,
0x0,0x53,
0x0,0x6f,0x0,0x63,0x0,0x63,0x0,0x65,0x0,0x72,0x0,0x5f,0x0,0x62,0x0,0x61,0x0,0x6c,0x0,0x6c,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67,
// basketball.png
0x0,0xe,
0x9,0x6c,0xd8,0x67,
0x0,0x62,
0x0,0x61,0x0,0x73,0x0,0x6b,0x0,0x65,0x0,0x74,0x0,0x62,0x0,0x61,0x0,0x6c,0x0,0x6c,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67,
};
static const unsigned char qt_resource_struct[] = {
// :
0x0,0x0,0x0,0x0,0x0,0x2,0x0,0x0,0x0,0x1,0x0,0x0,0x0,0x1,
// :/resourse
0x0,0x0,0x0,0x0,0x0,0x2,0x0,0x0,0x0,0x3,0x0,0x0,0x0,0x2,
// :/resourse/Soccer_ball.png
0x0,0x0,0x0,0x36,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x8,0x5,
// :/resourse/aqua_ball.png
0x0,0x0,0x0,0x16,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x0,0x0,
// :/resourse/basketball.png
0x0,0x0,0x0,0x5a,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x10,0x63,
};
QT_BEGIN_NAMESPACE
extern Q_CORE_EXPORT bool qRegisterResourceData
(int, const unsigned char *, const unsigned char *, const unsigned char *);
extern Q_CORE_EXPORT bool qUnregisterResourceData
(int, const unsigned char *, const unsigned char *, const unsigned char *);
QT_END_NAMESPACE
int QT_MANGLE_NAMESPACE(qInitResources_a)()
{
QT_PREPEND_NAMESPACE(qRegisterResourceData)
(0x01, qt_resource_struct, qt_resource_name, qt_resource_data);
return 1;
}
Q_CONSTRUCTOR_FUNCTION(QT_MANGLE_NAMESPACE(qInitResources_a))
int QT_MANGLE_NAMESPACE(qCleanupResources_a)()
{
QT_PREPEND_NAMESPACE(qUnregisterResourceData)
(0x01, qt_resource_struct, qt_resource_name, qt_resource_data);
return 1;
}
Q_DESTRUCTOR_FUNCTION(QT_MANGLE_NAMESPACE(qCleanupResources_a))
| [
"[email protected]"
] | |
63884b293b0b52cfe96b68b97af00af96274ad36 | e3f8537e483a0354afc5d5f11e6e1176bb6a1a06 | /ada_4sys/ETALON.HPP | e8bd5d7be0a6b81e4a9b388401bab17bb7733395 | [] | no_license | freeduke33/old_ada4sys | dd2ab614800a895151498f0dab0fd2cb5233813b | 542e76d15aceaebcc34ab6f35ab41eaeaa3327ef | refs/heads/master | 2021-01-19T13:21:29.149216 | 2017-02-18T10:21:34 | 2017-02-18T10:21:34 | 82,378,753 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 108 | hpp | #ifndef __ETALON_HPP__
#define __ETALON_HPP__
class Buffer;
int MakeEtalon(int ,Buffer **);
#endif
| [
"[email protected]"
] | |
1c5fc9790613c5e5fea151439d2b2de5ee0a9e48 | 08b8cf38e1936e8cec27f84af0d3727321cec9c4 | /data/crawl/git/old_hunk_662.cpp | fe7951d0bb1a1087bfeb1a85753dbb10f3b9a438 | [] | no_license | ccdxc/logSurvey | eaf28e9c2d6307140b17986d5c05106d1fd8e943 | 6b80226e1667c1e0760ab39160893ee19b0e9fb1 | refs/heads/master | 2022-01-07T21:31:55.446839 | 2018-04-21T14:12:43 | 2018-04-21T14:12:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,253 | cpp | struct object_id old_oid;
};
struct ref_entry;
/*
* Information used (along with the information in ref_entry) to
* describe a single cached reference. This data structure only
* occurs embedded in a union in struct ref_entry, and only when
* (ref_entry->flag & REF_DIR) is zero.
*/
struct ref_value {
/*
* The name of the object to which this reference resolves
* (which may be a tag object). If REF_ISBROKEN, this is
* null. If REF_ISSYMREF, then this is the name of the object
* referred to by the last reference in the symlink chain.
*/
struct object_id oid;
/*
* If REF_KNOWS_PEELED, then this field holds the peeled value
* of this reference, or null if the reference is known not to
* be peelable. See the documentation for peel_ref() for an
* exact definition of "peelable".
*/
struct object_id peeled;
};
struct files_ref_store;
/*
* Information used (along with the information in ref_entry) to
* describe a level in the hierarchy of references. This data
* structure only occurs embedded in a union in struct ref_entry, and
* only when (ref_entry.flag & REF_DIR) is set. In that case,
* (ref_entry.flag & REF_INCOMPLETE) determines whether the references
* in the directory have already been read:
*
* (ref_entry.flag & REF_INCOMPLETE) unset -- a directory of loose
* or packed references, already read.
*
* (ref_entry.flag & REF_INCOMPLETE) set -- a directory of loose
* references that hasn't been read yet (nor has any of its
* subdirectories).
*
* Entries within a directory are stored within a growable array of
* pointers to ref_entries (entries, nr, alloc). Entries 0 <= i <
* sorted are sorted by their component name in strcmp() order and the
* remaining entries are unsorted.
*
* Loose references are read lazily, one directory at a time. When a
* directory of loose references is read, then all of the references
* in that directory are stored, and REF_INCOMPLETE stubs are created
* for any subdirectories, but the subdirectories themselves are not
* read. The reading is triggered by get_ref_dir().
*/
struct ref_dir {
int nr, alloc;
/*
* Entries with index 0 <= i < sorted are sorted by name. New
* entries are appended to the list unsorted, and are sorted
* only when required; thus we avoid the need to sort the list
* after the addition of every reference.
*/
int sorted;
/* A pointer to the files_ref_store that contains this ref_dir. */
struct files_ref_store *ref_store;
struct ref_entry **entries;
};
/*
* Bit values for ref_entry::flag. REF_ISSYMREF=0x01,
* REF_ISPACKED=0x02, REF_ISBROKEN=0x04 and REF_BAD_NAME=0x08 are
* public values; see refs.h.
*/
/*
* The field ref_entry->u.value.peeled of this value entry contains
* the correct peeled value for the reference, which might be
* null_sha1 if the reference is not a tag or if it is broken.
*/
#define REF_KNOWS_PEELED 0x10
/* ref_entry represents a directory of references */
#define REF_DIR 0x20
/*
* Entry has not yet been read from disk (used only for REF_DIR
* entries representing loose references)
*/
#define REF_INCOMPLETE 0x40
/*
* A ref_entry represents either a reference or a "subdirectory" of
* references.
*
* Each directory in the reference namespace is represented by a
* ref_entry with (flags & REF_DIR) set and containing a subdir member
* that holds the entries in that directory that have been read so
* far. If (flags & REF_INCOMPLETE) is set, then the directory and
* its subdirectories haven't been read yet. REF_INCOMPLETE is only
* used for loose reference directories.
*
* References are represented by a ref_entry with (flags & REF_DIR)
* unset and a value member that describes the reference's value. The
* flag member is at the ref_entry level, but it is also needed to
* interpret the contents of the value field (in other words, a
* ref_value object is not very much use without the enclosing
* ref_entry).
*
* Reference names cannot end with slash and directories' names are
* always stored with a trailing slash (except for the top-level
* directory, which is always denoted by ""). This has two nice
* consequences: (1) when the entries in each subdir are sorted
* lexicographically by name (as they usually are), the references in
* a whole tree can be generated in lexicographic order by traversing
* the tree in left-to-right, depth-first order; (2) the names of
* references and subdirectories cannot conflict, and therefore the
* presence of an empty subdirectory does not block the creation of a
* similarly-named reference. (The fact that reference names with the
* same leading components can conflict *with each other* is a
* separate issue that is regulated by verify_refname_available().)
*
* Please note that the name field contains the fully-qualified
* reference (or subdirectory) name. Space could be saved by only
* storing the relative names. But that would require the full names
* to be generated on the fly when iterating in do_for_each_ref(), and
* would break callback functions, who have always been able to assume
* that the name strings that they are passed will not be freed during
* the iteration.
*/
struct ref_entry {
unsigned char flag; /* ISSYMREF? ISPACKED? */
union {
struct ref_value value; /* if not (flags&REF_DIR) */
struct ref_dir subdir; /* if (flags&REF_DIR) */
} u;
/*
* The full name of the reference (e.g., "refs/heads/master")
* or the full name of the directory with a trailing slash
* (e.g., "refs/heads/"):
*/
char name[FLEX_ARRAY];
};
static void read_loose_refs(const char *dirname, struct ref_dir *dir);
static int search_ref_dir(struct ref_dir *dir, const char *refname, size_t len);
static struct ref_entry *create_dir_entry(struct files_ref_store *ref_store,
const char *dirname, size_t len,
int incomplete);
static void add_entry_to_dir(struct ref_dir *dir, struct ref_entry *entry);
static int files_log_ref_write(struct files_ref_store *refs,
const char *refname, const unsigned char *old_sha1,
const unsigned char *new_sha1, const char *msg,
int flags, struct strbuf *err);
static struct ref_dir *get_ref_dir(struct ref_entry *entry)
{
struct ref_dir *dir;
assert(entry->flag & REF_DIR);
dir = &entry->u.subdir;
if (entry->flag & REF_INCOMPLETE) {
read_loose_refs(entry->name, dir);
/*
* Manually add refs/bisect, which, being
* per-worktree, might not appear in the directory
* listing for refs/ in the main repo.
*/
if (!strcmp(entry->name, "refs/")) {
int pos = search_ref_dir(dir, "refs/bisect/", 12);
if (pos < 0) {
struct ref_entry *child_entry;
child_entry = create_dir_entry(dir->ref_store,
"refs/bisect/",
12, 1);
add_entry_to_dir(dir, child_entry);
}
}
entry->flag &= ~REF_INCOMPLETE;
}
return dir;
}
static struct ref_entry *create_ref_entry(const char *refname,
const unsigned char *sha1, int flag,
int check_name)
{
struct ref_entry *ref;
if (check_name &&
check_refname_format(refname, REFNAME_ALLOW_ONELEVEL))
die("Reference has invalid format: '%s'", refname);
FLEX_ALLOC_STR(ref, name, refname);
hashcpy(ref->u.value.oid.hash, sha1);
oidclr(&ref->u.value.peeled);
ref->flag = flag;
return ref;
}
static void clear_ref_dir(struct ref_dir *dir);
static void free_ref_entry(struct ref_entry *entry)
{
if (entry->flag & REF_DIR) {
/*
* Do not use get_ref_dir() here, as that might
* trigger the reading of loose refs.
*/
clear_ref_dir(&entry->u.subdir);
}
free(entry);
}
/*
* Add a ref_entry to the end of dir (unsorted). Entry is always
* stored directly in dir; no recursion into subdirectories is
* done.
*/
static void add_entry_to_dir(struct ref_dir *dir, struct ref_entry *entry)
{
ALLOC_GROW(dir->entries, dir->nr + 1, dir->alloc);
dir->entries[dir->nr++] = entry;
/* optimize for the case that entries are added in order */
if (dir->nr == 1 ||
(dir->nr == dir->sorted + 1 &&
strcmp(dir->entries[dir->nr - 2]->name,
dir->entries[dir->nr - 1]->name) < 0))
dir->sorted = dir->nr;
}
/*
* Clear and free all entries in dir, recursively.
*/
static void clear_ref_dir(struct ref_dir *dir)
{
int i;
for (i = 0; i < dir->nr; i++)
free_ref_entry(dir->entries[i]);
free(dir->entries);
dir->sorted = dir->nr = dir->alloc = 0;
dir->entries = NULL;
}
/*
* Create a struct ref_entry object for the specified dirname.
* dirname is the name of the directory with a trailing slash (e.g.,
* "refs/heads/") or "" for the top-level directory.
*/
static struct ref_entry *create_dir_entry(struct files_ref_store *ref_store,
const char *dirname, size_t len,
int incomplete)
{
struct ref_entry *direntry;
FLEX_ALLOC_MEM(direntry, name, dirname, len);
direntry->u.subdir.ref_store = ref_store;
direntry->flag = REF_DIR | (incomplete ? REF_INCOMPLETE : 0);
return direntry;
}
static int ref_entry_cmp(const void *a, const void *b)
{
struct ref_entry *one = *(struct ref_entry **)a;
struct ref_entry *two = *(struct ref_entry **)b;
return strcmp(one->name, two->name);
}
static void sort_ref_dir(struct ref_dir *dir);
struct string_slice {
size_t len;
const char *str;
};
static int ref_entry_cmp_sslice(const void *key_, const void *ent_)
{
const struct string_slice *key = key_;
const struct ref_entry *ent = *(const struct ref_entry * const *)ent_;
int cmp = strncmp(key->str, ent->name, key->len);
if (cmp)
return cmp;
return '\0' - (unsigned char)ent->name[key->len];
}
/*
* Return the index of the entry with the given refname from the
* ref_dir (non-recursively), sorting dir if necessary. Return -1 if
* no such entry is found. dir must already be complete.
*/
static int search_ref_dir(struct ref_dir *dir, const char *refname, size_t len)
{
struct ref_entry **r;
struct string_slice key;
if (refname == NULL || !dir->nr)
return -1;
sort_ref_dir(dir);
key.len = len;
key.str = refname;
r = bsearch(&key, dir->entries, dir->nr, sizeof(*dir->entries),
ref_entry_cmp_sslice);
if (r == NULL)
return -1;
return r - dir->entries;
}
/*
* Search for a directory entry directly within dir (without
* recursing). Sort dir if necessary. subdirname must be a directory
* name (i.e., end in '/'). If mkdir is set, then create the
* directory if it is missing; otherwise, return NULL if the desired
* directory cannot be found. dir must already be complete.
*/
static struct ref_dir *search_for_subdir(struct ref_dir *dir,
const char *subdirname, size_t len,
int mkdir)
{
int entry_index = search_ref_dir(dir, subdirname, len);
struct ref_entry *entry;
if (entry_index == -1) {
if (!mkdir)
return NULL;
/*
* Since dir is complete, the absence of a subdir
* means that the subdir really doesn't exist;
* therefore, create an empty record for it but mark
* the record complete.
*/
entry = create_dir_entry(dir->ref_store, subdirname, len, 0);
add_entry_to_dir(dir, entry);
} else {
entry = dir->entries[entry_index];
}
return get_ref_dir(entry);
}
/*
* If refname is a reference name, find the ref_dir within the dir
* tree that should hold refname. If refname is a directory name
* (i.e., ends in '/'), then return that ref_dir itself. dir must
* represent the top-level directory and must already be complete.
* Sort ref_dirs and recurse into subdirectories as necessary. If
* mkdir is set, then create any missing directories; otherwise,
* return NULL if the desired directory cannot be found.
*/
static struct ref_dir *find_containing_dir(struct ref_dir *dir,
const char *refname, int mkdir)
{
const char *slash;
for (slash = strchr(refname, '/'); slash; slash = strchr(slash + 1, '/')) {
size_t dirnamelen = slash - refname + 1;
struct ref_dir *subdir;
subdir = search_for_subdir(dir, refname, dirnamelen, mkdir);
if (!subdir) {
dir = NULL;
break;
}
dir = subdir;
}
return dir;
}
/*
* Find the value entry with the given name in dir, sorting ref_dirs
* and recursing into subdirectories as necessary. If the name is not
* found or it corresponds to a directory entry, return NULL.
*/
static struct ref_entry *find_ref_entry(struct ref_dir *dir, const char *refname)
{
int entry_index;
struct ref_entry *entry;
dir = find_containing_dir(dir, refname, 0);
if (!dir)
return NULL;
entry_index = search_ref_dir(dir, refname, strlen(refname));
if (entry_index == -1)
return NULL;
entry = dir->entries[entry_index];
return (entry->flag & REF_DIR) ? NULL : entry;
}
/*
* Remove the entry with the given name from dir, recursing into
* subdirectories as necessary. If refname is the name of a directory
* (i.e., ends with '/'), then remove the directory and its contents.
* If the removal was successful, return the number of entries
* remaining in the directory entry that contained the deleted entry.
* If the name was not found, return -1. Please note that this
* function only deletes the entry from the cache; it does not delete
* it from the filesystem or ensure that other cache entries (which
* might be symbolic references to the removed entry) are updated.
* Nor does it remove any containing dir entries that might be made
* empty by the removal. dir must represent the top-level directory
* and must already be complete.
*/
static int remove_entry_from_dir(struct ref_dir *dir, const char *refname)
{
int refname_len = strlen(refname);
int entry_index;
struct ref_entry *entry;
int is_dir = refname[refname_len - 1] == '/';
if (is_dir) {
/*
* refname represents a reference directory. Remove
* the trailing slash; otherwise we will get the
* directory *representing* refname rather than the
* one *containing* it.
*/
char *dirname = xmemdupz(refname, refname_len - 1);
dir = find_containing_dir(dir, dirname, 0);
free(dirname);
} else {
dir = find_containing_dir(dir, refname, 0);
}
if (!dir)
return -1;
entry_index = search_ref_dir(dir, refname, refname_len);
if (entry_index == -1)
return -1;
entry = dir->entries[entry_index];
memmove(&dir->entries[entry_index],
&dir->entries[entry_index + 1],
(dir->nr - entry_index - 1) * sizeof(*dir->entries)
);
dir->nr--;
if (dir->sorted > entry_index)
dir->sorted--;
free_ref_entry(entry);
return dir->nr;
}
/*
* Add a ref_entry to the ref_dir (unsorted), recursing into
* subdirectories as necessary. dir must represent the top-level
* directory. Return 0 on success.
*/
static int add_ref_entry(struct ref_dir *dir, struct ref_entry *ref)
{
dir = find_containing_dir(dir, ref->name, 1);
if (!dir)
return -1;
add_entry_to_dir(dir, ref);
return 0;
}
/*
* Emit a warning and return true iff ref1 and ref2 have the same name
* and the same sha1. Die if they have the same name but different
* sha1s.
*/
static int is_dup_ref(const struct ref_entry *ref1, const struct ref_entry *ref2)
{
if (strcmp(ref1->name, ref2->name))
return 0;
/* Duplicate name; make sure that they don't conflict: */
if ((ref1->flag & REF_DIR) || (ref2->flag & REF_DIR))
/* This is impossible by construction */
die("Reference directory conflict: %s", ref1->name);
if (oidcmp(&ref1->u.value.oid, &ref2->u.value.oid))
die("Duplicated ref, and SHA1s don't match: %s", ref1->name);
warning("Duplicated ref: %s", ref1->name);
return 1;
}
/*
* Sort the entries in dir non-recursively (if they are not already
* sorted) and remove any duplicate entries.
*/
static void sort_ref_dir(struct ref_dir *dir)
{
int i, j;
struct ref_entry *last = NULL;
/*
* This check also prevents passing a zero-length array to qsort(),
* which is a problem on some platforms.
*/
if (dir->sorted == dir->nr)
return;
QSORT(dir->entries, dir->nr, ref_entry_cmp);
/* Remove any duplicates: */
for (i = 0, j = 0; j < dir->nr; j++) {
struct ref_entry *entry = dir->entries[j];
if (last && is_dup_ref(last, entry))
free_ref_entry(entry);
else
last = dir->entries[i++] = entry;
}
dir->sorted = dir->nr = i;
}
/*
* Return true if refname, which has the specified oid and flags, can
* be resolved to an object in the database. If the referred-to object
| [
"[email protected]"
] | |
4603c83ef40793708a653b80c3b6b8e53e1f8cbe | c5f1af303fc7409de7220f20f7c89d4f204d2370 | /project1.09/src/main.cpp | f95f7b6d7b206e06b278dca8cd4d6b233165137e | [] | no_license | joel0/CS327-Spring2016 | 94b1f8181e86a51f185d83a0c403d2ecdcf47330 | e90bc86d750dad7de81d0909e857142c084a284e | refs/heads/master | 2016-09-14T03:05:39.001176 | 2016-04-15T15:11:42 | 2016-04-15T15:11:42 | 59,449,360 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 9,959 | cpp | //
// Created by joelm on 2016-01-25.
//
#include <stdio.h>
#include <string.h>
#include <libgen.h>
#include <stdlib.h>
#include <time.h>
#include <curses.h>
#include <vector>
#include <sstream>
#include "main.h"
#include "dungeon.h"
#include "path.h"
#include "turn.h"
#include "screen.h"
#include "utils.h"
#include "message_queue.h"
bool parse_monster_descrip_file(std::vector<monster_descrip*> &monster_descrips);
bool parse_item_descrip_file(std::vector<item_descrip*>& item_descrips);
std::string itemDescFileName();
std::string monsterDescFileName();
int main(int argc, char* argv[]) {
int errLevel;
dungeon_t dungeon;
std::vector<monster_descrip*> monster_descrips;
std::vector<item_descrip*> item_descrips;
int numMonSpecified = 0;
//init random
unsigned int seed;
seed = (unsigned int)time(NULL); //1453848819;
srand(seed);
printf("Seed: %d\n", seed);
// parse arguments
int save = 0;
int load = 0;
for (int i = 1; i < argc; i++) {
if (strcmp(argv[i], "--save") == 0) {
save = 1;
} else if (strcmp(argv[i], "--load") == 0) {
load = 1;
} else if (strcmp(argv[i], "--nummon") == 0) {
if (i + 1 >= argc) {
showUsage(argv[0]);
return 0;
}
dungeon.monsterCount = atoi(argv[++i]);
numMonSpecified = 1;
} else {
showUsage(argv[0]);
return 0;
}
}
if (!parse_monster_descrip_file(monster_descrips)) {
std::cout << "Error parsing the monster descriptions." << std::endl;
return -1;
}
if (!parse_item_descrip_file(item_descrips)) {
std::cout << "Error parsing the object descriptions." << std::endl;
return -1;
}
if (!numMonSpecified) {
dungeon.monsterCount = rand() % (42 / 3);
}
// load or generate dungeon
if (load) {
errLevel = loadDungeon(&dungeon, dungeonFileName(), monster_descrips, item_descrips);
if (errLevel) {
printf("Failed to load the dungeon. Read error %d\n", errLevel);
return -1;
}
populateRooms(dungeon);
} else {
errLevel = generateDungeon(&dungeon, monster_descrips, item_descrips);
if (errLevel) {
printf("Failed to allocate memory for the dungeon grid.\n");
return errLevel;
}
}
pathMallocDistGrid(&dungeon.tunnelingDist);
pathMallocDistGrid(&dungeon.nontunnelingDist);
// save dungeon
if (save) {
errLevel = saveDungeon(dungeon, dungeonFileName());
if (errLevel) {
printf("Failed to save the dungeon. Save error %d\n", errLevel);
return -1;
}
}
// make calculations
pathTunneling(&dungeon);
pathNontunneling(&dungeon);
// print dungeon
initTerminal();
printDungeon(dungeon.grid);
// do move
PC_action userAction = actionMovement;
while (dungeon.PCPtr->alive && dungeon.monsterCount > 1 && userAction != actionSave) {
int PCTurn = turnIsPC(&dungeon);
if (PCTurn) {
dungeon.PCPtr->updateGridKnown(dungeon.grid);
printDungeon(dungeon.PCPtr->gridKnown);
userAction = turnDoPC(&dungeon);
switch (userAction) {
case actionStairsUp:
case actionStairsDn:
// Destroy old dungeon
pathFreeDistGrid(dungeon.nontunnelingDist);
pathFreeDistGrid(dungeon.tunnelingDist);
destroyDungeon(dungeon);
dungeon.monsterCount--; // PC was counted as a "monster". He must be removed for reinitialisation.
// Build new dungeon
errLevel = generateDungeon(&dungeon, monster_descrips, item_descrips);
if (errLevel) {
endwin();
printf("Failed to allocate memory for the dungeon grid.\n");
return errLevel;
}
pathMallocDistGrid(&dungeon.tunnelingDist);
pathMallocDistGrid(&dungeon.nontunnelingDist);
pathTunneling(&dungeon);
pathNontunneling(&dungeon);
break;
case actionListMonsters:
monsterList(&dungeon);
break;
case actionListInventory:
dungeon.PCPtr->show_inventory(true);
break;
case actionListEquipment:
dungeon.PCPtr->show_equipment(true);
break;
case actionDropItem:
dungeon.PCPtr->drop_item(dungeon);
break;
case actionInspectItem:
dungeon.PCPtr->inspect_item();
break;
case actionExpungeItem:
dungeon.PCPtr->expunge_item();
break;
case actionWearItem:
dungeon.PCPtr->wear_item();
break;
case actionTakeOffItem:
dungeon.PCPtr->take_off_item();
break;
default: break;
}
} else {
turnDo(&dungeon);
}
}
screenClearRow(0);
if (userAction == actionSave) {
mvprintw(0, 0, "Game saved (haha, not really!). Press any key to exit.");
} else if (!dungeon.PCPtr->alive) {
mvprintw(0, 0, "You died! Press any key to exit.");
} else {
mvprintw(0, 0, "Yay! You defeated all the monsters. Press any key to exit.");
}
// Clean up
getch(); // "press any key"
endwin();
pathFreeDistGrid(dungeon.nontunnelingDist);
pathFreeDistGrid(dungeon.tunnelingDist);
destroyDungeon(dungeon);
delete_descrips(monster_descrips);
delete_descrips(item_descrips);
delete message_queue::instance();
return 0;
}
bool parse_monster_descrip_file(std::vector<monster_descrip *> &monster_descrips) {
std::ifstream f(monsterDescFileName().c_str());
std::string str;
//std::vector<monster_descrip*> monsters;
monster_descrip* tempMonsterPtr;
std::vector<monster_descrip*>::iterator monster_iterator;
std::getline(f, str);
util_remove_cr(str);
// The \357\273\277 is the UTF-8 header. Some Windows programs will append it at the start of a file.
if (str != "RLG327 MONSTER DESCRIPTION 1" && str != "\357\273\277RLG327 MONSTER DESCRIPTION 1") {
return false;
}
while (!f.eof()) {
try {
tempMonsterPtr = new monster_descrip(f);
monster_descrips.push_back(tempMonsterPtr);
} catch (std::string ex) {
std::cout << ex << std::endl;
} catch (const char* ex) {
// EOF is expected when the file contains no more monsters
if (strcmp(ex, "EOF") != 0) {
std::cout << ex << std::endl;
}
}
}
monster_iterator = monster_descrips.begin();
while (monster_iterator != monster_descrips.end()) {
std::cout << (*monster_iterator)->to_string() << std::endl;
//delete *monster_iterator;
monster_iterator++;
}
f.close();
return true;
}
bool parse_item_descrip_file(std::vector<item_descrip*>& item_descrips) {
std::ifstream f(itemDescFileName().c_str());
std::string str;
item_descrip* tempItemPtr;
std::vector<item_descrip*>::iterator item_iterator;
std::getline(f, str);
util_remove_cr(str);
// The \357\273\277 is the UTF-8 header. Some Windows programs will append it at the start of a file.
if (str != "RLG327 OBJECT DESCRIPTION 1" && str != "\357\273\277RLG327 OBJECT DESCRIPTION 1") {
return false;
}
while (!f.eof()) {
try {
tempItemPtr = new item_descrip(f);
item_descrips.push_back(tempItemPtr);
} catch (std::string ex) {
std::cout << ex << std::endl;
} catch (const char* ex) {
// EOF is expected when the file contains no more objects
if (strcmp(ex, "EOF") != 0) {
std::cout << ex << std::endl;
}
}
}
item_iterator = item_descrips.begin();
while (item_iterator != item_descrips.end()) {
std::cout << (*item_iterator)->to_string() << std::endl;
item_iterator++;
}
f.close();
return true;
}
template<typename T> void delete_descrips(std::vector<T*>& descrips) {
typename std::vector<T*>::iterator item_iterator;
item_iterator = descrips.begin();
while (item_iterator != descrips.end()) {
delete *item_iterator;
item_iterator++;
}
}
void showUsage(char* name) {
printf("Usage: %s [--save|--load] [--nummon num]\n\n", basename(name));
printf("\t--save\tSaves a randomly generated dungeon to ~/.rlg327/dungeon\n");
printf("\t--load\tLoads ~/.rgl327/dungeon and displays it\n");
printf("\t--nummon\tSpecifies the number of monitors to place in the dungeon.\n");
}
char* dungeonFileName() {
char* fullPath;
char* homeDir;
const char *relativePath = "/.rlg327/dungeon";
homeDir = getenv("HOME");
fullPath = (char *) malloc(sizeof(char) * (strlen(homeDir) + strlen(relativePath) + 1));
sprintf(fullPath, "%s/.rlg327/dungeon", homeDir);
return fullPath;
}
std::string monsterDescFileName() {
std::ostringstream out;
char* homeDir;
const char *relativePath = "/.rlg327/monster_desc.txt";
homeDir = getenv("HOME");
out << homeDir << relativePath;
return out.str();
}
std::string itemDescFileName() {
std::ostringstream out;
char* homeDir;
const char *relativePath = "/.rlg327/object_desc.txt";
homeDir = getenv("HOME");
out << homeDir << relativePath;
return out.str();
} | [
"[email protected]"
] | |
c19004d9963a8ea8f1dc485e72e32209848fb84c | 911cfb02673eb9a4a3872fa36da5136780892e67 | /NativeUI/src/message_box.h | d7f09258cdbf0439037e8533becc4e6eba83d4e2 | [] | no_license | sebgen/Dungeon-Crawler-2.5D | 7537622d26995c85e917b2efe99f7284f6965f5e | c58d027c26aae3d351ed75e52ca5e05a458e7a7a | refs/heads/master | 2021-01-13T05:54:47.227439 | 2018-07-21T14:55:16 | 2018-07-21T14:55:16 | 94,979,190 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 159 | h | #ifndef NATIVEUI_MESSAGEBOX
#define NATIVEUI_MESSAGEBOX
#include <Windows.h>
namespace NativeUI
{
class MessageBox
{
};
}
#endif // NATIVEUI_MESSAGEBOX
| [
"[email protected]"
] | |
6e14fc303e4fd44f3093e3e2354842c4dba4f357 | e763b855be527d69fb2e824dfb693d09e59cdacb | /aws-cpp-sdk-gamelift/source/model/DescribeFleetPortSettingsRequest.cpp | 75dc968bbeb8b3a20a2f3df585271ce2e1f089b7 | [
"MIT",
"Apache-2.0",
"JSON"
] | permissive | 34234344543255455465/aws-sdk-cpp | 47de2d7bde504273a43c99188b544e497f743850 | 1d04ff6389a0ca24361523c58671ad0b2cde56f5 | refs/heads/master | 2023-06-10T16:15:54.618966 | 2018-05-07T23:32:08 | 2018-05-07T23:32:08 | 132,632,360 | 1 | 0 | Apache-2.0 | 2023-06-01T23:20:47 | 2018-05-08T15:56:35 | C++ | UTF-8 | C++ | false | false | 1,404 | cpp | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include <aws/gamelift/model/DescribeFleetPortSettingsRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::GameLift::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
DescribeFleetPortSettingsRequest::DescribeFleetPortSettingsRequest() :
m_fleetIdHasBeenSet(false)
{
}
Aws::String DescribeFleetPortSettingsRequest::SerializePayload() const
{
JsonValue payload;
if(m_fleetIdHasBeenSet)
{
payload.WithString("FleetId", m_fleetId);
}
return payload.WriteReadable();
}
Aws::Http::HeaderValueCollection DescribeFleetPortSettingsRequest::GetRequestSpecificHeaders() const
{
Aws::Http::HeaderValueCollection headers;
headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "GameLift.DescribeFleetPortSettings"));
return headers;
}
| [
"[email protected]"
] | |
6001d77f590993bcebd7f5bb71968d436eec0b69 | dbf6af60e4e65306bfd23388de33cf11acb00b12 | /assignment3/meerkat.h | 4a0e628dc1ac6fbf7a3cd6745b8c607b77f423f0 | [] | no_license | Jace-Parks/CS162-intro-to-computer-science2 | 3b7fa48fa633afec7895433f3957aec5d47d2d44 | 2723b486c5eb23bb02596a09d16def9377f99a18 | refs/heads/master | 2023-03-05T09:55:36.213697 | 2021-02-16T03:53:30 | 2021-02-16T03:53:30 | 339,277,983 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 263 | h | #ifndef MEERKAT_H
#define MEERKAT_H
#include "animal.h"
#include <iostream>
#include <string>
using namespace std;
class meerkat: public animal{
private:
protected:
public:
meerkat();
meerkat& operator=(const meerkat&);
~meerkat();
};
#endif
| [
"[email protected]"
] | |
289d150c8ec273f87438854d1ae41e71c2774abc | 74d1dd1b2fb76ee4a65ec86cda22ddd2cdc64883 | /libs/STLPort-4.0/test/regression/hmset1.cpp | 0fe36fb043894c783b6b6a0482f6a296984d00ec | [
"LicenseRef-scancode-stlport-4.5",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | haekb/nolf2-modernizer | f9d966d7b9660610b47ea7618c4d53507b17adc4 | 75b2e715f804e10f1380e1c7bdb43664db61a01b | refs/heads/master | 2023-05-11T00:06:00.516030 | 2020-12-24T03:59:45 | 2020-12-24T03:59:45 | 207,464,324 | 30 | 4 | null | 2023-04-29T04:36:51 | 2019-09-10T04:20:07 | C++ | UTF-8 | C++ | false | false | 1,252 | cpp | // STLport regression testsuite component.
// To compile as a separate example, please #define MAIN.
#include <iostream>
#include <hash_set>
#ifdef MAIN
#define hmset1_test main
#endif
// struct hash<string> {
// size_t operator()(const string& s) const { return __stl_hash_string(s.c_str()); }
//};
#if defined (__MVS__)
#define star 92
#else
#define star 42
#if !defined (STLPORT) || defined(__STL_USE_NAMESPACES)
using namespace std;
#endif
typedef hash_multiset<char, hash<char>, equal_to<char> > hmset;
#endif
// __STL_TYPE_TRAITS_POD_SPECIALIZE(_Hashtable_node<char>*);
int hmset1_test(int, char**)
{
cout<<"Results of hmset1_test:"<<endl;
hmset s;
cout << "count(" << star << ") = " << s.count(star) << endl;
s.insert(star);
cout << "count(" << star << ") = " << s.count(star) << endl;
s.insert(star);
cout << "count(" << star << ") = " << s.count(star) << endl;
hmset::iterator i = s.find(40);
if(i == s.end())
cout << "40 Not found" << endl;
else
cout << "Found " << *i << endl;
i = s.find(star);
if(i == s.end())
cout << "Not found" << endl;
else
cout << "Found " << *i << endl;
int count = s.erase(star);
cout << "Erased " << count << " instances" << endl;
return 0;
}
| [
"[email protected]"
] | |
75cda481ed3d58cc1503262cb6c90d04d1bfe393 | a5600adb9d6317b7901258a5f9f8a3c34318e302 | /src/interpreter/bytecode-array-writer.cc | a4e214c7453d6ce2950267f42f6151b25fafc6e1 | [
"BSD-3-Clause",
"Apache-2.0",
"bzip2-1.0.6",
"SunPro"
] | permissive | jie-pan/v8-mirror | a00e708cc8e3c52e8346d419a6caa8f3a129d65c | 41ac27a7dc6c82d4458d757d490a6f4bc4927c38 | refs/heads/revec | 2023-01-09T06:15:28.866627 | 2019-09-10T08:05:54 | 2019-09-10T08:05:54 | 186,524,598 | 0 | 0 | NOASSERTION | 2023-01-07T09:31:17 | 2019-05-14T01:50:33 | C++ | UTF-8 | C++ | false | false | 18,806 | cc | // Copyright 2015 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/interpreter/bytecode-array-writer.h"
#include "src/api-inl.h"
#include "src/interpreter/bytecode-jump-table.h"
#include "src/interpreter/bytecode-label.h"
#include "src/interpreter/bytecode-node.h"
#include "src/interpreter/bytecode-register.h"
#include "src/interpreter/bytecode-source-info.h"
#include "src/interpreter/constant-array-builder.h"
#include "src/interpreter/handler-table-builder.h"
#include "src/log.h"
#include "src/objects-inl.h"
namespace v8 {
namespace internal {
namespace interpreter {
STATIC_CONST_MEMBER_DEFINITION const size_t
BytecodeArrayWriter::kMaxSizeOfPackedBytecode;
BytecodeArrayWriter::BytecodeArrayWriter(
Zone* zone, ConstantArrayBuilder* constant_array_builder,
SourcePositionTableBuilder::RecordingMode source_position_mode)
: bytecodes_(zone),
unbound_jumps_(0),
source_position_table_builder_(source_position_mode),
constant_array_builder_(constant_array_builder),
last_bytecode_(Bytecode::kIllegal),
last_bytecode_offset_(0),
last_bytecode_had_source_info_(false),
elide_noneffectful_bytecodes_(FLAG_ignition_elide_noneffectful_bytecodes),
exit_seen_in_block_(false) {
bytecodes_.reserve(512); // Derived via experimentation.
}
Handle<BytecodeArray> BytecodeArrayWriter::ToBytecodeArray(
Isolate* isolate, int register_count, int parameter_count,
Handle<ByteArray> handler_table) {
DCHECK_EQ(0, unbound_jumps_);
int bytecode_size = static_cast<int>(bytecodes()->size());
int frame_size = register_count * kSystemPointerSize;
Handle<FixedArray> constant_pool =
constant_array_builder()->ToFixedArray(isolate);
Handle<BytecodeArray> bytecode_array = isolate->factory()->NewBytecodeArray(
bytecode_size, &bytecodes()->front(), frame_size, parameter_count,
constant_pool);
bytecode_array->set_handler_table(*handler_table);
if (!source_position_table_builder_.Lazy()) {
Handle<ByteArray> source_position_table =
source_position_table_builder_.Omit()
? ReadOnlyRoots(isolate).empty_byte_array_handle()
: source_position_table_builder()->ToSourcePositionTable(isolate);
bytecode_array->set_source_position_table(*source_position_table);
LOG_CODE_EVENT(isolate, CodeLinePosInfoRecordEvent(
bytecode_array->GetFirstBytecodeAddress(),
*source_position_table));
}
return bytecode_array;
}
void BytecodeArrayWriter::Write(BytecodeNode* node) {
DCHECK(!Bytecodes::IsJump(node->bytecode()));
if (exit_seen_in_block_) return; // Don't emit dead code.
UpdateExitSeenInBlock(node->bytecode());
MaybeElideLastBytecode(node->bytecode(), node->source_info().is_valid());
UpdateSourcePositionTable(node);
EmitBytecode(node);
}
void BytecodeArrayWriter::WriteJump(BytecodeNode* node, BytecodeLabel* label) {
DCHECK(Bytecodes::IsForwardJump(node->bytecode()));
if (exit_seen_in_block_) return; // Don't emit dead code.
UpdateExitSeenInBlock(node->bytecode());
MaybeElideLastBytecode(node->bytecode(), node->source_info().is_valid());
UpdateSourcePositionTable(node);
EmitJump(node, label);
}
void BytecodeArrayWriter::WriteJumpLoop(BytecodeNode* node,
BytecodeLoopHeader* loop_header) {
DCHECK_EQ(node->bytecode(), Bytecode::kJumpLoop);
if (exit_seen_in_block_) return; // Don't emit dead code.
UpdateExitSeenInBlock(node->bytecode());
MaybeElideLastBytecode(node->bytecode(), node->source_info().is_valid());
UpdateSourcePositionTable(node);
EmitJumpLoop(node, loop_header);
}
void BytecodeArrayWriter::WriteSwitch(BytecodeNode* node,
BytecodeJumpTable* jump_table) {
DCHECK(Bytecodes::IsSwitch(node->bytecode()));
if (exit_seen_in_block_) return; // Don't emit dead code.
UpdateExitSeenInBlock(node->bytecode());
MaybeElideLastBytecode(node->bytecode(), node->source_info().is_valid());
UpdateSourcePositionTable(node);
EmitSwitch(node, jump_table);
}
void BytecodeArrayWriter::BindLabel(BytecodeLabel* label) {
DCHECK(label->has_referrer_jump());
size_t current_offset = bytecodes()->size();
// Update the jump instruction's location.
PatchJump(current_offset, label->jump_offset());
label->bind();
StartBasicBlock();
}
void BytecodeArrayWriter::BindLoopHeader(BytecodeLoopHeader* loop_header) {
size_t current_offset = bytecodes()->size();
loop_header->bind_to(current_offset);
StartBasicBlock();
}
void BytecodeArrayWriter::BindJumpTableEntry(BytecodeJumpTable* jump_table,
int case_value) {
DCHECK(!jump_table->is_bound(case_value));
size_t current_offset = bytecodes()->size();
size_t relative_jump = current_offset - jump_table->switch_bytecode_offset();
constant_array_builder()->SetJumpTableSmi(
jump_table->ConstantPoolEntryFor(case_value),
Smi::FromInt(static_cast<int>(relative_jump)));
jump_table->mark_bound(case_value);
StartBasicBlock();
}
void BytecodeArrayWriter::BindHandlerTarget(
HandlerTableBuilder* handler_table_builder, int handler_id) {
size_t current_offset = bytecodes()->size();
StartBasicBlock();
handler_table_builder->SetHandlerTarget(handler_id, current_offset);
}
void BytecodeArrayWriter::BindTryRegionStart(
HandlerTableBuilder* handler_table_builder, int handler_id) {
size_t current_offset = bytecodes()->size();
// Try blocks don't have to be in a separate basic block, but we do have to
// invalidate the bytecode to avoid eliding it and changing the offset.
InvalidateLastBytecode();
handler_table_builder->SetTryRegionStart(handler_id, current_offset);
}
void BytecodeArrayWriter::BindTryRegionEnd(
HandlerTableBuilder* handler_table_builder, int handler_id) {
// Try blocks don't have to be in a separate basic block, but we do have to
// invalidate the bytecode to avoid eliding it and changing the offset.
InvalidateLastBytecode();
size_t current_offset = bytecodes()->size();
handler_table_builder->SetTryRegionEnd(handler_id, current_offset);
}
void BytecodeArrayWriter::StartBasicBlock() {
InvalidateLastBytecode();
exit_seen_in_block_ = false;
}
void BytecodeArrayWriter::UpdateSourcePositionTable(
const BytecodeNode* const node) {
int bytecode_offset = static_cast<int>(bytecodes()->size());
const BytecodeSourceInfo& source_info = node->source_info();
if (source_info.is_valid()) {
source_position_table_builder()->AddPosition(
bytecode_offset, SourcePosition(source_info.source_position()),
source_info.is_statement());
}
}
void BytecodeArrayWriter::UpdateExitSeenInBlock(Bytecode bytecode) {
switch (bytecode) {
case Bytecode::kReturn:
case Bytecode::kThrow:
case Bytecode::kReThrow:
case Bytecode::kAbort:
case Bytecode::kJump:
case Bytecode::kJumpConstant:
case Bytecode::kSuspendGenerator:
exit_seen_in_block_ = true;
break;
default:
break;
}
}
void BytecodeArrayWriter::MaybeElideLastBytecode(Bytecode next_bytecode,
bool has_source_info) {
if (!elide_noneffectful_bytecodes_) return;
// If the last bytecode loaded the accumulator without any external effect,
// and the next bytecode clobbers this load without reading the accumulator,
// then the previous bytecode can be elided as it has no effect.
if (Bytecodes::IsAccumulatorLoadWithoutEffects(last_bytecode_) &&
Bytecodes::GetAccumulatorUse(next_bytecode) == AccumulatorUse::kWrite &&
(!last_bytecode_had_source_info_ || !has_source_info)) {
DCHECK_GT(bytecodes()->size(), last_bytecode_offset_);
bytecodes()->resize(last_bytecode_offset_);
// If the last bytecode had source info we will transfer the source info
// to this bytecode.
has_source_info |= last_bytecode_had_source_info_;
}
last_bytecode_ = next_bytecode;
last_bytecode_had_source_info_ = has_source_info;
last_bytecode_offset_ = bytecodes()->size();
}
void BytecodeArrayWriter::InvalidateLastBytecode() {
last_bytecode_ = Bytecode::kIllegal;
}
void BytecodeArrayWriter::EmitBytecode(const BytecodeNode* const node) {
DCHECK_NE(node->bytecode(), Bytecode::kIllegal);
Bytecode bytecode = node->bytecode();
OperandScale operand_scale = node->operand_scale();
if (operand_scale != OperandScale::kSingle) {
Bytecode prefix = Bytecodes::OperandScaleToPrefixBytecode(operand_scale);
bytecodes()->push_back(Bytecodes::ToByte(prefix));
}
bytecodes()->push_back(Bytecodes::ToByte(bytecode));
const uint32_t* const operands = node->operands();
const int operand_count = node->operand_count();
const OperandSize* operand_sizes =
Bytecodes::GetOperandSizes(bytecode, operand_scale);
for (int i = 0; i < operand_count; ++i) {
switch (operand_sizes[i]) {
case OperandSize::kNone:
UNREACHABLE();
break;
case OperandSize::kByte:
bytecodes()->push_back(static_cast<uint8_t>(operands[i]));
break;
case OperandSize::kShort: {
uint16_t operand = static_cast<uint16_t>(operands[i]);
const uint8_t* raw_operand = reinterpret_cast<const uint8_t*>(&operand);
bytecodes()->push_back(raw_operand[0]);
bytecodes()->push_back(raw_operand[1]);
break;
}
case OperandSize::kQuad: {
const uint8_t* raw_operand =
reinterpret_cast<const uint8_t*>(&operands[i]);
bytecodes()->push_back(raw_operand[0]);
bytecodes()->push_back(raw_operand[1]);
bytecodes()->push_back(raw_operand[2]);
bytecodes()->push_back(raw_operand[3]);
break;
}
}
}
}
// static
Bytecode GetJumpWithConstantOperand(Bytecode jump_bytecode) {
switch (jump_bytecode) {
case Bytecode::kJump:
return Bytecode::kJumpConstant;
case Bytecode::kJumpIfTrue:
return Bytecode::kJumpIfTrueConstant;
case Bytecode::kJumpIfFalse:
return Bytecode::kJumpIfFalseConstant;
case Bytecode::kJumpIfToBooleanTrue:
return Bytecode::kJumpIfToBooleanTrueConstant;
case Bytecode::kJumpIfToBooleanFalse:
return Bytecode::kJumpIfToBooleanFalseConstant;
case Bytecode::kJumpIfNull:
return Bytecode::kJumpIfNullConstant;
case Bytecode::kJumpIfNotNull:
return Bytecode::kJumpIfNotNullConstant;
case Bytecode::kJumpIfUndefined:
return Bytecode::kJumpIfUndefinedConstant;
case Bytecode::kJumpIfNotUndefined:
return Bytecode::kJumpIfNotUndefinedConstant;
case Bytecode::kJumpIfJSReceiver:
return Bytecode::kJumpIfJSReceiverConstant;
default:
UNREACHABLE();
}
}
void BytecodeArrayWriter::PatchJumpWith8BitOperand(size_t jump_location,
int delta) {
Bytecode jump_bytecode = Bytecodes::FromByte(bytecodes()->at(jump_location));
DCHECK(Bytecodes::IsForwardJump(jump_bytecode));
DCHECK(Bytecodes::IsJumpImmediate(jump_bytecode));
DCHECK_EQ(Bytecodes::GetOperandType(jump_bytecode, 0), OperandType::kUImm);
DCHECK_GT(delta, 0);
size_t operand_location = jump_location + 1;
DCHECK_EQ(bytecodes()->at(operand_location), k8BitJumpPlaceholder);
if (Bytecodes::ScaleForUnsignedOperand(delta) == OperandScale::kSingle) {
// The jump fits within the range of an UImm8 operand, so cancel
// the reservation and jump directly.
constant_array_builder()->DiscardReservedEntry(OperandSize::kByte);
bytecodes()->at(operand_location) = static_cast<uint8_t>(delta);
} else {
// The jump does not fit within the range of an UImm8 operand, so
// commit reservation putting the offset into the constant pool,
// and update the jump instruction and operand.
size_t entry = constant_array_builder()->CommitReservedEntry(
OperandSize::kByte, Smi::FromInt(delta));
DCHECK_EQ(Bytecodes::SizeForUnsignedOperand(static_cast<uint32_t>(entry)),
OperandSize::kByte);
jump_bytecode = GetJumpWithConstantOperand(jump_bytecode);
bytecodes()->at(jump_location) = Bytecodes::ToByte(jump_bytecode);
bytecodes()->at(operand_location) = static_cast<uint8_t>(entry);
}
}
void BytecodeArrayWriter::PatchJumpWith16BitOperand(size_t jump_location,
int delta) {
Bytecode jump_bytecode = Bytecodes::FromByte(bytecodes()->at(jump_location));
DCHECK(Bytecodes::IsForwardJump(jump_bytecode));
DCHECK(Bytecodes::IsJumpImmediate(jump_bytecode));
DCHECK_EQ(Bytecodes::GetOperandType(jump_bytecode, 0), OperandType::kUImm);
DCHECK_GT(delta, 0);
size_t operand_location = jump_location + 1;
uint8_t operand_bytes[2];
if (Bytecodes::ScaleForUnsignedOperand(delta) <= OperandScale::kDouble) {
// The jump fits within the range of an Imm16 operand, so cancel
// the reservation and jump directly.
constant_array_builder()->DiscardReservedEntry(OperandSize::kShort);
WriteUnalignedUInt16(reinterpret_cast<Address>(operand_bytes),
static_cast<uint16_t>(delta));
} else {
// The jump does not fit within the range of an Imm16 operand, so
// commit reservation putting the offset into the constant pool,
// and update the jump instruction and operand.
size_t entry = constant_array_builder()->CommitReservedEntry(
OperandSize::kShort, Smi::FromInt(delta));
jump_bytecode = GetJumpWithConstantOperand(jump_bytecode);
bytecodes()->at(jump_location) = Bytecodes::ToByte(jump_bytecode);
WriteUnalignedUInt16(reinterpret_cast<Address>(operand_bytes),
static_cast<uint16_t>(entry));
}
DCHECK(bytecodes()->at(operand_location) == k8BitJumpPlaceholder &&
bytecodes()->at(operand_location + 1) == k8BitJumpPlaceholder);
bytecodes()->at(operand_location++) = operand_bytes[0];
bytecodes()->at(operand_location) = operand_bytes[1];
}
void BytecodeArrayWriter::PatchJumpWith32BitOperand(size_t jump_location,
int delta) {
DCHECK(Bytecodes::IsJumpImmediate(
Bytecodes::FromByte(bytecodes()->at(jump_location))));
constant_array_builder()->DiscardReservedEntry(OperandSize::kQuad);
uint8_t operand_bytes[4];
WriteUnalignedUInt32(reinterpret_cast<Address>(operand_bytes),
static_cast<uint32_t>(delta));
size_t operand_location = jump_location + 1;
DCHECK(bytecodes()->at(operand_location) == k8BitJumpPlaceholder &&
bytecodes()->at(operand_location + 1) == k8BitJumpPlaceholder &&
bytecodes()->at(operand_location + 2) == k8BitJumpPlaceholder &&
bytecodes()->at(operand_location + 3) == k8BitJumpPlaceholder);
bytecodes()->at(operand_location++) = operand_bytes[0];
bytecodes()->at(operand_location++) = operand_bytes[1];
bytecodes()->at(operand_location++) = operand_bytes[2];
bytecodes()->at(operand_location) = operand_bytes[3];
}
void BytecodeArrayWriter::PatchJump(size_t jump_target, size_t jump_location) {
Bytecode jump_bytecode = Bytecodes::FromByte(bytecodes()->at(jump_location));
int delta = static_cast<int>(jump_target - jump_location);
int prefix_offset = 0;
OperandScale operand_scale = OperandScale::kSingle;
if (Bytecodes::IsPrefixScalingBytecode(jump_bytecode)) {
// If a prefix scaling bytecode is emitted the target offset is one
// less than the case of no prefix scaling bytecode.
delta -= 1;
prefix_offset = 1;
operand_scale = Bytecodes::PrefixBytecodeToOperandScale(jump_bytecode);
jump_bytecode =
Bytecodes::FromByte(bytecodes()->at(jump_location + prefix_offset));
}
DCHECK(Bytecodes::IsJump(jump_bytecode));
switch (operand_scale) {
case OperandScale::kSingle:
PatchJumpWith8BitOperand(jump_location, delta);
break;
case OperandScale::kDouble:
PatchJumpWith16BitOperand(jump_location + prefix_offset, delta);
break;
case OperandScale::kQuadruple:
PatchJumpWith32BitOperand(jump_location + prefix_offset, delta);
break;
default:
UNREACHABLE();
}
unbound_jumps_--;
}
void BytecodeArrayWriter::EmitJumpLoop(BytecodeNode* node,
BytecodeLoopHeader* loop_header) {
DCHECK_EQ(node->bytecode(), Bytecode::kJumpLoop);
DCHECK_EQ(0u, node->operand(0));
size_t current_offset = bytecodes()->size();
CHECK_GE(current_offset, loop_header->offset());
CHECK_LE(current_offset, static_cast<size_t>(kMaxUInt32));
// Label has been bound already so this is a backwards jump.
uint32_t delta =
static_cast<uint32_t>(current_offset - loop_header->offset());
OperandScale operand_scale = Bytecodes::ScaleForUnsignedOperand(delta);
if (operand_scale > OperandScale::kSingle) {
// Adjust for scaling byte prefix for wide jump offset.
delta += 1;
}
node->update_operand0(delta);
EmitBytecode(node);
}
void BytecodeArrayWriter::EmitJump(BytecodeNode* node, BytecodeLabel* label) {
DCHECK(Bytecodes::IsForwardJump(node->bytecode()));
DCHECK_EQ(0u, node->operand(0));
size_t current_offset = bytecodes()->size();
// The label has not yet been bound so this is a forward reference
// that will be patched when the label is bound. We create a
// reservation in the constant pool so the jump can be patched
// when the label is bound. The reservation means the maximum size
// of the operand for the constant is known and the jump can
// be emitted into the bytecode stream with space for the operand.
unbound_jumps_++;
label->set_referrer(current_offset);
OperandSize reserved_operand_size =
constant_array_builder()->CreateReservedEntry();
DCHECK_NE(Bytecode::kJumpLoop, node->bytecode());
switch (reserved_operand_size) {
case OperandSize::kNone:
UNREACHABLE();
case OperandSize::kByte:
node->update_operand0(k8BitJumpPlaceholder);
break;
case OperandSize::kShort:
node->update_operand0(k16BitJumpPlaceholder);
break;
case OperandSize::kQuad:
node->update_operand0(k32BitJumpPlaceholder);
break;
}
EmitBytecode(node);
}
void BytecodeArrayWriter::EmitSwitch(BytecodeNode* node,
BytecodeJumpTable* jump_table) {
DCHECK(Bytecodes::IsSwitch(node->bytecode()));
size_t current_offset = bytecodes()->size();
if (node->operand_scale() > OperandScale::kSingle) {
// Adjust for scaling byte prefix.
current_offset += 1;
}
jump_table->set_switch_bytecode_offset(current_offset);
EmitBytecode(node);
}
} // namespace interpreter
} // namespace internal
} // namespace v8
| [
"[email protected]"
] | |
8110feee0cc4fc9205e2a8a40c9f6a1f587ed62b | cb984436ef3630d6185ab26c4f48aa15c7af55a1 | /MotionCapture/Source/MotionCapture.h | 52fe042fccd277fb1431af9cb5d57d7b4199a6ac | [] | no_license | koichi210/CPP | 8591a358a45a32d4370a6d869c99586e5b625d6d | 95d80f2e9967561c617c236a22db6bb007edadcc | refs/heads/master | 2021-06-25T08:36:21.866798 | 2020-09-28T23:19:49 | 2020-09-28T23:19:49 | 93,343,559 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 662 | h |
// MotionCapture.h : PROJECT_NAME アプリケーションのメイン ヘッダー ファイルです。
//
#pragma once
#ifndef __AFXWIN_H__
#error "PCH に対してこのファイルをインクルードする前に 'stdafx.h' をインクルードしてください"
#endif
#include "resource.h" // メイン シンボル
// CMotionCaptureApp:
// このクラスの実装については、MotionCapture.cpp を参照してください。
//
class CMotionCaptureApp : public CWinApp
{
public:
CMotionCaptureApp();
// オーバーライド
public:
virtual BOOL InitInstance();
// 実装
DECLARE_MESSAGE_MAP()
};
extern CMotionCaptureApp theApp; | [
"[email protected]"
] | |
819bed4934a0b52b686cf521b1f4540ace5e9622 | cc6fc7b8fab0b25e83dfd148c18bcbb322dd4209 | /app/src/main/jni/Global.h | 81b8065942ba8899ff3436a56bc22d8641f61135 | [] | no_license | HuyNguyen1590/live2d-android-wear | 372071c9e96ee565d81e16c3b5e826154e14ee2a | 6b733d4d1b0c3fe0a7824e91276bebf242c1d48a | refs/heads/master | 2021-05-31T19:01:20.843536 | 2016-06-19T23:46:01 | 2016-06-19T23:46:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 70 | h | #include <jni.h>
using namespace std;
extern JNIEnv* currentJNIEnv;
| [
"[email protected]"
] | |
6d06d51c196339861edc29be921de0a4606a4fd4 | 10afb5aec434e06b92c28d31f52f878aac755211 | /Cloak/TextureLoader.h | 23f306ea0fcd67ec25c2204fd4218df102082fae | [] | no_license | jmoorman/cloak-opengl | 5eaa9aa9ddc219fd648c93b4d72016e109e2056f | f9d5b2952c7553368f0cc930a67e68f725e24300 | refs/heads/master | 2020-04-09T07:35:13.584586 | 2016-02-19T07:22:18 | 2016-02-19T07:22:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 260 | h | #pragma once
#include "stdafx.h"
class TextureLoader
{
public:
TextureLoader(void);
~TextureLoader(void);
GLuint GetTexture(const std::string& filename);
static const std::string TEXTURE_PATH;
private:
std::map<std::string, GLuint> mTextureMap;
};
| [
"[email protected]"
] | |
59bbc965c572887e6feeb3bc5ce2c17c922a2d0d | 17aa1f6af4ead251bcfbca16006cdd82ca089e08 | /GameLoopPattern/EffectTest.cpp | 9950eea0bc4d9ce143ddb043cf5355c6a2881fc1 | [] | no_license | hohoho3661/Study1005 | 4bbd1b71ccf89415d1e6dc2e4a006197f5eedee0 | 7a1ca5853081194559e7f552b1809f7bb8884239 | refs/heads/master | 2020-03-30T23:12:10.243331 | 2018-10-05T08:45:37 | 2018-10-05T08:45:37 | 151,693,562 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 943 | cpp | #include "stdafx.h"
#include "EffectTest.h"
EffectTest::EffectTest()
{
}
EffectTest::~EffectTest()
{
}
bool EffectTest::Init()
{
EFFECTMANAGER->AddEffect(TEXT("Effect1"), TEXT("Image/effect5.bmp"),
740, 444, 148, 148, 1, 1.0f, 10);
EFFECTMANAGER->AddEffect(TEXT("Effect2"), TEXT("Image/explosion.bmp"),
832, 62, 32, 62, 1, 1.0f, 10); // 맨뒤 인자가 이펙트의 갯수.
// 이미지가 출력이되는 객체를 만듬.
//
return true;
}
void EffectTest::Release()
{
}
void EffectTest::Update()
{
if (KEYMANAGER->isStayKeyDown(VK_LBUTTON))
{
GetCursorPos(&_ptMouse);
ScreenToClient(_hWnd, &_ptMouse);
EFFECTMANAGER->Play(TEXT("Effect1"), _ptMouse);
}
if (KEYMANAGER->isStayKeyDown(VK_RBUTTON))
{
GetCursorPos(&_ptMouse);
ScreenToClient(_hWnd, &_ptMouse);
EFFECTMANAGER->Play(TEXT("Effect2"), _ptMouse);
}
EFFECTMANAGER->Update();
}
void EffectTest::Render(HDC hdc)
{
EFFECTMANAGER->Render(hdc);
}
| [
"[email protected]"
] | |
561b0ce6ae5abe1ff40f4db8a8a7ce2114ef3998 | 563f76150795fd1820ec4bd42e514d534a6d1099 | /src/net.cpp | 55ef850b7a86e9fbb80718cdbfd016ca3c8ddf44 | [
"MIT"
] | permissive | selabie68/SmartBlock | cc8e8fd19cf7c875ce7b337c933aae28510395c7 | ff9e739592811299704378788fcd56514f9a4c92 | refs/heads/master | 2020-04-09T23:37:46.156490 | 2018-12-09T05:25:57 | 2018-12-09T05:25:57 | 160,662,204 | 0 | 0 | MIT | 2018-12-06T11:01:40 | 2018-12-06T11:01:40 | null | UTF-8 | C++ | false | false | 74,475 | cpp | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2018 The SMARTBLOCK developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include "config/smartblock-config.h"
#endif
#include "net.h"
#include "addrman.h"
#include "chainparams.h"
#include "clientversion.h"
#include "miner.h"
#include "obfuscation.h"
#include "primitives/transaction.h"
#include "scheduler.h"
#include "ui_interface.h"
#include "wallet.h"
#ifdef WIN32
#include <string.h>
#else
#include <fcntl.h>
#endif
#ifdef USE_UPNP
#include <miniupnpc/miniupnpc.h>
#include <miniupnpc/miniwget.h>
#include <miniupnpc/upnpcommands.h>
#include <miniupnpc/upnperrors.h>
#endif
#include <boost/filesystem.hpp>
#include <boost/thread.hpp>
// Dump addresses to peers.dat every 15 minutes (900s)
#define DUMP_ADDRESSES_INTERVAL 900
#if !defined(HAVE_MSG_NOSIGNAL) && !defined(MSG_NOSIGNAL)
#define MSG_NOSIGNAL 0
#endif
// Fix for ancient MinGW versions, that don't have defined these in ws2tcpip.h.
// Todo: Can be removed when our pull-tester is upgraded to a modern MinGW version.
#ifdef WIN32
#ifndef PROTECTION_LEVEL_UNRESTRICTED
#define PROTECTION_LEVEL_UNRESTRICTED 10
#endif
#ifndef IPV6_PROTECTION_LEVEL
#define IPV6_PROTECTION_LEVEL 23
#endif
#endif
using namespace boost;
using namespace std;
namespace
{
const int MAX_OUTBOUND_CONNECTIONS = 16;
struct ListenSocket {
SOCKET socket;
bool whitelisted;
ListenSocket(SOCKET socket, bool whitelisted) : socket(socket), whitelisted(whitelisted) {}
};
}
//
// Global state variables
//
bool fDiscover = true;
bool fListen = true;
uint64_t nLocalServices = NODE_NETWORK;
CCriticalSection cs_mapLocalHost;
map<CNetAddr, LocalServiceInfo> mapLocalHost;
static bool vfLimited[NET_MAX] = {};
static CNode* pnodeLocalHost = NULL;
uint64_t nLocalHostNonce = 0;
static std::vector<ListenSocket> vhListenSocket;
CAddrMan addrman;
int nMaxConnections = 125;
bool fAddressesInitialized = false;
vector<CNode*> vNodes;
CCriticalSection cs_vNodes;
map<CInv, CDataStream> mapRelay;
deque<pair<int64_t, CInv> > vRelayExpiration;
CCriticalSection cs_mapRelay;
limitedmap<CInv, int64_t> mapAlreadyAskedFor(MAX_INV_SZ);
static deque<string> vOneShots;
CCriticalSection cs_vOneShots;
set<CNetAddr> setservAddNodeAddresses;
CCriticalSection cs_setservAddNodeAddresses;
vector<std::string> vAddedNodes;
CCriticalSection cs_vAddedNodes;
NodeId nLastNodeId = 0;
CCriticalSection cs_nLastNodeId;
static CSemaphore* semOutbound = NULL;
boost::condition_variable messageHandlerCondition;
// Signals for message handling
static CNodeSignals g_signals;
CNodeSignals& GetNodeSignals() { return g_signals; }
void AddOneShot(string strDest)
{
LOCK(cs_vOneShots);
vOneShots.push_back(strDest);
}
unsigned short GetListenPort()
{
return (unsigned short)(GetArg("-port", Params().GetDefaultPort()));
}
// find 'best' local address for a particular peer
bool GetLocal(CService& addr, const CNetAddr* paddrPeer)
{
if (!fListen)
return false;
int nBestScore = -1;
int nBestReachability = -1;
{
LOCK(cs_mapLocalHost);
for (map<CNetAddr, LocalServiceInfo>::iterator it = mapLocalHost.begin(); it != mapLocalHost.end(); it++) {
int nScore = (*it).second.nScore;
int nReachability = (*it).first.GetReachabilityFrom(paddrPeer);
if (nReachability > nBestReachability || (nReachability == nBestReachability && nScore > nBestScore)) {
addr = CService((*it).first, (*it).second.nPort);
nBestReachability = nReachability;
nBestScore = nScore;
}
}
}
return nBestScore >= 0;
}
// get best local address for a particular peer as a CAddress
// Otherwise, return the unroutable 0.0.0.0 but filled in with
// the normal parameters, since the IP may be changed to a useful
// one by discovery.
CAddress GetLocalAddress(const CNetAddr* paddrPeer)
{
CAddress ret(CService("0.0.0.0", GetListenPort()), 0);
CService addr;
if (GetLocal(addr, paddrPeer)) {
ret = CAddress(addr);
}
ret.nServices = nLocalServices;
ret.nTime = GetAdjustedTime();
return ret;
}
bool RecvLine(SOCKET hSocket, string& strLine)
{
strLine = "";
while (true) {
char c;
int nBytes = recv(hSocket, &c, 1, 0);
if (nBytes > 0) {
if (c == '\n')
continue;
if (c == '\r')
return true;
strLine += c;
if (strLine.size() >= 9000)
return true;
} else if (nBytes <= 0) {
boost::this_thread::interruption_point();
if (nBytes < 0) {
int nErr = WSAGetLastError();
if (nErr == WSAEMSGSIZE)
continue;
if (nErr == WSAEWOULDBLOCK || nErr == WSAEINTR || nErr == WSAEINPROGRESS) {
MilliSleep(10);
continue;
}
}
if (!strLine.empty())
return true;
if (nBytes == 0) {
// socket closed
LogPrint("net", "socket closed\n");
return false;
} else {
// socket error
int nErr = WSAGetLastError();
LogPrint("net", "recv failed: %s\n", NetworkErrorString(nErr));
return false;
}
}
}
}
int GetnScore(const CService& addr)
{
LOCK(cs_mapLocalHost);
if (mapLocalHost.count(addr) == LOCAL_NONE)
return 0;
return mapLocalHost[addr].nScore;
}
// Is our peer's addrLocal potentially useful as an external IP source?
bool IsPeerAddrLocalGood(CNode* pnode)
{
return fDiscover && pnode->addr.IsRoutable() && pnode->addrLocal.IsRoutable() &&
!IsLimited(pnode->addrLocal.GetNetwork());
}
// pushes our own address to a peer
void AdvertizeLocal(CNode* pnode)
{
if (fListen && pnode->fSuccessfullyConnected) {
CAddress addrLocal = GetLocalAddress(&pnode->addr);
// If discovery is enabled, sometimes give our peer the address it
// tells us that it sees us as in case it has a better idea of our
// address than we do.
if (IsPeerAddrLocalGood(pnode) && (!addrLocal.IsRoutable() ||
GetRand((GetnScore(addrLocal) > LOCAL_MANUAL) ? 8 : 2) == 0)) {
addrLocal.SetIP(pnode->addrLocal);
}
if (addrLocal.IsRoutable()) {
LogPrintf("AdvertizeLocal: advertizing address %s\n", addrLocal.ToString());
pnode->PushAddress(addrLocal);
}
}
}
// learn a new local address
bool AddLocal(const CService& addr, int nScore)
{
if (!addr.IsRoutable())
return false;
if (!fDiscover && nScore < LOCAL_MANUAL)
return false;
if (IsLimited(addr))
return false;
LogPrintf("AddLocal(%s,%i)\n", addr.ToString(), nScore);
{
LOCK(cs_mapLocalHost);
bool fAlready = mapLocalHost.count(addr) > 0;
LocalServiceInfo& info = mapLocalHost[addr];
if (!fAlready || nScore >= info.nScore) {
info.nScore = nScore + (fAlready ? 1 : 0);
info.nPort = addr.GetPort();
}
}
return true;
}
bool AddLocal(const CNetAddr& addr, int nScore)
{
return AddLocal(CService(addr, GetListenPort()), nScore);
}
bool RemoveLocal(const CService& addr)
{
LOCK(cs_mapLocalHost);
LogPrintf("RemoveLocal(%s)\n", addr.ToString());
mapLocalHost.erase(addr);
return true;
}
/** Make a particular network entirely off-limits (no automatic connects to it) */
void SetLimited(enum Network net, bool fLimited)
{
if (net == NET_UNROUTABLE)
return;
LOCK(cs_mapLocalHost);
vfLimited[net] = fLimited;
}
bool IsLimited(enum Network net)
{
LOCK(cs_mapLocalHost);
return vfLimited[net];
}
bool IsLimited(const CNetAddr& addr)
{
return IsLimited(addr.GetNetwork());
}
/** vote for a local address */
bool SeenLocal(const CService& addr)
{
{
LOCK(cs_mapLocalHost);
if (mapLocalHost.count(addr) == 0)
return false;
mapLocalHost[addr].nScore++;
}
return true;
}
/** check whether a given address is potentially local */
bool IsLocal(const CService& addr)
{
LOCK(cs_mapLocalHost);
return mapLocalHost.count(addr) > 0;
}
/** check whether a given network is one we can probably connect to */
bool IsReachable(enum Network net)
{
LOCK(cs_mapLocalHost);
return !vfLimited[net];
}
/** check whether a given address is in a network we can probably connect to */
bool IsReachable(const CNetAddr& addr)
{
enum Network net = addr.GetNetwork();
return IsReachable(net);
}
void AddressCurrentlyConnected(const CService& addr)
{
addrman.Connected(addr);
}
uint64_t CNode::nTotalBytesRecv = 0;
uint64_t CNode::nTotalBytesSent = 0;
CCriticalSection CNode::cs_totalBytesRecv;
CCriticalSection CNode::cs_totalBytesSent;
CNode* FindNode(const CNetAddr& ip)
{
LOCK(cs_vNodes);
for (CNode* pnode : vNodes)
if ((CNetAddr)pnode->addr == ip)
return (pnode);
return NULL;
}
CNode* FindNode(const CSubNet& subNet)
{
LOCK(cs_vNodes);
for (CNode* pnode : vNodes)
if (subNet.Match((CNetAddr)pnode->addr))
return (pnode);
return NULL;
}
CNode* FindNode(const std::string& addrName)
{
LOCK(cs_vNodes);
for (CNode* pnode : vNodes)
if (pnode->addrName == addrName)
return (pnode);
return NULL;
}
CNode* FindNode(const CService& addr)
{
LOCK(cs_vNodes);
for (CNode* pnode : vNodes) {
if (Params().NetworkID() == CBaseChainParams::REGTEST) {
//if using regtest, just check the IP
if ((CNetAddr)pnode->addr == (CNetAddr)addr)
return (pnode);
} else {
if (pnode->addr == addr)
return (pnode);
}
}
return NULL;
}
CNode* ConnectNode(CAddress addrConnect, const char* pszDest, bool obfuScationMaster)
{
if (pszDest == NULL) {
// we clean masternode connections in CMasternodeMan::ProcessMasternodeConnections()
// so should be safe to skip this and connect to local Hot MN on CActiveMasternode::ManageStatus()
if (IsLocal(addrConnect) && !obfuScationMaster)
return NULL;
// Look for an existing connection
CNode* pnode = FindNode((CService)addrConnect);
if (pnode) {
pnode->fObfuScationMaster = obfuScationMaster;
pnode->AddRef();
return pnode;
}
}
/// debug print
LogPrint("net", "trying connection %s lastseen=%.1fhrs\n",
pszDest ? pszDest : addrConnect.ToString(),
pszDest ? 0.0 : (double)(GetAdjustedTime() - addrConnect.nTime) / 3600.0);
// Connect
SOCKET hSocket;
bool proxyConnectionFailed = false;
if (pszDest ? ConnectSocketByName(addrConnect, hSocket, pszDest, Params().GetDefaultPort(), nConnectTimeout, &proxyConnectionFailed) :
ConnectSocket(addrConnect, hSocket, nConnectTimeout, &proxyConnectionFailed)) {
if (!IsSelectableSocket(hSocket)) {
LogPrintf("Cannot create connection: non-selectable socket created (fd >= FD_SETSIZE ?)\n");
CloseSocket(hSocket);
return NULL;
}
addrman.Attempt(addrConnect);
// Add node
CNode* pnode = new CNode(hSocket, addrConnect, pszDest ? pszDest : "", false);
pnode->AddRef();
{
LOCK(cs_vNodes);
vNodes.push_back(pnode);
}
pnode->nTimeConnected = GetTime();
if (obfuScationMaster) pnode->fObfuScationMaster = true;
return pnode;
} else if (!proxyConnectionFailed) {
// If connecting to the node failed, and failure is not caused by a problem connecting to
// the proxy, mark this as an attempt.
addrman.Attempt(addrConnect);
}
return NULL;
}
void CNode::CloseSocketDisconnect()
{
fDisconnect = true;
if (hSocket != INVALID_SOCKET) {
LogPrint("net", "disconnecting peer=%d\n", id);
CloseSocket(hSocket);
}
// in case this fails, we'll empty the recv buffer when the CNode is deleted
TRY_LOCK(cs_vRecvMsg, lockRecv);
if (lockRecv)
vRecvMsg.clear();
}
bool CNode::DisconnectOldProtocol(int nVersionRequired, string strLastCommand)
{
fDisconnect = false;
if (nVersion < nVersionRequired) {
LogPrintf("%s : peer=%d using obsolete version %i; disconnecting\n", __func__, id, nVersion);
PushMessage("reject", strLastCommand, REJECT_OBSOLETE, strprintf("Version must be %d or greater", ActiveProtocol()));
fDisconnect = true;
}
return fDisconnect;
}
void CNode::PushVersion()
{
int nBestHeight = g_signals.GetHeight().get_value_or(0);
/// when NTP implemented, change to just nTime = GetAdjustedTime()
int64_t nTime = (fInbound ? GetAdjustedTime() : GetTime());
CAddress addrYou = (addr.IsRoutable() && !IsProxy(addr) ? addr : CAddress(CService("0.0.0.0", 0)));
CAddress addrMe = GetLocalAddress(&addr);
GetRandBytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce));
if (fLogIPs)
LogPrint("net", "send version message: version %d, blocks=%d, us=%s, them=%s, peer=%d\n", PROTOCOL_VERSION, nBestHeight, addrMe.ToString(), addrYou.ToString(), id);
else
LogPrint("net", "send version message: version %d, blocks=%d, us=%s, peer=%d\n", PROTOCOL_VERSION, nBestHeight, addrMe.ToString(), id);
PushMessage("version", PROTOCOL_VERSION, nLocalServices, nTime, addrYou, addrMe,
nLocalHostNonce, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<string>()), nBestHeight, true);
}
banmap_t CNode::setBanned;
CCriticalSection CNode::cs_setBanned;
bool CNode::setBannedIsDirty;
void CNode::ClearBanned()
{
{
LOCK(cs_setBanned);
setBanned.clear();
setBannedIsDirty = true;
}
DumpBanlist(); // store banlist to Disk
uiInterface.BannedListChanged();
}
bool CNode::IsBanned(CNetAddr ip)
{
bool fResult = false;
{
LOCK(cs_setBanned);
for (banmap_t::iterator it = setBanned.begin(); it != setBanned.end(); it++)
{
CSubNet subNet = (*it).first;
CBanEntry banEntry = (*it).second;
if(subNet.Match(ip) && GetTime() < banEntry.nBanUntil)
fResult = true;
}
}
return fResult;
}
bool CNode::IsBanned(CSubNet subnet)
{
bool fResult = false;
{
LOCK(cs_setBanned);
banmap_t::iterator i = setBanned.find(subnet);
if (i != setBanned.end()) {
CBanEntry banEntry = (*i).second;
if (GetTime() < banEntry.nBanUntil)
fResult = true;
}
}
return fResult;
}
void CNode::Ban(const CNetAddr& addr, const BanReason &banReason, int64_t bantimeoffset, bool sinceUnixEpoch)
{
CSubNet subNet(addr);
Ban(subNet, banReason, bantimeoffset, sinceUnixEpoch);
}
void CNode::Ban(const CSubNet& subNet, const BanReason &banReason, int64_t bantimeoffset, bool sinceUnixEpoch)
{
CBanEntry banEntry(GetTime());
banEntry.banReason = banReason;
if (bantimeoffset <= 0)
{
bantimeoffset = GetArg("-bantime", 60*60*24); // Default 24-hour ban
sinceUnixEpoch = false;
}
banEntry.nBanUntil = (sinceUnixEpoch ? 0 : GetTime() )+bantimeoffset;
{
LOCK(cs_setBanned);
if (setBanned[subNet].nBanUntil < banEntry.nBanUntil) {
setBanned[subNet] = banEntry;
setBannedIsDirty = true;
}
else
return;
}
uiInterface.BannedListChanged();
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes) {
if (subNet.Match((CNetAddr)pnode->addr))
pnode->fDisconnect = true;
}
}
if(banReason == BanReasonManuallyAdded)
DumpBanlist(); //store banlist to disk immediately if user requested ban
}
bool CNode::Unban(const CNetAddr &addr)
{
CSubNet subNet(addr);
return Unban(subNet);
}
bool CNode::Unban(const CSubNet &subNet)
{
{
LOCK(cs_setBanned);
if (!setBanned.erase(subNet))
return false;
setBannedIsDirty = true;
}
uiInterface.BannedListChanged();
DumpBanlist(); //store banlist to disk immediately
return true;
}
void CNode::GetBanned(banmap_t &banMap)
{
LOCK(cs_setBanned);
banMap = setBanned; //create a thread safe copy
}
void CNode::SetBanned(const banmap_t &banMap)
{
LOCK(cs_setBanned);
setBanned = banMap;
setBannedIsDirty = true;
}
void CNode::SweepBanned()
{
int64_t now = GetTime();
bool notifyUI = false;
{
LOCK(cs_setBanned);
banmap_t::iterator it = setBanned.begin();
while(it != setBanned.end())
{
CSubNet subNet = (*it).first;
CBanEntry banEntry = (*it).second;
if(now > banEntry.nBanUntil)
{
setBanned.erase(it++);
setBannedIsDirty = true;
notifyUI = true;
LogPrint("net", "%s: Removed banned node ip/subnet from banlist.dat: %s\n", __func__, subNet.ToString());
}
else
++it;
}
}
// update UI
if(notifyUI) {
uiInterface.BannedListChanged();
}
}
bool CNode::BannedSetIsDirty()
{
LOCK(cs_setBanned);
return setBannedIsDirty;
}
void CNode::SetBannedSetDirty(bool dirty)
{
LOCK(cs_setBanned); //reuse setBanned lock for the isDirty flag
setBannedIsDirty = dirty;
}
std::vector<CSubNet> CNode::vWhitelistedRange;
CCriticalSection CNode::cs_vWhitelistedRange;
bool CNode::IsWhitelistedRange(const CNetAddr& addr)
{
LOCK(cs_vWhitelistedRange);
BOOST_FOREACH (const CSubNet& subnet, vWhitelistedRange) {
if (subnet.Match(addr))
return true;
}
return false;
}
void CNode::AddWhitelistedRange(const CSubNet& subnet)
{
LOCK(cs_vWhitelistedRange);
vWhitelistedRange.push_back(subnet);
}
#undef X
#define X(name) stats.name = name
void CNode::copyStats(CNodeStats& stats)
{
stats.nodeid = this->GetId();
X(nServices);
X(nLastSend);
X(nLastRecv);
X(nTimeConnected);
X(nTimeOffset);
X(addrName);
X(nVersion);
X(cleanSubVer);
X(fInbound);
X(nStartingHeight);
X(nSendBytes);
X(nRecvBytes);
X(fWhitelisted);
// It is common for nodes with good ping times to suddenly become lagged,
// due to a new block arriving or other large transfer.
// Merely reporting pingtime might fool the caller into thinking the node was still responsive,
// since pingtime does not update until the ping is complete, which might take a while.
// So, if a ping is taking an unusually long time in flight,
// the caller can immediately detect that this is happening.
int64_t nPingUsecWait = 0;
if ((0 != nPingNonceSent) && (0 != nPingUsecStart)) {
nPingUsecWait = GetTimeMicros() - nPingUsecStart;
}
// Raw ping time is in microseconds, but show it to user as whole seconds (SMARTBLOCK users should be well used to small numbers with many decimal places by now :)
stats.dPingTime = (((double)nPingUsecTime) / 1e6);
stats.dPingWait = (((double)nPingUsecWait) / 1e6);
// Leave string empty if addrLocal invalid (not filled in yet)
stats.addrLocal = addrLocal.IsValid() ? addrLocal.ToString() : "";
}
#undef X
// requires LOCK(cs_vRecvMsg)
bool CNode::ReceiveMsgBytes(const char* pch, unsigned int nBytes)
{
while (nBytes > 0) {
// get current incomplete message, or create a new one
if (vRecvMsg.empty() ||
vRecvMsg.back().complete())
vRecvMsg.push_back(CNetMessage(SER_NETWORK, nRecvVersion));
CNetMessage& msg = vRecvMsg.back();
// absorb network data
int handled;
if (!msg.in_data)
handled = msg.readHeader(pch, nBytes);
else
handled = msg.readData(pch, nBytes);
if (handled < 0)
return false;
if (msg.in_data && msg.hdr.nMessageSize > MAX_PROTOCOL_MESSAGE_LENGTH) {
LogPrint("net", "Oversized message from peer=%i, disconnecting", GetId());
return false;
}
pch += handled;
nBytes -= handled;
if (msg.complete()) {
msg.nTime = GetTimeMicros();
messageHandlerCondition.notify_one();
}
}
return true;
}
int CNetMessage::readHeader(const char* pch, unsigned int nBytes)
{
// copy data to temporary parsing buffer
unsigned int nRemaining = 24 - nHdrPos;
unsigned int nCopy = std::min(nRemaining, nBytes);
memcpy(&hdrbuf[nHdrPos], pch, nCopy);
nHdrPos += nCopy;
// if header incomplete, exit
if (nHdrPos < 24)
return nCopy;
// deserialize to CMessageHeader
try {
hdrbuf >> hdr;
} catch (const std::exception&) {
return -1;
}
// reject messages larger than MAX_SIZE
if (hdr.nMessageSize > MAX_SIZE)
return -1;
// switch state to reading message data
in_data = true;
return nCopy;
}
int CNetMessage::readData(const char* pch, unsigned int nBytes)
{
unsigned int nRemaining = hdr.nMessageSize - nDataPos;
unsigned int nCopy = std::min(nRemaining, nBytes);
if (vRecv.size() < nDataPos + nCopy) {
// Allocate up to 256 KiB ahead, but never more than the total message size.
vRecv.resize(std::min(hdr.nMessageSize, nDataPos + nCopy + 256 * 1024));
}
memcpy(&vRecv[nDataPos], pch, nCopy);
nDataPos += nCopy;
return nCopy;
}
// requires LOCK(cs_vSend)
void SocketSendData(CNode* pnode)
{
std::deque<CSerializeData>::iterator it = pnode->vSendMsg.begin();
while (it != pnode->vSendMsg.end()) {
const CSerializeData& data = *it;
assert(data.size() > pnode->nSendOffset);
int nBytes = send(pnode->hSocket, &data[pnode->nSendOffset], data.size() - pnode->nSendOffset, MSG_NOSIGNAL | MSG_DONTWAIT);
if (nBytes > 0) {
pnode->nLastSend = GetTime();
pnode->nSendBytes += nBytes;
pnode->nSendOffset += nBytes;
pnode->RecordBytesSent(nBytes);
if (pnode->nSendOffset == data.size()) {
pnode->nSendOffset = 0;
pnode->nSendSize -= data.size();
it++;
} else {
// could not send full message; stop sending more
break;
}
} else {
if (nBytes < 0) {
// error
int nErr = WSAGetLastError();
if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS) {
LogPrintf("socket send error %s\n", NetworkErrorString(nErr));
pnode->CloseSocketDisconnect();
}
}
// couldn't send anything at all
break;
}
}
if (it == pnode->vSendMsg.end()) {
assert(pnode->nSendOffset == 0);
assert(pnode->nSendSize == 0);
}
pnode->vSendMsg.erase(pnode->vSendMsg.begin(), it);
}
static list<CNode*> vNodesDisconnected;
void ThreadSocketHandler()
{
unsigned int nPrevNodeCount = 0;
while (true) {
//
// Disconnect nodes
//
{
LOCK(cs_vNodes);
// Disconnect unused nodes
vector<CNode*> vNodesCopy = vNodes;
BOOST_FOREACH (CNode* pnode, vNodesCopy) {
if (pnode->fDisconnect ||
(pnode->GetRefCount() <= 0 && pnode->vRecvMsg.empty() && pnode->nSendSize == 0 && pnode->ssSend.empty())) {
// remove from vNodes
vNodes.erase(remove(vNodes.begin(), vNodes.end(), pnode), vNodes.end());
// release outbound grant (if any)
pnode->grantOutbound.Release();
// close socket and cleanup
pnode->CloseSocketDisconnect();
// hold in disconnected pool until all refs are released
if (pnode->fNetworkNode || pnode->fInbound)
pnode->Release();
vNodesDisconnected.push_back(pnode);
}
}
}
{
// Delete disconnected nodes
list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected;
BOOST_FOREACH (CNode* pnode, vNodesDisconnectedCopy) {
// wait until threads are done using it
if (pnode->GetRefCount() <= 0) {
bool fDelete = false;
{
TRY_LOCK(pnode->cs_vSend, lockSend);
if (lockSend) {
TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);
if (lockRecv) {
TRY_LOCK(pnode->cs_inventory, lockInv);
if (lockInv)
fDelete = true;
}
}
}
if (fDelete) {
vNodesDisconnected.remove(pnode);
delete pnode;
}
}
}
}
size_t vNodesSize;
{
LOCK(cs_vNodes);
vNodesSize = vNodes.size();
}
if(vNodesSize != nPrevNodeCount) {
nPrevNodeCount = vNodesSize;
uiInterface.NotifyNumConnectionsChanged(nPrevNodeCount);
}
//
// Find which sockets have data to receive
//
struct timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 50000; // frequency to poll pnode->vSend
fd_set fdsetRecv;
fd_set fdsetSend;
fd_set fdsetError;
FD_ZERO(&fdsetRecv);
FD_ZERO(&fdsetSend);
FD_ZERO(&fdsetError);
SOCKET hSocketMax = 0;
bool have_fds = false;
BOOST_FOREACH (const ListenSocket& hListenSocket, vhListenSocket) {
FD_SET(hListenSocket.socket, &fdsetRecv);
hSocketMax = max(hSocketMax, hListenSocket.socket);
have_fds = true;
}
{
LOCK(cs_vNodes);
BOOST_FOREACH (CNode* pnode, vNodes) {
if (pnode->hSocket == INVALID_SOCKET)
continue;
FD_SET(pnode->hSocket, &fdsetError);
hSocketMax = max(hSocketMax, pnode->hSocket);
have_fds = true;
// Implement the following logic:
// * If there is data to send, select() for sending data. As this only
// happens when optimistic write failed, we choose to first drain the
// write buffer in this case before receiving more. This avoids
// needlessly queueing received data, if the remote peer is not themselves
// receiving data. This means properly utilizing TCP flow control signalling.
// * Otherwise, if there is no (complete) message in the receive buffer,
// or there is space left in the buffer, select() for receiving data.
// * (if neither of the above applies, there is certainly one message
// in the receiver buffer ready to be processed).
// Together, that means that at least one of the following is always possible,
// so we don't deadlock:
// * We send some data.
// * We wait for data to be received (and disconnect after timeout).
// * We process a message in the buffer (message handler thread).
{
TRY_LOCK(pnode->cs_vSend, lockSend);
if (lockSend && !pnode->vSendMsg.empty()) {
FD_SET(pnode->hSocket, &fdsetSend);
continue;
}
}
{
TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);
if (lockRecv && (pnode->vRecvMsg.empty() || !pnode->vRecvMsg.front().complete() ||
pnode->GetTotalRecvSize() <= ReceiveFloodSize()))
FD_SET(pnode->hSocket, &fdsetRecv);
}
}
}
int nSelect = select(have_fds ? hSocketMax + 1 : 0,
&fdsetRecv, &fdsetSend, &fdsetError, &timeout);
boost::this_thread::interruption_point();
if (nSelect == SOCKET_ERROR) {
if (have_fds) {
int nErr = WSAGetLastError();
LogPrintf("socket select error %s\n", NetworkErrorString(nErr));
for (unsigned int i = 0; i <= hSocketMax; i++)
FD_SET(i, &fdsetRecv);
}
FD_ZERO(&fdsetSend);
FD_ZERO(&fdsetError);
MilliSleep(timeout.tv_usec / 1000);
}
//
// Accept new connections
//
BOOST_FOREACH (const ListenSocket& hListenSocket, vhListenSocket) {
if (hListenSocket.socket != INVALID_SOCKET && FD_ISSET(hListenSocket.socket, &fdsetRecv)) {
struct sockaddr_storage sockaddr;
socklen_t len = sizeof(sockaddr);
SOCKET hSocket = accept(hListenSocket.socket, (struct sockaddr*)&sockaddr, &len);
CAddress addr;
int nInbound = 0;
if (hSocket != INVALID_SOCKET)
if (!addr.SetSockAddr((const struct sockaddr*)&sockaddr))
LogPrintf("Warning: Unknown socket family\n");
bool whitelisted = hListenSocket.whitelisted || CNode::IsWhitelistedRange(addr);
{
LOCK(cs_vNodes);
BOOST_FOREACH (CNode* pnode, vNodes)
if (pnode->fInbound)
nInbound++;
}
if (hSocket == INVALID_SOCKET) {
int nErr = WSAGetLastError();
if (nErr != WSAEWOULDBLOCK)
LogPrintf("socket error accept failed: %s\n", NetworkErrorString(nErr));
} else if (!IsSelectableSocket(hSocket)) {
LogPrintf("connection from %s dropped: non-selectable socket\n", addr.ToString());
CloseSocket(hSocket);
} else if (nInbound >= nMaxConnections - MAX_OUTBOUND_CONNECTIONS) {
LogPrint("net", "connection from %s dropped (full)\n", addr.ToString());
CloseSocket(hSocket);
} else if (CNode::IsBanned(addr) && !whitelisted) {
LogPrintf("connection from %s dropped (banned)\n", addr.ToString());
CloseSocket(hSocket);
} else {
CNode* pnode = new CNode(hSocket, addr, "", true);
pnode->AddRef();
pnode->fWhitelisted = whitelisted;
{
LOCK(cs_vNodes);
vNodes.push_back(pnode);
}
}
}
}
//
// Service each socket
//
vector<CNode*> vNodesCopy;
{
LOCK(cs_vNodes);
vNodesCopy = vNodes;
BOOST_FOREACH (CNode* pnode, vNodesCopy)
pnode->AddRef();
}
BOOST_FOREACH (CNode* pnode, vNodesCopy) {
boost::this_thread::interruption_point();
//
// Receive
//
if (pnode->hSocket == INVALID_SOCKET)
continue;
if (FD_ISSET(pnode->hSocket, &fdsetRecv) || FD_ISSET(pnode->hSocket, &fdsetError)) {
TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);
if (lockRecv) {
{
// typical socket buffer is 8K-64K
char pchBuf[0x10000];
int nBytes = recv(pnode->hSocket, pchBuf, sizeof(pchBuf), MSG_DONTWAIT);
if (nBytes > 0) {
if (!pnode->ReceiveMsgBytes(pchBuf, nBytes))
pnode->CloseSocketDisconnect();
pnode->nLastRecv = GetTime();
pnode->nRecvBytes += nBytes;
pnode->RecordBytesRecv(nBytes);
} else if (nBytes == 0) {
// socket closed gracefully
if (!pnode->fDisconnect)
LogPrint("net", "socket closed\n");
pnode->CloseSocketDisconnect();
} else if (nBytes < 0) {
// error
int nErr = WSAGetLastError();
if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS) {
if (!pnode->fDisconnect)
LogPrintf("socket recv error %s\n", NetworkErrorString(nErr));
pnode->CloseSocketDisconnect();
}
}
}
}
}
//
// Send
//
if (pnode->hSocket == INVALID_SOCKET)
continue;
if (FD_ISSET(pnode->hSocket, &fdsetSend)) {
TRY_LOCK(pnode->cs_vSend, lockSend);
if (lockSend)
SocketSendData(pnode);
}
//
// Inactivity checking
//
int64_t nTime = GetTime();
if (nTime - pnode->nTimeConnected > 60) {
if (pnode->nLastRecv == 0 || pnode->nLastSend == 0) {
LogPrint("net", "socket no message in first 60 seconds, %d %d from %d\n", pnode->nLastRecv != 0, pnode->nLastSend != 0, pnode->id);
pnode->fDisconnect = true;
} else if (nTime - pnode->nLastSend > TIMEOUT_INTERVAL) {
LogPrintf("socket sending timeout: %is\n", nTime - pnode->nLastSend);
pnode->fDisconnect = true;
} else if (nTime - pnode->nLastRecv > (pnode->nVersion > BIP0031_VERSION ? TIMEOUT_INTERVAL : 90 * 60)) {
LogPrintf("socket receive timeout: %is\n", nTime - pnode->nLastRecv);
pnode->fDisconnect = true;
} else if (pnode->nPingNonceSent && pnode->nPingUsecStart + TIMEOUT_INTERVAL * 1000000 < GetTimeMicros()) {
LogPrintf("ping timeout: %fs\n", 0.000001 * (GetTimeMicros() - pnode->nPingUsecStart));
pnode->fDisconnect = true;
}
}
}
{
LOCK(cs_vNodes);
BOOST_FOREACH (CNode* pnode, vNodesCopy)
pnode->Release();
}
}
}
#ifdef USE_UPNP
void ThreadMapPort()
{
std::string port = strprintf("%u", GetListenPort());
const char* multicastif = 0;
const char* minissdpdpath = 0;
struct UPNPDev* devlist = 0;
char lanaddr[64];
#ifndef UPNPDISCOVER_SUCCESS
/* miniupnpc 1.5 */
devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0);
#elif MINIUPNPC_API_VERSION < 14
/* miniupnpc 1.6 */
int error = 0;
devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, &error);
#else
/* miniupnpc 1.9.20150730 */
int error = 0;
devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, 2, &error);
#endif
struct UPNPUrls urls;
struct IGDdatas data;
int r;
r = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr));
if (r == 1) {
if (fDiscover) {
char externalIPAddress[40];
r = UPNP_GetExternalIPAddress(urls.controlURL, data.first.servicetype, externalIPAddress);
if (r != UPNPCOMMAND_SUCCESS)
LogPrintf("UPnP: GetExternalIPAddress() returned %d\n", r);
else {
if (externalIPAddress[0]) {
LogPrintf("UPnP: ExternalIPAddress = %s\n", externalIPAddress);
AddLocal(CNetAddr(externalIPAddress), LOCAL_UPNP);
} else
LogPrintf("UPnP: GetExternalIPAddress failed.\n");
}
}
string strDesc = "SMARTBLOCK " + FormatFullVersion();
try {
while (true) {
#ifndef UPNPDISCOVER_SUCCESS
/* miniupnpc 1.5 */
r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0);
#else
/* miniupnpc 1.6 */
r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0, "0");
#endif
if (r != UPNPCOMMAND_SUCCESS)
LogPrintf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n",
port, port, lanaddr, r, strupnperror(r));
else
LogPrintf("UPnP Port Mapping successful.\n");
;
MilliSleep(20 * 60 * 1000); // Refresh every 20 minutes
}
} catch (boost::thread_interrupted) {
r = UPNP_DeletePortMapping(urls.controlURL, data.first.servicetype, port.c_str(), "TCP", 0);
LogPrintf("UPNP_DeletePortMapping() returned : %d\n", r);
freeUPNPDevlist(devlist);
devlist = 0;
FreeUPNPUrls(&urls);
throw;
}
} else {
LogPrintf("No valid UPnP IGDs found\n");
freeUPNPDevlist(devlist);
devlist = 0;
if (r != 0)
FreeUPNPUrls(&urls);
}
}
void MapPort(bool fUseUPnP)
{
static boost::thread* upnp_thread = NULL;
if (fUseUPnP) {
if (upnp_thread) {
upnp_thread->interrupt();
upnp_thread->join();
delete upnp_thread;
}
upnp_thread = new boost::thread(boost::bind(&TraceThread<void (*)()>, "upnp", &ThreadMapPort));
} else if (upnp_thread) {
upnp_thread->interrupt();
upnp_thread->join();
delete upnp_thread;
upnp_thread = NULL;
}
}
#else
void MapPort(bool)
{
// Intentionally left blank.
}
#endif
void ThreadDNSAddressSeed()
{
// goal: only query DNS seeds if address need is acute
if ((addrman.size() > 0) &&
(!GetBoolArg("-forcednsseed", false))) {
MilliSleep(11 * 1000);
LOCK(cs_vNodes);
if (vNodes.size() >= 2) {
LogPrintf("P2P peers available. Skipped DNS seeding.\n");
return;
}
}
const vector<CDNSSeedData>& vSeeds = Params().DNSSeeds();
int found = 0;
LogPrintf("Loading addresses from DNS seeds (could take a while)\n");
BOOST_FOREACH (const CDNSSeedData& seed, vSeeds) {
if (HaveNameProxy()) {
AddOneShot(seed.host);
} else {
vector<CNetAddr> vIPs;
vector<CAddress> vAdd;
if (LookupHost(seed.host.c_str(), vIPs)) {
BOOST_FOREACH (CNetAddr& ip, vIPs) {
int nOneDay = 24 * 3600;
CAddress addr = CAddress(CService(ip, Params().GetDefaultPort()));
addr.nTime = GetTime() - 3 * nOneDay - GetRand(4 * nOneDay); // use a random age between 3 and 7 days old
vAdd.push_back(addr);
found++;
}
}
addrman.Add(vAdd, CNetAddr(seed.name, true));
}
}
LogPrintf("%d addresses found from DNS seeds\n", found);
}
void DumpAddresses()
{
int64_t nStart = GetTimeMillis();
CAddrDB adb;
adb.Write(addrman);
LogPrint("net", "Flushed %d addresses to peers.dat %dms\n",
addrman.size(), GetTimeMillis() - nStart);
}
void DumpData()
{
DumpAddresses();
DumpBanlist();
}
void static ProcessOneShot()
{
string strDest;
{
LOCK(cs_vOneShots);
if (vOneShots.empty())
return;
strDest = vOneShots.front();
vOneShots.pop_front();
}
CAddress addr;
CSemaphoreGrant grant(*semOutbound, true);
if (grant) {
if (!OpenNetworkConnection(addr, &grant, strDest.c_str(), true))
AddOneShot(strDest);
}
}
void ThreadOpenConnections()
{
// Connect to specific addresses
if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) {
for (int64_t nLoop = 0;; nLoop++) {
ProcessOneShot();
BOOST_FOREACH (string strAddr, mapMultiArgs["-connect"]) {
CAddress addr;
OpenNetworkConnection(addr, NULL, strAddr.c_str());
for (int i = 0; i < 10 && i < nLoop; i++) {
MilliSleep(500);
}
}
MilliSleep(500);
}
}
// Initiate network connections
int64_t nStart = GetTime();
while (true) {
ProcessOneShot();
MilliSleep(500);
CSemaphoreGrant grant(*semOutbound);
boost::this_thread::interruption_point();
// Add seed nodes if DNS seeds are all down (an infrastructure attack?).
if (addrman.size() == 0 && (GetTime() - nStart > 60)) {
static bool done = false;
if (!done) {
LogPrintf("Adding fixed seed nodes as DNS doesn't seem to be available.\n");
addrman.Add(Params().FixedSeeds(), CNetAddr("127.0.0.1"));
done = true;
}
}
//
// Choose an address to connect to based on most recently seen
//
CAddress addrConnect;
// Only connect out to one peer per network group (/16 for IPv4).
// Do this here so we don't have to critsect vNodes inside mapAddresses critsect.
int nOutbound = 0;
set<vector<unsigned char> > setConnected;
{
LOCK(cs_vNodes);
BOOST_FOREACH (CNode* pnode, vNodes) {
if (!pnode->fInbound) {
setConnected.insert(pnode->addr.GetGroup());
nOutbound++;
}
}
}
int64_t nANow = GetAdjustedTime();
int nTries = 0;
while (true) {
CAddress addr = addrman.Select();
// if we selected an invalid address, restart
if (!addr.IsValid() || setConnected.count(addr.GetGroup()) || IsLocal(addr))
break;
// If we didn't find an appropriate destination after trying 100 addresses fetched from addrman,
// stop this loop, and let the outer loop run again (which sleeps, adds seed nodes, recalculates
// already-connected network ranges, ...) before trying new addrman addresses.
nTries++;
if (nTries > 100)
break;
if (IsLimited(addr))
continue;
// only consider very recently tried nodes after 30 failed attempts
if (nANow - addr.nLastTry < 600 && nTries < 30)
continue;
// do not allow non-default ports, unless after 50 invalid addresses selected already
if (addr.GetPort() != Params().GetDefaultPort() && nTries < 50)
continue;
addrConnect = addr;
break;
}
if (addrConnect.IsValid())
OpenNetworkConnection(addrConnect, &grant);
}
}
void ThreadOpenAddedConnections()
{
{
LOCK(cs_vAddedNodes);
vAddedNodes = mapMultiArgs["-addnode"];
}
if (HaveNameProxy()) {
while (true) {
list<string> lAddresses(0);
{
LOCK(cs_vAddedNodes);
BOOST_FOREACH (string& strAddNode, vAddedNodes)
lAddresses.push_back(strAddNode);
}
BOOST_FOREACH (string& strAddNode, lAddresses) {
CAddress addr;
CSemaphoreGrant grant(*semOutbound);
OpenNetworkConnection(addr, &grant, strAddNode.c_str());
MilliSleep(500);
}
MilliSleep(120000); // Retry every 2 minutes
}
}
for (unsigned int i = 0; true; i++) {
list<string> lAddresses(0);
{
LOCK(cs_vAddedNodes);
BOOST_FOREACH (string& strAddNode, vAddedNodes)
lAddresses.push_back(strAddNode);
}
list<vector<CService> > lservAddressesToAdd(0);
BOOST_FOREACH (string& strAddNode, lAddresses) {
vector<CService> vservNode(0);
if (Lookup(strAddNode.c_str(), vservNode, Params().GetDefaultPort(), fNameLookup, 0)) {
lservAddressesToAdd.push_back(vservNode);
{
LOCK(cs_setservAddNodeAddresses);
BOOST_FOREACH (CService& serv, vservNode)
setservAddNodeAddresses.insert(serv);
}
}
}
// Attempt to connect to each IP for each addnode entry until at least one is successful per addnode entry
// (keeping in mind that addnode entries can have many IPs if fNameLookup)
{
LOCK(cs_vNodes);
BOOST_FOREACH (CNode* pnode, vNodes)
for (list<vector<CService> >::iterator it = lservAddressesToAdd.begin(); it != lservAddressesToAdd.end(); it++)
BOOST_FOREACH (CService& addrNode, *(it))
if (pnode->addr == addrNode) {
it = lservAddressesToAdd.erase(it);
it--;
break;
}
}
BOOST_FOREACH (vector<CService>& vserv, lservAddressesToAdd) {
CSemaphoreGrant grant(*semOutbound);
OpenNetworkConnection(CAddress(vserv[i % vserv.size()]), &grant);
MilliSleep(500);
}
MilliSleep(120000); // Retry every 2 minutes
}
}
// if successful, this moves the passed grant to the constructed node
bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant* grantOutbound, const char* pszDest, bool fOneShot)
{
//
// Initiate outbound network connection
//
boost::this_thread::interruption_point();
if (!pszDest) {
if (IsLocal(addrConnect) ||
FindNode((CNetAddr)addrConnect) || CNode::IsBanned(addrConnect) ||
FindNode(addrConnect.ToStringIPPort()))
return false;
} else if (FindNode(pszDest))
return false;
CNode* pnode = ConnectNode(addrConnect, pszDest);
boost::this_thread::interruption_point();
if (!pnode)
return false;
if (grantOutbound)
grantOutbound->MoveTo(pnode->grantOutbound);
pnode->fNetworkNode = true;
if (fOneShot)
pnode->fOneShot = true;
return true;
}
void ThreadMessageHandler()
{
boost::mutex condition_mutex;
boost::unique_lock<boost::mutex> lock(condition_mutex);
SetThreadPriority(THREAD_PRIORITY_BELOW_NORMAL);
while (true) {
vector<CNode*> vNodesCopy;
{
LOCK(cs_vNodes);
vNodesCopy = vNodes;
BOOST_FOREACH (CNode* pnode, vNodesCopy) {
pnode->AddRef();
}
}
// Poll the connected nodes for messages
CNode* pnodeTrickle = NULL;
if (!vNodesCopy.empty())
pnodeTrickle = vNodesCopy[GetRand(vNodesCopy.size())];
bool fSleep = true;
BOOST_FOREACH (CNode* pnode, vNodesCopy) {
if (pnode->fDisconnect)
continue;
// Receive messages
{
TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);
if (lockRecv) {
if (!g_signals.ProcessMessages(pnode))
pnode->CloseSocketDisconnect();
if (pnode->nSendSize < SendBufferSize()) {
if (!pnode->vRecvGetData.empty() || (!pnode->vRecvMsg.empty() && pnode->vRecvMsg[0].complete())) {
fSleep = false;
}
}
}
}
boost::this_thread::interruption_point();
// Send messages
{
TRY_LOCK(pnode->cs_vSend, lockSend);
if (lockSend)
g_signals.SendMessages(pnode, pnode == pnodeTrickle || pnode->fWhitelisted);
}
boost::this_thread::interruption_point();
}
{
LOCK(cs_vNodes);
BOOST_FOREACH (CNode* pnode, vNodesCopy)
pnode->Release();
}
if (fSleep)
messageHandlerCondition.timed_wait(lock, boost::posix_time::microsec_clock::universal_time() + boost::posix_time::milliseconds(100));
}
}
// ppcoin: stake minter thread
void static ThreadStakeMinter()
{
boost::this_thread::interruption_point();
LogPrintf("ThreadStakeMinter started\n");
CWallet* pwallet = pwalletMain;
try {
BitcoinMiner(pwallet, true);
boost::this_thread::interruption_point();
} catch (std::exception& e) {
LogPrintf("ThreadStakeMinter() exception \n");
} catch (...) {
LogPrintf("ThreadStakeMinter() error \n");
}
LogPrintf("ThreadStakeMinter exiting,\n");
}
bool BindListenPort(const CService& addrBind, string& strError, bool fWhitelisted)
{
strError = "";
int nOne = 1;
// Create socket for listening for incoming connections
struct sockaddr_storage sockaddr;
socklen_t len = sizeof(sockaddr);
if (!addrBind.GetSockAddr((struct sockaddr*)&sockaddr, &len)) {
strError = strprintf("Error: Bind address family for %s not supported", addrBind.ToString());
LogPrintf("%s\n", strError);
return false;
}
SOCKET hListenSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
if (hListenSocket == INVALID_SOCKET) {
strError = strprintf("Error: Couldn't open socket for incoming connections (socket returned error %s)", NetworkErrorString(WSAGetLastError()));
LogPrintf("%s\n", strError);
return false;
}
if (!IsSelectableSocket(hListenSocket)) {
strError = "Error: Couldn't create a listenable socket for incoming connections";
LogPrintf("%s\n", strError);
return false;
}
#ifndef WIN32
#ifdef SO_NOSIGPIPE
// Different way of disabling SIGPIPE on BSD
setsockopt(hListenSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&nOne, sizeof(int));
#endif
// Allow binding if the port is still in TIME_WAIT state after
// the program was closed and restarted. Not an issue on windows!
setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (void*)&nOne, sizeof(int));
#endif
// Set to non-blocking, incoming connections will also inherit this
if (!SetSocketNonBlocking(hListenSocket, true)) {
strError = strprintf("BindListenPort: Setting listening socket to non-blocking failed, error %s\n", NetworkErrorString(WSAGetLastError()));
LogPrintf("%s\n", strError);
return false;
}
// some systems don't have IPV6_V6ONLY but are always v6only; others do have the option
// and enable it by default or not. Try to enable it, if possible.
if (addrBind.IsIPv6()) {
#ifdef IPV6_V6ONLY
#ifdef WIN32
setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&nOne, sizeof(int));
#else
setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&nOne, sizeof(int));
#endif
#endif
#ifdef WIN32
int nProtLevel = PROTECTION_LEVEL_UNRESTRICTED;
setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_PROTECTION_LEVEL, (const char*)&nProtLevel, sizeof(int));
#endif
}
if (::bind(hListenSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR) {
int nErr = WSAGetLastError();
if (nErr == WSAEADDRINUSE)
strError = strprintf(_("Unable to bind to %s on this computer. SMARTBLOCK Core is probably already running."), addrBind.ToString());
else
strError = strprintf(_("Unable to bind to %s on this computer (bind returned error %s)"), addrBind.ToString(), NetworkErrorString(nErr));
LogPrintf("%s\n", strError);
CloseSocket(hListenSocket);
return false;
}
LogPrintf("Bound to %s\n", addrBind.ToString());
// Listen for incoming connections
if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR) {
strError = strprintf(_("Error: Listening for incoming connections failed (listen returned error %s)"), NetworkErrorString(WSAGetLastError()));
LogPrintf("%s\n", strError);
CloseSocket(hListenSocket);
return false;
}
vhListenSocket.push_back(ListenSocket(hListenSocket, fWhitelisted));
if (addrBind.IsRoutable() && fDiscover && !fWhitelisted)
AddLocal(addrBind, LOCAL_BIND);
return true;
}
void static Discover(boost::thread_group& threadGroup)
{
if (!fDiscover)
return;
#ifdef WIN32
// Get local host IP
char pszHostName[256] = "";
if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR) {
vector<CNetAddr> vaddr;
if (LookupHost(pszHostName, vaddr)) {
BOOST_FOREACH (const CNetAddr& addr, vaddr) {
if (AddLocal(addr, LOCAL_IF))
LogPrintf("%s: %s - %s\n", __func__, pszHostName, addr.ToString());
}
}
}
#else
// Get local host ip
struct ifaddrs* myaddrs;
if (getifaddrs(&myaddrs) == 0) {
for (struct ifaddrs* ifa = myaddrs; ifa != NULL; ifa = ifa->ifa_next) {
if (ifa->ifa_addr == NULL) continue;
if ((ifa->ifa_flags & IFF_UP) == 0) continue;
if (strcmp(ifa->ifa_name, "lo") == 0) continue;
if (strcmp(ifa->ifa_name, "lo0") == 0) continue;
if (ifa->ifa_addr->sa_family == AF_INET) {
struct sockaddr_in* s4 = (struct sockaddr_in*)(ifa->ifa_addr);
CNetAddr addr(s4->sin_addr);
if (AddLocal(addr, LOCAL_IF))
LogPrintf("%s: IPv4 %s: %s\n", __func__, ifa->ifa_name, addr.ToString());
} else if (ifa->ifa_addr->sa_family == AF_INET6) {
struct sockaddr_in6* s6 = (struct sockaddr_in6*)(ifa->ifa_addr);
CNetAddr addr(s6->sin6_addr);
if (AddLocal(addr, LOCAL_IF))
LogPrintf("%s: IPv6 %s: %s\n", __func__, ifa->ifa_name, addr.ToString());
}
}
freeifaddrs(myaddrs);
}
#endif
}
void StartNode(boost::thread_group& threadGroup, CScheduler& scheduler)
{
uiInterface.InitMessage(_("Loading addresses..."));
// Load addresses for peers.dat
int64_t nStart = GetTimeMillis();
{
CAddrDB adb;
if (!adb.Read(addrman))
LogPrintf("Invalid or missing peers.dat; recreating\n");
}
//try to read stored banlist
CBanDB bandb;
banmap_t banmap;
if (!bandb.Read(banmap))
LogPrintf("Invalid or missing banlist.dat; recreating\n");
CNode::SetBanned(banmap); //thread save setter
CNode::SetBannedSetDirty(false); //no need to write down just read or nonexistent data
CNode::SweepBanned(); //sweap out unused entries
// Initialize random numbers. Even when rand() is only usable for trivial use-cases most nodes should have a different
// seed after all the file-IO done at this point. Should be good enough even when nodes are started via scripts.
srand(time(NULL));
LogPrintf("Loaded %i addresses from peers.dat %dms\n",
addrman.size(), GetTimeMillis() - nStart);
fAddressesInitialized = true;
if (semOutbound == NULL) {
// initialize semaphore
int nMaxOutbound = min(MAX_OUTBOUND_CONNECTIONS, nMaxConnections);
semOutbound = new CSemaphore(nMaxOutbound);
}
if (pnodeLocalHost == NULL)
pnodeLocalHost = new CNode(INVALID_SOCKET, CAddress(CService("127.0.0.1", 0), nLocalServices));
Discover(threadGroup);
//
// Start threads
//
if (!GetBoolArg("-dnsseed", true))
LogPrintf("DNS seeding disabled\n");
else
threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "dnsseed", &ThreadDNSAddressSeed));
// Map ports with UPnP
MapPort(GetBoolArg("-upnp", DEFAULT_UPNP));
// Send and receive from sockets, accept connections
threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "net", &ThreadSocketHandler));
// Initiate outbound connections from -addnode
threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "addcon", &ThreadOpenAddedConnections));
// Initiate outbound connections
threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "opencon", &ThreadOpenConnections));
// Process messages
threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "msghand", &ThreadMessageHandler));
// Dump network addresses
scheduler.scheduleEvery(&DumpData, DUMP_ADDRESSES_INTERVAL);
// ppcoin:mint proof-of-stake blocks in the background
if (GetBoolArg("-staking", true))
threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "stakemint", &ThreadStakeMinter));
}
bool StopNode()
{
LogPrintf("StopNode()\n");
MapPort(false);
if (semOutbound)
for (int i = 0; i < MAX_OUTBOUND_CONNECTIONS; i++)
semOutbound->post();
if (fAddressesInitialized) {
DumpData();
fAddressesInitialized = false;
}
return true;
}
class CNetCleanup
{
public:
CNetCleanup() {}
~CNetCleanup()
{
// Close sockets
BOOST_FOREACH (CNode* pnode, vNodes)
if (pnode->hSocket != INVALID_SOCKET)
CloseSocket(pnode->hSocket);
BOOST_FOREACH (ListenSocket& hListenSocket, vhListenSocket)
if (hListenSocket.socket != INVALID_SOCKET)
if (!CloseSocket(hListenSocket.socket))
LogPrintf("CloseSocket(hListenSocket) failed with error %s\n", NetworkErrorString(WSAGetLastError()));
// clean up some globals (to help leak detection)
BOOST_FOREACH (CNode* pnode, vNodes)
delete pnode;
BOOST_FOREACH (CNode* pnode, vNodesDisconnected)
delete pnode;
vNodes.clear();
vNodesDisconnected.clear();
vhListenSocket.clear();
delete semOutbound;
semOutbound = NULL;
delete pnodeLocalHost;
pnodeLocalHost = NULL;
#ifdef WIN32
// Shutdown Windows Sockets
WSACleanup();
#endif
}
} instance_of_cnetcleanup;
void CExplicitNetCleanup::callCleanup()
{
// Explicit call to destructor of CNetCleanup because it's not implicitly called
// when the wallet is restarted from within the wallet itself.
CNetCleanup* tmp = new CNetCleanup();
delete tmp; // Stroustrup's gonna kill me for that
}
void RelayTransaction(const CTransaction& tx)
{
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss.reserve(10000);
ss << tx;
RelayTransaction(tx, ss);
}
void RelayTransaction(const CTransaction& tx, const CDataStream& ss)
{
CInv inv(MSG_TX, tx.GetHash());
{
LOCK(cs_mapRelay);
// Expire old relay messages
while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime()) {
mapRelay.erase(vRelayExpiration.front().second);
vRelayExpiration.pop_front();
}
// Save original serialized message so newer versions are preserved
mapRelay.insert(std::make_pair(inv, ss));
vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv));
}
LOCK(cs_vNodes);
BOOST_FOREACH (CNode* pnode, vNodes) {
if (!pnode->fRelayTxes)
continue;
LOCK(pnode->cs_filter);
if (pnode->pfilter) {
if (pnode->pfilter->IsRelevantAndUpdate(tx))
pnode->PushInventory(inv);
} else
pnode->PushInventory(inv);
}
}
void RelayTransactionLockReq(const CTransaction& tx, bool relayToAll)
{
CInv inv(MSG_TXLOCK_REQUEST, tx.GetHash());
//broadcast the new lock
LOCK(cs_vNodes);
BOOST_FOREACH (CNode* pnode, vNodes) {
if (!relayToAll && !pnode->fRelayTxes)
continue;
pnode->PushMessage("ix", tx);
}
}
void RelayInv(CInv& inv)
{
LOCK(cs_vNodes);
BOOST_FOREACH (CNode* pnode, vNodes){
if((pnode->nServices==NODE_BLOOM_WITHOUT_MN) && inv.IsMasterNodeType())continue;
if (pnode->nVersion >= ActiveProtocol())
pnode->PushInventory(inv);
}
}
void CNode::RecordBytesRecv(uint64_t bytes)
{
LOCK(cs_totalBytesRecv);
nTotalBytesRecv += bytes;
}
void CNode::RecordBytesSent(uint64_t bytes)
{
LOCK(cs_totalBytesSent);
nTotalBytesSent += bytes;
}
uint64_t CNode::GetTotalBytesRecv()
{
LOCK(cs_totalBytesRecv);
return nTotalBytesRecv;
}
uint64_t CNode::GetTotalBytesSent()
{
LOCK(cs_totalBytesSent);
return nTotalBytesSent;
}
void CNode::Fuzz(int nChance)
{
if (!fSuccessfullyConnected) return; // Don't fuzz initial handshake
if (GetRand(nChance) != 0) return; // Fuzz 1 of every nChance messages
switch (GetRand(3)) {
case 0:
// xor a random byte with a random value:
if (!ssSend.empty()) {
CDataStream::size_type pos = GetRand(ssSend.size());
ssSend[pos] ^= (unsigned char)(GetRand(256));
}
break;
case 1:
// delete a random byte:
if (!ssSend.empty()) {
CDataStream::size_type pos = GetRand(ssSend.size());
ssSend.erase(ssSend.begin() + pos);
}
break;
case 2:
// insert a random byte at a random position
{
CDataStream::size_type pos = GetRand(ssSend.size());
char ch = (char)GetRand(256);
ssSend.insert(ssSend.begin() + pos, ch);
}
break;
}
// Chance of more than one change half the time:
// (more changes exponentially less likely):
Fuzz(2);
}
//
// CAddrDB
//
CAddrDB::CAddrDB()
{
pathAddr = GetDataDir() / "peers.dat";
}
bool CAddrDB::Write(const CAddrMan& addr)
{
// Generate random temporary filename
unsigned short randv = 0;
GetRandBytes((unsigned char*)&randv, sizeof(randv));
std::string tmpfn = strprintf("peers.dat.%04x", randv);
// serialize addresses, checksum data up to that point, then append csum
CDataStream ssPeers(SER_DISK, CLIENT_VERSION);
ssPeers << FLATDATA(Params().MessageStart());
ssPeers << addr;
uint256 hash = Hash(ssPeers.begin(), ssPeers.end());
ssPeers << hash;
// open output file, and associate with CAutoFile
boost::filesystem::path pathAddr = GetDataDir() / "peers.dat";
FILE* file = fopen(pathAddr.string().c_str(), "wb");
CAutoFile fileout(file, SER_DISK, CLIENT_VERSION);
if (fileout.IsNull())
return error("%s : Failed to open file %s", __func__, pathAddr.string());
// Write and commit header, data
try {
fileout << ssPeers;
} catch (std::exception& e) {
return error("%s : Serialize or I/O error - %s", __func__, e.what());
}
FileCommit(fileout.Get());
fileout.fclose();
return true;
}
bool CAddrDB::Read(CAddrMan& addr)
{
// open input file, and associate with CAutoFile
FILE* file = fopen(pathAddr.string().c_str(), "rb");
CAutoFile filein(file, SER_DISK, CLIENT_VERSION);
if (filein.IsNull())
return error("%s : Failed to open file %s", __func__, pathAddr.string());
// use file size to size memory buffer
uint64_t fileSize = boost::filesystem::file_size(pathAddr);
uint64_t dataSize = fileSize - sizeof(uint256);
// Don't try to resize to a negative number if file is small
if (fileSize >= sizeof(uint256))
dataSize = fileSize - sizeof(uint256);
vector<unsigned char> vchData;
vchData.resize(dataSize);
uint256 hashIn;
// read data and checksum from file
try {
filein.read((char*)&vchData[0], dataSize);
filein >> hashIn;
} catch (std::exception& e) {
return error("%s : Deserialize or I/O error - %s", __func__, e.what());
}
filein.fclose();
CDataStream ssPeers(vchData, SER_DISK, CLIENT_VERSION);
// verify stored checksum matches input data
uint256 hashTmp = Hash(ssPeers.begin(), ssPeers.end());
if (hashIn != hashTmp)
return error("%s : Checksum mismatch, data corrupted", __func__);
unsigned char pchMsgTmp[4];
try {
// de-serialize file header (network specific magic number) and ..
ssPeers >> FLATDATA(pchMsgTmp);
// ... verify the network matches ours
if (memcmp(pchMsgTmp, Params().MessageStart(), sizeof(pchMsgTmp)))
return error("%s : Invalid network magic number", __func__);
// de-serialize address data into one CAddrMan object
ssPeers >> addr;
} catch (std::exception& e) {
return error("%s : Deserialize or I/O error - %s", __func__, e.what());
}
return true;
}
unsigned int ReceiveFloodSize() { return 1000 * GetArg("-maxreceivebuffer", 5 * 1000); }
unsigned int SendBufferSize() { return 1000 * GetArg("-maxsendbuffer", 1 * 1000); }
CNode::CNode(SOCKET hSocketIn, CAddress addrIn, std::string addrNameIn, bool fInboundIn) : ssSend(SER_NETWORK, INIT_PROTO_VERSION), setAddrKnown(5000)
{
nServices = 0;
hSocket = hSocketIn;
nRecvVersion = INIT_PROTO_VERSION;
nLastSend = 0;
nLastRecv = 0;
nSendBytes = 0;
nRecvBytes = 0;
nTimeConnected = GetTime();
nTimeOffset = 0;
addr = addrIn;
addrName = addrNameIn == "" ? addr.ToStringIPPort() : addrNameIn;
nVersion = 0;
strSubVer = "";
fWhitelisted = false;
fOneShot = false;
fClient = false; // set by version message
fInbound = fInboundIn;
fNetworkNode = false;
fSuccessfullyConnected = false;
fDisconnect = false;
nRefCount = 0;
nSendSize = 0;
nSendOffset = 0;
hashContinue = 0;
nStartingHeight = -1;
fGetAddr = false;
fRelayTxes = false;
setInventoryKnown.max_size(SendBufferSize() / 1000);
pfilter = new CBloomFilter();
nPingNonceSent = 0;
nPingUsecStart = 0;
nPingUsecTime = 0;
fPingQueued = false;
fObfuScationMaster = false;
{
LOCK(cs_nLastNodeId);
id = nLastNodeId++;
}
if (fLogIPs)
LogPrint("net", "Added connection to %s peer=%d\n", addrName, id);
else
LogPrint("net", "Added connection peer=%d\n", id);
// Be shy and don't send version until we hear
if (hSocket != INVALID_SOCKET && !fInbound)
PushVersion();
GetNodeSignals().InitializeNode(GetId(), this);
}
CNode::~CNode()
{
CloseSocket(hSocket);
if (pfilter)
delete pfilter;
GetNodeSignals().FinalizeNode(GetId());
}
void CNode::AskFor(const CInv& inv)
{
if (mapAskFor.size() > MAPASKFOR_MAX_SZ)
return;
// We're using mapAskFor as a priority queue,
// the key is the earliest time the request can be sent
int64_t nRequestTime;
limitedmap<CInv, int64_t>::const_iterator it = mapAlreadyAskedFor.find(inv);
if (it != mapAlreadyAskedFor.end())
nRequestTime = it->second;
else
nRequestTime = 0;
LogPrint("net", "askfor %s %d (%s) peer=%d\n", inv.ToString(), nRequestTime, DateTimeStrFormat("%H:%M:%S", nRequestTime / 1000000), id);
// Make sure not to reuse time indexes to keep things in the same order
int64_t nNow = GetTimeMicros() - 1000000;
static int64_t nLastTime;
++nLastTime;
nNow = std::max(nNow, nLastTime);
nLastTime = nNow;
// Each retry is 2 minutes after the last
nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow);
if (it != mapAlreadyAskedFor.end())
mapAlreadyAskedFor.update(it, nRequestTime);
else
mapAlreadyAskedFor.insert(std::make_pair(inv, nRequestTime));
mapAskFor.insert(std::make_pair(nRequestTime, inv));
}
void CNode::BeginMessage(const char* pszCommand) EXCLUSIVE_LOCK_FUNCTION(cs_vSend)
{
ENTER_CRITICAL_SECTION(cs_vSend);
assert(ssSend.size() == 0);
ssSend << CMessageHeader(pszCommand, 0);
LogPrint("net", "sending: %s ", SanitizeString(pszCommand));
}
void CNode::AbortMessage() UNLOCK_FUNCTION(cs_vSend)
{
ssSend.clear();
LEAVE_CRITICAL_SECTION(cs_vSend);
LogPrint("net", "(aborted)\n");
}
void CNode::EndMessage() UNLOCK_FUNCTION(cs_vSend)
{
// The -*messagestest options are intentionally not documented in the help message,
// since they are only used during development to debug the networking code and are
// not intended for end-users.
if (mapArgs.count("-dropmessagestest") && GetRand(GetArg("-dropmessagestest", 2)) == 0) {
LogPrint("net", "dropmessages DROPPING SEND MESSAGE\n");
AbortMessage();
return;
}
if (mapArgs.count("-fuzzmessagestest"))
Fuzz(GetArg("-fuzzmessagestest", 10));
if (ssSend.size() == 0) {
LEAVE_CRITICAL_SECTION(cs_vSend);
return;
}
// Set the size
unsigned int nSize = ssSend.size() - CMessageHeader::HEADER_SIZE;
memcpy((char*)&ssSend[CMessageHeader::MESSAGE_SIZE_OFFSET], &nSize, sizeof(nSize));
// Set the checksum
uint256 hash = Hash(ssSend.begin() + CMessageHeader::HEADER_SIZE, ssSend.end());
unsigned int nChecksum = 0;
memcpy(&nChecksum, &hash, sizeof(nChecksum));
assert(ssSend.size() >= CMessageHeader::CHECKSUM_OFFSET + sizeof(nChecksum));
memcpy((char*)&ssSend[CMessageHeader::CHECKSUM_OFFSET], &nChecksum, sizeof(nChecksum));
LogPrint("net", "(%d bytes) peer=%d\n", nSize, id);
std::deque<CSerializeData>::iterator it = vSendMsg.insert(vSendMsg.end(), CSerializeData());
ssSend.GetAndClear(*it);
nSendSize += (*it).size();
// If write queue empty, attempt "optimistic write"
if (it == vSendMsg.begin())
SocketSendData(this);
LEAVE_CRITICAL_SECTION(cs_vSend);
}
//
// CBanDB
//
CBanDB::CBanDB()
{
pathBanlist = GetDataDir() / "banlist.dat";
}
bool CBanDB::Write(const banmap_t& banSet)
{
// Generate random temporary filename
unsigned short randv = 0;
GetRandBytes((unsigned char*)&randv, sizeof(randv));
std::string tmpfn = strprintf("banlist.dat.%04x", randv);
// serialize banlist, checksum data up to that point, then append csum
CDataStream ssBanlist(SER_DISK, CLIENT_VERSION);
ssBanlist << FLATDATA(Params().MessageStart());
ssBanlist << banSet;
uint256 hash = Hash(ssBanlist.begin(), ssBanlist.end());
ssBanlist << hash;
// open temp output file, and associate with CAutoFile
boost::filesystem::path pathTmp = GetDataDir() / tmpfn;
FILE *file = fopen(pathTmp.string().c_str(), "wb");
CAutoFile fileout(file, SER_DISK, CLIENT_VERSION);
if (fileout.IsNull())
return error("%s: Failed to open file %s", __func__, pathTmp.string());
// Write and commit header, data
try {
fileout << ssBanlist;
}
catch (const std::exception& e) {
return error("%s: Serialize or I/O error - %s", __func__, e.what());
}
FileCommit(fileout.Get());
fileout.fclose();
// replace existing banlist.dat, if any, with new banlist.dat.XXXX
if (!RenameOver(pathTmp, pathBanlist))
return error("%s: Rename-into-place failed", __func__);
return true;
}
bool CBanDB::Read(banmap_t& banSet)
{
// open input file, and associate with CAutoFile
FILE *file = fopen(pathBanlist.string().c_str(), "rb");
CAutoFile filein(file, SER_DISK, CLIENT_VERSION);
if (filein.IsNull())
return error("%s: Failed to open file %s", __func__, pathBanlist.string());
// use file size to size memory buffer
uint64_t fileSize = boost::filesystem::file_size(pathBanlist);
uint64_t dataSize = 0;
// Don't try to resize to a negative number if file is small
if (fileSize >= sizeof(uint256))
dataSize = fileSize - sizeof(uint256);
vector<unsigned char> vchData;
vchData.resize(dataSize);
uint256 hashIn;
// read data and checksum from file
try {
filein.read((char *)&vchData[0], dataSize);
filein >> hashIn;
}
catch (const std::exception& e) {
return error("%s: Deserialize or I/O error - %s", __func__, e.what());
}
filein.fclose();
CDataStream ssBanlist(vchData, SER_DISK, CLIENT_VERSION);
// verify stored checksum matches input data
uint256 hashTmp = Hash(ssBanlist.begin(), ssBanlist.end());
if (hashIn != hashTmp)
return error("%s: Checksum mismatch, data corrupted", __func__);
unsigned char pchMsgTmp[4];
try {
// de-serialize file header (network specific magic number) and ..
ssBanlist >> FLATDATA(pchMsgTmp);
// ... verify the network matches ours
if (memcmp(pchMsgTmp, Params().MessageStart(), sizeof(pchMsgTmp)))
return error("%s: Invalid network magic number", __func__);
// de-serialize address data into one CAddrMan object
ssBanlist >> banSet;
}
catch (const std::exception& e) {
return error("%s: Deserialize or I/O error - %s", __func__, e.what());
}
return true;
}
void DumpBanlist()
{
CNode::SweepBanned(); // clean unused entries (if bantime has expired)
if (!CNode::BannedSetIsDirty())
return;
int64_t nStart = GetTimeMillis();
CBanDB bandb;
banmap_t banmap;
CNode::GetBanned(banmap);
if (bandb.Write(banmap)) {
CNode::SetBannedSetDirty(false);
}
LogPrint("net", "Flushed %d banned node ips/subnets to banlist.dat %dms\n",
banmap.size(), GetTimeMillis() - nStart);
}
| [
"[email protected]"
] | |
27c821e709ffdbcd5e2d83a3150891264eac03b6 | 60063ed46d687e2bc78c6451856ba35493543faf | /CortanaMorpion/IA.h | 0e0add61d86df057e1efa05dee32f064a944d6d9 | [] | no_license | MinZhang20171225/Cortana | 4278cbbc528976bd22d514bc45d8b97f22c8ae19 | d8921a24571cd14b2e3253970bab895ff760d240 | refs/heads/master | 2021-05-14T06:54:07.659646 | 2015-01-03T00:23:01 | 2015-01-03T00:23:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 188 | h | #pragma once
#include "Morpion.h"
class IA
{
protected:
int shape_;
Morpion *morpion_;
bool first_;
public:
IA();
~IA();
virtual int eval() = 0;
virtual void calculIA() = 0;
};
| [
"[email protected]"
] | |
973c84ff27e379c6c1209b2b2be03abd23c580d0 | 697b13b5682243a2f974cbd4b3de714a83465d59 | /task2.cpp | 36ec7828f77e1c3b534a97b1d3d4be6299d80cb7 | [] | no_license | ytiolllok/labs_cpp | a2cf1e7342dd9ac4a4b9aad7d007337f210f108f | 06ddaaa486b1ba0540f18984af20e107099f18db | refs/heads/master | 2023-04-12T00:32:55.322774 | 2021-05-16T14:46:46 | 2021-05-16T14:46:46 | 334,892,146 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 551 | cpp | /******************************************************************************
Online C++ Compiler.
Code, Compile, Run and Debug C++ program online.
Write your code in this editor and press "Run" button to compile and execute it.
*******************************************************************************/
#include <iostream>
#include <math.h>
using namespace std;
double a = 0;
double b = 0;
double c = 0;
int main()
{
cin >> a >> b;
c = sqrt(a*a + b*b);
cout << c;
return(0);
}
| [
"[email protected]"
] | |
2b4a780d6569e402b532e53b33656321346fa076 | a3bdcf514214d4b91bc7205365e3028045308725 | /code/树/1。二叉树遍历/144. Binary Tree Preorder Traversal/117. Populating Next Right Pointers in Each Node II/源.cpp | ddef063f784abbffbee1959ae77fe688c2d61dae | [] | no_license | jiye-algorithm/LeetCode | 137ecde4955492a9c0a3977289d621d8ab5d98da | 7a45be3285d8232e1388e550d052a174ba462227 | refs/heads/master | 2021-08-27T21:48:27.154411 | 2021-08-21T02:20:10 | 2021-08-21T02:20:10 | 184,591,853 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 670 | cpp | #include <vector>
#include <queue>
#include <algorithm>
using namespace std;
struct TreeLinkNode {
int val;
TreeLinkNode *left, *right, *next;
TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
};
class Solution {
public:
void connect(TreeLinkNode *root) {
if (root == nullptr) return;
queue<TreeLinkNode*> cur, next;
TreeLinkNode* p = root;
cur.push(p);
while (!cur.empty())
{
while (!cur.empty())
{
p = cur.front(); cur.pop();
if (!cur.empty())
p->next = cur.front();
if (p->left) next.push(p->left);
if (p->right) next.push(p->right);
}
p->next = nullptr;
swap(cur, next);
}
}
}; | [
"[email protected]"
] | |
2387beb020ee6f28432717d65affe1c967d495ae | 6cd69d24276d418be9fb3ad5fbb850bdcaca9f7e | /oss_src/lambda/rcpplambda_worker.cpp | 2a49d107d7da37484e6107d5e5b50c418f2e87fd | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | charles2648/SFrame | e8cd14074932635af067aa20a86d1a9cbf7cf698 | 43fdd3ed9fde4ec0f26d548b5f1eebb4cdf1bea5 | refs/heads/master | 2021-01-18T11:23:21.447110 | 2016-03-16T08:51:56 | 2016-03-16T08:51:56 | 54,029,970 | 1 | 0 | null | 2016-03-16T12:29:02 | 2016-03-16T12:29:02 | null | UTF-8 | C++ | false | false | 3,832 | cpp | /*
* Copyright (C) 2015 Dato, Inc.
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the BSD license. See the LICENSE file for details.
*/
#include <boost/program_options.hpp>
#include <cppipc/server/comm_server.hpp>
#include <logger/logger.hpp>
#include <lambda/rcpplambda.hpp>
#include <process/process_util.hpp>
#include <parallel/thread_pool.hpp>
#include <RInside.h>
#ifdef HAS_TCMALLOC
#include <google/malloc_extension.h>
#endif
namespace po = boost::program_options;
using namespace graphlab;
#ifdef HAS_TCMALLOC
/**
* If TCMalloc is available, we try to release memory back to the
* system every 15 seconds or so. TCMalloc is otherwise somewhat...
* aggressive about keeping memory around.
*/
static bool stop_memory_release_thread = false;
graphlab::mutex memory_release_lock;
graphlab::conditional memory_release_cond;
void memory_release_loop() {
memory_release_lock.lock();
while (!stop_memory_release_thread) {
memory_release_cond.timedwait(memory_release_lock, 15);
MallocExtension::instance()->ReleaseFreeMemory();
}
memory_release_lock.unlock();
}
#endif
void print_help(std::string program_name, po::options_description& desc) {
std::cerr << "Lambda Server\n"
<< desc << "\n"
<< "Example: " << program_name << " ipc:///tmp/lambda_worker\n"
<< "Example: " << program_name << " tcp://127.0.0.1:10020\n"
<< "Example: " << program_name << " tcp://*:10020\n"
<< "Example: " << program_name << " tcp://127.0.0.1:10020 tcp://127.0.0.1:10021\n"
<< "Example: " << program_name << " ipc:///tmp/unity_test_server --auth_token=secretkey\n"
<< "Example: " << program_name << " ipc:///tmp/unity_test_server ipc:///tmp/unity_status secretkey\n";
}
int main(int argc, char** argv) {
size_t parent_pid = get_parent_pid();
// Options
std::string program_name = argv[0];
std::string server_address;
boost::program_options::variables_map vm;
po::options_description desc("Allowed options");
desc.add_options()
("help", "Print this help message.")
("server_address",
po::value<std::string>(&server_address)->implicit_value(server_address),
"This must be a valid ZeroMQ endpoint and "
"is the address the server listens on");
po::positional_options_description positional;
positional.add("server_address", 1);
// try to parse the command line options
try {
po::command_line_parser parser(argc, argv);
parser.options(desc);
parser.positional(positional);
po::parsed_options parsed = parser.run();
po::store(parsed, vm);
po::notify(vm);
} catch(std::exception& error) {
std::cout << "Invalid syntax:\n"
<< "\t" << error.what()
<< "\n\n" << std::endl
<< "Description:"
<< std::endl;
print_help(program_name, desc);
return 1;
}
if(vm.count("help")) {
print_help(program_name, desc);
return 0;
}
// initialize a new R instance and pass to unity server
RInside * R = new RInside(0, 0);
cppipc::comm_server server(std::vector<std::string>(), "", server_address);
// pass a R instance to unity server
server.register_type<graphlab::lambda::lambda_evaluator_interface>([&]() {
return new graphlab::lambda::rcpplambda_evaluator(R);
});
server.start();
#ifdef HAS_TCMALLOC
graphlab::thread memory_release_thread;
memory_release_thread.launch(memory_release_loop);
#endif
wait_for_parent_exit(parent_pid);
#ifdef HAS_TCMALLOC
stop_memory_release_thread = true;
memory_release_cond.signal();
memory_release_thread.join();
#endif
}
| [
"[email protected]"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.