blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 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 listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6398de66ab94a5d8a31094a2767efacf96a6bd63 | 8a5b7bfcc386c92a04ed4ec8f8e15ab503294a77 | /Material.cpp | 51cba667391b5a6b8ad8772f73b7af57d1ef3655 | [] | no_license | goatofcheese/FineTea | 18030ed78c0dfc5edf75187fbd60b411d1ec2fbd | 0638e069454df3ece61f4471b585b9a3191446e9 | refs/heads/master | 2016-09-06T03:57:53.309374 | 2014-04-23T16:18:11 | 2014-04-23T16:18:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,192 | cpp | /*
* Material.cpp
*
*
* Created by Donald House on 9/8/08.
* Copyright 2008 Clemson University. All rights reserved.
*
*/
#include "Material.h"
#ifdef __APPLE__
# include <GLUT/glut.h>
#else
# include <GL/glut.h>
#endif
#include <cstring>
Material::Material(char *mname){
name = NULL;
setName(mname);
amap = dmap = smap = NULL;
alpha = n = 1.0;
illum_model = 1;
textureid = -1;
setProperties(0.2, 0.8, 0, 1);
}
Material::Material(const Color &ambient, const Color &diffuse, const Color &specular,
double spexp){
name = NULL;
amap = dmap = smap = NULL;
alpha = n = 1.0;
illum_model = 1;
setProperties(ambient, diffuse, specular, spexp);
}
void Material::setName(char *mname){
delete name;
if(mname == NULL)
name = NULL;
else{
name = new char[strlen(mname) + 1];
strcpy(name, mname);
}
}
bool Material::isNamed(char *mname){
if(name == NULL || mname == NULL)
return false;
return strcmp(mname, name) == 0;
}
void Material::setProperties(const Color &ambient, const Color &diffuse, const Color &specular,
double spexp){
a = ambient;
d = diffuse;
s = specular;
exp = spexp;
}
void Material::setProperties(double ambient, double diffuse, double specular,
double spexp){
Color ca, cd, cs;
ca.set(ambient, ambient, ambient);
cd.set(diffuse, diffuse, diffuse);
cs.set(specular, specular, specular);
setProperties(ca, cd, cs, spexp);
}
void Material::setK(int k, const Color &c){
switch(k){
case 0:
a = c;
break;
case 1:
d = c;
break;
case 2:
s = c;
break;
}
}
void Material::setTransmission(const Color &c){
t = c;
}
void Material::setExp(double spexp){
exp = spexp;
}
void Material::setAlpha(double alfa){
alpha = alfa;
}
void Material::setIOR(double ior){
n = ior;
}
void Material::setIllum(int i){
illum_model = i;
}
void Material::setMap(int mtype, Pixmap *p){
switch(mtype){
case 0:
amap = p;
break;
case 1:
dmap = p;
break;
case 2:
smap = p;
break;
}
}
void Material::createTexture(){
if(illum_model < 1 || dmap == NULL || textureid != -1)
return;
glGenTextures(1, &textureid); // OpenGL ID for this texture
glBindTexture(GL_TEXTURE_2D, textureid);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, dmap->NCols(), dmap->NRows(),
GL_RGBA, GL_UNSIGNED_BYTE, dmap->Pixels());
}
ostream& operator<< (ostream& os, const Material& m){
os << "[Material " << m.name << ": a = " << m.a << ", d = " << m.d <<
", s = " << m.s << ", exp = " << m.exp << "\n";
os << " alpha = " << m.alpha << ", t = " << m.t <<
", illum model = " << m.illum_model << "\n";
os << " textures: (" << (m.amap? "ambient": "no ambient") << ", " <<
(m.dmap? "diffuse": "no diffuse") << ", " <<
(m.smap? "specular": "no specular") << ")";
os << "]";
return os;
}
| [
"james@ubuntu.(none)"
] | james@ubuntu.(none) |
46fe11010c2e03f375f37190e647ad5121d4989d | 48a31b8838ec23cdab88613d5d50f1f1a5f1b6bb | /src/catchup/ApplyBufferedLedgersWork.h | 5acb1917e6c42ae9c1b4cbf0f19acc0b0a656b38 | [
"BSD-3-Clause",
"MIT",
"BSL-1.0",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause"
] | permissive | errmin98/stellar-core | 38dbb42aabcd642f88c744005e9be8ecb4806b3a | 9227c85518ea84c27530bc96d325afcb080ca2a5 | refs/heads/master | 2023-02-22T07:59:20.292937 | 2021-01-24T16:06:11 | 2021-01-24T16:06:11 | 260,118,920 | 2 | 0 | NOASSERTION | 2020-04-30T05:09:28 | 2020-04-30T05:09:28 | null | UTF-8 | C++ | false | false | 711 | h | // Copyright 2019 Stellar Development Foundation and contributors. Licensed
// under the Apache License, Version 2.0. See the COPYING file at the root
// of this distribution or at http://www.apache.org/licenses/LICENSE-2.0
#pragma once
#include "herder/LedgerCloseData.h"
#include "work/BasicWork.h"
#include "work/ConditionalWork.h"
namespace stellar
{
class ApplyBufferedLedgersWork : public BasicWork
{
std::shared_ptr<ConditionalWork> mConditionalWork;
public:
ApplyBufferedLedgersWork(Application& app);
std::string getStatus() const override;
protected:
void onReset() override;
State onRun() override;
bool
onAbort() override
{
return true;
};
};
} | [
"siddharth@stellar.org"
] | siddharth@stellar.org |
fd536d8604c9f62578ff2bdd27dfbe307e820e60 | e9c4e3e37e03081c255525d777559f63b5fe56a7 | /CPlusPlusFundamentals/STL-AssociativeConteiners/HomeWork/01.EvenOddInMap/01.EvenOddinMap.cpp | a56f73d906f6b6845372ee27a05652cf4002408e | [
"MIT"
] | permissive | bozhikovstanislav/Cpp-SoftUni | 7111b56ece7fd2773a9892afb590fd7e550959a6 | 6562d15b9e3a550b11566630a1bc1ec65670bff7 | refs/heads/master | 2020-04-14T15:56:13.260889 | 2019-01-20T10:04:49 | 2019-01-20T10:04:49 | 163,940,361 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 803 | cpp | #include <iostream>
#include <string>
#include <algorithm>
#include <utility>
#include <map>
bool isEven(int number) {
bool isEven = false;
if (number % 2 == 0) {
isEven = true;
}
return isEven;
}
int main() {
int anumber = 0;
std::cin >> anumber;
std::string oddevenWord[] = {"ODD", "EVEN"};
std::map<int, std::string> a;
for ( int i = 0; i < anumber; ++i ) {
if (isEven(i)) {
std::string str = oddevenWord[1];
a.insert(std::pair<int, std::string>(i, str));
} else {
std::string str = oddevenWord[0];
a.insert(std::pair<int, std::string>(i, str));
}
}
for ( auto &j : a ) {
std::cout << "KEY: " << j.first << " VALUE: " << j.second << std::endl;
}
return 0;
} | [
"bozhikov.stanidlav@gmail.com"
] | bozhikov.stanidlav@gmail.com |
218f86f9abbcbd4035511e39b9f47da2b8af9e60 | c3e5c04bdce1836710f247c8b9f7fdb0b26e07c5 | /complexTextureLighting/ofApp.cpp | 7da701aa0cedf853515d3aaa77873315fba70546 | [] | no_license | harryhaaren/creativeCoding | b9be103d3f54ca272557d3643d676c71d5df4452 | 99672014db15c8403e9f25e074b21fbb0c64cdf2 | refs/heads/master | 2020-05-20T03:10:23.886620 | 2015-03-20T01:34:18 | 2015-03-20T01:34:18 | 30,035,423 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,615 | cpp | #include "ofApp.h"
//--------------------------------------------------------------
void ofApp::setup()
{
ofSetVerticalSync(true);
ofSetFrameRate(60);
ofBackground(10, 10, 10);
ofEnableDepthTest();
// turn on smooth lighting //
bSmoothLighting = true;
ofSetSmoothLighting(true);
// lets make a high-res sphere //
// default is 20 //
ofSetSphereResolution(128);
// radius of the sphere //
radius = 180.f;
center.set(ofGetWidth()*.5, ofGetHeight()*.5, 0);
// Point lights emit light in all directions //
// set the diffuse color, color reflected from the light source //
pointLight.setDiffuseColor( ofColor(0.f, 255.f, 0.f));
// specular color, the highlight/shininess color //
pointLight.setSpecularColor( ofColor(255.f, 255.f, 0.f));
pointLight.setPointLight();
spotLight.setDiffuseColor( ofColor(255.f, 0.f, 0.f));
spotLight.setSpecularColor( ofColor(255.f, 255.f, 255.f));
// turn the light into spotLight, emit a cone of light //
spotLight.setSpotlight();
// size of the cone of emitted light, angle between light axis and side of cone //
// angle range between 0 - 90 in degrees //
spotLight.setSpotlightCutOff( 50 );
// rate of falloff, illumitation decreases as the angle from the cone axis increases //
// range 0 - 128, zero is even illumination, 128 is max falloff //
spotLight.setSpotConcentration( 45 );
// Directional Lights emit light based on their orientation, regardless of their position //
directionalLight.setDiffuseColor(ofColor(0.f, 0.f, 255.f));
directionalLight.setSpecularColor(ofColor(255.f, 255.f, 255.f));
directionalLight.setDirectional();
// set the direction of the light
// set it pointing from left to right -> //
directionalLight.setOrientation( ofVec3f(0, 90, 0) );
bShiny = true;
// shininess is a value between 0 - 128, 128 being the most shiny //
material.setShininess( 120 );
// the light highlight of the material //
material.setSpecularColor(ofColor(255, 255, 255, 255));
bPointLight = bSpotLight = bDirLight = true;
// tex coords for 3D objects in OF are from 0 -> 1, not 0 -> image.width
// so we must disable the arb rectangle call to allow 0 -> 1
ofDisableArbTex();
// load an image to use as the texture //
ofLogoImage.loadImage("of.png");
bUseTexture = true;
}
//--------------------------------------------------------------
void ofApp::update()
{
pointLight.setPosition(cos(ofGetElapsedTimef()*.6f) * radius * 2 + center.x,
sin(ofGetElapsedTimef()*.8f) * radius * 2 + center.y,
-cos(ofGetElapsedTimef()*.8f) * radius * 2 + center.z);
spotLight.setOrientation( ofVec3f( 0, cos(ofGetElapsedTimef()) * RAD_TO_DEG, 0) );
spotLight.setPosition( mouseX, mouseY, 200);
}
//--------------------------------------------------------------
void ofApp::draw()
{
// enable lighting //
ofEnableLighting();
// enable the material, so that it applies to all 3D objects before material.end() call //
material.begin();
// activate the lights //
if (bPointLight) pointLight.enable();
if (bSpotLight) spotLight.enable();
if (bDirLight) directionalLight.enable();
// grab the texture reference and bind it //
// this will apply the texture to all drawing (vertex) calls before unbind() //
if(bUseTexture) ofLogoImage.getTextureReference().bind();
ofSetColor(255, 255, 255, 255);
ofPushMatrix();
ofTranslate(center.x, center.y, center.z-300);
ofRotate(ofGetElapsedTimef() * .8 * RAD_TO_DEG, 0, 1, 0);
ofDrawSphere( 0,0,0, radius);
ofPopMatrix();
ofPushMatrix();
ofTranslate(300, 300, cos(ofGetElapsedTimef()*1.4) * 300.f);
ofRotate(ofGetElapsedTimef()*.6 * RAD_TO_DEG, 1, 0, 0);
ofRotate(ofGetElapsedTimef()*.8 * RAD_TO_DEG, 0, 1, 0);
ofDrawBox(0, 0, 0, 60);
ofPopMatrix();
ofPushMatrix();
ofTranslate(center.x, center.y, -900);
ofRotate(ofGetElapsedTimef() * .2 * RAD_TO_DEG, 0, 1, 0);
ofDrawBox( 0, 0, 0, 850);
ofPopMatrix();
if(bUseTexture) ofLogoImage.getTextureReference().unbind();
if (!bPointLight) pointLight.disable();
if (!bSpotLight) spotLight.disable();
if (!bDirLight) directionalLight.disable();
material.end();
// turn off lighting //
ofDisableLighting();
ofSetColor( pointLight.getDiffuseColor() );
if(bPointLight) pointLight.draw();
ofSetColor(255, 255, 255);
ofSetColor( spotLight.getDiffuseColor() );
if(bSpotLight) spotLight.draw();
ofSetColor(255, 255, 255);
ofDrawBitmapString("Point Light On (1) : "+ofToString(bPointLight) +"\n"+
"Spot Light On (2) : "+ofToString(bSpotLight) +"\n"+
"Directional Light On (3) : "+ofToString(bDirLight)+"\n"+
"Shiny Objects On (s) : "+ofToString(bShiny)+"\n"+
"Spot Light Cutoff (up/down) : "+ofToString(spotLight.getSpotlightCutOff(),0)+"\n"+
"Spot Light Concentration (right/left) : " + ofToString(spotLight.getSpotConcentration(),0)+"\n"+
"Smooth Lighting enabled (x) : "+ofToString(bSmoothLighting,0)+"\n"+
"Textured (t) : "+ofToString(bUseTexture,0),
20, 20);
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
switch (key) {
case '1':
bPointLight = !bPointLight;
break;
case '2':
bSpotLight = !bSpotLight;
break;
case '3':
bDirLight = !bDirLight;
break;
case 's':
bShiny = !bShiny;
if (bShiny) material.setShininess( 120 );
else material.setShininess( 30 );
break;
case 'x':
bSmoothLighting = !bSmoothLighting;
ofSetSmoothLighting(bSmoothLighting);
break;
case 't':
bUseTexture = !bUseTexture;
break;
case OF_KEY_UP:
// setSpotlightCutOff is clamped between 0 - 90 degrees //
spotLight.setSpotlightCutOff(spotLight.getSpotlightCutOff()+1);
break;
case OF_KEY_DOWN:
// setSpotlightCutOff is clamped between 0 - 90 degrees //
spotLight.setSpotlightCutOff(spotLight.getSpotlightCutOff()-1);
break;
case OF_KEY_RIGHT:
// setSpotConcentration is clamped between 0 - 128 //
spotLight.setSpotConcentration(spotLight.getSpotConcentration()+1);
break;
case OF_KEY_LEFT:
// setSpotConcentration is clamped between 0 - 128 //
spotLight.setSpotConcentration(spotLight.getSpotConcentration()-1);
break;
default:
break;
}
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y ){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
| [
"harryhaaren@gmail.com"
] | harryhaaren@gmail.com |
49cb8036eff199e67a3d158ae0f0819ccce7aa90 | e45d2fec02e5989bf222163de19f54f9df40992c | /Aoria/JsonManager.h | 9afb3ccfee45599206a56c466787fac56de648f2 | [] | no_license | Mixxy3k/Aoria-2.0 | 7bdd915e3ef5768fecd99011339800249057c2e4 | 0839b70096ee708e682417f7859e348630f4037f | refs/heads/master | 2020-05-09T15:01:17.879940 | 2019-04-21T11:30:21 | 2019-04-21T11:30:21 | 181,218,275 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,065 | h | #pragma once
#include "ConsoleManager.h"
#include "nlohmann JSON Library/json.hpp"
#include <iostream>
#include <fstream>
#include <string>
#include <filesystem>
#include <map>
#include <vector>
using json = nlohmann::json;
namespace fs = std::experimental::filesystem;
using namespace std;
class JsonMenager {
public:
JsonMenager(ConsoleManager *consoleManager);
~JsonMenager();
std::string getDataFromJson(const string jsonName, const std::string name, std::vector<string> subname = std::vector<string> {"TEST"}, bool onlyCheck = false, bool asInt = false);
int getDataFromJsonAsInt(const string jsonName, const std::string name, std::vector<string> subname);
sf::Color getColorFromJson(const string jsonName, const std::string name, std::vector<string> subname);
bool loadAllJsons();
string jsonOutOfRange = "OUT OF RANGE";
private:
ConsoleManager *consoleManager;
std::map<std::string, json> *jsons = new std::map<std::string, json>;
std::map<string, bool>* mustBeJsosn = new std::map<string, bool>;
std::fstream file;
fs::path jsonsPath;
}; | [
"mixxy@op.pl"
] | mixxy@op.pl |
cca896dc31be048ebf8cb4c284afe2f4fad0c698 | 6f16621b74eae36fe867786556244592140dda07 | /Code/Graph.cpp | f62be5e7802c6be819601249ba14bd97c94ca41d | [] | no_license | Anthony11234/Maps-Graphs | cf28c054fad2d099029a6a4489a9f054659232b8 | f10c7660664ed15717d459191a28b2e2461ee19d | refs/heads/master | 2023-04-16T04:22:46.894380 | 2017-12-11T20:32:58 | 2017-12-11T20:32:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,763 | cpp |
// Graph.cpp
// STL_DirGraph
//
// Created by Bill Komanetsky on 11/27/17.
// Copyright © 2017 Bill Komanetsky. All rights reserved.
//
#include <stack>
#include "Graph.hpp"
#include <iostream>
Graph::Graph() {
initGraph();
}//Graph()
//The Destructor will go through each array entry and delete the vertex at that array
//position if it has been created. It will then clear the vector of adjacent vertecies
//You don't need to worry about loosing those vertices because they will be deleted
//when we get to their position in the array
Graph::~Graph() {
for (int i=0; i<STARTSIZE; i++) {
if (edgeArray[i].first != nullptr) {
delete edgeArray[i].first; //Delete the vertex
edgeArray[i].first = nullptr; //Set its poiner to nullptr since it's been deleted
edgeArray[i].second->clear(); //Clear the vector of adjacent vertices
delete edgeArray[i].second; //Now, delete the dynamically allocated vector
}//if
else {}
}//for i
}//~Graph()
//Set everything up in the array so we can store vertices and their adjacent vertices (edges)
//Each of the array's memory locations shall contain a pair of data
// first: A vertex structure
// second: A vector of vertex structures
// Each of these will be the end-point of an edge eminating from the vertex (first)
void Graph::initGraph(void) {
for (int i=0; i<STARTSIZE; i++) {
edgeArray[i].first = nullptr;
edgeArray[i].second = new vector<GraphVertex*>;
}//for
}//initGraph
//Return the pointer to a vector of vertex pointers which shall contain all
//of the end-points for each edge eminating from the vertex (first) in that pair
vector<GraphVertex*>* Graph::getDestVertex(int sourceVertex) {
if (sourceVertex >= STARTSIZE) {
return nullptr;
}//if
else {
return edgeArray[sourceVertex].second;
}//else
}//getDestVertex(int)
//Add a vertex to the array if that vertex hasn't yet been created
//Will return doing nothing if that vertex has already been setup, or, if the value
//which the vertex shall contain is greater than the arrayt capacity or less than zero
void Graph::addVertex(int vertexValue) {
//If the vertex value is larger than the graph capacity or
// the vertex already exists, then leave.
if (vertexValue >= STARTSIZE || vertexValue < 0 || this->edgeArray[vertexValue].first != nullptr) {
return;
}//if
else {
//Create a new vertex and populate its value
GraphVertex* tempVertex = new GraphVertex;
tempVertex->Value = vertexValue;
tempVertex->Visited = false;
//Now, add it to the first of the pair
edgeArray[vertexValue].first = tempVertex;
}//else
}//addVertex
//Add a directed edge
//Will do nothing if the range of the source or destination values are beyond the size of the
//array, or, if the source or destination vertices have not yet been added, in other words, if
//you try to create an edge for a vertex that does not yet exist, this function will do nothing
void Graph::addEdgeDir(int source, int destination) {
//if the source or destination vertex values are grater than the size of the array of vectors
//or if the soruce or destination vertecis do not exist, then return
if (source >= STARTSIZE || source < 0 || destination >= STARTSIZE || destination < 0 ||
edgeArray[source].first == nullptr ||
edgeArray[destination].first == nullptr) {
return;
}//if
else {
//Add to the source vector an existing vertex located at destination in the array
edgeArray[source].second->push_back(edgeArray[destination].first);
}//else
}//adEdge(int, int)
//Add a directed edge
//Will do nothing if the range of the source or destination values are beyond the size of the
//array, or, if the source or destination vertices have not yet been added, in other words, if
//you try to create an edge for a vertex that does not yet exist, this function will do nothing
void Graph::addEdgeUnDir(int source, int destination) {
//if the source or destination vertex values are grater than the size of the array of vectors
//or if the soruce or destination vertecis do not exist, then return
if (source >= STARTSIZE || source < 0 || destination >= STARTSIZE || destination < 0 ||
edgeArray[source].first == nullptr ||
edgeArray[destination].first == nullptr) {
return;
}//if
else {
//Add to the source vector an existing vertex located at destination in the array
edgeArray[source].second->push_back(edgeArray[destination].first);
//Add to the destination vector an existing vertex located at source in the array
edgeArray[destination].second->push_back(edgeArray[source].first);
}//else
}//adEdge(int, int)
//Do a Depth first Search for the graph
//This function will return a vector of vertices showing how the graph was navigated
//If you try to start with a vertex which does not exist, this function will return
//an empty vector
vector<GraphVertex*> Graph::searchDFS(int start) {
vector<GraphVertex*> returnVector;
stack <GraphVertex*> tempStack;
vector <GraphVertex*> *temp;
GraphVertex *ptr;
if(start > STARTSIZE || start < 0 || edgeArray[start].first == nullptr){
cout << "No Position at Pounter " << start << endl;
return returnVector;
}
else{
clearAllVisited();
tempStack.push(edgeArray[start].first);
while(!tempStack.empty()){
ptr = tempStack.top();
tempStack.pop();
if (!edgeArray[ptr->Value].first->Visited){
returnVector.push_back(edgeArray[ptr->Value].first);
edgeArray[ptr->Value].first->Visited = true;
}
temp = getDestVertex(ptr->Value);
for (int i = 0; i < temp->size(); i++) {
if (!edgeArray[temp->at(i)->Value].first->Visited) {
tempStack.push(temp->at(i));
}
}
}
}
return returnVector;
}//searchDFS
//Do a Breadth first Search for the graph
//This function will return a vector of vertices showing how the graph was navigated
//If you try to start with a vertex which does not exist, this function will return
//an empty vector
vector<GraphVertex*> Graph::searchBFS(int start) {
vector<GraphVertex*> returnVector;
queue<GraphVertex*> tempQueue;
vector<GraphVertex*> *temp;
GraphVertex* ptr;
tempQueue.push(edgeArray[start].first);
if(start > STARTSIZE || start < 0 || edgeArray[start].first == nullptr){
cout << "No Position at Pounter " << start << endl;
return returnVector;
}
else{
clearAllVisited();
tempQueue.push(edgeArray[start].first);
while(!tempQueue.empty()){
ptr = tempQueue.front();
tempQueue.pop();
if (!edgeArray[ptr->Value].first->Visited){
returnVector.push_back(edgeArray[ptr->Value].first);
edgeArray[ptr->Value].first->Visited = true;
}
temp = getDestVertex(ptr->Value);
for (int i = 0; i < temp->size(); i++) {
if (!edgeArray[temp->at(i)->Value].first->Visited) {
tempQueue.push(temp->at(i));
}
}
}
}
return returnVector;
}//searchBFS
//This function shall set to false all vertices visited variable to false
void Graph::clearAllVisited(void) {
for (int i=0; i<STARTSIZE; i++) {
if (edgeArray[i].first != nullptr) {
edgeArray[i].first->Visited = false;
}//if
else {}
}//for
}//clearAllVisited
| [
"adamgonzalez005@gmail.com"
] | adamgonzalez005@gmail.com |
1aed573080bdd957210c87f0fe385da082c6352f | 08fae5bd7f16809b84cf6463693732f2308ab4da | /ETS/EtsEod/EtsEodServer/MsBasketIndex.h | 04f80a47817035c7f36c6dcdc59670bdf11831e2 | [] | no_license | psallandre/IVRM | a7738c31534e1bbff32ded5cfc7330c52b378f19 | 5a674d10caba23b126e9bcea982dee30eee72ee1 | refs/heads/master | 2021-01-21T03:22:33.658311 | 2014-09-24T11:47:10 | 2014-09-24T11:47:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,615 | h | #ifndef __MSBASKETINDEX_H__
#define __MSBASKETINDEX_H__
#include "MsIndex.h"
#include "MsUnd.h"
#include "MsUndWeight.h"
namespace EODMS
{
/////////////////////////////////////////////////////////////////////////////
//
class CMsBasketIndex : public CMsIndex
{
public:
CMsBasketIndex(void)
: m_spUndWeight(new CMsUndWeightColl)
{
}
~CMsBasketIndex(void)
{
}
bool IsBasket()
{
return true;
}
CMsUndWeightCollPtr UndWeight()
{
Trace(EODCO::enTrLogDebug,__FUNCTION__,_T("Enter"));
return m_spUndWeight;
}
CMsUndWeightPtr UndWeight(long nUndID)
{
Trace(EODCO::enTrLogDebug,__FUNCTION__,_T("Enter"));
return GetCollectionItem<CMsUndWeightPtr>(m_spUndWeight, nUndID);
}
unsigned long BasketDivsCount() const
{
Trace(EODCO::enTrLogDebug,__FUNCTION__,_T("Enter"));
return static_cast<unsigned long>(m_vecDivs.size());
}
bool InitBasketDivs(CMsUndByIDCollPtr pUndColl);
void GetBasketDivs(REGULAR_DIVIDENDS* pDivs, unsigned long nMaxCount) const;
void BasketDiv(unsigned long nIndex, REGULAR_DIVIDENDS& aDiv) const;
virtual long FillDivsForCalc(EODCO::EsDoubleVec& vecDivDte, EODCO::EsDoubleVec& vecDivAmt,
long nToday, long nDTE, double& dYield);
protected:
CMsUndWeightCollPtr m_spUndWeight; // underlings weights by underlying ID
RegularDividendVec m_vecDivs;
};
typedef boost::shared_ptr<CMsBasketIndex> CMsBasketIndexPtr;
typedef std::map<long, CMsBasketIndexPtr> CMsBasketIndexColl;
typedef CMsBasketIndexColl::value_type CMsBasketIndexPair;
typedef boost::shared_ptr<CMsBasketIndexColl> CMsBasketIndexCollPtr;
};
#endif //__MSBASKETINDEX_H__ | [
"alex2172@gmail.com"
] | alex2172@gmail.com |
e1b2cc9a67220ab08799d53ec15216ea02e3435e | 6c100784a1a1f43ee1714fb8bacbf6d695a8902c | /src/key.h | 53773e6fbae6208628a6c666857b6ca623342fb8 | [
"MIT"
] | permissive | BITCREXCOIN/BitcrexCoin-Core | 54645084675c12fcac928ed1c59c30e805a1ac5e | 4b51f09b8f999ff7c176524dfc2e6364111bc536 | refs/heads/main | 2023-03-25T04:52:39.603419 | 2021-03-24T04:16:14 | 2021-03-24T04:16:14 | 347,030,863 | 0 | 4 | MIT | 2021-03-22T14:33:04 | 2021-03-12T10:42:17 | C++ | UTF-8 | C++ | false | false | 6,236 | h | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2015-2018 The BITCREXCOIN developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCREXCOIN_KEY_H
#define BITCREXCOIN_KEY_H
#include "allocators.h"
#include "serialize.h"
#include "uint256.h"
#include "pubkey.h"
#include <stdexcept>
#include <vector>
class CPubKey;
struct CExtPubKey;
/**
* secure_allocator is defined in allocators.h
* CPrivKey is a serialized private key, with all parameters included
* (PRIVATE_KEY_SIZE bytes)
*/
typedef std::vector<unsigned char, secure_allocator<unsigned char> > CPrivKey;
/** An encapsulated private key. */
class CKey
{
public:
/**
* secp256k1:
*/
static const unsigned int PRIVATE_KEY_SIZE = 279;
static const unsigned int COMPRESSED_PRIVATE_KEY_SIZE = 214;
/**
* see www.keylength.com
* script supports up to 75 for single byte push
*/
static_assert(
PRIVATE_KEY_SIZE >= COMPRESSED_PRIVATE_KEY_SIZE,
"COMPRESSED_PRIVATE_KEY_SIZE is larger than PRIVATE_KEY_SIZE");
private:
//! Whether this private key is valid. We check for correctness when modifying the key
//! data, so fValid should always correspond to the actual state.
bool fValid;
//! Whether the public key corresponding to this private key is (to be) compressed.
bool fCompressed;
//! The actual byte data
std::vector<unsigned char, secure_allocator<unsigned char> > keydata;
//! Check whether the 32-byte array pointed to be vch is valid keydata.
bool static Check(const unsigned char* vch);
public:
//! Construct an invalid private key.
CKey() : fValid(false), fCompressed(false)
{
// Important: vch must be 32 bytes in length to not break serialization
keydata.resize(32);
}
friend bool operator==(const CKey& a, const CKey& b)
{
return a.fCompressed == b.fCompressed &&
a.size() == b.size() &&
memcmp(a.keydata.data(), b.keydata.data(), a.size()) == 0;
}
//! Initialize using begin and end iterators to byte data.
template <typename T>
void Set(const T pbegin, const T pend, bool fCompressedIn)
{
if (size_t(pend - pbegin) != keydata.size()) {
fValid = false;
} else if (Check(&pbegin[0])) {
memcpy(keydata.data(), (unsigned char*)&pbegin[0], keydata.size());
fValid = true;
fCompressed = fCompressedIn;
} else {
fValid = false;
}
}
//! Simple read-only vector-like interface.
unsigned int size() const { return (fValid ? keydata.size() : 0); }
const unsigned char* begin() const { return keydata.data(); }
const unsigned char* end() const { return keydata.data() + size(); }
//! Check whether this private key is valid.
bool IsValid() const { return fValid; }
//! Check whether the public key corresponding to this private key is (to be) compressed.
bool IsCompressed() const { return fCompressed; }
//! Initialize from a CPrivKey (serialized OpenSSL private key data).
bool SetPrivKey(const CPrivKey& vchPrivKey, bool fCompressed);
//! Generate a new private key using a cryptographic PRNG.
void MakeNewKey(bool fCompressed);
uint256 GetPrivKey_256();
/**
* Convert the private key to a CPrivKey (serialized OpenSSL private key data).
* This is expensive.
*/
CPrivKey GetPrivKey() const;
/**
* Compute the public key from a private key.
* This is expensive.
*/
CPubKey GetPubKey() const;
/**
* Create a DER-serialized signature.
* The test_case parameter tweaks the deterministic nonce.
*/
bool Sign(const uint256& hash, std::vector<unsigned char>& vchSig, uint32_t test_case = 0) const;
/**
* Create a compact signature (65 bytes), which allows reconstructing the used public key.
* The format is one header byte, followed by two times 32 bytes for the serialized r and s values.
* The header byte: 0x1B = first key with even y, 0x1C = first key with odd y,
* 0x1D = second key with even y, 0x1E = second key with odd y,
* add 0x04 for compressed keys.
*/
bool SignCompact(const uint256& hash, std::vector<unsigned char>& vchSig) const;
//! Derive BIP32 child key.
bool Derive(CKey& keyChild, ChainCode &ccChild, unsigned int nChild, const ChainCode& cc) const;
/**
* Verify thoroughly whether a private key and a public key match.
* This is done using a different mechanism than just regenerating it.
*/
bool VerifyPubKey(const CPubKey& vchPubKey) const;
//! Load private key and check that public key matches.
bool Load(const CPrivKey& privkey, const CPubKey& vchPubKey, bool fSkipCheck);
//! Check whether an element of a signature (r or s) is valid.
static bool CheckSignatureElement(const unsigned char* vch, int len, bool half);
};
struct CExtKey {
unsigned char nDepth;
unsigned char vchFingerprint[4];
unsigned int nChild;
ChainCode chaincode;
CKey key;
friend bool operator==(const CExtKey& a, const CExtKey& b)
{
return a.nDepth == b.nDepth &&
memcmp(&a.vchFingerprint[0], &b.vchFingerprint[0], sizeof(vchFingerprint)) == 0 &&
a.nChild == b.nChild &&
a.chaincode == b.chaincode &&
a.key == b.key;
}
void Encode(unsigned char code[BIP32_EXTKEY_SIZE]) const;
void Decode(const unsigned char code[BIP32_EXTKEY_SIZE]);
bool Derive(CExtKey& out, unsigned int nChild) const;
CExtPubKey Neuter() const;
void SetMaster(const unsigned char* seed, unsigned int nSeedLen);
};
/** Initialize the elliptic curve support. May not be called twice without calling ECC_Stop first. */
void ECC_Start(void);
/** Deinitialize the elliptic curve support. No-op if ECC_Start wasn't called first. */
void ECC_Stop(void);
/** Check that required EC support is available at runtime. */
bool ECC_InitSanityCheck(void);
#endif // BITCREXCOIN_KEY_H
| [
"alonewolf2ksk@gmail.com"
] | alonewolf2ksk@gmail.com |
ddbfb6e444d7ac3bd7e9a436f64ec665a4e8d3d0 | c9ecb0ca891e0f2cd980279ba062fc34378c832a | /test/源.cpp | 1f4b37ff8f93091238573f32966e177ef9af5362 | [] | no_license | liuzetianxiadiyi/big-project | 01b08524c1c226a0e6ce2b07f4cfb311d2b28a44 | 5a14c597a753f2651ea953d934eec6be0d3b9cb1 | refs/heads/master | 2020-03-18T13:46:55.911958 | 2018-06-27T05:34:16 | 2018-06-27T05:34:16 | 134,808,173 | 1 | 15 | null | 2018-06-27T17:12:41 | 2018-05-25T05:36:49 | C++ | ISO-8859-7 | C++ | false | false | 3,294 | cpp | #include <iostream>
#include <vector>
#include "class.h"
#include <algorithm>
#include <stdlib.h>
using namespace std;
vector<MyTile> openTile;
vector<MyTile> closeTile;
MyTile colsCheck[10][10]; //΄ύ³υΚΌ»―
vector<Position> FindWay(Position start, Position goal)
{
MyTile& sta = colsCheck[start.x][start.y];
sta.init(NULL,start, goal);
openTile.push_back(sta);
sta.setOpen();
Position pos = start;
//cout << "x=" << pos.x << " y=" << pos.y << endl;
//system("pause");
int count = 0;
while (pos != goal)
{
cout << "x=" << pos.x << " y=" << pos.y << endl;
//system("pause");
colsCheck[pos.x][pos.y].setClose();
closeTile.push_back(*openTile.begin());
openTile.erase(openTile.begin());
int flag_x, flag_y;
for (int i = 0; i < 4; ++i)
{
switch (i)
{
case 0:
flag_x = 1;
flag_y = 0;
break;
case 1:
flag_x = 0;
flag_y = 1;
break;
case 2:
flag_x = -1;
flag_y = 0;
break;
case 3:
flag_x = 0;
flag_y = -1;
break;
}
Position temp;
temp.x = pos.x + flag_x;
temp.y = pos.y + flag_y;
if (colsCheck[temp.x][temp.y].available)
{
MyTile nextWay = colsCheck[temp.x][temp.y];
nextWay.init(&colsCheck[pos.x][pos.y],temp,goal);
nextWay.f_value -= count;
vector<MyTile>::iterator iter;
iter = find(closeTile.begin(), closeTile.end(), nextWay);
//is not in closeTile
if (iter == closeTile.end())
{
vector<MyTile>::iterator it;
it = find(openTile.begin(), openTile.end(), nextWay);
if (it != openTile.end())
{
if (nextWay < *it)
{
*it = nextWay;
colsCheck[temp.x][temp.y] = nextWay;
colsCheck[temp.x][temp.y].setOpen();
}
}
else
{
//cout << "pushback in openTile"<<endl;
colsCheck[temp.x][temp.y] = nextWay;
colsCheck[temp.x][temp.y].setOpen();
openTile.push_back(nextWay);
nextWay.setOpen();
}
}
}
}
sort(openTile.begin(), openTile.end());
pos = openTile.begin()->GetPosition();
putchar(' ');
putchar(' ');
for (int i = 0; i < 10; i++)
{
printf(" %2d", i);
}
for (int j = 0; j < 10; j++)
{
printf("\n\n%2d", j);
for (int i = 0; i < 10; i++)
{
if (!colsCheck[j][i].available)
{
printf(" X");
}
else if (colsCheck[j][i].inClose)
{
printf(" C");
}
else if (colsCheck[j][i].inOpen)
{
printf(" O");
}
else if (colsCheck[j][i].out)
{
printf(" ");
}
}
}
printf("\n\n");
//system("pause");
char c;
cin >> c;
++count;
}
vector<Position> Way;
Way.push_back(goal);
MyTile* temp = &closeTile[closeTile.size()-1];
do
{
Way.push_back(temp->GetPosition());
cout << "x=" << temp->GetPosition().x << " y=" << temp->GetPosition().y << endl;
temp = temp->GetParent();
} while (temp!= NULL);
reverse(Way.begin(), Way.end());
return Way;
}
int main()
{
for (int i = 0; i < 10; ++i)
{
for (int j = 0; j < 10; ++j)
{
colsCheck[i][j].available = true;
colsCheck[i][j].serOut();
}
}
colsCheck[3][5].available = false;
colsCheck[4][5].available = false;
colsCheck[5][5].available = false;
cout << "start" << endl;
//system("pause");
FindWay(Position(5, 2), Position(4, 7));
printf("out");
system("pause");
} | [
"958457134@qq.com"
] | 958457134@qq.com |
88c55fce40d692eb172d1f155926472ab461aab8 | c769df3c7ae8e03a01bbd5b351d2318f990bb212 | /3rd_party/cereal/include/cereal/types/unordered_map.hpp | 68ee9c4a8fecf858ee17c84a6358521d5ec799d7 | [
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | Segs/Segs | 0519ed2bc75963607fcb2d61a7162c1ce3216836 | bccea0b253ddece6254d2c6410ed2c7ec42a86f5 | refs/heads/develop | 2022-12-02T16:50:30.325109 | 2022-11-21T13:37:46 | 2022-11-21T13:37:46 | 8,205,781 | 231 | 113 | BSD-3-Clause | 2023-09-02T15:50:20 | 2013-02-14T19:15:30 | C++ | UTF-8 | C++ | false | false | 1,893 | hpp | /*! \file unordered_map.hpp
\brief Support for types found in \<unordered_map\>
\ingroup STLSupport */
/*
Copyright (c) 2014, Randolph Voorhies, Shane Grant
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of cereal nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL RANDOLPH VOORHIES OR SHANE GRANT 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.
*/
#ifndef CEREAL_TYPES_UNORDERED_MAP_HPP_
#define CEREAL_TYPES_UNORDERED_MAP_HPP_
#include <cereal/types/concepts/pair_associative_container.hpp>
#include <unordered_map>
#endif // CEREAL_TYPES_UNORDERED_MAP_HPP_
| [
"nemerle5@gmail.com"
] | nemerle5@gmail.com |
22be39828b096c5d80b36ffcb50aa4bb18351d63 | ed3c1ef2540e1f5e5738da42cef16537bb697889 | /src/librhino3dm_native/on_material.cpp | e3a26681ccb3a646fc4f132c6cf7f910db00b793 | [
"MIT"
] | permissive | SuperPawer/rhino3dm | 6037c03880ccf8347f1554814e480ccb36509b3d | a023ffccdab84b21b20f82bccf6a1537ecce711f | refs/heads/master | 2023-03-30T11:07:59.951891 | 2021-04-04T22:25:12 | 2021-04-04T22:25:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 26,252 | cpp | #include "stdafx.h"
RH_C_FUNCTION ON_Material* ON_Material_New(const ON_Material* pConstOther)
{
ON_Material* rc = new ON_Material();
if( pConstOther )
*rc = *pConstOther;
return rc;
}
RH_C_FUNCTION void ON_Material_CopyFrom(ON_Material* pThis, const ON_Material* pConstOther)
{
if( pThis && pConstOther )
{
*pThis = *pConstOther;
}
}
RH_C_FUNCTION void ON_Material_Default(ON_Material* pMaterial)
{
if( pMaterial )
*pMaterial = ON_Material::Unset;
}
RH_C_FUNCTION int ON_Material_Index(const ON_Material* pConstMaterial)
{
if( pConstMaterial )
return pConstMaterial->Index();
return -1;
}
RH_C_FUNCTION int ON_Material_FindBitmapTexture(const ON_Material* pConstMaterial, const RHMONO_STRING* filename)
{
int rc = -1;
INPUTSTRINGCOERCE(_filename, filename);
if( pConstMaterial )
{
rc = pConstMaterial->FindTexture(_filename, ON_Texture::TYPE::bitmap_texture);
}
return rc;
}
RH_C_FUNCTION void ON_Material_SetBitmapTexture(ON_Material* pMaterial, int index, const RHMONO_STRING* filename)
{
INPUTSTRINGCOERCE(_filename, filename);
if( pMaterial && index>=0 && index<pMaterial->m_textures.Count())
{
pMaterial->m_textures[index].m_image_file_reference.SetFullPath( _filename, false );
}
}
RH_C_FUNCTION int ON_Material_AddBitmapTexture(ON_Material* pMaterial, const RHMONO_STRING* filename)
{
int rc = -1;
INPUTSTRINGCOERCE(_filename, filename);
if( pMaterial && _filename)
{
rc = pMaterial->AddTexture(_filename, ON_Texture::TYPE::bitmap_texture);
}
return rc;
}
RH_C_FUNCTION int ON_Material_AddBumpTexture(ON_Material* pMaterial, const RHMONO_STRING* filename)
{
int rc = -1;
INPUTSTRINGCOERCE(_filename, filename);
if( pMaterial && _filename)
{
rc = pMaterial->AddTexture(_filename, ON_Texture::TYPE::bump_texture);
}
return rc;
}
RH_C_FUNCTION int ON_Material_AddEnvironmentTexture(ON_Material* pMaterial, const RHMONO_STRING* filename)
{
int rc = -1;
INPUTSTRINGCOERCE(_filename, filename);
if( pMaterial && _filename)
{
rc = pMaterial->AddTexture(_filename, ON_Texture::TYPE::emap_texture);
}
return rc;
}
RH_C_FUNCTION int ON_Material_AddTransparencyTexture(ON_Material* pMaterial, const RHMONO_STRING* filename)
{
int rc = -1;
INPUTSTRINGCOERCE(_filename, filename);
if( pMaterial && _filename)
{
rc = pMaterial->AddTexture(_filename, ON_Texture::TYPE::transparency_texture);
}
return rc;
}
RH_C_FUNCTION bool ON_Material_ModifyTexture(ON_Material* pMaterial, ON_UUID texture_id, const ON_Texture* pConstTexture)
{
bool rc = false;
if( pMaterial && pConstTexture )
{
int index = pMaterial->FindTexture(texture_id);
if( index>=0 )
{
pMaterial->m_textures[index] = *pConstTexture;
rc = true;
}
}
return rc;
}
RH_C_FUNCTION double ON_Material_GetDouble(const ON_Material* pConstMaterial, int which)
{
const int idxShine = 0;
const int idxTransparency = 1;
const int idxIOR = 2;
const int idxReflectivity = 3;
const int idxFresnelIOR = 4;
const int idxRefractionGlossiness = 5;
const int idxReflectionGlossiness = 6;
double rc = 0;
if( pConstMaterial )
{
switch(which)
{
case idxShine:
rc = pConstMaterial->m_shine;
break;
case idxTransparency:
rc = pConstMaterial->m_transparency;
break;
case idxIOR:
rc = pConstMaterial->m_index_of_refraction;
break;
case idxReflectivity:
rc = pConstMaterial->m_reflectivity;
break;
case idxFresnelIOR:
rc = pConstMaterial->m_fresnel_index_of_refraction;
break;
case idxRefractionGlossiness:
rc = pConstMaterial->m_refraction_glossiness;
break;
case idxReflectionGlossiness:
rc = pConstMaterial->m_reflection_glossiness;
break;
default:
break;
}
}
return rc;
}
RH_C_FUNCTION void ON_Material_SetDouble(ON_Material* pMaterial, int which, double val)
{
const int idxShine = 0;
const int idxTransparency = 1;
const int idxIOR = 2;
const int idxReflectivity = 3;
const int idxFresnelIOR = 4;
const int idxRefractionGlossiness = 5;
const int idxReflectionGlossiness = 6;
if( pMaterial )
{
switch(which)
{
case idxShine:
pMaterial->SetShine(val);
break;
case idxTransparency:
pMaterial->SetTransparency(val);
break;
case idxIOR:
pMaterial->m_index_of_refraction = val;
break;
case idxReflectivity:
pMaterial->m_reflectivity = val;
break;
case idxFresnelIOR:
pMaterial->m_fresnel_index_of_refraction = val;
break;
case idxRefractionGlossiness:
pMaterial->m_refraction_glossiness = val;
break;
case idxReflectionGlossiness:
pMaterial->m_reflection_glossiness = val;
break;
default:
break;
}
}
}
RH_C_FUNCTION bool ON_Material_AddTexture(ON_Material* pMaterial, const RHMONO_STRING* filename, int which)
{
bool rc = false;
if (pMaterial && filename)
{
ON_Texture::TYPE tex_type = (ON_Texture::TYPE)which;
int index = pMaterial->FindTexture(nullptr, tex_type);
if (index >= 0)
{
pMaterial->DeleteTexture(nullptr, tex_type);
}
INPUTSTRINGCOERCE(_filename, filename);
rc = pMaterial->AddTexture(_filename, tex_type) >= 0;
}
return rc;
}
RH_C_FUNCTION bool ON_Material_SetTexture(ON_Material* pMaterial, const ON_Texture* pConstTexture, int which)
{
bool rc = false;
if (pMaterial && pConstTexture)
{
ON_Texture::TYPE tex_type = (ON_Texture::TYPE)which;
int index = pMaterial->FindTexture(nullptr, tex_type);
if (index >= 0)
{
pMaterial->DeleteTexture(nullptr, tex_type);
}
ON_Texture texture(*pConstTexture);
texture.m_type = tex_type;
rc = pMaterial->AddTexture(texture) >= 0;
}
return rc;
}
RH_C_FUNCTION int ON_Material_GetTexture(const ON_Material* pConstMaterial, int which)
{
int rc = -1;
if( pConstMaterial )
{
ON_Texture::TYPE tex_type = (ON_Texture::TYPE)which;
rc = pConstMaterial->FindTexture(nullptr, tex_type);
}
return rc;
}
RH_C_FUNCTION int ON_Material_GetTextureCount(const ON_Material* pConstMaterial)
{
if( pConstMaterial )
return pConstMaterial->m_textures.Count();
return 0;
}
RH_C_FUNCTION int ON_Material_PreviewColor(const ON_Material* pConstMaterial)
{
return (int)pConstMaterial->PreviewColor();
}
RH_C_FUNCTION int ON_Material_GetColor( const ON_Material* pConstMaterial, int which )
{
const int idxDiffuse = 0;
const int idxAmbient = 1;
const int idxEmission = 2;
const int idxSpecular = 3;
const int idxReflection = 4;
const int idxTransparent = 5;
int rc = 0;
if( pConstMaterial )
{
unsigned int abgr = 0;
switch(which)
{
case idxDiffuse:
abgr = (unsigned int)(pConstMaterial->m_diffuse);
break;
case idxAmbient:
abgr = (unsigned int)(pConstMaterial->m_ambient);
break;
case idxEmission:
abgr = (unsigned int)(pConstMaterial->m_emission);
break;
case idxSpecular:
abgr = (unsigned int)(pConstMaterial->m_specular);
break;
case idxReflection:
abgr = (unsigned int)(pConstMaterial->m_reflection);
break;
case idxTransparent:
abgr = (unsigned int)(pConstMaterial->m_transparent);
break;
default:
break;
}
rc = (int)abgr;
}
return rc;
}
RH_C_FUNCTION void ON_Material_SetColor( ON_Material* pMaterial, int which, int argb )
{
const int idxDiffuse = 0;
const int idxAmbient = 1;
const int idxEmission = 2;
const int idxSpecular = 3;
const int idxReflection = 4;
const int idxTransparent = 5;
int abgr = ARGB_to_ABGR(argb);
if( pMaterial )
{
switch(which)
{
case idxDiffuse:
pMaterial->m_diffuse = abgr;
break;
case idxAmbient:
pMaterial->m_ambient = abgr;
break;
case idxEmission:
pMaterial->m_emission = abgr;
break;
case idxSpecular:
pMaterial->m_specular = abgr;
break;
case idxReflection:
pMaterial->m_reflection = abgr;
break;
case idxTransparent:
pMaterial->m_transparent = abgr;
break;
default:
break;
}
}
}
RH_C_FUNCTION void ON_Material_GetName(const ON_Material* pConstMaterial, CRhCmnStringHolder* pString)
{
if( pConstMaterial && pString )
{
pString->Set(pConstMaterial->Name());
}
}
RH_C_FUNCTION void ON_Material_SetName(ON_Material* pMaterial, const RHMONO_STRING* name)
{
if( pMaterial )
{
INPUTSTRINGCOERCE(_name, name);
pMaterial->SetName( _name );
}
}
/////////////////////////////////////////////////////////////
RH_C_FUNCTION ON_Texture* ON_Texture_New()
{
return new ON_Texture();
}
RH_C_FUNCTION const ON_Texture* ON_Material_GetTexturePointer(const ON_Material* pConstMaterial, int index)
{
const ON_Texture* rc = nullptr;
if( pConstMaterial && index>=0 )
{
rc = pConstMaterial->m_textures.At(index);
}
return rc;
}
RH_C_FUNCTION int ON_Material_NextBitmapTexture(const ON_Material* pConstMaterial, int index)
{
if( pConstMaterial )
return pConstMaterial->FindTexture(nullptr, ON_Texture::TYPE::bitmap_texture, index);
return -1;
}
RH_C_FUNCTION int ON_Material_NextBumpTexture(const ON_Material* pConstMaterial, int index)
{
if( pConstMaterial )
return pConstMaterial->FindTexture(nullptr, ON_Texture::TYPE::bump_texture, index);
return -1;
}
RH_C_FUNCTION int ON_Material_NextEnvironmentTexture(const ON_Material* pConstMaterial, int index)
{
if( pConstMaterial )
return pConstMaterial->FindTexture(nullptr, ON_Texture::TYPE::emap_texture, index);
return -1;
}
RH_C_FUNCTION int ON_Material_NextTransparencyTexture(const ON_Material* pConstMaterial, int index)
{
if( pConstMaterial )
return pConstMaterial->FindTexture(nullptr, ON_Texture::TYPE::transparency_texture, index);
return -1;
}
#if !defined(RHINO3DM_BUILD)
RH_C_FUNCTION ON_UUID ON_Material_MaterialChannelIdFromIndex(const CRhinoMaterial* pMaterial, int material_channel_index)
{
if (pMaterial == nullptr)
return ON_nil_uuid;
// This code is copied from ON_Material::MaterialChannelIdFromIndex @ 7.x
// 7.x should call the above function directly
for (;;)
{
if (material_channel_index <= 0)
break;
const int count = pMaterial->m_material_channel.Count();
if (count <= 0)
break;
const ON_UuidIndex* a = pMaterial->m_material_channel.Array();
for (const ON_UuidIndex* a1 = a + count; a < a1; ++a)
{
if (material_channel_index == a->m_i)
return a->m_id;
}
break;
}
return ON_nil_uuid;
}
RH_C_FUNCTION int ON_Material_MaterialChannelIndexFromId(CRhinoMaterial* pMaterial, ON_UUID material_channel_id, bool bAddIdIfNotPresent)
{
if (pMaterial == nullptr)
return -1;
// This code is copied from ON_Material::MaterialChannelIndexFromId @ 7.x
// 7.x should call the above function directly
for (;;)
{
if (ON_nil_uuid == material_channel_id)
break;
int unused_index = 0;
const int count = pMaterial->m_material_channel.Count();
if (count > 0)
{
const ON_UuidIndex* a = pMaterial->m_material_channel.Array();
for (const ON_UuidIndex* a1 = a + count; a < a1; ++a)
{
if (material_channel_id == a->m_id)
return a->m_i;
if (a->m_i > unused_index)
unused_index = a->m_i;
}
}
if (false == bAddIdIfNotPresent)
break;
if (count >= 65536)
break; // some rogue actor filled the m_material_channel[] array.
++unused_index;
if (unused_index <= 0 || unused_index > 65536)
{
// int overflow or too big for a material channel index
for (unused_index = 1; unused_index <= count + 1; ++unused_index)
{
if (ON_nil_uuid == ON_Material_MaterialChannelIdFromIndex(pMaterial, unused_index))
break;
}
}
ON_UuidIndex ui;
ui.m_id = material_channel_id;
ui.m_i = unused_index;
pMaterial->m_material_channel.Append(ui);
return ui.m_i;
}
return 0;
}
RH_C_FUNCTION void ON_Material_ClearMaterialChannels(CRhinoMaterial* pMaterial)
{
if (pMaterial != nullptr)
{
pMaterial->m_material_channel.Empty();
}
}
#endif
RH_C_FUNCTION void ON_Texture_GetFileName(const ON_Texture* pConstTexture, CRhCmnStringHolder* pString)
{
if( pConstTexture && pString )
{
pString->Set(pConstTexture->m_image_file_reference.FullPath());
}
}
RH_C_FUNCTION void ON_Texture_SetFileName(ON_Texture* pTexture, const RHMONO_STRING* filename)
{
if( pTexture )
{
INPUTSTRINGCOERCE(_filename, filename);
pTexture->m_image_file_reference.SetFullPath( _filename, false );
}
}
RH_C_FUNCTION const ON_FileReference* ON_Texture_GetFileReference(const ON_Texture* pConstTexture)
{
const ON_FileReference* rc = nullptr;
if (pConstTexture)
{
rc = new ON_FileReference(pConstTexture->m_image_file_reference);
}
return rc;
}
RH_C_FUNCTION bool ON_Texture_SetFileReference(ON_Texture* pTexture, const ON_FileReference* pConstFileReference)
{
bool rc = false;
if (pTexture)
{
if (pConstFileReference)
pTexture->m_image_file_reference = *pConstFileReference;
else
pTexture->m_image_file_reference = ON_FileReference::Unset;
rc = true;
}
return rc;
}
RH_C_FUNCTION ON_UUID ON_Texture_GetId(const ON_Texture* pConstTexture)
{
if( pConstTexture )
return pConstTexture->m_texture_id;
return ON_nil_uuid;
}
RH_C_FUNCTION bool ON_Texture_GetEnabled(const ON_Texture* pConstTexture)
{
if( pConstTexture )
return pConstTexture->m_bOn;
return false;
}
RH_C_FUNCTION void ON_Texture_SetEnabled(ON_Texture* pTexture, bool enabled)
{
if( pTexture )
{
pTexture->m_bOn = enabled;
}
}
RH_C_FUNCTION int ON_Texture_TextureType(const ON_Texture* pConstTexture)
{
if( pConstTexture )
return (int)pConstTexture->m_type;
return (int)ON_Texture::TYPE::no_texture_type;
}
RH_C_FUNCTION void ON_Texture_SetTextureType(ON_Texture* pTexture, int texture_type)
{
if( pTexture )
pTexture->m_type = ON_Texture::TypeFromUnsigned(texture_type);
}
RH_C_FUNCTION int ON_Texture_Mode(const ON_Texture* pConstTexture)
{
if( pConstTexture )
return (int)pConstTexture->m_mode;
return (int)ON_Texture::MODE::no_texture_mode;
}
RH_C_FUNCTION void ON_Texture_SetMode(ON_Texture* pTexture, int value)
{
if( pTexture )
pTexture->m_mode = ON_Texture::ModeFromUnsigned(value);
}
const int IDX_WRAPMODE_U = 0;
const int IDX_WRAPMODE_V = 1;
const int IDX_WRAPMODE_W = 2;
RH_C_FUNCTION int ON_Texture_wrapuvw(const ON_Texture* pConstTexture, int uvw)
{
if ( nullptr == pConstTexture )
pConstTexture = &ON_Texture::Default;
if (uvw == IDX_WRAPMODE_U)
return static_cast<unsigned int>(pConstTexture->m_wrapu);
if (uvw == IDX_WRAPMODE_V)
return static_cast<unsigned int>(pConstTexture->m_wrapv);
if (uvw == IDX_WRAPMODE_W)
return static_cast<unsigned int>(pConstTexture->m_wrapw);
return static_cast<unsigned int>(ON_Texture::WRAP::repeat_wrap);
}
RH_C_FUNCTION void ON_Texture_Set_wrapuvw(ON_Texture* pTexture, int uvw, int value)
{
if( pTexture )
{
if (uvw == IDX_WRAPMODE_U)
pTexture->m_wrapu = ON_Texture::WrapFromUnsigned(value);
else if (uvw == IDX_WRAPMODE_V)
pTexture->m_wrapv = ON_Texture::WrapFromUnsigned(value);
else if (uvw == IDX_WRAPMODE_W)
pTexture->m_wrapw = ON_Texture::WrapFromUnsigned(value);
}
}
RH_C_FUNCTION void ON_Texture_uvw(const ON_Texture* pConstTexture, ON_Xform* instanceXform)
{
if (pConstTexture && instanceXform)
*instanceXform = pConstTexture->m_uvw;
}
RH_C_FUNCTION void ON_Texture_Setuvw(ON_Texture* pTexture, ON_Xform* instanceXform)
{
if (pTexture && instanceXform)
pTexture->m_uvw = *instanceXform;
}
RH_C_FUNCTION void ON_Texture_GetAlphaBlendValues(const ON_Texture* pConstTexture, double* c, double* a0, double* a1, double* a2, double* a3)
{
if( pConstTexture && c && a0 && a1 && a2 && a3 )
{
*c = pConstTexture->m_blend_constant_A;
*a0 = pConstTexture->m_blend_A0;
*a1 = pConstTexture->m_blend_A1;
*a2 = pConstTexture->m_blend_A2;
*a3 = pConstTexture->m_blend_A3;
}
}
RH_C_FUNCTION void ON_Texture_SetAlphaBlendValues(ON_Texture* pTexture, double c, double a0, double a1, double a2, double a3)
{
if( pTexture )
{
pTexture->m_blend_constant_A = c;
pTexture->m_blend_A0 = a0;
pTexture->m_blend_A1 = a1;
pTexture->m_blend_A2 = a2;
pTexture->m_blend_A3 = a3;
}
}
RH_C_FUNCTION void ON_Texture_SetRGBBlendValues(ON_Texture* pTexture, unsigned int color, double a0, double a1, double a2, double a3)
{
if (pTexture)
{
pTexture->m_blend_constant_RGB = ON_Color(color);
pTexture->m_blend_RGB0 = a0;
pTexture->m_blend_RGB1 = a1;
pTexture->m_blend_RGB2 = a2;
pTexture->m_blend_RGB3 = a3;
}
}
RH_C_FUNCTION int ON_Texture_GetMappingChannelId(const ON_Texture* pConstTexture)
{
if (pConstTexture) return pConstTexture->m_mapping_channel_id;
return 0;
}
RH_C_FUNCTION ON_UUID ON_Material_PlugInId(const ON_Material* pConstMaterial)
{
if( pConstMaterial )
return pConstMaterial->MaterialPlugInId();
return ON_nil_uuid;
}
RH_C_FUNCTION void ON_Material_SetPlugInId(ON_Material* pMaterial, ON_UUID id)
{
if( pMaterial )
pMaterial->SetMaterialPlugInId(id);
}
enum MaterialBool : int
{
FresnelReflections,
AlphaTransparency,
DisableLighting
};
RH_C_FUNCTION bool ON_Material_GetBool(const ON_Material* pConstMaterial, enum MaterialBool which)
{
bool rc = false;
if( pConstMaterial )
{
switch(which)
{
case FresnelReflections:
rc = pConstMaterial->FresnelReflections();
break;
case AlphaTransparency:
rc = pConstMaterial->UseDiffuseTextureAlphaForObjectTransparencyTexture();
break;
case DisableLighting:
rc = pConstMaterial->DisableLighting();
break;
}
}
return rc;
}
RH_C_FUNCTION void ON_Material_SetBool(ON_Material* pMaterial, enum MaterialBool which, bool value)
{
if (pMaterial)
{
switch (which) {
case FresnelReflections:
pMaterial->SetFresnelReflections(value);
break;
case AlphaTransparency:
pMaterial->SetUseDiffuseTextureAlphaForObjectTransparencyTexture(value);
break;
case DisableLighting:
pMaterial->SetDisableLighting(value);
break;
}
}
}
RH_C_FUNCTION bool ON_Material_PBR_Supported(const ON_Material* p)
{
return p ? p->IsPhysicallyBased() : false;
}
RH_C_FUNCTION void ON_Material_PBR_SynchronizeLegacyMaterial(ON_Material* p)
{
if (p)
{
p->PhysicallyBased()->SynchronizeLegacyMaterial();
}
}
RH_C_FUNCTION void ON_Material_PBR_BaseColor(const ON_Material* p, ON_4fPoint* pColor)
{
if (p && pColor && p->IsPhysicallyBased())
{
auto c = p->PhysicallyBased()->BaseColor();
pColor->x = c.Red();
pColor->y = c.Green();
pColor->z = c.Blue();
pColor->w = c.Alpha();
}
}
RH_C_FUNCTION void ON_Material_PBR_SetBaseColor(ON_Material* p, ON_4FVECTOR_STRUCT in_color)
{
if (p && p->IsPhysicallyBased())
{
ON_4fColor color;
color.SetRed(in_color.val[0]);
color.SetGreen(in_color.val[1]);
color.SetBlue(in_color.val[2]);
color.SetAlpha(in_color.val[3]);
p->PhysicallyBased()->SetBaseColor(color);
}
}
RH_C_FUNCTION double ON_Material_PBR_Subsurface(const ON_Material* p) { return p && p->IsPhysicallyBased() ? p->PhysicallyBased()->Subsurface() : 0.0; }
RH_C_FUNCTION void ON_Material_PBR_SetSubsurface(ON_Material* p, double d) { if (p && p->IsPhysicallyBased()) { p->PhysicallyBased()->SetSubsurface(d); } }
RH_C_FUNCTION double ON_Material_PBR_SubsurfaceScatteringRadius(const ON_Material* p) { return p && p->IsPhysicallyBased() ? p->PhysicallyBased()->Subsurface() : 0.0; }
RH_C_FUNCTION void ON_Material_PBR_SetSubsurfaceScatteringRadius(ON_Material* p, double d) { if (p && p->IsPhysicallyBased()) { p->PhysicallyBased()->SetSubsurfaceScatteringRadius(d); } }
RH_C_FUNCTION void ON_Material_PBR_SubsurfaceScatteringColor(const ON_Material* p, ON_4fPoint* pColor)
{
if (p && pColor)
{
auto c = p->PhysicallyBased()->SubsurfaceScatteringColor();
pColor->x = c.Red();
pColor->y = c.Green();
pColor->z = c.Blue();
pColor->w = c.Alpha();
}
}
RH_C_FUNCTION void ON_Material_PBR_SetSubsurfaceScatteringColor(ON_Material* p, ON_4FVECTOR_STRUCT in_color)
{
if (p)
{
ON_4fColor color;
color.SetRed(in_color.val[0]);
color.SetGreen(in_color.val[1]);
color.SetBlue(in_color.val[2]);
color.SetAlpha(in_color.val[3]);
p->PhysicallyBased()->SetSubsurfaceScatteringColor(color);
}
}
RH_C_FUNCTION int ON_Material_PBR_BRDF(const ON_Material* p) { return p && p->IsPhysicallyBased() ? (int)p->PhysicallyBased()->BRDF() : (int)ON_PhysicallyBasedMaterial::BRDFs::GGX; }
RH_C_FUNCTION void ON_Material_PBR_SetBRDF(ON_Material* p, int i) { if (p && p->IsPhysicallyBased()) { p->PhysicallyBased()->SetBRDF((ON_PhysicallyBasedMaterial::BRDFs)i); } }
RH_C_FUNCTION double ON_Material_PBR_Metallic(const ON_Material* p) { return p && p->IsPhysicallyBased() ? p->PhysicallyBased()->Metallic() : 0.0; }
RH_C_FUNCTION void ON_Material_PBR_SetMetallic(ON_Material* p, double d) { if (p && p->IsPhysicallyBased()) { p->PhysicallyBased()->SetMetallic(d); } }
RH_C_FUNCTION double ON_Material_PBR_Specular(const ON_Material* p) { return p && p->IsPhysicallyBased() ? p->PhysicallyBased()->Specular() : 0.0; }
RH_C_FUNCTION void ON_Material_PBR_SetSpecular(ON_Material* p, double d) { if (p && p->IsPhysicallyBased()) { p->PhysicallyBased()->SetSpecular(d); } }
RH_C_FUNCTION double ON_Material_PBR_ReflectiveIOR(const ON_Material* p) { return p && p->IsPhysicallyBased() ? p->PhysicallyBased()->ReflectiveIOR() : 0.0; }
RH_C_FUNCTION void ON_Material_PBR_SetReflectiveIOR(ON_Material* p, double d) { if (p && p->IsPhysicallyBased()) { p->PhysicallyBased()->SetReflectiveIOR(d); } }
RH_C_FUNCTION double ON_Material_PBR_SpecularTint(const ON_Material* p) { return p && p->IsPhysicallyBased() ? p->PhysicallyBased()->SpecularTint() : 0.0; }
RH_C_FUNCTION void ON_Material_PBR_SetSpecularTint(ON_Material* p, double d) { if (p && p->IsPhysicallyBased()) { p->PhysicallyBased()->SetSpecularTint(d); } }
RH_C_FUNCTION double ON_Material_PBR_Roughness(const ON_Material* p) { return p && p->IsPhysicallyBased() ? p->PhysicallyBased()->Roughness() : 0.0; }
RH_C_FUNCTION void ON_Material_PBR_SetRoughness(ON_Material* p, double d) { if (p && p->IsPhysicallyBased()) { p->PhysicallyBased()->SetRoughness(d); } }
RH_C_FUNCTION double ON_Material_PBR_Anisotropic(const ON_Material* p) { return p && p->IsPhysicallyBased() ? p->PhysicallyBased()->Anisotropic() : 0.0; }
RH_C_FUNCTION void ON_Material_PBR_SetAnisotropic(ON_Material* p, double d) { if (p) { p->PhysicallyBased()->SetAnisotropic(d); } }
RH_C_FUNCTION double ON_Material_PBR_AnisotropicRotation(const ON_Material* p) { return p && p->IsPhysicallyBased() ? p->PhysicallyBased()->AnisotropicRotation() : 0.0; }
RH_C_FUNCTION void ON_Material_PBR_SetAnisotropicRotation(ON_Material* p, double d) { if (p && p->IsPhysicallyBased()) { p->PhysicallyBased()->SetAnisotropicRotation(d); } }
RH_C_FUNCTION double ON_Material_PBR_Sheen(const ON_Material* p) { return p && p->IsPhysicallyBased() ? p->PhysicallyBased()->Sheen() : 0.0; }
RH_C_FUNCTION void ON_Material_PBR_SetSheen(ON_Material* p, double d) { if (p && p->IsPhysicallyBased()) { p->PhysicallyBased()->SetSheen(d); } }
RH_C_FUNCTION double ON_Material_PBR_SheenTint(const ON_Material* p) { return p && p->IsPhysicallyBased() ? p->PhysicallyBased()->SheenTint() : 0.0; }
RH_C_FUNCTION void ON_Material_PBR_SetSheenTint(ON_Material* p, double d) { if (p && p->IsPhysicallyBased()) { p->PhysicallyBased()->SetSheenTint(d); } }
RH_C_FUNCTION double ON_Material_PBR_Clearcoat(const ON_Material* p) { return p && p->IsPhysicallyBased() ? p->PhysicallyBased()->Clearcoat() : 0.0; }
RH_C_FUNCTION void ON_Material_PBR_SetClearcoat(ON_Material* p, double d) { if (p && p->IsPhysicallyBased()) { p->PhysicallyBased()->SetClearcoat(d); } }
RH_C_FUNCTION double ON_Material_PBR_ClearcoatRoughness(const ON_Material* p) { return p && p->IsPhysicallyBased() ? p->PhysicallyBased()->ClearcoatRoughness() : 0.0; }
RH_C_FUNCTION void ON_Material_PBR_SetClearcoatRoughness(ON_Material* p, double d) { if (p && p->IsPhysicallyBased()) { p->PhysicallyBased()->SetClearcoatRoughness(d); } }
RH_C_FUNCTION double ON_Material_PBR_OpacityIOR(const ON_Material* p) { return p && p->IsPhysicallyBased() ? p->PhysicallyBased()->OpacityIOR() : 0.0; }
RH_C_FUNCTION void ON_Material_PBR_SetOpacityIOR(ON_Material* p, double d) { if (p && p->IsPhysicallyBased()) { p->PhysicallyBased()->SetOpacityIOR(d); } }
RH_C_FUNCTION double ON_Material_PBR_Opacity(const ON_Material* p) { return p && p->IsPhysicallyBased() ? p->PhysicallyBased()->Opacity() : 0.0; }
RH_C_FUNCTION void ON_Material_PBR_SetOpacity(ON_Material* p, double d) { if (p && p->IsPhysicallyBased()) { p->PhysicallyBased()->SetOpacity(d); } }
RH_C_FUNCTION double ON_Material_PBR_OpacityRoughness(const ON_Material* p) { return p && p->IsPhysicallyBased() ? p->PhysicallyBased()->OpacityRoughness() : 0.0; }
RH_C_FUNCTION void ON_Material_PBR_SetOpacityRoughness(ON_Material* p, double d) { if (p && p->IsPhysicallyBased()) { p->PhysicallyBased()->SetOpacityRoughness(d); } }
RH_C_FUNCTION void ON_Material_PBR_Emission(const ON_Material* p, ON_4fPoint* pColor)
{
if (p && pColor && p->IsPhysicallyBased())
{
auto c = p->PhysicallyBased()->Emission();
pColor->x = c.Red();
pColor->y = c.Green();
pColor->z = c.Blue();
pColor->w = c.Alpha();
}
}
RH_C_FUNCTION void ON_Material_PBR_SetEmission(ON_Material* p, ON_4FVECTOR_STRUCT in_color)
{
if (p && p->IsPhysicallyBased())
{
ON_4fColor color;
color.SetRed(in_color.val[0]);
color.SetGreen(in_color.val[1]);
color.SetBlue(in_color.val[2]);
color.SetAlpha(in_color.val[3]);
p->PhysicallyBased()->SetEmission(color);
}
}
RH_C_FUNCTION bool ON_Material_IsPhysicallyBased(const ON_Material* p)
{
if (p)
{
return p->IsPhysicallyBased();
}
return false;
}
RH_C_FUNCTION void ON_Material_ConvertToPBR(ON_Material* p)
{
if (p)
{
p->ToPhysicallyBased();
}
}
| [
"steve@mcneel.com"
] | steve@mcneel.com |
bc7719338d1770880ff63782e06a9de4d641778e | 58ed734eac33bfb073e794e95df8280b81dce883 | /Soul-Liberty/SlimeAttack.h | 2ed8eb5b917652a5f6340d3ea9c6bfa7f0fce214 | [] | no_license | syougun360/Soul-Liberty | 9fce5a85fd8dcde48252d5034230adb259c1f9a2 | d8abae71efdda1e7044d6df50183d08765ba2d1b | refs/heads/master | 2020-04-17T20:16:18.442404 | 2019-04-18T13:52:23 | 2019-04-18T13:52:23 | 24,497,281 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 319 | h | /**
*
* @author yamada masamitsu
* @date 2014.11.06
*
*/
#pragma once
#include "EnemyAttack.h"
class CSlimeAttack:public CEnemyAttack
{
public:
CSlimeAttack(const int power, const float jumpforce, const float mass, const float speed);
void Update(CEnemyActor *actor);
void Init(CEnemyActor *actor);
private:
};
| [
"syougun360@infoseek.jp"
] | syougun360@infoseek.jp |
eba43266885df2098b56c1fcaf96b24d7009c591 | 97112cac8c87e45b7b5b33d68745593d406e6ce2 | /OS/OSlab1/mainwindow.cpp | 6cd7237f9164b6fd6add75c1db0afb841ab87d30 | [] | no_license | PALinoleum/SEM5 | 1dde325361db1884e5fa33a4b9f5360db9610f23 | 9d138d9d4a36e914f1afed4cde151514af6d50bd | refs/heads/master | 2022-11-16T08:46:02.369247 | 2020-07-08T15:10:14 | 2020-07-08T15:10:14 | 278,112,469 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 603 | cpp | #include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QLabel>
#include "windows.h"
#include "base.h"
MainWindow::MainWindow(QWidget *parent):QMainWindow(parent), ui(new Ui::MainWindow)
{
char* computerName;
computerName = getComputerNameMY();
QLabel lLabel;
lLabel.setText ("ПОМОГИТЕ");
// lLabel.setGeometry ( 200, 200, 300, 150 );
lLabel.setAlignment (Qt::AlignHCenter | Qt::AlignVCenter );
QFont lBlackFont(" Arial Black ", 12);
lLabel.setFont(lBlackFont);
lLabel.show();
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
| [
"68017323+PALinoleum@users.noreply.github.com"
] | 68017323+PALinoleum@users.noreply.github.com |
7f006805928c077d4fc766eff39e417999b982e2 | 0c40e97b69dcd00f0b0b05f249d0fce448320fd8 | /src/logging.cpp | 4e1a94ffa9556d850a6d84f72ea1ec69ba960e85 | [
"MIT"
] | permissive | Arhipovladimir/Earthcoin | 9908912df9b10b97512c545b855c3670767039d9 | bc5b5ee538c76e7232e93434aedd8688bae70792 | refs/heads/main | 2023-07-16T05:50:52.755250 | 2021-08-25T09:19:40 | 2021-08-25T09:19:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,885 | cpp | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2018 The Earthcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <logging.h>
#include <utiltime.h>
const char * const DEFAULT_DEBUGLOGFILE = "debug.log";
/**
* NOTE: the logger instances is leaked on exit. This is ugly, but will be
* cleaned up by the OS/libc. Defining a logger as a global object doesn't work
* since the order of destruction of static/global objects is undefined.
* Consider if the logger gets destroyed, and then some later destructor calls
* LogPrintf, maybe indirectly, and you get a core dump at shutdown trying to
* access the logger. When the shutdown sequence is fully audited and tested,
* explicit destruction of these objects can be implemented by changing this
* from a raw pointer to a std::unique_ptr.
*
* This method of initialization was originally introduced in
* ee3374234c60aba2cc4c5cd5cac1c0aefc2d817c.
*/
BCLog::Logger* const g_logger = new BCLog::Logger();
bool fLogIPs = DEFAULT_LOGIPS;
static int FileWriteStr(const std::string &str, FILE *fp)
{
return fwrite(str.data(), 1, str.size(), fp);
}
bool BCLog::Logger::OpenDebugLog()
{
std::lock_guard<std::mutex> scoped_lock(m_file_mutex);
assert(m_fileout == nullptr);
assert(!m_file_path.empty());
m_fileout = fsbridge::fopen(m_file_path, "a");
if (!m_fileout) {
return false;
}
setbuf(m_fileout, nullptr); // unbuffered
// dump buffered messages from before we opened the log
while (!m_msgs_before_open.empty()) {
FileWriteStr(m_msgs_before_open.front(), m_fileout);
m_msgs_before_open.pop_front();
}
return true;
}
void BCLog::Logger::EnableCategory(BCLog::LogFlags flag)
{
m_categories |= flag;
}
bool BCLog::Logger::EnableCategory(const std::string& str)
{
BCLog::LogFlags flag;
if (!GetLogCategory(flag, str)) return false;
EnableCategory(flag);
return true;
}
void BCLog::Logger::DisableCategory(BCLog::LogFlags flag)
{
m_categories &= ~flag;
}
bool BCLog::Logger::DisableCategory(const std::string& str)
{
BCLog::LogFlags flag;
if (!GetLogCategory(flag, str)) return false;
DisableCategory(flag);
return true;
}
bool BCLog::Logger::WillLogCategory(BCLog::LogFlags category) const
{
return (m_categories.load(std::memory_order_relaxed) & category) != 0;
}
bool BCLog::Logger::DefaultShrinkDebugFile() const
{
return m_categories == BCLog::NONE;
}
struct CLogCategoryDesc
{
BCLog::LogFlags flag;
std::string category;
};
const CLogCategoryDesc LogCategories[] =
{
{BCLog::NONE, "0"},
{BCLog::NONE, "none"},
{BCLog::NET, "net"},
{BCLog::TOR, "tor"},
{BCLog::MEMPOOL, "mempool"},
{BCLog::HTTP, "http"},
{BCLog::BENCH, "bench"},
{BCLog::ZMQ, "zmq"},
{BCLog::DB, "db"},
{BCLog::RPC, "rpc"},
{BCLog::ESTIMATEFEE, "estimatefee"},
{BCLog::ADDRMAN, "addrman"},
{BCLog::SELECTCOINS, "selectcoins"},
{BCLog::REINDEX, "reindex"},
{BCLog::CMPCTBLOCK, "cmpctblock"},
{BCLog::RAND, "rand"},
{BCLog::PRUNE, "prune"},
{BCLog::PROXY, "proxy"},
{BCLog::MEMPOOLREJ, "mempoolrej"},
{BCLog::LIBEVENT, "libevent"},
{BCLog::COINDB, "coindb"},
{BCLog::QT, "qt"},
{BCLog::LEVELDB, "leveldb"},
{BCLog::ALL, "1"},
{BCLog::ALL, "all"},
};
bool GetLogCategory(BCLog::LogFlags& flag, const std::string& str)
{
if (str == "") {
flag = BCLog::ALL;
return true;
}
for (const CLogCategoryDesc& category_desc : LogCategories) {
if (category_desc.category == str) {
flag = category_desc.flag;
return true;
}
}
return false;
}
std::string ListLogCategories()
{
std::string ret;
int outcount = 0;
for (const CLogCategoryDesc& category_desc : LogCategories) {
// Omit the special cases.
if (category_desc.flag != BCLog::NONE && category_desc.flag != BCLog::ALL) {
if (outcount != 0) ret += ", ";
ret += category_desc.category;
outcount++;
}
}
return ret;
}
std::vector<CLogCategoryActive> ListActiveLogCategories()
{
std::vector<CLogCategoryActive> ret;
for (const CLogCategoryDesc& category_desc : LogCategories) {
// Omit the special cases.
if (category_desc.flag != BCLog::NONE && category_desc.flag != BCLog::ALL) {
CLogCategoryActive catActive;
catActive.category = category_desc.category;
catActive.active = LogAcceptCategory(category_desc.flag);
ret.push_back(catActive);
}
}
return ret;
}
std::string BCLog::Logger::LogTimestampStr(const std::string &str)
{
std::string strStamped;
if (!m_log_timestamps)
return str;
if (m_started_new_line) {
int64_t nTimeMicros = GetTimeMicros();
strStamped = FormatISO8601DateTime(nTimeMicros/1000000);
if (m_log_time_micros) {
strStamped.pop_back();
strStamped += strprintf(".%06dZ", nTimeMicros%1000000);
}
int64_t mocktime = GetMockTime();
if (mocktime) {
strStamped += " (mocktime: " + FormatISO8601DateTime(mocktime) + ")";
}
strStamped += ' ' + str;
} else
strStamped = str;
if (!str.empty() && str[str.size()-1] == '\n')
m_started_new_line = true;
else
m_started_new_line = false;
return strStamped;
}
void BCLog::Logger::LogPrintStr(const std::string &str)
{
std::string strTimestamped = LogTimestampStr(str);
if (m_print_to_console) {
// print to console
fwrite(strTimestamped.data(), 1, strTimestamped.size(), stdout);
fflush(stdout);
}
if (m_print_to_file) {
std::lock_guard<std::mutex> scoped_lock(m_file_mutex);
// buffer if we haven't opened the log yet
if (m_fileout == nullptr) {
m_msgs_before_open.push_back(strTimestamped);
}
else
{
// reopen the log file, if requested
if (m_reopen_file) {
m_reopen_file = false;
m_fileout = fsbridge::freopen(m_file_path, "a", m_fileout);
if (!m_fileout) {
return;
}
setbuf(m_fileout, nullptr); // unbuffered
}
FileWriteStr(strTimestamped, m_fileout);
}
}
}
void BCLog::Logger::ShrinkDebugFile()
{
// Amount of debug.log to save at end when shrinking (must fit in memory)
constexpr size_t RECENT_DEBUG_HISTORY_SIZE = 10 * 1000000;
assert(!m_file_path.empty());
// Scroll debug.log if it's getting too big
FILE* file = fsbridge::fopen(m_file_path, "r");
// Special files (e.g. device nodes) may not have a size.
size_t log_size = 0;
try {
log_size = fs::file_size(m_file_path);
} catch (boost::filesystem::filesystem_error &) {}
// If debug.log file is more than 10% bigger the RECENT_DEBUG_HISTORY_SIZE
// trim it down by saving only the last RECENT_DEBUG_HISTORY_SIZE bytes
if (file && log_size > 11 * (RECENT_DEBUG_HISTORY_SIZE / 10))
{
// Restart the file with some of the end
std::vector<char> vch(RECENT_DEBUG_HISTORY_SIZE, 0);
if (fseek(file, -((long)vch.size()), SEEK_END)) {
LogPrintf("Failed to shrink debug log file: fseek(...) failed\n");
fclose(file);
return;
}
int nBytes = fread(vch.data(), 1, vch.size(), file);
fclose(file);
file = fsbridge::fopen(m_file_path, "w");
if (file)
{
fwrite(vch.data(), 1, nBytes, file);
fclose(file);
}
}
else if (file != nullptr)
fclose(file);
}
| [
"mail@deveac.com"
] | mail@deveac.com |
2a8f6344508e16d848e9432a1dce482ef6608cc1 | 3e4fd5153015d03f147e0f105db08e4cf6589d36 | /Cpp/SDK/PhysicsCore_classes.h | 6c40400ea4dfaa19066a3c8d2eb21134d6927492 | [] | no_license | zH4x-SDK/zTorchlight3-SDK | a96f50b84e6b59ccc351634c5cea48caa0d74075 | 24135ee60874de5fd3f412e60ddc9018de32a95c | refs/heads/main | 2023-07-20T12:17:14.732705 | 2021-08-27T13:59:21 | 2021-08-27T13:59:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,787 | h | #pragma once
// Name: Torchlight3, Version: 4.26.1
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Classes
//---------------------------------------------------------------------------
// Class PhysicsCore.BodySetupCore
// 0x0020 (FullSize[0x0048] - InheritedSize[0x0028])
class UBodySetupCore : public UObject
{
public:
struct FName BoneName; // 0x0028(0x0008) (Edit, ZeroConstructor, EditConst, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
TEnumAsByte<PhysicsCore_EPhysicsType> PhysicsType; // 0x0030(0x0001) (Edit, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
TEnumAsByte<PhysicsCore_ECollisionTraceFlag> CollisionTraceFlag; // 0x0031(0x0001) (Edit, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
TEnumAsByte<PhysicsCore_EBodyCollisionResponse> CollisionReponse; // 0x0032(0x0001) (Edit, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
unsigned char UnknownData_HS64[0x15]; // 0x0033(0x0015) MISSED OFFSET (PADDING)
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("Class PhysicsCore.BodySetupCore");
return ptr;
}
};
// Class PhysicsCore.ChaosPhysicalMaterial
// 0x0020 (FullSize[0x0048] - InheritedSize[0x0028])
class UChaosPhysicalMaterial : public UObject
{
public:
float Friction; // 0x0028(0x0004) (Edit, BlueprintVisible, BlueprintReadOnly, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
float StaticFriction; // 0x002C(0x0004) (Edit, BlueprintVisible, BlueprintReadOnly, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
float Restitution; // 0x0030(0x0004) (Edit, BlueprintVisible, BlueprintReadOnly, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
float LinearEtherDrag; // 0x0034(0x0004) (Edit, BlueprintVisible, BlueprintReadOnly, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
float AngularEtherDrag; // 0x0038(0x0004) (Edit, BlueprintVisible, BlueprintReadOnly, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
float SleepingLinearVelocityThreshold; // 0x003C(0x0004) (Edit, BlueprintVisible, BlueprintReadOnly, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
float SleepingAngularVelocityThreshold; // 0x0040(0x0004) (Edit, BlueprintVisible, BlueprintReadOnly, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
unsigned char UnknownData_L3E1[0x4]; // 0x0044(0x0004) MISSED OFFSET (PADDING)
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("Class PhysicsCore.ChaosPhysicalMaterial");
return ptr;
}
};
// Class PhysicsCore.PhysicalMaterial
// 0x0058 (FullSize[0x0080] - InheritedSize[0x0028])
class UPhysicalMaterial : public UObject
{
public:
float Friction; // 0x0028(0x0004) (Edit, BlueprintVisible, BlueprintReadOnly, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
float StaticFriction; // 0x002C(0x0004) (Edit, BlueprintVisible, BlueprintReadOnly, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
TEnumAsByte<PhysicsCore_EFrictionCombineMode> FrictionCombineMode; // 0x0030(0x0001) (Edit, BlueprintVisible, BlueprintReadOnly, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
bool bOverrideFrictionCombineMode; // 0x0031(0x0001) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
unsigned char UnknownData_PTAO[0x2]; // 0x0032(0x0002) MISSED OFFSET (FIX SPACE BETWEEN PREVIOUS PROPERTY)
float Restitution; // 0x0034(0x0004) (Edit, BlueprintVisible, BlueprintReadOnly, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
TEnumAsByte<PhysicsCore_EFrictionCombineMode> RestitutionCombineMode; // 0x0038(0x0001) (Edit, BlueprintVisible, BlueprintReadOnly, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
bool bOverrideRestitutionCombineMode; // 0x0039(0x0001) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
unsigned char UnknownData_Q6WA[0x2]; // 0x003A(0x0002) MISSED OFFSET (FIX SPACE BETWEEN PREVIOUS PROPERTY)
float Density; // 0x003C(0x0004) (Edit, BlueprintVisible, BlueprintReadOnly, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
float SleepLinearVelocityThreshold; // 0x0040(0x0004) (Edit, BlueprintVisible, BlueprintReadOnly, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
float SleepAngularVelocityThreshold; // 0x0044(0x0004) (Edit, BlueprintVisible, BlueprintReadOnly, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
int SleepCounterThreshold; // 0x0048(0x0004) (Edit, BlueprintVisible, BlueprintReadOnly, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
float RaiseMassToPower; // 0x004C(0x0004) (Edit, BlueprintVisible, BlueprintReadOnly, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
float DestructibleDamageThresholdScale; // 0x0050(0x0004) (Edit, BlueprintVisible, BlueprintReadOnly, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
unsigned char UnknownData_K6DO[0x4]; // 0x0054(0x0004) MISSED OFFSET (FIX SPACE BETWEEN PREVIOUS PROPERTY)
class UPhysicalMaterialPropertyBase* PhysicalMaterialProperty; // 0x0058(0x0008) (ZeroConstructor, Deprecated, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
TEnumAsByte<PhysicsCore_EPhysicalSurface> SurfaceType; // 0x0060(0x0001) (Edit, BlueprintVisible, BlueprintReadOnly, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
unsigned char UnknownData_P9ZM[0x1F]; // 0x0061(0x001F) MISSED OFFSET (PADDING)
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("Class PhysicsCore.PhysicalMaterial");
return ptr;
}
};
// Class PhysicsCore.PhysicalMaterialPropertyBase
// 0x0000 (FullSize[0x0028] - InheritedSize[0x0028])
class UPhysicalMaterialPropertyBase : public UObject
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("Class PhysicsCore.PhysicalMaterialPropertyBase");
return ptr;
}
};
// Class PhysicsCore.PhysicsSettingsCore
// 0x00A8 (FullSize[0x00E0] - InheritedSize[0x0038])
class UPhysicsSettingsCore : public UDeveloperSettings
{
public:
float DefaultGravityZ; // 0x0038(0x0004) (Edit, ZeroConstructor, Config, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
float DefaultTerminalVelocity; // 0x003C(0x0004) (Edit, ZeroConstructor, Config, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
float DefaultFluidFriction; // 0x0040(0x0004) (Edit, ZeroConstructor, Config, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
int SimulateScratchMemorySize; // 0x0044(0x0004) (Edit, ZeroConstructor, Config, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
int RagdollAggregateThreshold; // 0x0048(0x0004) (Edit, ZeroConstructor, Config, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
float TriangleMeshTriangleMinAreaThreshold; // 0x004C(0x0004) (Edit, ZeroConstructor, Config, IsPlainOldData, NoDestructor, AdvancedDisplay, HasGetValueTypeHash, NativeAccessSpecifierPublic)
bool bEnableShapeSharing; // 0x0050(0x0001) (Edit, ZeroConstructor, Config, IsPlainOldData, NoDestructor, AdvancedDisplay, HasGetValueTypeHash, NativeAccessSpecifierPublic)
bool bEnablePCM; // 0x0051(0x0001) (Edit, ZeroConstructor, Config, IsPlainOldData, NoDestructor, AdvancedDisplay, HasGetValueTypeHash, NativeAccessSpecifierPublic)
bool bEnableStabilization; // 0x0052(0x0001) (Edit, ZeroConstructor, Config, IsPlainOldData, NoDestructor, AdvancedDisplay, HasGetValueTypeHash, NativeAccessSpecifierPublic)
bool bWarnMissingLocks; // 0x0053(0x0001) (Edit, ZeroConstructor, Config, IsPlainOldData, NoDestructor, AdvancedDisplay, HasGetValueTypeHash, NativeAccessSpecifierPublic)
bool bEnable2DPhysics; // 0x0054(0x0001) (Edit, ZeroConstructor, Config, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
bool bDefaultHasComplexCollision; // 0x0055(0x0001) (ZeroConstructor, Config, Deprecated, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
unsigned char UnknownData_JGVJ[0x2]; // 0x0056(0x0002) MISSED OFFSET (FIX SPACE BETWEEN PREVIOUS PROPERTY)
float BounceThresholdVelocity; // 0x0058(0x0004) (Edit, ZeroConstructor, Config, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
TEnumAsByte<PhysicsCore_EFrictionCombineMode> FrictionCombineMode; // 0x005C(0x0001) (Edit, ZeroConstructor, Config, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
TEnumAsByte<PhysicsCore_EFrictionCombineMode> RestitutionCombineMode; // 0x005D(0x0001) (Edit, ZeroConstructor, Config, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
unsigned char UnknownData_K5A3[0x2]; // 0x005E(0x0002) MISSED OFFSET (FIX SPACE BETWEEN PREVIOUS PROPERTY)
float MaxAngularVelocity; // 0x0060(0x0004) (Edit, ZeroConstructor, Config, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
float MaxDepenetrationVelocity; // 0x0064(0x0004) (Edit, ZeroConstructor, Config, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
float ContactOffsetMultiplier; // 0x0068(0x0004) (Edit, ZeroConstructor, Config, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
float MinContactOffset; // 0x006C(0x0004) (Edit, ZeroConstructor, Config, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
float MaxContactOffset; // 0x0070(0x0004) (Edit, ZeroConstructor, Config, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
bool bSimulateSkeletalMeshOnDedicatedServer; // 0x0074(0x0001) (Edit, ZeroConstructor, Config, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
TEnumAsByte<PhysicsCore_ECollisionTraceFlag> DefaultShapeComplexity; // 0x0075(0x0001) (Edit, ZeroConstructor, Config, IsPlainOldData, NoDestructor, HasGetValueTypeHash, NativeAccessSpecifierPublic)
unsigned char UnknownData_XI7H[0x2]; // 0x0076(0x0002) MISSED OFFSET (FIX SPACE BETWEEN PREVIOUS PROPERTY)
struct FChaosSolverConfiguration SolverOptions; // 0x0078(0x0068) (Edit, Config, NoDestructor, NativeAccessSpecifierPublic)
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("Class PhysicsCore.PhysicsSettingsCore");
return ptr;
}
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"zp2kshield@gmail.com"
] | zp2kshield@gmail.com |
f8af2fa8e551ddbd0beba239fee02db5f87c3783 | 1217c20270a48a0cdaab73a5a11d050c11f33416 | /transcode_audio/src/AddSamplesToFifo.cpp | c32b0fac628a838f2e5e61471a4fa6d8cfb73ea2 | [] | no_license | yurychu/media_decoding | 3b31d2ba4c85f6226d20d157affb1d1221204b3a | fda34f20323a4d71a3cefe71563273e8decea0ac | refs/heads/master | 2023-03-31T21:31:35.054591 | 2021-03-23T14:34:29 | 2021-03-23T14:34:29 | 271,351,126 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 801 | cpp | #include <transcode_audio/AddSamplesToFifo.hpp>
int tr_au::add_samples_to_fifo(AVAudioFifo *fifo,
uint8_t **converted_input_samples,
const int frame_size)
{
int error;
/* Make the FIFO as large as it needs to be to hold both,
* the old and the new samples. */
if ((error = av_audio_fifo_realloc(fifo, av_audio_fifo_size(fifo) + frame_size)) < 0) {
fprintf(stderr, "Could not reallocate FIFO\n");
return error;
}
/* Store the new samples in the FIFO buffer. */
if (av_audio_fifo_write(fifo, (void **)converted_input_samples,
frame_size) < frame_size) {
fprintf(stderr, "Could not write data to FIFO\n");
return AVERROR_EXIT;
}
return 0;
}
| [
"yury_chugunov@mail.ru"
] | yury_chugunov@mail.ru |
451e5f08377d7343c4c49ac1c1c3d366c27252fa | 6b2a8dd202fdce77c971c412717e305e1caaac51 | /solutions_5630113748090880_0/C++/Lucaskywalker/cjb.cpp | 5f45550c9bacb01b6dd816517f8f57304cebbe57 | [] | no_license | alexandraback/datacollection | 0bc67a9ace00abbc843f4912562f3a064992e0e9 | 076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf | refs/heads/master | 2021-01-24T18:27:24.417992 | 2017-05-23T09:23:38 | 2017-05-23T09:23:38 | 84,313,442 | 2 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 807 | cpp | #include<bits/stdc++.h>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
int te;
cin>>te;
int ocor[2505];
for(int t=1;t<=te;t++)
{
for(int i=0;i<2505;i++) ocor[i]=0;
int n;
cin>>n;
for(int i=0;i<2*n-1;i++)
{
for(int j=0;j<n;j++)
{
int a;
cin>>a;
ocor[a]++;
}
}
vector<int> resp;
for(int i=0;i<2505;i++)
{
if(ocor[i]&1)
{
resp.push_back(i);
}
}
cout<<"Case #"<<t<<": ";
for(int i=0;i<resp.size();i++)
{
cout<<resp[i]<<" ";
}
cout<<endl;
}
return 0;
}
| [
"alexandra1.back@gmail.com"
] | alexandra1.back@gmail.com |
01e3f197482d7dc1280ac6c27b85f62a87e110ce | e8b9e24cf5cbd96178dbc4cb08c38d62dab6bdce | /Source/Designer/support.cpp | 91a9603061090509686c5499fb3d4a8f6f26f9c0 | [] | no_license | pbarounis/ActiveBar2 | 3116aa48c6dde179ee06ff53108d55644b797550 | efbe8b367e975813677da68414a4f1457d4c812e | refs/heads/master | 2021-01-10T05:25:21.717387 | 2016-03-06T00:33:50 | 2016-03-06T00:33:50 | 53,230,406 | 0 | 2 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 15,280 | cpp | //
// Copyright © 1995-1999, Data Dynamics. All rights reserved.
//
// Unpublished -- rights reserved under the copyright laws of the United
// States. USE OF A COPYRIGHT NOTICE IS PRECAUTIONARY ONLY AND DOES NOT
// IMPLY PUBLICATION OR DISCLOSURE.
//
//
#include "precomp.h"
#include <stddef.h>
#include "ipserver.h"
#include "Resource.h"
#include "Globals.h"
#include "..\EventLog.h"
#include "support.h"
#include "debug.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
extern HINSTANCE g_hInstance;
const WCHAR wszCtlSaveStream [] = L"CONTROLSAVESTREAM";
short _SpecialKeyState()
{
// don't appear to be able to reduce number of calls to GetKeyState
//
BOOL bShift = (GetKeyState(VK_SHIFT) < 0);
BOOL bCtrl = (GetKeyState(VK_CONTROL) < 0);
BOOL bAlt = (GetKeyState(VK_MENU) < 0);
return (short)(bShift + (bCtrl << 1) + (bAlt << 2));
}
LPWSTR MakeWideStrFromAnsi(LPSTR psz,BYTE bType)
{
LPWSTR pwsz;
int i;
// arg checking.
//
if (!psz)
return NULL;
// compute the length of the required BSTR
//
i = MultiByteToWideChar(CP_ACP, 0, psz, -1, NULL, 0);
if (i <= 0) return NULL;
// allocate the widestr
//
switch (bType) {
case STR_BSTR:
// -1 since it'll add it's own space for a NULL terminator
//
pwsz = (LPWSTR) SysAllocStringLen(NULL, i - 1);
break;
case STR_OLESTR:
pwsz = (LPWSTR) CoTaskMemAlloc(i * sizeof(WCHAR));
break;
default:
TRACE(1, "Bogus String Type in MakeWideStrFromAnsi.\n");
return NULL;
}
if (!pwsz) return NULL;
MultiByteToWideChar(CP_ACP, 0, psz, -1, pwsz, i);
pwsz[i - 1] = 0;
return pwsz;
}
//=--------------------------------------------------------------------------=
// MakeWideStrFromResId
//=--------------------------------------------------------------------------=
// given a resource ID, load it, and allocate a wide string for it.
//
// Parameters:
// WORD - [in] resource id.
// BYTE - [in] type of string desired.
//
// Output:
// LPWSTR - needs to be cast to desired string type.
//
// Notes:
//
LPWSTR MakeWideStrFromResourceId(WORD wId,BYTE bType)
{
int i;
TCHAR szTmp[512];
#ifdef UNICODE
LPWSTR pwszTmp;
#endif
i = LoadString(g_hInstance, wId, szTmp, 512*sizeof(TCHAR));
// load the string from the resources.
if (!i)
return NULL;
#ifdef UNICODE
pwszTmp = (LPWSTR)CoTaskMemAlloc((i * sizeof(WCHAR)) + sizeof(WCHAR));
memcpy(pwszTmp,szTmp,(i * sizeof(WCHAR)) + sizeof(WCHAR));
return pwszTmp;
#else
return MakeWideStrFromAnsi(szTmp, bType);
#endif
}
//=--------------------------------------------------------------------------=
// MakeWideStrFromWide
//=--------------------------------------------------------------------------=
// given a wide string, make a new wide string with it of the given type.
//
// Parameters:
// LPWSTR - [in] current wide str.
// BYTE - [in] desired type of string.
//
// Output:
// LPWSTR
//
// Notes:
//
LPWSTR MakeWideStrFromWide
(
LPWSTR pwsz,
BYTE bType
)
{
LPWSTR pwszTmp;
int i;
if (!pwsz) return NULL;
// just copy the string, depending on what type they want.
//
switch (bType) {
case STR_OLESTR:
i = lstrlenW(pwsz);
pwszTmp = (LPWSTR)CoTaskMemAlloc((i * sizeof(WCHAR)) + sizeof(WCHAR));
if (!pwszTmp) return NULL;
memcpy(pwszTmp, pwsz, (sizeof(WCHAR) * i) + sizeof(WCHAR));
break;
case STR_BSTR:
pwszTmp = (LPWSTR)SysAllocString(pwsz);
break;
}
return pwszTmp;
}
//////////////// IOLEOBJECT
void WINAPI CopyOLEVERB(void *pvDest,const void *pvSrc,DWORD cbCopy)
{
memcpy(pvDest,pvSrc,cbCopy);
((OLEVERB *)pvDest)->lpszVerbName=MakeWideStrFromResourceId((UINT)(((OLEVERB *)pvSrc)->lpszVerbName), STR_OLESTR);
}
int s_iXppli; // Pixels per logical inch along width
int s_iYppli; // Pixels per logical inch along height
static BYTE s_fGotScreenMetrics; // Are above valid?
void CacheScreenMetrics(void)
{
HDC hDCScreen;
// we have to critical section this in case two threads are converting
// things at the same time
//
#ifdef DEF_CRITSECTION
EnterCriticalSection(&g_CriticalSection);
#endif
if (s_fGotScreenMetrics)
goto Done;
// we want the metrics for the screen
//
hDCScreen = GetDC(NULL);
ASSERT(hDCScreen, "couldn't get a DC for the screen.");
s_iXppli = GetDeviceCaps(hDCScreen, LOGPIXELSX);
s_iYppli = GetDeviceCaps(hDCScreen, LOGPIXELSY);
ReleaseDC(NULL, hDCScreen);
s_fGotScreenMetrics = TRUE;
// we're done with our critical seciton. clean it up
//
Done:;
#ifdef DEF_CRITSECTION
LeaveCriticalSection(&g_CriticalSection);
#endif
}
void PixelToHiMetric(const SIZEL *pixsizel,SIZEL *hisizel)
{
CacheScreenMetrics();
hisizel->cx = MAP_PIX_TO_LOGHIM(pixsizel->cx, s_iXppli);
hisizel->cy = MAP_PIX_TO_LOGHIM(pixsizel->cy, s_iYppli);
}
void HiMetricToPixel(const SIZEL *hisizel,SIZEL *pixsizel)
{
CacheScreenMetrics();
pixsizel->cx = MAP_LOGHIM_TO_PIX(hisizel->cx, s_iXppli);
pixsizel->cy = MAP_LOGHIM_TO_PIX(hisizel->cy, s_iYppli);
}
void PixelToTwips(const SIZEL *pixsizel,SIZEL *twipssizel)
{
CacheScreenMetrics();
twipssizel->cx = MAP_PIX_TO_TWIPS(pixsizel->cx, s_iXppli);
twipssizel->cy = MAP_PIX_TO_TWIPS(pixsizel->cy, s_iYppli);
}
void TwipsToPixel(const SIZEL *twipssizel, SIZEL *pixsizel)
{
CacheScreenMetrics();
pixsizel->cx = MAP_TWIPS_TO_PIX(twipssizel->cx, s_iXppli);
pixsizel->cy = MAP_TWIPS_TO_PIX(twipssizel->cy, s_iYppli);
}
//=--------------------------------------------------------------------------=
// _CreateOleDC
//=--------------------------------------------------------------------------=
// creates an HDC given a DVTARGETDEVICE structure.
HDC _CreateOleDC(DVTARGETDEVICE *ptd)
{
LPDEVMODEW pDevModeW;
HDC hdc;
LPOLESTR lpwszDriverName;
LPOLESTR lpwszDeviceName;
LPOLESTR lpwszPortName;
// return screen DC for NULL target device
if (!ptd)
return CreateDC(_T("DISPLAY"), NULL, NULL, NULL);
if (ptd->tdExtDevmodeOffset == 0)
pDevModeW = NULL;
else
pDevModeW = (LPDEVMODEW)((LPSTR)ptd + ptd->tdExtDevmodeOffset);
lpwszDriverName = (LPOLESTR)((BYTE*)ptd + ptd->tdDriverNameOffset);
lpwszDeviceName = (LPOLESTR)((BYTE*)ptd + ptd->tdDeviceNameOffset);
lpwszPortName = (LPOLESTR)((BYTE*)ptd + ptd->tdPortNameOffset);
#ifdef UNICODE
hdc = CreateDC(lpwszDriverName, lpwszDeviceName, lpwszPortName, pDevModeW);
#else
DEVMODEA DevModeA, *pDevModeA;
MAKE_ANSIPTR_FROMWIDE(pszDriverName, lpwszDriverName);
MAKE_ANSIPTR_FROMWIDE(pszDeviceName, lpwszDeviceName);
MAKE_ANSIPTR_FROMWIDE(pszPortName, lpwszPortName);
if (pDevModeW)
{
WideCharToMultiByte(CP_ACP, 0, pDevModeW->dmDeviceName, -1, (LPSTR)DevModeA.dmDeviceName, CCHDEVICENAME, NULL, NULL);
memcpy(&DevModeA.dmSpecVersion, &pDevModeW->dmSpecVersion,
offsetof(DEVMODEA, dmFormName) - offsetof(DEVMODEA, dmSpecVersion));
WideCharToMultiByte(CP_ACP, 0, pDevModeW->dmFormName, -1, (LPSTR)DevModeA.dmFormName, CCHFORMNAME, NULL, NULL);
memcpy(&DevModeA.dmLogPixels, &pDevModeW->dmLogPixels, sizeof(DEVMODEA) - offsetof(DEVMODEA, dmLogPixels));
if (pDevModeW->dmDriverExtra)
{
pDevModeA = (DEVMODEA *)HeapAlloc(g_hHeap, 0, sizeof(DEVMODEA) + pDevModeW->dmDriverExtra);
if (!pDevModeA)
return NULL;
memcpy(pDevModeA, &DevModeA, sizeof(DEVMODEA));
memcpy(pDevModeA + 1, pDevModeW + 1, pDevModeW->dmDriverExtra);
}
else
pDevModeA = &DevModeA;
DevModeA.dmSize = sizeof(DEVMODEA);
}
else
pDevModeA = NULL;
hdc = CreateDC(pszDriverName, pszDeviceName, pszPortName, pDevModeA);
if (pDevModeA != &DevModeA)
HeapFree(g_hHeap, 0, pDevModeA);
#endif
return hdc;
}
LPTSTR g_szReflectClassName= _T("XBuilderReflector");
BYTE g_fRegisteredReflect=FALSE;
HWND CreateReflectWindow(BOOL fVisible,HWND hwndParent,int x,int y,SIZEL *pSize,CALLBACKFUNC pReflectWindowProc)
{
WNDCLASS wndclass;
// first thing to do is register the window class. crit sect this
// so we don't have to move it into the control
//
#ifdef DEF_CRITSECTION
EnterCriticalSection(&g_CriticalSection);
#endif
if (!g_fRegisteredReflect)
{
memset(&wndclass, 0, sizeof(wndclass));
wndclass.lpfnWndProc = pReflectWindowProc;
wndclass.hInstance = g_hInstance;
wndclass.lpszClassName = g_szReflectClassName;
if (!RegisterClass(&wndclass))
{
TRACE(1,"Couldn't Register Parking Window Class!");
#ifdef DEF_CRITSECTION
LeaveCriticalSection(&g_CriticalSection);
#endif
return NULL;
}
g_fRegisteredReflect = TRUE;
}
#ifdef DEF_CRITSECTION
LeaveCriticalSection(&g_CriticalSection);
#endif
// go and create the window.
return CreateWindowEx(0, g_szReflectClassName, NULL,
WS_CHILD | WS_CLIPSIBLINGS |((fVisible) ? WS_VISIBLE : 0),
x, y, pSize->cx, pSize->cy,
hwndParent,
NULL, g_hInstance, NULL);
}
LPTSTR szparkingclass=_T("XBuilder_Parking");
WNDPROC g_ParkingWindowProc = NULL;
HWND g_hwndParking=NULL;
HWND GetParkingWindow(void)
{
WNDCLASS wndclass;
// crit sect this creation for apartment threading support.
//
// EnterCriticalSection(&g_CriticalSection);
if (g_hwndParking)
goto CleanUp;
ZeroMemory(&wndclass, sizeof(wndclass));
wndclass.lpfnWndProc = (g_ParkingWindowProc) ? g_ParkingWindowProc : DefWindowProc;
wndclass.hInstance = g_hInstance;
wndclass.lpszClassName = szparkingclass;
if (!RegisterClass(&wndclass)) {
TRACE(1, "Couldn't Register Parking Window Class!");
goto CleanUp;
}
g_hwndParking = CreateWindow(szparkingclass, NULL, WS_POPUP, 0, 0, 0, 0, NULL, NULL, g_hInstance, NULL);
if (g_hwndParking != NULL)
++g_cLocks;
ASSERT(g_hwndParking, "Couldn't Create Global parking window!!");
CleanUp:
// LeaveCriticalSection(&g_CriticalSection);
return g_hwndParking;
}
void WINAPI CopyAndAddRefObject(void *pDest,const void *pSource,DWORD dwSize)
{
*((IUnknown **)pDest) = *((IUnknown **)pSource);
if ((*((IUnknown **)pDest))!=NULL)
(*((IUnknown **)pDest))->AddRef();
return;
}
///////////////// PERSISTANCE
void PersistBin(IStream *pStream,void *ptr,int size,BOOL save)
{
if (save)
pStream->Write(ptr,size,NULL);
else
pStream->Read(ptr,size,NULL);
}
void PersistBSTR(IStream *pStream,BSTR *pbstr,BOOL save)
{
short size;
BSTR bstr;
if (save)
{
bstr=*pbstr;
if (bstr==NULL || *bstr==0)
size=0;
else
size=(wcslen(bstr)+1)*sizeof(WCHAR);
pStream->Write(&size,sizeof(short),NULL);
if (size)
pStream->Write(bstr,size,0);
}
else
{
pStream->Read(&size,sizeof(short),NULL);
SysFreeString(*pbstr);
if (size!=0)
{
*pbstr=SysAllocStringByteLen(NULL,size);
pStream->Read(*pbstr,size,NULL);
}
else
*pbstr=NULL;
}
}
void PersistPict(IStream *pStream,CPictureHolder *pict,BOOL save)
{
}
void PersistVariant(IStream *pStream,VARIANT *v,BOOL save)
{
}
HRESULT PersistBagI2(IPropertyBag *pPropBag,LPCOLESTR propName,IErrorLog *pErrorLog,short *ptr,BOOL save)
{
HRESULT hr;
VARIANT v;
VariantInit(&v);
v.vt=VT_I2;
if (save)
{
v.iVal=*ptr;
hr=pPropBag->Write(propName,&v);
}
else
{
hr=pPropBag->Read(propName,&v,pErrorLog);
if (SUCCEEDED(hr))
*ptr=v.iVal;
}
return hr;
}
HRESULT PersistBagI4(IPropertyBag *pPropBag,LPCOLESTR propName,IErrorLog *pErrorLog,long *ptr,BOOL save)
{
HRESULT hr;
VARIANT v;
VariantInit(&v);
v.vt=VT_I4;
if (save)
{
v.lVal=*ptr;
hr=pPropBag->Write(propName,&v);
}
else
{
hr=pPropBag->Read(propName,&v,pErrorLog);
if (SUCCEEDED(hr))
*ptr=v.lVal;
}
return hr;
}
HRESULT PersistBagR4(IPropertyBag *pPropBag,LPCOLESTR propName,IErrorLog *pErrorLog,float *ptr,BOOL save)
{
HRESULT hr;
VARIANT v;
VariantInit(&v);
v.vt=VT_R4;
if (save)
{
v.fltVal=*ptr;
hr=pPropBag->Write(propName,&v);
}
else
{
hr=pPropBag->Read(propName,&v,pErrorLog);
if (SUCCEEDED(hr))
*ptr=v.fltVal;
}
return hr;
}
HRESULT PersistBagR8(IPropertyBag *pPropBag,LPCOLESTR propName,IErrorLog *pErrorLog,double *ptr,BOOL save)
{
HRESULT hr;
VARIANT v;
VariantInit(&v);
v.vt=VT_R8;
if (save)
{
v.dblVal=*ptr;
hr=pPropBag->Write(propName,&v);
}
else
{
hr=pPropBag->Read(propName,&v,pErrorLog);
if (SUCCEEDED(hr))
*ptr=v.dblVal;
}
return hr;
}
HRESULT PersistBagBSTR(IPropertyBag *pPropBag,LPCOLESTR propName,IErrorLog *pErrorLog,BSTR *ptr,BOOL save)
{
HRESULT hr;
VARIANT v;
VariantInit(&v);
v.vt=VT_BSTR;
if (save)
{
v.bstrVal=*ptr;
hr=pPropBag->Write(propName,&v);
}
else
{
v.bstrVal=NULL;
hr=pPropBag->Read(propName,&v,pErrorLog);
SysFreeString(*ptr);
if (SUCCEEDED(hr))
*ptr=v.bstrVal;
else
*ptr=NULL;
}
return hr;
}
HRESULT PersistBagBOOL(IPropertyBag *pPropBag,LPCOLESTR propName,IErrorLog *pErrorLog,VARIANT_BOOL *ptr,BOOL save)
{
HRESULT hr;
VARIANT v;
VariantInit(&v);
v.vt=VT_BOOL;
if (save)
{
v.boolVal=*ptr;
hr=pPropBag->Write(propName,&v);
}
else
{
hr=pPropBag->Read(propName,&v,pErrorLog);
if (SUCCEEDED(hr))
*ptr=v.boolVal;
}
return hr;
}
HRESULT PersistBagCurrency(IPropertyBag *pPropBag,LPCOLESTR propName,IErrorLog *pErrorLog,CY *ptr,BOOL save)
{
HRESULT hr;
VARIANT v;
VariantInit(&v);
v.vt=VT_CY;
if (save)
{
v.cyVal=*ptr;
hr=pPropBag->Write(propName,&v);
}
else
{
hr=pPropBag->Read(propName,&v,pErrorLog);
if (SUCCEEDED(hr))
*ptr=v.cyVal;
}
return hr;
}
HRESULT PersistBagDate(IPropertyBag *pPropBag,LPCOLESTR propName,IErrorLog *pErrorLog,DATE *ptr,BOOL save)
{
HRESULT hr;
VARIANT v;
VariantInit(&v);
v.vt=VT_DATE;
if (save)
{
v.date=*ptr;
hr=pPropBag->Write(propName,&v);
}
else
{
hr=pPropBag->Read(propName,&v,pErrorLog);
if (SUCCEEDED(hr))
*ptr=v.date;
}
return hr;
}
HRESULT PersistBagPict(IPropertyBag *pPropBag,LPCOLESTR propName,IErrorLog *pErrorLog,CPictureHolder *pict,BOOL save)
{
return E_FAIL;
}
HRESULT PersistBagVariant(IPropertyBag *pPropBag,LPCOLESTR propName,IErrorLog *pErrorLog,VARIANT *ptr,BOOL save)
{
HRESULT hr;
if (save)
hr=pPropBag->Write(propName,ptr);
else
hr=pPropBag->Read(propName,ptr,pErrorLog);
return hr;
}
| [
"pbarounis@yahoo.com"
] | pbarounis@yahoo.com |
113f995e3a0539c5a78e0b9455a7d56349748edf | c3c848ae6c90313fed11be129187234e487c5f96 | /VC6PLATSDK/samples/Com/Administration/Spy/comspyctl/ComSpyproppage.Cpp | 50ed78f38c26db5bfda475c3b7b611bb7d33dcba | [] | no_license | timxx/VC6-Platform-SDK | 247e117cfe77109cd1b1effcd68e8a428ebe40f0 | 9fd59ed5e8e25a1a72652b44cbefb433c62b1c0f | refs/heads/master | 2023-07-04T06:48:32.683084 | 2021-08-10T12:52:47 | 2021-08-10T12:52:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,713 | cpp | // ----------------------------------------------------------------------------
//
// This file is part of the Microsoft COM+ Samples.
//
// Copyright (C) 1995-2000 Microsoft Corporation. All rights reserved.
//
// This source code is intended only as a supplement to Microsoft
// Development Tools and/or on-line documentation. See these other
// materials for detailed information regarding Microsoft code samples.
//
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// ----------------------------------------------------------------------------
#include "stdafx.h"
#include "ComSpyCtl.h"
#include "ComSpyAudit.h"
#include "CComSpy.h"
#include "ComSpyPropPage.h"
#include "comsvcs.h"
#include "AppInfo.h"
TCHAR * szColNames[] =
{
_T("Count"),
_T("Event"),
_T("TickCount"),
_T("Application"),
_T("Parameter"),
_T("Value")
};
/////////////////////////////////////////////////////////////////////////////
// CComSpyPropPage
LRESULT CComSpyPropPage::OnInitDialog(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
bHandled = FALSE;
m_ppUnk[0]->QueryInterface(IID_IComSpy, (void**)&m_pSpy);
_ASSERTE(m_pSpy);
CComBSTR bstr;
m_pSpy -> get_LogFile(&bstr);
SetDlgItemText(IDC_LOG_FILE, bstr);
// grid lines
BOOL bVal;
m_pSpy -> get_ShowGridLines(&bVal);
SendDlgItemMessage(IDC_SHOW_GRID_LINES, BM_SETCHECK, (bVal) ? BST_CHECKED : BST_UNCHECKED);
// show on screen
m_pSpy -> get_ShowOnScreen(&bVal);
SendDlgItemMessage(IDC_SHOW_ON_SCREEN, BM_SETCHECK, (bVal) ? BST_CHECKED : BST_UNCHECKED);
// log to file
m_pSpy -> get_LogToFile(&bVal);
SendDlgItemMessage(IDC_LOG_TO_FILE, BM_SETCHECK, (bVal) ? BST_CHECKED : BST_UNCHECKED);
int i;
for (i=0;i<sizeof(szColNames)/sizeof(szColNames[0]);i++)
SendDlgItemMessage(IDC_COLUMN_NAMES, CB_ADDSTRING, 0, (LPARAM)(LPTSTR)szColNames[i]);
SendDlgItemMessage(IDC_COLUMN_NAMES, CB_SETCURSEL, 0, 0);
BOOL bH;
OnSelectColumn(CBN_SELCHANGE, 0,0, bH);
return 0;
}
LRESULT CComSpyPropPage::OnSelectColumn(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled)
{
if (wNotifyCode == CBN_SELCHANGE)
{
int nSel = SendDlgItemMessage(IDC_COLUMN_NAMES, CB_GETCURSEL, 0, 0L);
if (nSel != CB_ERR)
{
// get the width
long lWidth;
_ASSERTE(m_pSpy);
m_pSpy -> get_ColWidth(nSel, &lWidth);
SetDlgItemInt(IDC_WIDTH, lWidth);
}
}
return 0;
}
STDMETHODIMP CComSpyPropPage::Apply()
{
ATLTRACE(_T("CComSpyPropPage::Apply\n"));
for (UINT i = 0; i < m_nObjects; i++)
{
CComQIPtr<IComSpy, &IID_IComSpy> pSpy(m_ppUnk[i]);
BSTR bstr;
GetDlgItemText(IDC_LOG_FILE, bstr);
pSpy -> put_LogFile(bstr);
::SysFreeString(bstr);
// grid lines
BOOL bVal = (SendDlgItemMessage(IDC_SHOW_GRID_LINES, BM_GETCHECK) == BST_CHECKED);
pSpy -> put_ShowGridLines(bVal);
// log to file
bVal = (SendDlgItemMessage(IDC_LOG_TO_FILE, BM_GETCHECK) == BST_CHECKED);
pSpy -> put_LogToFile(bVal);
// show on screen
bVal = (SendDlgItemMessage(IDC_SHOW_ON_SCREEN, BM_GETCHECK) == BST_CHECKED);
pSpy -> put_ShowOnScreen(bVal);
int j;
UINT nWidth;
for (j=0;j<sizeof(szColNames)/sizeof(szColNames[0]);j++)
{
nWidth = SendDlgItemMessage(IDC_COLUMN_NAMES, CB_GETITEMDATA, j) ;
if (nWidth)
{
pSpy -> put_ColWidth(j,nWidth);
SendDlgItemMessage(IDC_COLUMN_NAMES, CB_SETITEMDATA, j, 0);
}
}
}
SetDirty(FALSE);
m_bDirty = FALSE;
return S_OK;
}
| [
"radiowebmasters@gmail.com"
] | radiowebmasters@gmail.com |
8d4105f2d11d087ab048c81cebf1a89b7e4b6930 | ba4db75b9d1f08c6334bf7b621783759cd3209c7 | /src_main/game/shared/dod/weapon_dodfullauto_punch.cpp | 1a8dd1014e3ee70b3eada79182d6201b8dc6a638 | [] | no_license | equalent/source-2007 | a27326c6eb1e63899e3b77da57f23b79637060c0 | d07be8d02519ff5c902e1eb6430e028e1b302c8b | refs/heads/master | 2020-03-28T22:46:44.606988 | 2017-03-27T18:05:57 | 2017-03-27T18:05:57 | 149,257,460 | 2 | 0 | null | 2018-09-18T08:52:10 | 2018-09-18T08:52:09 | null | WINDOWS-1252 | C++ | false | false | 1,830 | cpp | //========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#include "cbase.h"
#include "weapon_dodfullauto_punch.h"
#include "in_buttons.h"
#include "dod_shareddefs.h"
#ifndef CLIENT_DLL
#include "dod_player.h"
#endif
IMPLEMENT_NETWORKCLASS_ALIASED( DODFullAutoPunchWeapon, DT_FullAutoPunchWeapon )
BEGIN_NETWORK_TABLE( CDODFullAutoPunchWeapon, DT_FullAutoPunchWeapon )
END_NETWORK_TABLE()
#ifdef CLIENT_DLL
BEGIN_PREDICTION_DATA( CDODFullAutoPunchWeapon )
END_PREDICTION_DATA()
#endif
void CDODFullAutoPunchWeapon::Spawn( void )
{
m_iAltFireHint = HINT_USE_MELEE;
BaseClass::Spawn();
}
void CDODFullAutoPunchWeapon::SecondaryAttack( void )
{
if ( m_bInReload )
{
m_bInReload = false;
GetPlayerOwner()->m_flNextAttack = gpGlobals->curtime;
}
else if ( GetPlayerOwner()->m_flNextAttack > gpGlobals->curtime )
{
return;
}
Punch();
// start calling ItemPostFrame
GetPlayerOwner()->m_flNextAttack = gpGlobals->curtime;
m_flNextPrimaryAttack = m_flNextSecondaryAttack;
#ifndef CLIENT_DLL
CDODPlayer *pPlayer = GetDODPlayerOwner();
if ( pPlayer )
{
pPlayer->RemoveHintTimer( m_iAltFireHint );
}
#endif
}
bool CDODFullAutoPunchWeapon::Reload( void )
{
bool bSuccess = BaseClass::Reload();
if ( bSuccess )
{
m_flNextSecondaryAttack = gpGlobals->curtime;
}
return bSuccess;
}
void CDODFullAutoPunchWeapon::ItemBusyFrame( void )
{
BaseClass::ItemBusyFrame();
CBasePlayer *pPlayer = GetPlayerOwner();
if ( pPlayer && (pPlayer->m_nButtons & IN_ATTACK2) && (m_flNextSecondaryAttack <= gpGlobals->curtime))
{
SecondaryAttack();
pPlayer->m_nButtons &= ~IN_ATTACK2;
}
}
| [
"sean@csnxs.uk"
] | sean@csnxs.uk |
be6d005f044be4b577d83b616c5a8202be94fa85 | fcc8a86c2b16ddb2777bd3b850027db3c2910094 | /arduino/museomix.ino | 72a101b4562409c51ded9db42d210a3d8a9b576d | [] | no_license | MuseomixCH/Equipe-2 | bddc815a8b2af01b25305bc29adfa8a1e9b92bd4 | eddaf9c037df03ea52eee576d54c608cea68afda | refs/heads/master | 2021-01-18T00:46:19.273340 | 2014-11-21T12:08:06 | 2014-11-21T12:08:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,519 | ino | #define trigPin 13
#define echoPin 12
#define led1 9
//#define led2 6
float color1=0;
//float color2=0;
boolean growAlpha=true;
int freq;
void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(led1, OUTPUT);
// pinMode(led2, OUTPUT);
}
void loop() {
long duration, distance;
digitalWrite(trigPin, LOW); // Added this line
delayMicroseconds(2); // Added this line
digitalWrite(trigPin, HIGH);
// delayMicroseconds(1000); - Removed this line
delayMicroseconds(10); // Added this line
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
if (distance >= 10 and distance <= 175){
growAlpha=true;
freq=1;
Serial.print(distance);
Serial.println(" right");
}
else {
growAlpha=false;
freq=3;
Serial.print(distance);
Serial.println(" cm");
}
Serial.print(color1);
Serial.println(" color1");
//Serial.print(color2);
//Serial.println(" color2");
color1=changeAlpha(color1, freq, 255, 0, growAlpha);
// color2=changeAlpha(color2, 1, 15, 0, growAlpha);
analogWrite(led1, color1);
//analogWrite(led2, color2);
delay(40);
}
float changeAlpha(float value, int frequence,int limitUp, int limitDown, boolean grow){
if(value < limitUp and grow){
value+= frequence;
}
else if(value>limitDown and !grow){
value-= frequence;
}
if(value>limitUp)
value=limitUp;
if(value<limitDown)
value=limitDown;
return value;
}
| [
"andrea.rovescalli@etu.hesge.ch"
] | andrea.rovescalli@etu.hesge.ch |
b1673cbbbf61af41ac3b650fd9284bbd20434620 | e365802f226810094ad5fc5715838e263509a8fe | /cf_447_A.cpp | ce9d871c4635bc7ea250174117b0f36f33fbd571 | [] | no_license | shivansofficial/Competitive | 1a2e781f149b5917302d69f879f7b6bf8949dc5b | b3c30da789b4375db3474ddff26cc9d0e194f327 | refs/heads/master | 2020-06-17T21:46:44.823023 | 2019-09-04T19:29:34 | 2019-09-04T19:29:34 | 196,067,168 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,276 | cpp | #include<iostream>
#include<iomanip>
#include<vector>
#include<stack>
#include<queue>
#include<deque>
#include<map>
#include<set>
#include<string>
#include<algorithm>
#include<math.h>
using namespace std;
#define X first
#define Y second
#define pb push_back
#define pf push_front
#define pob pop_back
#define pof pop_front
#define mp make_pair
#define mod 1000000007
//#define max 100007
#define itr ::iterator it
#define gcd(a,b) __gcd((a),(b))
#define lcm(a,b) ((a)*(b))/gcd((a),(b))
#define rep(X,Y) for (int (X) = 0;(X) < (Y);++(X))
#define repp(X,a,Y) for (int (X) = a;(X) < (Y);++(X))
#define set(a, b) memset(a, b, sizeof(a));
typedef long long ll;
typedef long double ld;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef vector<double> vd;
typedef vector<vi> vvi;
typedef vector<vl> vvl;
typedef vector<vd> vvd;
typedef vector<pii> vii;
typedef vector<string> vs;
#define endl '\n'
int count(string a,string b,int m,int n)
{
if((m==0 && n==0)||n==0)
return 1;
if(m==0)
return 0;
if(a[m-1]==b[n-1])
return count(a,b,m-1,n-1)+count(a,b,m-1,n);
else
return count(a,b,m-1,n);
}
int main()
{
string a;
cin>>a;
string b="QAQ";
cout<<count(a,b,a.size(),b.size())<<endl;
return 0;
}
| [
"shivanssingh82@Shivanss-MacBook-Air.local"
] | shivanssingh82@Shivanss-MacBook-Air.local |
e392f94a9fbba8d01fd90b6d5a49b676911830f2 | 5c0bc7d833e37161ad7409d2e56fd1207e3234b2 | /HW_6/simpsons.cpp | 92ce9d0b62bfc0180d963378eaddc6ad43ba605e | [] | no_license | gabrieletrata/MTH_3300 | 9888c00b2c75cca307817fd7c19cdfe36123fe77 | 24030cac363181b50841bf73ad8ee0547393d6a3 | refs/heads/master | 2020-03-24T05:56:59.347450 | 2018-07-27T00:58:38 | 2018-07-27T00:58:38 | 142,510,175 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,230 | cpp | //******************************************************************************
// simpsons.cpp
// Approximates the integral of the probability density function using Simpson's rule.
//******************************************************************************
// Name: Gabriel Etrata
// Class: MTH 3300
// Professor: Evan Fink
// Homework_6
//******************************************************************************
// Collaborators/outside sources used: NONE
//******************************************************************************
// @author Gabriel Etrata
// @version 1.0 03/27/17
#include <iostream>
#include <stdlib.h>
#include <cmath>
using namespace std;
double exp (float);
double const pi = 4 * atan(1);
/** Probability density function
@param x input value
@return phi value of the function at x
*/
double PDF(double x){
double phi = (1/sqrt(2*pi)) * exp( -0.5 * pow(x, 2));
return phi;
}
/** Simpson's rule for approximating an integral
@param a lower limit
@param b upper limit
@param n number of intervals
@return sum
*/
double simpson(double a, double b, int n){
double deltaX = (b - a) / n;
double sum = 0;
for(int i = 0; i <= n; i++){
double x_i = a + i * deltaX;
if(i == 0 || i == n){ // checks if i the first or last term of the sum (coefficient of 1)
sum += PDF(x_i);
} else if (i % 2 == 0 && i != 0 && i != n) { // checks if i is an even term of the of the sum (multiply by coefficient of 2)
sum += 2 * PDF(x_i);
} else {
sum += 4 * PDF(x_i); // checks if i is an odd term of the of the sum (multiply by coefficient of 4)
}
}
sum *= (deltaX / 3); //multiply the sum of terms by (delta x) / 3
cout << "The area under the curve is approximately: " << sum << endl;
return sum;
}
//Initializes the program and prompts user input
int main()
{
double a, b;
int n;
cout << "Input the upper limit." << endl;
cin >> b;
cout << "Input the lower limit." << endl;
cin >> a;
cout << "How many intervals? (N must be even)." << endl;
cin >> n;
simpson(a, b, n);
system("pause");
return 0;
}
| [
"gabrieletrata@gmail.com"
] | gabrieletrata@gmail.com |
842562ead4c4dd7b3d91142d5a3e4916bcfa57fd | 080a0047de59189518fdaa61249585e7ef4c5214 | /eg020-029/cpp020_validparentheses.cpp | 0bb81a8013f3b0f0c455c19d64da3a70e946cde0 | [] | no_license | jjeff-han/leetcode | ba9565e5e4c3e4468711ba6e7eb6bc3cbeca9dc5 | 30f3d0b31cccbe83a65a6527b5e2fee79ddd59ec | refs/heads/master | 2021-06-25T13:22:49.425376 | 2021-01-18T04:25:08 | 2021-01-18T04:25:08 | 195,916,790 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 743 | cpp |
#include <stdio.h>
#include <string>
#include <stack>
using namespace std;
class Solution {
public:
bool isValid(string s) {
stack<char> parentheses;
for(int i=0; i<s.size(); i++) {
if(s[i] == '(' || s[i] == '[' || s[i] == '{')
parentheses.push(s[i]);
else {
if(parentheses.empty())
return false;
if(s[i] == ')' && parentheses.top() != '(') return false;
if (s[i] == ']' && parentheses.top() != '[') return false;
if (s[i] == '}' && parentheses.top() != '{') return false;
parentheses.pop();
}
}
return parentheses.empty();
}
};
int main(void) {
Solution solve;
printf("the result is %d\n",solve.isValid("{([]){}}"));
printf("the result is %d\n",solve.isValid("([)){}"));
return 0;
}
| [
"hjf11aa@126.com"
] | hjf11aa@126.com |
509569967e56f68b2589abd54fcadeae3393372f | 4250f0f92be511b618f1d33d1dac8c785c6c8ac3 | /plugins/hid/macx/hidapi.cpp | 706a6dc109cdc60b35a6099f017ba2f56f67f326 | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | markusb/qlcplus | 833bc5a8ee4ecca6021a363cf52debe70c93620b | 1aae45b8d1914114b9a7ea6174e83e51e81ab8a1 | refs/heads/master | 2021-01-17T17:55:24.692692 | 2018-07-08T11:43:55 | 2018-07-08T11:43:55 | 29,502,948 | 0 | 0 | Apache-2.0 | 2018-07-08T11:36:46 | 2015-01-20T00:00:51 | C++ | UTF-8 | C++ | false | false | 31,645 | cpp | /*
HIDAPI - Multi-Platform library for
communication with HID devices.
Copyright (c) 2010 Alan Ott - Signal 11 Software
2010-07-03
This software may be used by anyone for any reason so
long as the copyright notice in the source files
remains intact.
*/
/* See Apple Technical Note TN2187 for details on IOHidManager. */
#include <IOKit/hid/IOHIDManager.h>
#include <IOKit/hid/IOHIDKeys.h>
#include <CoreFoundation/CoreFoundation.h>
#include <wchar.h>
#include <locale.h>
#include <pthread.h>
#include <sys/time.h>
#include <unistd.h>
#include "hidapi.h"
/* Barrier implementation because Mac OSX doesn't have pthread_barrier.
It also doesn't have clock_gettime(). So much for POSIX and SUSv2.
This implementation came from Brent Priddy and was posted on
StackOverflow. It is used with his permission. */
typedef int pthread_barrierattr_t;
typedef struct pthread_barrier {
pthread_mutex_t mutex;
pthread_cond_t cond;
int count;
int trip_count;
} pthread_barrier_t;
static int pthread_barrier_init(pthread_barrier_t *barrier, const pthread_barrierattr_t *, unsigned int count)
{
if(count == 0) {
errno = EINVAL;
return -1;
}
if(pthread_mutex_init(&barrier->mutex, 0) < 0) {
return -1;
}
if(pthread_cond_init(&barrier->cond, 0) < 0) {
pthread_mutex_destroy(&barrier->mutex);
return -1;
}
barrier->trip_count = count;
barrier->count = 0;
return 0;
}
static int pthread_barrier_destroy(pthread_barrier_t *barrier)
{
pthread_cond_destroy(&barrier->cond);
pthread_mutex_destroy(&barrier->mutex);
return 0;
}
static int pthread_barrier_wait(pthread_barrier_t *barrier)
{
pthread_mutex_lock(&barrier->mutex);
++(barrier->count);
if(barrier->count >= barrier->trip_count)
{
barrier->count = 0;
pthread_cond_broadcast(&barrier->cond);
pthread_mutex_unlock(&barrier->mutex);
return 1;
}
else
{
pthread_cond_wait(&barrier->cond, &(barrier->mutex));
pthread_mutex_unlock(&barrier->mutex);
return 0;
}
}
static int return_data(hid_device *dev, unsigned char *data, size_t length);
/* Linked List of input reports received from the device. */
struct input_report {
uint8_t *data;
size_t len;
struct input_report *next;
};
struct hid_device_ {
IOHIDDeviceRef device_handle;
int blocking;
int uses_numbered_reports;
int disconnected;
CFStringRef run_loop_mode;
CFRunLoopRef run_loop;
CFRunLoopSourceRef source;
uint8_t *input_report_buf;
CFIndex max_input_report_len;
struct input_report *input_reports;
pthread_t thread;
pthread_mutex_t mutex; /* Protects input_reports */
pthread_cond_t condition;
pthread_barrier_t barrier; /* Ensures correct startup sequence */
pthread_barrier_t shutdown_barrier; /* Ensures correct shutdown sequence */
int shutdown_thread;
};
static hid_device *new_hid_device(void)
{
hid_device *dev = (hid_device *)calloc(1, sizeof(hid_device));
dev->device_handle = NULL;
dev->blocking = 1;
dev->uses_numbered_reports = 0;
dev->disconnected = 0;
dev->run_loop_mode = NULL;
dev->run_loop = NULL;
dev->source = NULL;
dev->input_report_buf = NULL;
dev->input_reports = NULL;
dev->shutdown_thread = 0;
/* Thread objects */
pthread_mutex_init(&dev->mutex, NULL);
pthread_cond_init(&dev->condition, NULL);
pthread_barrier_init(&dev->barrier, NULL, 2);
pthread_barrier_init(&dev->shutdown_barrier, NULL, 2);
return dev;
}
static void free_hid_device(hid_device *dev)
{
if (!dev)
return;
/* Delete any input reports still left over. */
struct input_report *rpt = dev->input_reports;
while (rpt) {
struct input_report *next = rpt->next;
free(rpt->data);
free(rpt);
rpt = next;
}
/* Free the string and the report buffer. The check for NULL
is necessary here as CFRelease() doesn't handle NULL like
free() and others do. */
if (dev->run_loop_mode)
CFRelease(dev->run_loop_mode);
if (dev->source)
CFRelease(dev->source);
free(dev->input_report_buf);
/* Clean up the thread objects */
pthread_barrier_destroy(&dev->shutdown_barrier);
pthread_barrier_destroy(&dev->barrier);
pthread_cond_destroy(&dev->condition);
pthread_mutex_destroy(&dev->mutex);
/* Free the structure itself. */
free(dev);
}
static IOHIDManagerRef hid_mgr = 0x0;
#if 0
static void register_error(hid_device *device, const char *op)
{
}
#endif
static int32_t get_int_property(IOHIDDeviceRef device, CFStringRef key)
{
CFTypeRef ref;
int32_t value;
ref = IOHIDDeviceGetProperty(device, key);
if (ref) {
if (CFGetTypeID(ref) == CFNumberGetTypeID()) {
CFNumberGetValue((CFNumberRef) ref, kCFNumberSInt32Type, &value);
return value;
}
}
return 0;
}
static unsigned short get_vendor_id(IOHIDDeviceRef device)
{
return get_int_property(device, CFSTR(kIOHIDVendorIDKey));
}
static unsigned short get_product_id(IOHIDDeviceRef device)
{
return get_int_property(device, CFSTR(kIOHIDProductIDKey));
}
static int32_t get_location_id(IOHIDDeviceRef device)
{
return get_int_property(device, CFSTR(kIOHIDLocationIDKey));
}
static int32_t get_max_report_length(IOHIDDeviceRef device)
{
return get_int_property(device, CFSTR(kIOHIDMaxInputReportSizeKey));
}
static int get_string_property(IOHIDDeviceRef device, CFStringRef prop, wchar_t *buf, size_t len)
{
CFStringRef str;
if (!len)
return 0;
str = (CFStringRef)IOHIDDeviceGetProperty(device, prop);
buf[0] = 0;
if (str) {
CFIndex str_len = CFStringGetLength(str);
CFRange range;
CFIndex used_buf_len;
CFIndex chars_copied;
len --;
range.location = 0;
range.length = ((size_t)str_len > len)? len: (size_t)str_len;
chars_copied = CFStringGetBytes(str,
range,
kCFStringEncodingUTF32LE,
(char)'?',
FALSE,
(UInt8*)buf,
len * sizeof(wchar_t),
&used_buf_len);
if (chars_copied == (CFIndex)len)
buf[len] = 0; /* len is decremented above */
else
buf[chars_copied] = 0;
return 0;
}
else
return -1;
}
static int get_string_property_utf8(IOHIDDeviceRef device, CFStringRef prop, char *buf, size_t len)
{
CFStringRef str;
if (!len)
return 0;
str = (CFStringRef)IOHIDDeviceGetProperty(device, prop);
buf[0] = 0;
if (str) {
len--;
CFIndex str_len = CFStringGetLength(str);
CFRange range;
range.location = 0;
range.length = str_len;
CFIndex used_buf_len;
CFIndex chars_copied;
chars_copied = CFStringGetBytes(str,
range,
kCFStringEncodingUTF8,
(char)'?',
FALSE,
(UInt8*)buf,
len,
&used_buf_len);
if (used_buf_len == (CFIndex)len)
buf[len] = 0; /* len is decremented above */
else
buf[used_buf_len] = 0;
return used_buf_len;
}
else
return 0;
}
static int get_serial_number(IOHIDDeviceRef device, wchar_t *buf, size_t len)
{
return get_string_property(device, CFSTR(kIOHIDSerialNumberKey), buf, len);
}
static int get_manufacturer_string(IOHIDDeviceRef device, wchar_t *buf, size_t len)
{
return get_string_property(device, CFSTR(kIOHIDManufacturerKey), buf, len);
}
static int get_product_string(IOHIDDeviceRef device, wchar_t *buf, size_t len)
{
return get_string_property(device, CFSTR(kIOHIDProductKey), buf, len);
}
/* Implementation of wcsdup() for Mac. */
static wchar_t *dup_wcs(const wchar_t *s)
{
size_t len = wcslen(s);
wchar_t *ret = (wchar_t *)malloc((len+1)*sizeof(wchar_t));
wcscpy(ret, s);
return ret;
}
static int make_path(IOHIDDeviceRef device, char *buf, size_t len)
{
int res;
unsigned short vid, pid;
char transport[32];
int32_t location;
buf[0] = '\0';
res = get_string_property_utf8(
device, CFSTR(kIOHIDTransportKey),
transport, sizeof(transport));
if (!res)
return -1;
location = get_location_id(device);
vid = get_vendor_id(device);
pid = get_product_id(device);
res = snprintf(buf, len, "%s_%04hx_%04hx_%x",
transport, vid, pid, location);
buf[len-1] = '\0';
return res+1;
}
/* Initialize the IOHIDManager. Return 0 for success and -1 for failure. */
static int init_hid_manager(void)
{
/* Initialize all the HID Manager Objects */
hid_mgr = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone);
if (hid_mgr) {
IOHIDManagerSetDeviceMatching(hid_mgr, NULL);
IOHIDManagerScheduleWithRunLoop(hid_mgr, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
return 0;
}
return -1;
}
/* Initialize the IOHIDManager if necessary. This is the public function, and
it is safe to call this function repeatedly. Return 0 for success and -1
for failure. */
int HID_API_EXPORT hid_init(void)
{
if (!hid_mgr) {
return init_hid_manager();
}
/* Already initialized. */
return 0;
}
int HID_API_EXPORT hid_exit(void)
{
if (hid_mgr) {
/* Close the HID manager. */
IOHIDManagerClose(hid_mgr, kIOHIDOptionsTypeNone);
CFRelease(hid_mgr);
hid_mgr = NULL;
}
return 0;
}
static void process_pending_events(void) {
SInt32 res;
do {
res = CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.001, FALSE);
} while(res != kCFRunLoopRunFinished && res != kCFRunLoopRunTimedOut);
}
struct hid_device_info HID_API_EXPORT *hid_enumerate(unsigned short vendor_id, unsigned short product_id)
{
struct hid_device_info *root = NULL; /* return object */
struct hid_device_info *cur_dev = NULL;
CFIndex num_devices;
int i;
/* Set up the HID Manager if it hasn't been done */
if (hid_init() < 0)
return NULL;
/* give the IOHIDManager a chance to update itself */
process_pending_events();
/* Get a list of the Devices */
IOHIDManagerSetDeviceMatching(hid_mgr, NULL);
CFSetRef device_set = IOHIDManagerCopyDevices(hid_mgr);
/* Convert the list into a C array so we can iterate easily. */
num_devices = CFSetGetCount(device_set);
IOHIDDeviceRef *device_array = (IOHIDDeviceRef *)calloc(num_devices, sizeof(IOHIDDeviceRef));
CFSetGetValues(device_set, (const void **) device_array);
/* Iterate over each device, making an entry for it. */
for (i = 0; i < num_devices; i++) {
unsigned short dev_vid;
unsigned short dev_pid;
#define BUF_LEN 256
wchar_t buf[BUF_LEN];
IOHIDDeviceRef dev = device_array[i];
if (!dev) {
continue;
}
dev_vid = get_vendor_id(dev);
dev_pid = get_product_id(dev);
/* Check the VID/PID against the arguments */
if ((vendor_id == 0x0 || vendor_id == dev_vid) &&
(product_id == 0x0 || product_id == dev_pid))
{
struct hid_device_info *tmp;
size_t len;
char cbuf[BUF_LEN];
/* VID/PID match. Create the record. */
tmp = (struct hid_device_info *)malloc(sizeof(struct hid_device_info));
if (cur_dev) {
cur_dev->next = tmp;
}
else {
root = tmp;
}
cur_dev = tmp;
/* Get the Usage Page and Usage for this device. */
cur_dev->usage_page = get_int_property(dev, CFSTR(kIOHIDPrimaryUsagePageKey));
cur_dev->usage = get_int_property(dev, CFSTR(kIOHIDPrimaryUsageKey));
/* Fill out the record */
cur_dev->next = NULL;
len = make_path(dev, cbuf, sizeof(cbuf));
cur_dev->path = strdup(cbuf);
/* Serial Number */
get_serial_number(dev, buf, BUF_LEN);
cur_dev->serial_number = dup_wcs(buf);
/* Manufacturer and Product strings */
get_manufacturer_string(dev, buf, BUF_LEN);
cur_dev->manufacturer_string = dup_wcs(buf);
get_product_string(dev, buf, BUF_LEN);
cur_dev->product_string = dup_wcs(buf);
/* VID/PID */
cur_dev->vendor_id = dev_vid;
cur_dev->product_id = dev_pid;
/* Release Number */
cur_dev->release_number = get_int_property(dev, CFSTR(kIOHIDVersionNumberKey));
/* Interface Number (Unsupported on Mac)*/
cur_dev->interface_number = -1;
}
}
free(device_array);
CFRelease(device_set);
return root;
}
void HID_API_EXPORT hid_free_enumeration(struct hid_device_info *devs)
{
/* This function is identical to the Linux version. Platform independent. */
struct hid_device_info *d = devs;
while (d) {
struct hid_device_info *next = d->next;
free(d->path);
free(d->serial_number);
free(d->manufacturer_string);
free(d->product_string);
free(d);
d = next;
}
}
hid_device * HID_API_EXPORT hid_open(unsigned short vendor_id, unsigned short product_id, const wchar_t *serial_number)
{
/* This function is identical to the Linux version. Platform independent. */
struct hid_device_info *devs, *cur_dev;
const char *path_to_open = NULL;
hid_device * handle = NULL;
devs = hid_enumerate(vendor_id, product_id);
cur_dev = devs;
while (cur_dev) {
if (cur_dev->vendor_id == vendor_id &&
cur_dev->product_id == product_id) {
if (serial_number) {
if (wcscmp(serial_number, cur_dev->serial_number) == 0) {
path_to_open = cur_dev->path;
break;
}
}
else {
path_to_open = cur_dev->path;
break;
}
}
cur_dev = cur_dev->next;
}
if (path_to_open) {
/* Open the device */
handle = hid_open_path(path_to_open);
}
hid_free_enumeration(devs);
return handle;
}
static void hid_device_removal_callback(void *context, IOReturn ,
void *)
{
/* Stop the Run Loop for this device. */
hid_device *d = (hid_device *)context;
d->disconnected = 1;
CFRunLoopStop(d->run_loop);
}
/* The Run Loop calls this function for each input report received.
This function puts the data into a linked list to be picked up by
hid_read(). */
static void hid_report_callback(void *context, IOReturn , void *,
IOHIDReportType , uint32_t ,
uint8_t *report, CFIndex report_length)
{
struct input_report *rpt;
hid_device *dev = (hid_device *)context;
/* Make a new Input Report object */
rpt = (struct input_report *)calloc(1, sizeof(struct input_report));
rpt->data = (uint8_t *)calloc(1, report_length);
memcpy(rpt->data, report, report_length);
rpt->len = report_length;
rpt->next = NULL;
/* Lock this section */
pthread_mutex_lock(&dev->mutex);
/* Attach the new report object to the end of the list. */
if (dev->input_reports == NULL) {
/* The list is empty. Put it at the root. */
dev->input_reports = rpt;
}
else {
/* Find the end of the list and attach. */
struct input_report *cur = dev->input_reports;
int num_queued = 0;
while (cur->next != NULL) {
cur = cur->next;
num_queued++;
}
cur->next = rpt;
/* Pop one off if we've reached 30 in the queue. This
way we don't grow forever if the user never reads
anything from the device. */
if (num_queued > 30) {
return_data(dev, NULL, 0);
}
}
/* Signal a waiting thread that there is data. */
pthread_cond_signal(&dev->condition);
/* Unlock */
pthread_mutex_unlock(&dev->mutex);
}
/* This gets called when the read_thred's run loop gets signaled by
hid_close(), and serves to stop the read_thread's run loop. */
static void perform_signal_callback(void *context)
{
hid_device *dev = (hid_device *)context;
CFRunLoopStop(dev->run_loop); /*TODO: CFRunLoopGetCurrent()*/
}
static void *read_thread(void *param)
{
hid_device *dev = (hid_device *)param;
SInt32 code;
/* Move the device's run loop to this thread. */
IOHIDDeviceScheduleWithRunLoop(dev->device_handle, CFRunLoopGetCurrent(), dev->run_loop_mode);
/* Create the RunLoopSource which is used to signal the
event loop to stop when hid_close() is called. */
CFRunLoopSourceContext ctx;
memset(&ctx, 0, sizeof(ctx));
ctx.version = 0;
ctx.info = dev;
ctx.perform = &perform_signal_callback;
dev->source = CFRunLoopSourceCreate(kCFAllocatorDefault, 0/*order*/, &ctx);
CFRunLoopAddSource(CFRunLoopGetCurrent(), dev->source, dev->run_loop_mode);
/* Store off the Run Loop so it can be stopped from hid_close()
and on device disconnection. */
dev->run_loop = CFRunLoopGetCurrent();
/* Notify the main thread that the read thread is up and running. */
pthread_barrier_wait(&dev->barrier);
/* Run the Event Loop. CFRunLoopRunInMode() will dispatch HID input
reports into the hid_report_callback(). */
while (!dev->shutdown_thread && !dev->disconnected) {
code = CFRunLoopRunInMode(dev->run_loop_mode, 1000/*sec*/, FALSE);
/* Return if the device has been disconnected */
if (code == kCFRunLoopRunFinished) {
dev->disconnected = 1;
break;
}
/* Break if The Run Loop returns Finished or Stopped. */
if (code != kCFRunLoopRunTimedOut &&
code != kCFRunLoopRunHandledSource) {
/* There was some kind of error. Setting
shutdown seems to make sense, but
there may be something else more appropriate */
dev->shutdown_thread = 1;
break;
}
}
/* Now that the read thread is stopping, Wake any threads which are
waiting on data (in hid_read_timeout()). Do this under a mutex to
make sure that a thread which is about to go to sleep waiting on
the condition acutally will go to sleep before the condition is
signaled. */
pthread_mutex_lock(&dev->mutex);
pthread_cond_broadcast(&dev->condition);
pthread_mutex_unlock(&dev->mutex);
/* Wait here until hid_close() is called and makes it past
the call to CFRunLoopWakeUp(). This thread still needs to
be valid when that function is called on the other thread. */
pthread_barrier_wait(&dev->shutdown_barrier);
return NULL;
}
hid_device * HID_API_EXPORT hid_open_path(const char *path)
{
int i;
hid_device *dev = NULL;
CFIndex num_devices;
dev = new_hid_device();
/* Set up the HID Manager if it hasn't been done */
if (hid_init() < 0)
return NULL;
/* give the IOHIDManager a chance to update itself */
process_pending_events();
CFSetRef device_set = IOHIDManagerCopyDevices(hid_mgr);
num_devices = CFSetGetCount(device_set);
IOHIDDeviceRef *device_array = (IOHIDDeviceRef *)calloc(num_devices, sizeof(IOHIDDeviceRef));
CFSetGetValues(device_set, (const void **) device_array);
for (i = 0; i < num_devices; i++) {
char cbuf[BUF_LEN];
size_t len;
IOHIDDeviceRef os_dev = device_array[i];
len = make_path(os_dev, cbuf, sizeof(cbuf));
if (!strcmp(cbuf, path)) {
/* Matched Paths. Open this Device. */
IOReturn ret = IOHIDDeviceOpen(os_dev, kIOHIDOptionsTypeSeizeDevice);
if (ret == kIOReturnSuccess) {
char str[32];
free(device_array);
CFRetain(os_dev);
CFRelease(device_set);
dev->device_handle = os_dev;
/* Create the buffers for receiving data */
dev->max_input_report_len = (CFIndex) get_max_report_length(os_dev);
dev->input_report_buf = (uint8_t *)calloc(dev->max_input_report_len, sizeof(uint8_t));
/* Create the Run Loop Mode for this device.
printing the reference seems to work. */
sprintf(str, "HIDAPI_%p", os_dev);
dev->run_loop_mode =
CFStringCreateWithCString(NULL, str, kCFStringEncodingASCII);
/* Attach the device to a Run Loop */
IOHIDDeviceRegisterInputReportCallback(
os_dev, dev->input_report_buf, dev->max_input_report_len,
&hid_report_callback, dev);
IOHIDDeviceRegisterRemovalCallback(dev->device_handle, hid_device_removal_callback, dev);
/* Start the read thread */
pthread_create(&dev->thread, NULL, read_thread, dev);
/* Wait here for the read thread to be initialized. */
pthread_barrier_wait(&dev->barrier);
return dev;
}
else {
goto return_error;
}
}
}
return_error:
free(device_array);
CFRelease(device_set);
free_hid_device(dev);
return NULL;
}
static int set_report(hid_device *dev, IOHIDReportType type, const unsigned char *data, size_t length)
{
const unsigned char *data_to_send;
size_t length_to_send;
IOReturn res;
/* Return if the device has been disconnected. */
if (dev->disconnected)
return -1;
if (data[0] == 0x0) {
/* Not using numbered Reports.
Don't send the report number. */
data_to_send = data+1;
length_to_send = length-1;
}
else {
/* Using numbered Reports.
Send the Report Number */
data_to_send = data;
length_to_send = length;
}
if (!dev->disconnected) {
res = IOHIDDeviceSetReport(dev->device_handle,
type,
data[0], /* Report ID*/
data_to_send, length_to_send);
if (res == kIOReturnSuccess) {
return length;
}
else
return -1;
}
return -1;
}
int HID_API_EXPORT hid_write(hid_device *dev, const unsigned char *data, size_t length)
{
return set_report(dev, kIOHIDReportTypeOutput, data, length);
}
/* Helper function, so that this isn't duplicated in hid_read(). */
static int return_data(hid_device *dev, unsigned char *data, size_t length)
{
/* Copy the data out of the linked list item (rpt) into the
return buffer (data), and delete the liked list item. */
struct input_report *rpt = dev->input_reports;
size_t len = (length < rpt->len)? length: rpt->len;
memcpy(data, rpt->data, len);
dev->input_reports = rpt->next;
free(rpt->data);
free(rpt);
return len;
}
static int cond_wait(const hid_device *dev, pthread_cond_t *cond, pthread_mutex_t *mutex)
{
while (!dev->input_reports) {
int res = pthread_cond_wait(cond, mutex);
if (res != 0)
return res;
/* A res of 0 means we may have been signaled or it may
be a spurious wakeup. Check to see that there's acutally
data in the queue before returning, and if not, go back
to sleep. See the pthread_cond_timedwait() man page for
details. */
if (dev->shutdown_thread || dev->disconnected)
return -1;
}
return 0;
}
static int cond_timedwait(const hid_device *dev, pthread_cond_t *cond, pthread_mutex_t *mutex, const struct timespec *abstime)
{
while (!dev->input_reports) {
int res = pthread_cond_timedwait(cond, mutex, abstime);
if (res != 0)
return res;
/* A res of 0 means we may have been signaled or it may
be a spurious wakeup. Check to see that there's acutally
data in the queue before returning, and if not, go back
to sleep. See the pthread_cond_timedwait() man page for
details. */
if (dev->shutdown_thread || dev->disconnected)
return -1;
}
return 0;
}
int HID_API_EXPORT hid_read_timeout(hid_device *dev, unsigned char *data, size_t length, int milliseconds)
{
int bytes_read = -1;
/* Lock the access to the report list. */
pthread_mutex_lock(&dev->mutex);
/* There's an input report queued up. Return it. */
if (dev->input_reports) {
/* Return the first one */
bytes_read = return_data(dev, data, length);
goto ret;
}
/* Return if the device has been disconnected. */
if (dev->disconnected) {
bytes_read = -1;
goto ret;
}
if (dev->shutdown_thread) {
/* This means the device has been closed (or there
has been an error. An error code of -1 should
be returned. */
bytes_read = -1;
goto ret;
}
/* There is no data. Go to sleep and wait for data. */
if (milliseconds == -1) {
/* Blocking */
int res;
res = cond_wait(dev, &dev->condition, &dev->mutex);
if (res == 0)
bytes_read = return_data(dev, data, length);
else {
/* There was an error, or a device disconnection. */
bytes_read = -1;
}
}
else if (milliseconds > 0) {
/* Non-blocking, but called with timeout. */
int res;
struct timespec ts;
struct timeval tv;
gettimeofday(&tv, NULL);
TIMEVAL_TO_TIMESPEC(&tv, &ts);
ts.tv_sec += milliseconds / 1000;
ts.tv_nsec += (milliseconds % 1000) * 1000000;
if (ts.tv_nsec >= 1000000000L) {
ts.tv_sec++;
ts.tv_nsec -= 1000000000L;
}
res = cond_timedwait(dev, &dev->condition, &dev->mutex, &ts);
if (res == 0)
bytes_read = return_data(dev, data, length);
else if (res == ETIMEDOUT)
bytes_read = 0;
else
bytes_read = -1;
}
else {
/* Purely non-blocking */
bytes_read = 0;
}
ret:
/* Unlock */
pthread_mutex_unlock(&dev->mutex);
return bytes_read;
}
int HID_API_EXPORT hid_read(hid_device *dev, unsigned char *data, size_t length)
{
return hid_read_timeout(dev, data, length, (dev->blocking)? -1: 0);
}
int HID_API_EXPORT hid_set_nonblocking(hid_device *dev, int nonblock)
{
/* All Nonblocking operation is handled by the library. */
dev->blocking = !nonblock;
return 0;
}
int HID_API_EXPORT hid_send_feature_report(hid_device *dev, const unsigned char *data, size_t length)
{
return set_report(dev, kIOHIDReportTypeFeature, data, length);
}
int HID_API_EXPORT hid_get_feature_report(hid_device *dev, unsigned char *data, size_t length)
{
CFIndex len = length;
IOReturn res;
/* Return if the device has been unplugged. */
if (dev->disconnected)
return -1;
res = IOHIDDeviceGetReport(dev->device_handle,
kIOHIDReportTypeFeature,
data[0], /* Report ID */
data, &len);
if (res == kIOReturnSuccess)
return len;
else
return -1;
}
void HID_API_EXPORT hid_close(hid_device *dev)
{
if (!dev)
return;
/* Disconnect the report callback before close. */
if (!dev->disconnected) {
IOHIDDeviceRegisterInputReportCallback(
dev->device_handle, dev->input_report_buf, dev->max_input_report_len,
NULL, dev);
IOHIDDeviceRegisterRemovalCallback(dev->device_handle, NULL, dev);
IOHIDDeviceUnscheduleFromRunLoop(dev->device_handle, dev->run_loop, dev->run_loop_mode);
IOHIDDeviceScheduleWithRunLoop(dev->device_handle, CFRunLoopGetMain(), kCFRunLoopDefaultMode);
}
/* Cause read_thread() to stop. */
dev->shutdown_thread = 1;
/* Wake up the run thread's event loop so that the thread can exit. */
CFRunLoopSourceSignal(dev->source);
CFRunLoopWakeUp(dev->run_loop);
/* Notify the read thread that it can shut down now. */
pthread_barrier_wait(&dev->shutdown_barrier);
/* Wait for read_thread() to end. */
pthread_join(dev->thread, NULL);
/* Close the OS handle to the device, but only if it's not
been unplugged. If it's been unplugged, then calling
IOHIDDeviceClose() will crash. */
if (!dev->disconnected) {
IOHIDDeviceClose(dev->device_handle, kIOHIDOptionsTypeSeizeDevice);
}
/* Clear out the queue of received reports. */
pthread_mutex_lock(&dev->mutex);
while (dev->input_reports) {
return_data(dev, NULL, 0);
}
pthread_mutex_unlock(&dev->mutex);
CFRelease(dev->device_handle);
free_hid_device(dev);
}
int HID_API_EXPORT_CALL hid_get_manufacturer_string(hid_device *dev, wchar_t *string, size_t maxlen)
{
return get_manufacturer_string(dev->device_handle, string, maxlen);
}
int HID_API_EXPORT_CALL hid_get_product_string(hid_device *dev, wchar_t *string, size_t maxlen)
{
return get_product_string(dev->device_handle, string, maxlen);
}
int HID_API_EXPORT_CALL hid_get_serial_number_string(hid_device *dev, wchar_t *string, size_t maxlen)
{
return get_serial_number(dev->device_handle, string, maxlen);
}
int HID_API_EXPORT_CALL hid_get_indexed_string(hid_device *, int , wchar_t *, size_t )
{
/* TODO: */
return 0;
}
HID_API_EXPORT const wchar_t * HID_API_CALL hid_error(hid_device *)
{
/* TODO: */
return NULL;
}
#if 0
static int32_t get_usage(IOHIDDeviceRef device)
{
int32_t res;
res = get_int_property(device, CFSTR(kIOHIDDeviceUsageKey));
if (!res)
res = get_int_property(device, CFSTR(kIOHIDPrimaryUsageKey));
return res;
}
static int32_t get_usage_page(IOHIDDeviceRef device)
{
int32_t res;
res = get_int_property(device, CFSTR(kIOHIDDeviceUsagePageKey));
if (!res)
res = get_int_property(device, CFSTR(kIOHIDPrimaryUsagePageKey));
return res;
}
static int get_transport(IOHIDDeviceRef device, wchar_t *buf, size_t len)
{
return get_string_property(device, CFSTR(kIOHIDTransportKey), buf, len);
}
int main(void)
{
IOHIDManagerRef mgr;
int i;
mgr = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone);
IOHIDManagerSetDeviceMatching(mgr, NULL);
IOHIDManagerOpen(mgr, kIOHIDOptionsTypeNone);
CFSetRef device_set = IOHIDManagerCopyDevices(mgr);
CFIndex num_devices = CFSetGetCount(device_set);
IOHIDDeviceRef *device_array = calloc(num_devices, sizeof(IOHIDDeviceRef));
CFSetGetValues(device_set, (const void **) device_array);
for (i = 0; i < num_devices; i++) {
IOHIDDeviceRef dev = device_array[i];
printf("Device: %p\n", dev);
printf(" %04hx %04hx\n", get_vendor_id(dev), get_product_id(dev));
wchar_t serial[256], buf[256];
char cbuf[256];
get_serial_number(dev, serial, 256);
printf(" Serial: %ls\n", serial);
printf(" Loc: %ld\n", get_location_id(dev));
get_transport(dev, buf, 256);
printf(" Trans: %ls\n", buf);
make_path(dev, cbuf, 256);
printf(" Path: %s\n", cbuf);
}
return 0;
}
#endif
| [
"massimocallegari@yahoo.it"
] | massimocallegari@yahoo.it |
9e1ade56117da77e379292797fe85acc658429f2 | ab350b170cf12aee36b0ebed48e436b96bacbc5e | /Sources/Audio/Mp3/SoundBufferMp3.hpp | 260b4aec8645a3e5c1bfaa4365d35c902d800f3f | [
"MIT"
] | permissive | Sondro/Acid | 742398265684d5370423ce36bbb699dca3e9ee2f | 3d66868256c8c0dcc50b661f5922be6f35481b1c | refs/heads/master | 2023-04-13T00:02:51.727143 | 2020-01-31T13:52:45 | 2020-01-31T13:52:45 | 237,893,969 | 1 | 0 | MIT | 2023-04-04T01:37:35 | 2020-02-03T05:44:41 | null | UTF-8 | C++ | false | false | 371 | hpp | #pragma once
#include "Audio/SoundBuffer.hpp"
namespace acid {
class ACID_EXPORT SoundBufferMp3 : public SoundBuffer::Registrar<SoundBufferMp3> {
public:
static void Load(SoundBuffer *soundBuffer, const std::filesystem::path &filename);
static void Write(const SoundBuffer *soundBuffer, const std::filesystem::path &filename);
private:
static bool registered;
};
}
| [
"mattparks5855@gmail.com"
] | mattparks5855@gmail.com |
462e368f4932ab2345c061c3805646e75d8f18e2 | 9f59296d69ad77f192b24ee64d3e20425e125d28 | /Plugins/SceneFusion/Source/SceneFusion/Private/UI/sfUI.h | 74e9989d2e9abf1f6ed38edc6f2908eab07af7f4 | [] | no_license | Carp3d/SPARAJJ_World | 67420f60500f2ca2bdaca627a6b1bc20857a1bc9 | 7fbb6bb2cc039c855c52f419137fb535d35dd1a9 | refs/heads/master | 2022-12-18T23:33:34.085627 | 2020-09-26T18:24:26 | 2020-09-26T18:24:26 | 238,057,306 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,883 | h | #pragma once
#include "sfUISessionsPanel.h"
#include "sfUILoginPanel.h"
#include "sfUIOnlinePanel.h"
#include "sfOutlinerManager.h"
#include "../sfSessionInfo.h"
#include <sfSession.h>
#include <ksEvent.h>
#include <CoreMinimal.h>
#include <Widgets/Layout/SWidgetSwitcher.h>
using namespace KS::SceneFusion2;
/**
* Scene Fusion User Interface
*/
class sfUI : public TSharedFromThis<sfUI>
{
public:
/**
* Initialize the styles and UI components used by Scene Fusion.
*/
void Initialize();
/**
* Clean up the styles and UI components used by Scene Fusion.
*/
void Cleanup();
/**
* Gets delegate for go to camera.
*
* @return sfUIOnlinePanel::OnGoToDelegate&
*/
sfUIOnlinePanel::OnGoToDelegate& OnGoToUser();
/**
* Gets delegate for follow camera.
*
* @return sfUIOnlinePanel::OnFollowDelegate&
*/
sfUIOnlinePanel::OnFollowDelegate& OnFollowUser();
/**
* Unfollows camera.
*/
void UnfollowCamera();
/**
* Connects to a session.
*
* @param TSharedPtr<sfSessionInfo> sessionInfoPtr - determines where to connect.
*/
void JoinSession(TSharedPtr<sfSessionInfo> sessionInfoPtr);
private:
// Commands
TSharedPtr<class FUICommandList> m_UICommandListPtr;
// UI components
TSharedPtr<SWidgetSwitcher> m_panelSwitcherPtr;
TSharedPtr<SWidget> m_activeWidget;
sfUISessionsPanel m_sessionsPanel;
sfUIOnlinePanel m_onlinePanel;
sfUILoginPanel m_loginPanel;
// Event pointers
KS::ksEvent<sfSession::SPtr&, const std::string&>::SPtr m_disconnectEventPtr;
KS::ksEvent<sfUser::SPtr&>::SPtr m_userJoinEventPtr;
KS::ksEvent<sfUser::SPtr&>::SPtr m_userLeaveEventPtr;
KS::ksEvent<sfUser::SPtr&>::SPtr m_userColorChangeEventPtr;
TSharedPtr<sfOutlinerManager> m_outlinerManagerPtr;
/**
* Initialize styles.
*/
void InitializeStyles();
/**
* Initialise commands.
*/
void InitializeCommands();
/**
* Extend the level editor tool bar with a SF button
*/
void ExtendToolBar();
/**
* Register a SF Tab panel with a tab spawner.
*/
void RegisterSFTab();
/**
* Register Scene Fusion event handlers.
*/
void RegisterSFHandlers();
/**
* Register UI event handlers
*/
void RegisterUIHandlers();
/**
* Show the login panel, and hide other panels.
*/
void ShowLoginPanel();
/**
* Show the sessions panel, and hide other panels.
*/
void ShowSessionsPanel();
/**
* Show the online panel, and hide other panels.
*/
void ShowOnlinePanel();
/**
* Called when a connection attempt completes.
*
* @param sfSession::SPtr sessionPtr we connected to. nullptr if the connection failed.
* @param const std::string& errorMessage. Empty string if the connection was successful.
*/
void OnConnectComplete(sfSession::SPtr sessionPtr, const std::string& errorMessage);
/**
* Called when we disconnect from a session.
*
* @param sfSession::SPtr sessionPtr we disconnected from.
* @param const std::string& errorMessage. Empty string if no error occurred.
*/
void OnDisconnect(sfSession::SPtr sessionPtr, const std::string& errorMessage);
/**
* Create the widgets used in the toolbar.
*
* @param FToolBarBuilder& - toolbar builder
*/
void OnExtendToolBar(FToolBarBuilder& builder);
/**
* Create tool bar menu.
*
* @return TSharedRef<SWidget>
*/
TSharedRef<SWidget> OnCreateToolBarMenu();
/**
* Create the Scene Fusion tab.
*
* @param const FSpawnTabArgs& - tab spawning arguments
* @return TSharedRef<SDockTab>
*/
TSharedRef<SDockTab> OnCreateSFTab(const FSpawnTabArgs& args);
}; | [
"57542114+nyxxaltios@users.noreply.github.com"
] | 57542114+nyxxaltios@users.noreply.github.com |
d056be42398a824424abbbf96808bc015406bef1 | ad273708d98b1f73b3855cc4317bca2e56456d15 | /aws-cpp-sdk-medialive/include/aws/medialive/model/AacVbrQuality.h | b751faca5d055ab19e32b0990300eadcfcb823a2 | [
"MIT",
"Apache-2.0",
"JSON"
] | permissive | novaquark/aws-sdk-cpp | b390f2e29f86f629f9efcf41c4990169b91f4f47 | a0969508545bec9ae2864c9e1e2bb9aff109f90c | refs/heads/master | 2022-08-28T18:28:12.742810 | 2020-05-27T15:46:18 | 2020-05-27T15:46:18 | 267,351,721 | 1 | 0 | Apache-2.0 | 2020-05-27T15:08:16 | 2020-05-27T15:08:15 | null | UTF-8 | C++ | false | false | 1,132 | h | /*
* 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.
*/
#pragma once
#include <aws/medialive/MediaLive_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
namespace Aws
{
namespace MediaLive
{
namespace Model
{
enum class AacVbrQuality
{
NOT_SET,
HIGH,
LOW,
MEDIUM_HIGH,
MEDIUM_LOW
};
namespace AacVbrQualityMapper
{
AWS_MEDIALIVE_API AacVbrQuality GetAacVbrQualityForName(const Aws::String& name);
AWS_MEDIALIVE_API Aws::String GetNameForAacVbrQuality(AacVbrQuality value);
} // namespace AacVbrQualityMapper
} // namespace Model
} // namespace MediaLive
} // namespace Aws
| [
"henso@amazon.com"
] | henso@amazon.com |
155ee5523a5b2dc01bea84e1790abc596eecb40e | 2071cbd28d3ddd961e0043c3cb161ca8a4770e23 | /AtCoderBeginnerContest122/A.cpp | a31f18643284198ea1a8d3e9dec075615d92d8ba | [] | no_license | ciws009/AtCoder-Beginner-Contest-122 | e57968c5cc1df3bc50611fbf3c97c2a309ecfa7b | bd008cbddf2a7df25cbb0e97883a77733237a743 | refs/heads/master | 2020-05-01T16:41:56.042911 | 2019-03-25T14:17:32 | 2019-03-25T14:17:32 | 177,579,481 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 328 | cpp | #include <iostream>
#include <string>
#include <map>
using namespace std;
int main() {
string s; cin >> s;
string before = "ATCG";
string after = "TAGC";
map<char, char> m;
for(int i = 0; i < before.size(); i++) {
m[before[i]] = after[i];
}
char ans = m[s[0]];
cout << ans << endl;
}
| [
"stariver0812@gmail.com"
] | stariver0812@gmail.com |
cdf63a4c67f8ae5d1b0e47f71a31e10301047dfc | a95b32b1001c157ca62cf4dbf782b5109010f122 | /agchess/libagchess/Bitboard.h | 1068f7d159fdc33e5b1f17661564ab3c20211ade | [] | no_license | shyamalschandra/kivy-chess | 2306e98e9f91b915bbff70102433c57fbb19202d | 08a238632a552d52c33b960e3d07ff3e6822b5bc | refs/heads/master | 2021-01-22T00:52:03.912163 | 2014-10-09T16:32:28 | 2014-10-09T16:32:28 | 26,282,941 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,252 | h | /*
libagchess, a chess library in C++.
Copyright (C) 2010-2011 Austen Green.
libagchess is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
libagchess is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with libagchess. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef AGCHESS_BITBOARD_H
#define AGCHESS_BITBOARD_H
#include <stdint.h>
#include <iostream>
#include "Square.h"
#include "ColoredPiece.h"
namespace AGChess {
typedef uint64_t Bitboard;
enum Direction{
noWe = 7, nort = 8, noEa = 9,
west = -1, east = 1,
soWe = -9, sout = -8, soEa = -7
};
extern const Bitboard RanksBB[8];
extern const Bitboard FilesBB[8];
extern const Bitboard SquaresBB[65];
extern const Bitboard PieceMovesBB[5][64];
extern const unsigned char occupancy_bitboards[8][256];
const Bitboard EmptyBB = 0;
const Bitboard notAFile = 0xfefefefefefefefeULL;
const Bitboard notHFile = 0x7f7f7f7f7f7f7f7fULL;
const Bitboard longDiag = 0x8040201008040201ULL; // Long diagonal a1-h8
const Bitboard longAdiag =0x0102040810204080ULL; // Long antidiagonal a8-h1
Bitboard pieceMoves(Piece, Square);
Bitboard generate_ray(Square, Direction);
unsigned char generate_first_rank(unsigned char, signed char);
/* Basic shifts */
inline Bitboard nortOne(const Bitboard& b) {return b << 8;}
inline Bitboard soutOne(const Bitboard& b) {return b >> 8;}
inline Bitboard eastOne(const Bitboard& b) {return (b << 1) & notAFile;}
inline Bitboard noEaOne(const Bitboard& b) {return (b << 9) & notAFile;}
inline Bitboard soEaOne(const Bitboard& b) {return (b >> 7) & notAFile;}
inline Bitboard westOne(const Bitboard& b) {return (b >> 1) & notHFile;}
inline Bitboard soWeOne(const Bitboard& b) {return (b >> 9) & notHFile;}
inline Bitboard noWeOne(const Bitboard& b) {return (b << 7) & notHFile;}
inline Bitboard nortX(const Bitboard& b, unsigned char x) {return (x < 8) ? b << (8 * x) : EmptyBB;}
inline Bitboard soutX(const Bitboard& b, unsigned char x) {return (x < 8) ? b >> (8 * x) : EmptyBB;}
inline Bitboard eastX(const Bitboard& b, unsigned char x) {
Bitboard bb = b;
for (int i = 0; i < x; i++) {
bb = eastOne(bb);
}
return bb;
}
inline Bitboard westX(const Bitboard& b, unsigned char x) {
Bitboard bb = b;
for (int i = 0; i < x; i++) {
bb = westOne(bb);
}
return bb;
}
/* The following four methods use kindergarten bitboards to generate a bitboard
* of attacked squares for sliding pieces along a given line (rank, file, or diagonal).
* The returned set of squares represents those squares which can be attacked
* by a sliding piece, and must be filtered based on color to make sure that a sliding
* piece cannot move to a square occupied by a friendly piece. */
Bitboard rank_attacks(Bitboard occupied, Square s);
Bitboard file_attacks(Bitboard occupied, Square s);
Bitboard diagonal_attacks(Bitboard occupied, Square s);
Bitboard antidiagonal_attacks(Bitboard occupied, Square s);
inline const Bitboard& squareBB(Square s) { return SquaresBB[char(s)]; }
//inline const Bitboard& squareBB(int s) { return SquaresBB[s]; } // Is this method really needed?
inline const Bitboard& ranksBB(unsigned char rank) {return RanksBB[rank]; }
inline const Bitboard& filesBB(unsigned char file) {return FilesBB[file]; }
Square squareForBitboard(Bitboard);
int BBPopCount(Bitboard);
// Debug
extern void print_bitboard(const Bitboard&);
inline void print_hex(const Bitboard& bb) {
printf("0x%016llXULL,\n", bb);
}
}
#endif | [
"sshivaji@gmail.com"
] | sshivaji@gmail.com |
9620b3d5a6800c3207a7a523da3dd41f9a1b6869 | de41e2930dbbb64f10116ce8361ca1099a2794fb | /APTrader/APTrader/System/Win32/NamedPipeListener.h | 4c30c1af9b1bb9d9bffbacf719efea0126718c0c | [] | no_license | alexfordc/APTrader | 4c8c6151c8e4465f28a2f16f08bbebb6f224ff8c | 905015d0dfd9612158ef30b0be21fbeffc810586 | refs/heads/master | 2021-05-24T17:18:04.904225 | 2018-04-12T10:05:22 | 2018-04-12T10:05:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 691 | h | #pragma once
#include <string>
#include <Windows.h>
#include "../../Common/InitializableObject.h"
#include <mutex>
#include <thread>
#include "../../Common/Singleton.h"
typedef void(*PipeCallback)(std::string msg);
class NamedPipeListener : public InitializableObject
{
public:
NamedPipeListener(std::string pipeName);
~NamedPipeListener();
virtual void init();
void start();
void listenPipe();
void setRun(bool run);
void registerPipeCallback(PipeCallback callback);
protected:
std::string m_pipeName;
std::mutex m_mutex;
std::thread m_listenThread;
HANDLE m_hPipe;
bool m_run;
LPCRITICAL_SECTION m_criticalSection;
HANDLE m_semaphore;
PipeCallback m_pipeCallback;
}; | [
"7cronaldo@sina.com"
] | 7cronaldo@sina.com |
dfdde0f8a4affd5c5acb586f1f18e3f975db1d7d | b511bb6461363cf84afa52189603bd9d1a11ad34 | /code/11384.cpp | 6f90da00edf67a7e5d57fd8fab7a453e0c1e8c93 | [] | no_license | masumr/problem_solve | ec0059479425e49cc4c76a107556972e1c545e89 | 1ad4ec3e27f28f10662c68bbc268eaad9f5a1a9e | refs/heads/master | 2021-01-16T19:07:01.198885 | 2017-08-12T21:21:59 | 2017-08-12T21:21:59 | 100,135,794 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 221 | cpp | #include<cstdio>
using namespace std;
int main(){
int n;
while(scanf("%d",&n)==1){
int count=0;
while(n!=0){
n>>=1;
count++;
}
printf("%d\n",count);
}
}
| [
"masumr455@gmial.com"
] | masumr455@gmial.com |
cd866c529f18d60802f9a207234c75ea84651818 | 90047daeb462598a924d76ddf4288e832e86417c | /chromeos/network/network_configuration_handler.cc | f6a128a22cf4048063bc561519e9f143f6f74b27 | [
"BSD-3-Clause"
] | permissive | massbrowser/android | 99b8c21fa4552a13c06bbedd0f9c88dd4a4ad080 | a9c4371682c9443d6e1d66005d4db61a24a9617c | refs/heads/master | 2022-11-04T21:15:50.656802 | 2017-06-08T12:31:39 | 2017-06-08T12:31:39 | 93,747,579 | 2 | 2 | BSD-3-Clause | 2022-10-31T10:34:25 | 2017-06-08T12:36:07 | null | UTF-8 | C++ | false | false | 26,756 | cc | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chromeos/network/network_configuration_handler.h"
#include <stddef.h>
#include "base/bind.h"
#include "base/format_macros.h"
#include "base/guid.h"
#include "base/json/json_writer.h"
#include "base/logging.h"
#include "base/macros.h"
#include "base/memory/ptr_util.h"
#include "base/memory/ref_counted.h"
#include "base/stl_util.h"
#include "base/strings/stringprintf.h"
#include "base/values.h"
#include "chromeos/dbus/dbus_thread_manager.h"
#include "chromeos/dbus/shill_manager_client.h"
#include "chromeos/dbus/shill_profile_client.h"
#include "chromeos/dbus/shill_service_client.h"
#include "chromeos/network/network_device_handler.h"
#include "chromeos/network/network_state.h"
#include "chromeos/network/network_state_handler.h"
#include "chromeos/network/shill_property_util.h"
#include "components/device_event_log/device_event_log.h"
#include "dbus/object_path.h"
#include "third_party/cros_system_api/dbus/service_constants.h"
namespace chromeos {
namespace {
// Strip surrounding "" from keys (if present).
std::string StripQuotations(const std::string& in_str) {
size_t len = in_str.length();
if (len >= 2 && in_str[0] == '"' && in_str[len - 1] == '"')
return in_str.substr(1, len - 2);
return in_str;
}
void InvokeErrorCallback(const std::string& service_path,
const network_handler::ErrorCallback& error_callback,
const std::string& error_name) {
std::string error_msg = "Config Error: " + error_name;
NET_LOG(ERROR) << error_msg << ": " << service_path;
network_handler::RunErrorCallback(error_callback, service_path, error_name,
error_msg);
}
void SetNetworkProfileErrorCallback(
const std::string& service_path,
const std::string& profile_path,
const network_handler::ErrorCallback& error_callback,
const std::string& dbus_error_name,
const std::string& dbus_error_message) {
network_handler::ShillErrorCallbackFunction(
"Config.SetNetworkProfile Failed: " + profile_path, service_path,
error_callback, dbus_error_name, dbus_error_message);
}
void LogConfigProperties(const std::string& desc,
const std::string& path,
const base::DictionaryValue& properties) {
for (base::DictionaryValue::Iterator iter(properties); !iter.IsAtEnd();
iter.Advance()) {
std::string v = "******";
if (shill_property_util::IsLoggableShillProperty(iter.key()))
base::JSONWriter::Write(iter.value(), &v);
NET_LOG(USER) << desc << ": " << path + "." + iter.key() + "=" + v;
}
}
} // namespace
// Helper class to request from Shill the profile entries associated with a
// Service and delete the service from each profile. Triggers either
// |callback| on success or |error_callback| on failure, and calls
// |handler|->ProfileEntryDeleterCompleted() on completion to delete itself.
class NetworkConfigurationHandler::ProfileEntryDeleter {
public:
ProfileEntryDeleter(NetworkConfigurationHandler* handler,
const std::string& service_path,
const std::string& guid,
NetworkConfigurationObserver::Source source,
const base::Closure& callback,
const network_handler::ErrorCallback& error_callback)
: owner_(handler),
service_path_(service_path),
guid_(guid),
source_(source),
callback_(callback),
error_callback_(error_callback),
weak_ptr_factory_(this) {}
void RestrictToProfilePath(const std::string& profile_path) {
restrict_to_profile_path_ = profile_path;
}
void Run() {
DBusThreadManager::Get()
->GetShillServiceClient()
->GetLoadableProfileEntries(
dbus::ObjectPath(service_path_),
base::Bind(&ProfileEntryDeleter::GetProfileEntriesToDeleteCallback,
weak_ptr_factory_.GetWeakPtr()));
}
private:
void GetProfileEntriesToDeleteCallback(
DBusMethodCallStatus call_status,
const base::DictionaryValue& profile_entries) {
if (call_status != DBUS_METHOD_CALL_SUCCESS) {
InvokeErrorCallback(service_path_, error_callback_,
"GetLoadableProfileEntriesFailed");
// ProfileEntryDeleterCompleted will delete this.
owner_->ProfileEntryDeleterCompleted(service_path_, guid_, source_,
false /* failed */);
return;
}
for (base::DictionaryValue::Iterator iter(profile_entries); !iter.IsAtEnd();
iter.Advance()) {
std::string profile_path = StripQuotations(iter.key());
std::string entry_path;
iter.value().GetAsString(&entry_path);
if (profile_path.empty() || entry_path.empty()) {
NET_LOG(ERROR) << "Failed to parse Profile Entry: " << profile_path
<< ": " << entry_path;
continue;
}
if (profile_delete_entries_.count(profile_path) != 0) {
NET_LOG(ERROR) << "Multiple Profile Entries: " << profile_path << ": "
<< entry_path;
continue;
}
if (!restrict_to_profile_path_.empty() &&
profile_path != restrict_to_profile_path_) {
NET_LOG(DEBUG) << "Skip deleting Profile Entry: " << profile_path
<< ": " << entry_path << " - removal is restricted to "
<< restrict_to_profile_path_ << " profile";
continue;
}
NET_LOG(DEBUG) << "Delete Profile Entry: " << profile_path << ": "
<< entry_path;
profile_delete_entries_[profile_path] = entry_path;
DBusThreadManager::Get()->GetShillProfileClient()->DeleteEntry(
dbus::ObjectPath(profile_path), entry_path,
base::Bind(&ProfileEntryDeleter::ProfileEntryDeletedCallback,
weak_ptr_factory_.GetWeakPtr(), profile_path, entry_path),
base::Bind(&ProfileEntryDeleter::ShillErrorCallback,
weak_ptr_factory_.GetWeakPtr(), profile_path, entry_path));
}
RunCallbackIfDone();
}
void ProfileEntryDeletedCallback(const std::string& profile_path,
const std::string& entry) {
NET_LOG(DEBUG) << "Profile Entry Deleted: " << profile_path << ": "
<< entry;
profile_delete_entries_.erase(profile_path);
RunCallbackIfDone();
}
void RunCallbackIfDone() {
if (!profile_delete_entries_.empty())
return;
// Run the callback if this is the last pending deletion.
if (!callback_.is_null())
callback_.Run();
// ProfileEntryDeleterCompleted will delete this.
owner_->ProfileEntryDeleterCompleted(service_path_, guid_, source_,
true /* success */);
}
void ShillErrorCallback(const std::string& profile_path,
const std::string& entry,
const std::string& dbus_error_name,
const std::string& dbus_error_message) {
// Any Shill Error triggers a failure / error.
network_handler::ShillErrorCallbackFunction(
"GetLoadableProfileEntries Failed", profile_path, error_callback_,
dbus_error_name, dbus_error_message);
// Delete this even if there are pending deletions; any callbacks will
// safely become no-ops (by invalidating the WeakPtrs).
owner_->ProfileEntryDeleterCompleted(service_path_, guid_, source_,
false /* failed */);
}
NetworkConfigurationHandler* owner_; // Unowned
std::string service_path_;
// Non empty if the service has to be removed only from a single profile. This
// value is the profile path of the profile in question.
std::string restrict_to_profile_path_;
std::string guid_;
NetworkConfigurationObserver::Source source_;
base::Closure callback_;
network_handler::ErrorCallback error_callback_;
// Map of pending profile entry deletions, indexed by profile path.
std::map<std::string, std::string> profile_delete_entries_;
base::WeakPtrFactory<ProfileEntryDeleter> weak_ptr_factory_;
DISALLOW_COPY_AND_ASSIGN(ProfileEntryDeleter);
};
// NetworkConfigurationHandler
void NetworkConfigurationHandler::AddObserver(
NetworkConfigurationObserver* observer) {
observers_.AddObserver(observer);
}
void NetworkConfigurationHandler::RemoveObserver(
NetworkConfigurationObserver* observer) {
observers_.RemoveObserver(observer);
}
void NetworkConfigurationHandler::GetShillProperties(
const std::string& service_path,
const network_handler::DictionaryResultCallback& callback,
const network_handler::ErrorCallback& error_callback) {
NET_LOG(USER) << "GetShillProperties: " << service_path;
const NetworkState* network_state =
network_state_handler_->GetNetworkState(service_path);
if (network_state &&
NetworkTypePattern::Tether().MatchesType(network_state->type())) {
// If this is a Tether network, use the properties present in the
// NetworkState object provided by NetworkStateHandler. Tether networks are
// not present in Shill, so the Shill call below will not work.
base::DictionaryValue dictionary;
network_state->GetStateProperties(&dictionary);
callback.Run(service_path, dictionary);
return;
}
DBusThreadManager::Get()->GetShillServiceClient()->GetProperties(
dbus::ObjectPath(service_path),
base::Bind(&NetworkConfigurationHandler::GetPropertiesCallback,
weak_ptr_factory_.GetWeakPtr(), callback, error_callback,
service_path));
}
void NetworkConfigurationHandler::SetShillProperties(
const std::string& service_path,
const base::DictionaryValue& shill_properties,
NetworkConfigurationObserver::Source source,
const base::Closure& callback,
const network_handler::ErrorCallback& error_callback) {
if (shill_properties.empty()) {
if (!callback.is_null())
callback.Run();
return;
}
NET_LOG(USER) << "SetShillProperties: " << service_path;
std::unique_ptr<base::DictionaryValue> properties_to_set(
shill_properties.DeepCopy());
// Make sure that the GUID is saved to Shill when setting properties.
std::string guid;
properties_to_set->GetStringWithoutPathExpansion(shill::kGuidProperty, &guid);
if (guid.empty()) {
const NetworkState* network_state =
network_state_handler_->GetNetworkState(service_path);
guid = network_state ? network_state->guid() : base::GenerateGUID();
properties_to_set->SetStringWithoutPathExpansion(shill::kGuidProperty,
guid);
}
LogConfigProperties("SetProperty", service_path, *properties_to_set);
std::unique_ptr<base::DictionaryValue> properties_copy(
properties_to_set->DeepCopy());
DBusThreadManager::Get()->GetShillServiceClient()->SetProperties(
dbus::ObjectPath(service_path), *properties_to_set,
base::Bind(&NetworkConfigurationHandler::SetPropertiesSuccessCallback,
weak_ptr_factory_.GetWeakPtr(), service_path,
base::Passed(&properties_copy), source, callback),
base::Bind(&NetworkConfigurationHandler::SetPropertiesErrorCallback,
weak_ptr_factory_.GetWeakPtr(), service_path, error_callback));
// If we set the StaticIPConfig property, request an IP config refresh
// after calling SetProperties.
if (properties_to_set->HasKey(shill::kStaticIPConfigProperty))
RequestRefreshIPConfigs(service_path);
}
void NetworkConfigurationHandler::ClearShillProperties(
const std::string& service_path,
const std::vector<std::string>& names,
const base::Closure& callback,
const network_handler::ErrorCallback& error_callback) {
if (names.empty()) {
if (!callback.is_null())
callback.Run();
return;
}
NET_LOG(USER) << "ClearShillProperties: " << service_path;
for (std::vector<std::string>::const_iterator iter = names.begin();
iter != names.end(); ++iter) {
NET_LOG(DEBUG) << "ClearProperty: " << service_path << "." << *iter;
}
DBusThreadManager::Get()->GetShillServiceClient()->ClearProperties(
dbus::ObjectPath(service_path), names,
base::Bind(&NetworkConfigurationHandler::ClearPropertiesSuccessCallback,
weak_ptr_factory_.GetWeakPtr(), service_path, names, callback),
base::Bind(&NetworkConfigurationHandler::ClearPropertiesErrorCallback,
weak_ptr_factory_.GetWeakPtr(), service_path, error_callback));
}
void NetworkConfigurationHandler::CreateShillConfiguration(
const base::DictionaryValue& shill_properties,
NetworkConfigurationObserver::Source source,
const network_handler::ServiceResultCallback& callback,
const network_handler::ErrorCallback& error_callback) {
ShillManagerClient* manager =
DBusThreadManager::Get()->GetShillManagerClient();
std::string type;
shill_properties.GetStringWithoutPathExpansion(shill::kTypeProperty, &type);
DCHECK(!type.empty());
std::string network_id =
shill_property_util::GetNetworkIdFromProperties(shill_properties);
if (NetworkTypePattern::Ethernet().MatchesType(type)) {
InvokeErrorCallback(network_id, error_callback,
"ConfigureServiceForProfile: Invalid type: " + type);
return;
}
std::unique_ptr<base::DictionaryValue> properties_to_set(
shill_properties.DeepCopy());
NET_LOG(USER) << "CreateShillConfiguration: " << type << ": " << network_id;
std::string profile_path;
properties_to_set->GetStringWithoutPathExpansion(shill::kProfileProperty,
&profile_path);
DCHECK(!profile_path.empty());
// Make sure that the GUID is saved to Shill when configuring networks.
std::string guid;
properties_to_set->GetStringWithoutPathExpansion(shill::kGuidProperty, &guid);
if (guid.empty()) {
guid = base::GenerateGUID();
properties_to_set->SetStringWithoutPathExpansion(
::onc::network_config::kGUID, guid);
}
LogConfigProperties("Configure", type, *properties_to_set);
std::unique_ptr<base::DictionaryValue> properties_copy(
properties_to_set->DeepCopy());
manager->ConfigureServiceForProfile(
dbus::ObjectPath(profile_path), *properties_to_set,
base::Bind(&NetworkConfigurationHandler::ConfigurationCompleted,
weak_ptr_factory_.GetWeakPtr(), profile_path, source,
base::Passed(&properties_copy), callback),
base::Bind(&network_handler::ShillErrorCallbackFunction,
"Config.CreateConfiguration Failed", "", error_callback));
}
void NetworkConfigurationHandler::RemoveConfiguration(
const std::string& service_path,
NetworkConfigurationObserver::Source source,
const base::Closure& callback,
const network_handler::ErrorCallback& error_callback) {
RemoveConfigurationFromProfile(service_path, "", source, callback,
error_callback);
}
void NetworkConfigurationHandler::RemoveConfigurationFromCurrentProfile(
const std::string& service_path,
NetworkConfigurationObserver::Source source,
const base::Closure& callback,
const network_handler::ErrorCallback& error_callback) {
const NetworkState* network_state =
network_state_handler_->GetNetworkState(service_path);
if (!network_state || network_state->profile_path().empty()) {
InvokeErrorCallback(service_path, error_callback, "NetworkNotConfigured");
return;
}
RemoveConfigurationFromProfile(service_path, network_state->profile_path(),
source, callback, error_callback);
}
void NetworkConfigurationHandler::RemoveConfigurationFromProfile(
const std::string& service_path,
const std::string& profile_path,
NetworkConfigurationObserver::Source source,
const base::Closure& callback,
const network_handler::ErrorCallback& error_callback) {
// Service.Remove is not reliable. Instead, request the profile entries
// for the service and remove each entry.
if (base::ContainsKey(profile_entry_deleters_, service_path)) {
InvokeErrorCallback(service_path, error_callback,
"RemoveConfigurationInProgress");
return;
}
std::string guid;
const NetworkState* network_state =
network_state_handler_->GetNetworkState(service_path);
if (network_state)
guid = network_state->guid();
NET_LOG(USER) << "Remove Configuration: " << service_path
<< " from profiles: "
<< (!profile_path.empty() ? profile_path : "all");
ProfileEntryDeleter* deleter = new ProfileEntryDeleter(
this, service_path, guid, source, callback, error_callback);
if (!profile_path.empty())
deleter->RestrictToProfilePath(profile_path);
profile_entry_deleters_[service_path] = base::WrapUnique(deleter);
deleter->Run();
}
void NetworkConfigurationHandler::SetNetworkProfile(
const std::string& service_path,
const std::string& profile_path,
NetworkConfigurationObserver::Source source,
const base::Closure& callback,
const network_handler::ErrorCallback& error_callback) {
NET_LOG(USER) << "SetNetworkProfile: " << service_path << ": "
<< profile_path;
base::Value profile_path_value(profile_path);
DBusThreadManager::Get()->GetShillServiceClient()->SetProperty(
dbus::ObjectPath(service_path), shill::kProfileProperty,
profile_path_value,
base::Bind(&NetworkConfigurationHandler::SetNetworkProfileCompleted,
weak_ptr_factory_.GetWeakPtr(), service_path, profile_path,
source, callback),
base::Bind(&SetNetworkProfileErrorCallback, service_path, profile_path,
error_callback));
}
// NetworkStateHandlerObserver methods
void NetworkConfigurationHandler::NetworkListChanged() {
for (auto iter = configure_callbacks_.begin();
iter != configure_callbacks_.end();) {
const std::string& service_path = iter->first;
const NetworkState* state =
network_state_handler_->GetNetworkStateFromServicePath(service_path,
true);
if (!state) {
NET_LOG(ERROR) << "Configured network not in list: " << service_path;
++iter;
continue;
}
network_handler::ServiceResultCallback& callback = iter->second;
callback.Run(service_path, state->guid());
iter = configure_callbacks_.erase(iter);
}
}
void NetworkConfigurationHandler::OnShuttingDown() {
network_state_handler_->RemoveObserver(this, FROM_HERE);
}
// NetworkConfigurationHandler Private methods
NetworkConfigurationHandler::NetworkConfigurationHandler()
: network_state_handler_(nullptr), weak_ptr_factory_(this) {}
NetworkConfigurationHandler::~NetworkConfigurationHandler() {
}
void NetworkConfigurationHandler::Init(
NetworkStateHandler* network_state_handler,
NetworkDeviceHandler* network_device_handler) {
network_state_handler_ = network_state_handler;
network_device_handler_ = network_device_handler;
// Observer is removed in OnShuttingDown() observer override.
network_state_handler_->AddObserver(this, FROM_HERE);
}
void NetworkConfigurationHandler::ConfigurationCompleted(
const std::string& profile_path,
NetworkConfigurationObserver::Source source,
std::unique_ptr<base::DictionaryValue> configure_properties,
const network_handler::ServiceResultCallback& callback,
const dbus::ObjectPath& service_path) {
// Shill should send a network list update, but to ensure that Shill sends
// the newly configured properties immediately, request an update here.
network_state_handler_->RequestUpdateForNetwork(service_path.value());
// Notify observers immediately. (Note: Currently this is primarily used
// by tests).
for (auto& observer : observers_) {
observer.OnConfigurationCreated(service_path.value(), profile_path,
*configure_properties, source);
}
if (callback.is_null())
return;
// |configure_callbacks_| will get triggered when NetworkStateHandler
// notifies this that a state list update has occurred. |service_path|
// is unique per configuration. In the unlikely case that an existing
// configuration is reconfigured twice without a NetworkStateHandler update,
// (the UI should prevent that) the first callback will not get called.
configure_callbacks_[service_path.value()] = callback;
}
void NetworkConfigurationHandler::ProfileEntryDeleterCompleted(
const std::string& service_path,
const std::string& guid,
NetworkConfigurationObserver::Source source,
bool success) {
if (success) {
for (auto& observer : observers_)
observer.OnConfigurationRemoved(service_path, guid, source);
}
auto iter = profile_entry_deleters_.find(service_path);
DCHECK(iter != profile_entry_deleters_.end());
profile_entry_deleters_.erase(iter);
}
void NetworkConfigurationHandler::SetNetworkProfileCompleted(
const std::string& service_path,
const std::string& profile_path,
NetworkConfigurationObserver::Source source,
const base::Closure& callback) {
if (!callback.is_null())
callback.Run();
for (auto& observer : observers_)
observer.OnConfigurationProfileChanged(service_path, profile_path, source);
}
void NetworkConfigurationHandler::GetPropertiesCallback(
const network_handler::DictionaryResultCallback& callback,
const network_handler::ErrorCallback& error_callback,
const std::string& service_path,
DBusMethodCallStatus call_status,
const base::DictionaryValue& properties) {
if (call_status != DBUS_METHOD_CALL_SUCCESS) {
// Because network services are added and removed frequently, we will see
// failures regularly, so don't log these.
network_handler::RunErrorCallback(error_callback, service_path,
network_handler::kDBusFailedError,
network_handler::kDBusFailedErrorMessage);
return;
}
if (callback.is_null())
return;
// Get the correct name from WifiHex if necessary.
std::unique_ptr<base::DictionaryValue> properties_copy(properties.DeepCopy());
std::string name =
shill_property_util::GetNameFromProperties(service_path, properties);
if (!name.empty())
properties_copy->SetStringWithoutPathExpansion(shill::kNameProperty, name);
// Get the GUID property from NetworkState if it is not set in Shill.
std::string guid;
properties.GetStringWithoutPathExpansion(::onc::network_config::kGUID, &guid);
if (guid.empty()) {
const NetworkState* network_state =
network_state_handler_->GetNetworkState(service_path);
if (network_state) {
properties_copy->SetStringWithoutPathExpansion(
::onc::network_config::kGUID, network_state->guid());
}
}
callback.Run(service_path, *properties_copy.get());
}
void NetworkConfigurationHandler::SetPropertiesSuccessCallback(
const std::string& service_path,
std::unique_ptr<base::DictionaryValue> set_properties,
NetworkConfigurationObserver::Source source,
const base::Closure& callback) {
if (!callback.is_null())
callback.Run();
const NetworkState* network_state =
network_state_handler_->GetNetworkState(service_path);
if (!network_state)
return; // Network no longer exists, do not notify or request update.
for (auto& observer : observers_) {
observer.OnPropertiesSet(service_path, network_state->guid(),
*set_properties, source);
}
network_state_handler_->RequestUpdateForNetwork(service_path);
}
void NetworkConfigurationHandler::SetPropertiesErrorCallback(
const std::string& service_path,
const network_handler::ErrorCallback& error_callback,
const std::string& dbus_error_name,
const std::string& dbus_error_message) {
network_handler::ShillErrorCallbackFunction(
"Config.SetProperties Failed", service_path, error_callback,
dbus_error_name, dbus_error_message);
// Some properties may have changed so request an update regardless.
network_state_handler_->RequestUpdateForNetwork(service_path);
}
void NetworkConfigurationHandler::ClearPropertiesSuccessCallback(
const std::string& service_path,
const std::vector<std::string>& names,
const base::Closure& callback,
const base::ListValue& result) {
const std::string kClearPropertiesFailedError("Error.ClearPropertiesFailed");
DCHECK(names.size() == result.GetSize())
<< "Incorrect result size from ClearProperties.";
for (size_t i = 0; i < result.GetSize(); ++i) {
bool success = false;
result.GetBoolean(i, &success);
if (!success) {
// If a property was cleared that has never been set, the clear will fail.
// We do not track which properties have been set, so just log the error.
NET_LOG(ERROR) << "ClearProperties Failed: " << service_path << ": "
<< names[i];
}
}
if (!callback.is_null())
callback.Run();
network_state_handler_->RequestUpdateForNetwork(service_path);
}
void NetworkConfigurationHandler::ClearPropertiesErrorCallback(
const std::string& service_path,
const network_handler::ErrorCallback& error_callback,
const std::string& dbus_error_name,
const std::string& dbus_error_message) {
network_handler::ShillErrorCallbackFunction(
"Config.ClearProperties Failed", service_path, error_callback,
dbus_error_name, dbus_error_message);
// Some properties may have changed so request an update regardless.
network_state_handler_->RequestUpdateForNetwork(service_path);
}
void NetworkConfigurationHandler::RequestRefreshIPConfigs(
const std::string& service_path) {
if (!network_device_handler_)
return;
const NetworkState* network_state =
network_state_handler_->GetNetworkState(service_path);
if (!network_state || network_state->device_path().empty())
return;
network_device_handler_->RequestRefreshIPConfigs(
network_state->device_path(), base::Bind(&base::DoNothing),
network_handler::ErrorCallback());
}
// static
NetworkConfigurationHandler* NetworkConfigurationHandler::InitializeForTest(
NetworkStateHandler* network_state_handler,
NetworkDeviceHandler* network_device_handler) {
NetworkConfigurationHandler* handler = new NetworkConfigurationHandler();
handler->Init(network_state_handler, network_device_handler);
return handler;
}
} // namespace chromeos
| [
"xElvis89x@gmail.com"
] | xElvis89x@gmail.com |
612ef14b3b9cc9de5143c6e96170daec7bd2e987 | acea6cd23fa94e2361c8a2bc8a85fe25d00b9d16 | /src/algorithm/cpp/count-and-say/Solution.cpp | 85bbe031c2a63f459cef6dad0f12948bdd9d56cc | [] | no_license | huaxiufeng/leetcode | 77742e90a11263475a49ce9beadfa923515d3109 | 5c5dec2044897e3ccb82d310e15ca608ec30e588 | refs/heads/master | 2021-06-04T08:50:59.125768 | 2019-10-21T09:11:42 | 2019-10-21T09:11:42 | 27,822,279 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,062 | cpp | class Solution
{
public:
string countAndSay(int n) {
if (1 == n) {
return "1";
} else {
return next(countAndSay(n-1));
}
}
private:
string next(string s) {
if (!s.length()) {
return s;
}
string result;
char c = s.at(0);
char count_str[256];
int count = 0;
for (size_t i = 0; i < s.length(); i++) {
if (count == 0) {
c = s.at(i);
count++;
} else {
if (c == s.at(i)) {
count++;
} else {
snprintf(count_str, sizeof(count_str), "%d", count);
result += count_str;
result += c;
c = s.at(i);
count = 1;
}
}
}
if (count > 0) {
snprintf(count_str, sizeof(count_str), "%d", count);
result += count_str;
result += c;
}
return result;
}
};
| [
"huaxiufeng@kaisquare.com.cn"
] | huaxiufeng@kaisquare.com.cn |
f8ecc2502607a4232866b7fe37b885abf171ac25 | 8309d4d3f6d7185541d0486fc92362aaac169481 | /libraries/MySQL_Connector_Arduino-master/examples/basic_insert_esp8266/basic_insert_esp8266.ino | 24ce11494bf4f09f63d8090b7f0bd42f998df915 | [] | no_license | jrfadrigalan/Arduino | cf9a1d5137e2b5961cb4ba7ddcc33fb73c29a43b | 795cee5d7891f2132132a4ebb5d984cdcabadb38 | refs/heads/master | 2021-03-27T20:06:34.132694 | 2018-03-07T00:50:22 | 2018-03-07T00:50:22 | 124,159,587 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,482 | ino | /*
MySQL Connector/Arduino Example : connect by wifi
This example demonstrates how to connect to a MySQL server from an
Arduino using an Arduino-compatible Wifi shield. Note that "compatible"
means it must conform to the Ethernet class library or be a derivative
thereof. See the documentation located in the /docs folder for more
details.
INSTRUCTIONS FOR USE
1) Change the address of the server to the IP address of the MySQL server
2) Change the user and password to a valid MySQL user and password
3) Change the SSID and pass to match your WiFi network
4) Connect a USB cable to your Arduino
5) Select the correct board and port
6) Compile and upload the sketch to your Arduino
7) Once uploaded, open Serial Monitor (use 115200 speed) and observe
If you do not see messages indicating you have a connection, refer to the
manual for troubleshooting tips. The most common issues are the server is
not accessible from the network or the user name and password is incorrect.
Created by: Dr. Charles A. Bell
*/
#include <ESP8266WiFi.h> // Use this for WiFi instead of Ethernet.h
#include <MySQL_Connection.h>
#include <MySQL_Cursor.h>
IPAddress server_addr(10,0,1,35); // IP of the MySQL *server* here
char user[] = "root"; // MySQL user login username
char password[] = "secret"; // MySQL user login password
// Sample query
char INSERT_SQL[] = "INSERT INTO test_arduino.hello_arduino (message) VALUES ('Hello, Arduino!')";
// WiFi card example
char ssid[] = "your-ssid"; // your SSID
char pass[] = "ssid-password"; // your SSID Password
WiFiClient client; // Use this for WiFi instead of EthernetClient
MySQL_Connection conn(&client);
MySQL_Cursor cursor(&conn);
void setup()
{
Serial.begin(115200);
while (!Serial); // wait for serial port to connect. Needed for Leonardo only
// Begin WiFi section
Serial.printf("\nConnecting to %s", ssid);
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
// print out info about the connection:
Serial.println("\nConnected to network");
Serial.print("My IP address is: ");
Serial.println(WiFi.localIP());
Serial.print("Connecting to SQL... ");
if (conn.connect(server_addr, 3306, user, password))
Serial.println("OK.");
else
Serial.println("FAILED.");
}
void loop()
{
if (conn.connected())
cursor.execute(INSERT_SQL);
delay(5000);
}
| [
"jrfadrigalan1@gmail.com"
] | jrfadrigalan1@gmail.com |
ff6d365e0843ef66070a3f87c7c7c0c669d2c385 | 693e799b1388422562d89c1fd7d0429e527a4d21 | /qtrobot_ws/devel_isolated/moveit_msgs/include/moveit_msgs/SaveRobotStateToWarehouseRequest.h | c7d4e5192e20d8d7f0a0dc29bf56b7708e3a0d0e | [] | no_license | ZouJennie/iReCheck | bb777a8524b0d1d23c65ac4be9c87a073a888de4 | 00e64899989869be6bcb82d6919ab1fb69fc0dea | refs/heads/master | 2022-12-06T15:13:41.873122 | 2020-08-19T13:42:42 | 2020-08-19T13:42:42 | 248,212,568 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 20,357 | h | // Generated by gencpp from file moveit_msgs/SaveRobotStateToWarehouseRequest.msg
// DO NOT EDIT!
#ifndef MOVEIT_MSGS_MESSAGE_SAVEROBOTSTATETOWAREHOUSEREQUEST_H
#define MOVEIT_MSGS_MESSAGE_SAVEROBOTSTATETOWAREHOUSEREQUEST_H
#include <string>
#include <vector>
#include <map>
#include <ros/types.h>
#include <ros/serialization.h>
#include <ros/builtin_message_traits.h>
#include <ros/message_operations.h>
#include <moveit_msgs/RobotState.h>
namespace moveit_msgs
{
template <class ContainerAllocator>
struct SaveRobotStateToWarehouseRequest_
{
typedef SaveRobotStateToWarehouseRequest_<ContainerAllocator> Type;
SaveRobotStateToWarehouseRequest_()
: name()
, robot()
, state() {
}
SaveRobotStateToWarehouseRequest_(const ContainerAllocator& _alloc)
: name(_alloc)
, robot(_alloc)
, state(_alloc) {
(void)_alloc;
}
typedef std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > _name_type;
_name_type name;
typedef std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > _robot_type;
_robot_type robot;
typedef ::moveit_msgs::RobotState_<ContainerAllocator> _state_type;
_state_type state;
typedef boost::shared_ptr< ::moveit_msgs::SaveRobotStateToWarehouseRequest_<ContainerAllocator> > Ptr;
typedef boost::shared_ptr< ::moveit_msgs::SaveRobotStateToWarehouseRequest_<ContainerAllocator> const> ConstPtr;
}; // struct SaveRobotStateToWarehouseRequest_
typedef ::moveit_msgs::SaveRobotStateToWarehouseRequest_<std::allocator<void> > SaveRobotStateToWarehouseRequest;
typedef boost::shared_ptr< ::moveit_msgs::SaveRobotStateToWarehouseRequest > SaveRobotStateToWarehouseRequestPtr;
typedef boost::shared_ptr< ::moveit_msgs::SaveRobotStateToWarehouseRequest const> SaveRobotStateToWarehouseRequestConstPtr;
// constants requiring out of line definition
template<typename ContainerAllocator>
std::ostream& operator<<(std::ostream& s, const ::moveit_msgs::SaveRobotStateToWarehouseRequest_<ContainerAllocator> & v)
{
ros::message_operations::Printer< ::moveit_msgs::SaveRobotStateToWarehouseRequest_<ContainerAllocator> >::stream(s, "", v);
return s;
}
} // namespace moveit_msgs
namespace ros
{
namespace message_traits
{
// BOOLTRAITS {'IsFixedSize': False, 'IsMessage': True, 'HasHeader': False}
// {'shape_msgs': ['/opt/ros/kinetic/share/shape_msgs/cmake/../msg'], 'std_msgs': ['/opt/ros/kinetic/share/std_msgs/cmake/../msg'], 'moveit_msgs': ['/home/jennie/irecheck/iReCheck/qtrobot_ws/devel_isolated/moveit_msgs/share/moveit_msgs/msg', '/home/jennie/irecheck/iReCheck/qtrobot_ws/src/moveit_msgs/msg'], 'trajectory_msgs': ['/opt/ros/kinetic/share/trajectory_msgs/cmake/../msg'], 'sensor_msgs': ['/opt/ros/kinetic/share/sensor_msgs/cmake/../msg'], 'object_recognition_msgs': ['/opt/ros/kinetic/share/object_recognition_msgs/cmake/../msg'], 'octomap_msgs': ['/opt/ros/kinetic/share/octomap_msgs/cmake/../msg'], 'geometry_msgs': ['/opt/ros/kinetic/share/geometry_msgs/cmake/../msg'], 'actionlib_msgs': ['/opt/ros/kinetic/share/actionlib_msgs/cmake/../msg']}
// !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types']
template <class ContainerAllocator>
struct IsFixedSize< ::moveit_msgs::SaveRobotStateToWarehouseRequest_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct IsFixedSize< ::moveit_msgs::SaveRobotStateToWarehouseRequest_<ContainerAllocator> const>
: FalseType
{ };
template <class ContainerAllocator>
struct IsMessage< ::moveit_msgs::SaveRobotStateToWarehouseRequest_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::moveit_msgs::SaveRobotStateToWarehouseRequest_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct HasHeader< ::moveit_msgs::SaveRobotStateToWarehouseRequest_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct HasHeader< ::moveit_msgs::SaveRobotStateToWarehouseRequest_<ContainerAllocator> const>
: FalseType
{ };
template<class ContainerAllocator>
struct MD5Sum< ::moveit_msgs::SaveRobotStateToWarehouseRequest_<ContainerAllocator> >
{
static const char* value()
{
return "2b4f627ca3cd5a0cdeac277b421f5197";
}
static const char* value(const ::moveit_msgs::SaveRobotStateToWarehouseRequest_<ContainerAllocator>&) { return value(); }
static const uint64_t static_value1 = 0x2b4f627ca3cd5a0cULL;
static const uint64_t static_value2 = 0xdeac277b421f5197ULL;
};
template<class ContainerAllocator>
struct DataType< ::moveit_msgs::SaveRobotStateToWarehouseRequest_<ContainerAllocator> >
{
static const char* value()
{
return "moveit_msgs/SaveRobotStateToWarehouseRequest";
}
static const char* value(const ::moveit_msgs::SaveRobotStateToWarehouseRequest_<ContainerAllocator>&) { return value(); }
};
template<class ContainerAllocator>
struct Definition< ::moveit_msgs::SaveRobotStateToWarehouseRequest_<ContainerAllocator> >
{
static const char* value()
{
return "string name\n\
string robot\n\
moveit_msgs/RobotState state\n\
\n\
\n\
================================================================================\n\
MSG: moveit_msgs/RobotState\n\
# This message contains information about the robot state, i.e. the positions of its joints and links\n\
sensor_msgs/JointState joint_state\n\
\n\
# Joints that may have multiple DOF are specified here\n\
sensor_msgs/MultiDOFJointState multi_dof_joint_state\n\
\n\
# Attached collision objects (attached to some link on the robot)\n\
AttachedCollisionObject[] attached_collision_objects\n\
\n\
# Flag indicating whether this scene is to be interpreted as a diff with respect to some other scene\n\
# This is mostly important for handling the attached bodies (whether or not to clear the attached bodies\n\
# of a moveit::core::RobotState before updating it with this message)\n\
bool is_diff\n\
\n\
================================================================================\n\
MSG: sensor_msgs/JointState\n\
# This is a message that holds data to describe the state of a set of torque controlled joints. \n\
#\n\
# The state of each joint (revolute or prismatic) is defined by:\n\
# * the position of the joint (rad or m),\n\
# * the velocity of the joint (rad/s or m/s) and \n\
# * the effort that is applied in the joint (Nm or N).\n\
#\n\
# Each joint is uniquely identified by its name\n\
# The header specifies the time at which the joint states were recorded. All the joint states\n\
# in one message have to be recorded at the same time.\n\
#\n\
# This message consists of a multiple arrays, one for each part of the joint state. \n\
# The goal is to make each of the fields optional. When e.g. your joints have no\n\
# effort associated with them, you can leave the effort array empty. \n\
#\n\
# All arrays in this message should have the same size, or be empty.\n\
# This is the only way to uniquely associate the joint name with the correct\n\
# states.\n\
\n\
\n\
Header header\n\
\n\
string[] name\n\
float64[] position\n\
float64[] velocity\n\
float64[] effort\n\
\n\
================================================================================\n\
MSG: std_msgs/Header\n\
# Standard metadata for higher-level stamped data types.\n\
# This is generally used to communicate timestamped data \n\
# in a particular coordinate frame.\n\
# \n\
# sequence ID: consecutively increasing ID \n\
uint32 seq\n\
#Two-integer timestamp that is expressed as:\n\
# * stamp.sec: seconds (stamp_secs) since epoch (in Python the variable is called 'secs')\n\
# * stamp.nsec: nanoseconds since stamp_secs (in Python the variable is called 'nsecs')\n\
# time-handling sugar is provided by the client library\n\
time stamp\n\
#Frame this data is associated with\n\
# 0: no frame\n\
# 1: global frame\n\
string frame_id\n\
\n\
================================================================================\n\
MSG: sensor_msgs/MultiDOFJointState\n\
# Representation of state for joints with multiple degrees of freedom, \n\
# following the structure of JointState.\n\
#\n\
# It is assumed that a joint in a system corresponds to a transform that gets applied \n\
# along the kinematic chain. For example, a planar joint (as in URDF) is 3DOF (x, y, yaw)\n\
# and those 3DOF can be expressed as a transformation matrix, and that transformation\n\
# matrix can be converted back to (x, y, yaw)\n\
#\n\
# Each joint is uniquely identified by its name\n\
# The header specifies the time at which the joint states were recorded. All the joint states\n\
# in one message have to be recorded at the same time.\n\
#\n\
# This message consists of a multiple arrays, one for each part of the joint state. \n\
# The goal is to make each of the fields optional. When e.g. your joints have no\n\
# wrench associated with them, you can leave the wrench array empty. \n\
#\n\
# All arrays in this message should have the same size, or be empty.\n\
# This is the only way to uniquely associate the joint name with the correct\n\
# states.\n\
\n\
Header header\n\
\n\
string[] joint_names\n\
geometry_msgs/Transform[] transforms\n\
geometry_msgs/Twist[] twist\n\
geometry_msgs/Wrench[] wrench\n\
\n\
================================================================================\n\
MSG: geometry_msgs/Transform\n\
# This represents the transform between two coordinate frames in free space.\n\
\n\
Vector3 translation\n\
Quaternion rotation\n\
\n\
================================================================================\n\
MSG: geometry_msgs/Vector3\n\
# This represents a vector in free space. \n\
# It is only meant to represent a direction. Therefore, it does not\n\
# make sense to apply a translation to it (e.g., when applying a \n\
# generic rigid transformation to a Vector3, tf2 will only apply the\n\
# rotation). If you want your data to be translatable too, use the\n\
# geometry_msgs/Point message instead.\n\
\n\
float64 x\n\
float64 y\n\
float64 z\n\
================================================================================\n\
MSG: geometry_msgs/Quaternion\n\
# This represents an orientation in free space in quaternion form.\n\
\n\
float64 x\n\
float64 y\n\
float64 z\n\
float64 w\n\
\n\
================================================================================\n\
MSG: geometry_msgs/Twist\n\
# This expresses velocity in free space broken into its linear and angular parts.\n\
Vector3 linear\n\
Vector3 angular\n\
\n\
================================================================================\n\
MSG: geometry_msgs/Wrench\n\
# This represents force in free space, separated into\n\
# its linear and angular parts.\n\
Vector3 force\n\
Vector3 torque\n\
\n\
================================================================================\n\
MSG: moveit_msgs/AttachedCollisionObject\n\
# The CollisionObject will be attached with a fixed joint to this link\n\
string link_name\n\
\n\
#This contains the actual shapes and poses for the CollisionObject\n\
#to be attached to the link\n\
#If action is remove and no object.id is set, all objects\n\
#attached to the link indicated by link_name will be removed\n\
CollisionObject object\n\
\n\
# The set of links that the attached objects are allowed to touch\n\
# by default - the link_name is already considered by default\n\
string[] touch_links\n\
\n\
# If certain links were placed in a particular posture for this object to remain attached \n\
# (e.g., an end effector closing around an object), the posture necessary for releasing\n\
# the object is stored here\n\
trajectory_msgs/JointTrajectory detach_posture\n\
\n\
# The weight of the attached object, if known\n\
float64 weight\n\
\n\
================================================================================\n\
MSG: moveit_msgs/CollisionObject\n\
# A header, used for interpreting the poses\n\
Header header\n\
\n\
# The id of the object (name used in MoveIt)\n\
string id\n\
\n\
# The object type in a database of known objects\n\
object_recognition_msgs/ObjectType type\n\
\n\
# The collision geometries associated with the object.\n\
# Their poses are with respect to the specified header\n\
\n\
# Solid geometric primitives\n\
shape_msgs/SolidPrimitive[] primitives\n\
geometry_msgs/Pose[] primitive_poses\n\
\n\
# Meshes\n\
shape_msgs/Mesh[] meshes\n\
geometry_msgs/Pose[] mesh_poses\n\
\n\
# Bounding planes (equation is specified, but the plane can be oriented using an additional pose)\n\
shape_msgs/Plane[] planes\n\
geometry_msgs/Pose[] plane_poses\n\
\n\
# Named subframes on the object. Use these to define points of interest on the object that you want\n\
# to plan with (e.g. \"tip\", \"spout\", \"handle\"). The id of the object will be prepended to the subframe.\n\
# If an object with the id \"screwdriver\" and a subframe \"tip\" is in the scene, you can use the frame\n\
# \"screwdriver/tip\" for planning.\n\
# The length of the subframe_names and subframe_poses has to be identical.\n\
string[] subframe_names\n\
geometry_msgs/Pose[] subframe_poses\n\
\n\
# Adds the object to the planning scene. If the object previously existed, it is replaced.\n\
byte ADD=0\n\
\n\
# Removes the object from the environment entirely (everything that matches the specified id)\n\
byte REMOVE=1\n\
\n\
# Append to an object that already exists in the planning scene. If the object does not exist, it is added.\n\
byte APPEND=2\n\
\n\
# If an object already exists in the scene, new poses can be sent (the geometry arrays must be left empty)\n\
# if solely moving the object is desired\n\
byte MOVE=3\n\
\n\
# Operation to be performed\n\
byte operation\n\
\n\
================================================================================\n\
MSG: object_recognition_msgs/ObjectType\n\
################################################## OBJECT ID #########################################################\n\
\n\
# Contains information about the type of a found object. Those two sets of parameters together uniquely define an\n\
# object\n\
\n\
# The key of the found object: the unique identifier in the given db\n\
string key\n\
\n\
# The db parameters stored as a JSON/compressed YAML string. An object id does not make sense without the corresponding\n\
# database. E.g., in object_recognition, it can look like: \"{'type':'CouchDB', 'root':'http://localhost'}\"\n\
# There is no conventional format for those parameters and it's nice to keep that flexibility.\n\
# The object_recognition_core as a generic DB type that can read those fields\n\
# Current examples:\n\
# For CouchDB:\n\
# type: 'CouchDB'\n\
# root: 'http://localhost:5984'\n\
# collection: 'object_recognition'\n\
# For SQL household database:\n\
# type: 'SqlHousehold'\n\
# host: 'wgs36'\n\
# port: 5432\n\
# user: 'willow'\n\
# password: 'willow'\n\
# name: 'household_objects'\n\
# module: 'tabletop'\n\
string db\n\
\n\
================================================================================\n\
MSG: shape_msgs/SolidPrimitive\n\
# Define box, sphere, cylinder, cone \n\
# All shapes are defined to have their bounding boxes centered around 0,0,0.\n\
\n\
uint8 BOX=1\n\
uint8 SPHERE=2\n\
uint8 CYLINDER=3\n\
uint8 CONE=4\n\
\n\
# The type of the shape\n\
uint8 type\n\
\n\
\n\
# The dimensions of the shape\n\
float64[] dimensions\n\
\n\
# The meaning of the shape dimensions: each constant defines the index in the 'dimensions' array\n\
\n\
# For the BOX type, the X, Y, and Z dimensions are the length of the corresponding\n\
# sides of the box.\n\
uint8 BOX_X=0\n\
uint8 BOX_Y=1\n\
uint8 BOX_Z=2\n\
\n\
\n\
# For the SPHERE type, only one component is used, and it gives the radius of\n\
# the sphere.\n\
uint8 SPHERE_RADIUS=0\n\
\n\
\n\
# For the CYLINDER and CONE types, the center line is oriented along\n\
# the Z axis. Therefore the CYLINDER_HEIGHT (CONE_HEIGHT) component\n\
# of dimensions gives the height of the cylinder (cone). The\n\
# CYLINDER_RADIUS (CONE_RADIUS) component of dimensions gives the\n\
# radius of the base of the cylinder (cone). Cone and cylinder\n\
# primitives are defined to be circular. The tip of the cone is\n\
# pointing up, along +Z axis.\n\
\n\
uint8 CYLINDER_HEIGHT=0\n\
uint8 CYLINDER_RADIUS=1\n\
\n\
uint8 CONE_HEIGHT=0\n\
uint8 CONE_RADIUS=1\n\
\n\
================================================================================\n\
MSG: geometry_msgs/Pose\n\
# A representation of pose in free space, composed of position and orientation. \n\
Point position\n\
Quaternion orientation\n\
\n\
================================================================================\n\
MSG: geometry_msgs/Point\n\
# This contains the position of a point in free space\n\
float64 x\n\
float64 y\n\
float64 z\n\
\n\
================================================================================\n\
MSG: shape_msgs/Mesh\n\
# Definition of a mesh\n\
\n\
# list of triangles; the index values refer to positions in vertices[]\n\
MeshTriangle[] triangles\n\
\n\
# the actual vertices that make up the mesh\n\
geometry_msgs/Point[] vertices\n\
\n\
================================================================================\n\
MSG: shape_msgs/MeshTriangle\n\
# Definition of a triangle's vertices\n\
uint32[3] vertex_indices\n\
\n\
================================================================================\n\
MSG: shape_msgs/Plane\n\
# Representation of a plane, using the plane equation ax + by + cz + d = 0\n\
\n\
# a := coef[0]\n\
# b := coef[1]\n\
# c := coef[2]\n\
# d := coef[3]\n\
\n\
float64[4] coef\n\
\n\
================================================================================\n\
MSG: trajectory_msgs/JointTrajectory\n\
Header header\n\
string[] joint_names\n\
JointTrajectoryPoint[] points\n\
================================================================================\n\
MSG: trajectory_msgs/JointTrajectoryPoint\n\
# Each trajectory point specifies either positions[, velocities[, accelerations]]\n\
# or positions[, effort] for the trajectory to be executed.\n\
# All specified values are in the same order as the joint names in JointTrajectory.msg\n\
\n\
float64[] positions\n\
float64[] velocities\n\
float64[] accelerations\n\
float64[] effort\n\
duration time_from_start\n\
";
}
static const char* value(const ::moveit_msgs::SaveRobotStateToWarehouseRequest_<ContainerAllocator>&) { return value(); }
};
} // namespace message_traits
} // namespace ros
namespace ros
{
namespace serialization
{
template<class ContainerAllocator> struct Serializer< ::moveit_msgs::SaveRobotStateToWarehouseRequest_<ContainerAllocator> >
{
template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m)
{
stream.next(m.name);
stream.next(m.robot);
stream.next(m.state);
}
ROS_DECLARE_ALLINONE_SERIALIZER
}; // struct SaveRobotStateToWarehouseRequest_
} // namespace serialization
} // namespace ros
namespace ros
{
namespace message_operations
{
template<class ContainerAllocator>
struct Printer< ::moveit_msgs::SaveRobotStateToWarehouseRequest_<ContainerAllocator> >
{
template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::moveit_msgs::SaveRobotStateToWarehouseRequest_<ContainerAllocator>& v)
{
s << indent << "name: ";
Printer<std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > >::stream(s, indent + " ", v.name);
s << indent << "robot: ";
Printer<std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > >::stream(s, indent + " ", v.robot);
s << indent << "state: ";
s << std::endl;
Printer< ::moveit_msgs::RobotState_<ContainerAllocator> >::stream(s, indent + " ", v.state);
}
};
} // namespace message_operations
} // namespace ros
#endif // MOVEIT_MSGS_MESSAGE_SAVEROBOTSTATETOWAREHOUSEREQUEST_H
| [
"zjl93128@hotmail.com"
] | zjl93128@hotmail.com |
c1f40c4b97e93e31ccdf37ebb721c1a69f127e0c | 9b32c32592460960ba322719aec6dd9bc3151ced | /eudaq/main/include/eudaq/LogSender.hh | 703ef5198b442afa7287becb9cbee5e219a0edbc | [] | no_license | beam-telescopes/USBpix | 1c867ad6060404652dc44305a002bbd876da2cca | f5350163a2675982b013711546edb72701d49fb0 | refs/heads/master | 2021-05-02T02:30:34.944845 | 2017-01-09T16:04:11 | 2017-01-09T16:04:11 | 120,883,980 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,058 | hh | #ifndef EUDAQ_INCLUDED_LogSender
#define EUDAQ_INCLUDED_LogSender
#include "eudaq/TransportClient.hh"
#include "eudaq/Serializer.hh"
#include "eudaq/Status.hh"
#include "Platform.hh"
#include <string>
namespace eudaq {
class LogMessage;
class DLLEXPORT LogSender {
public:
LogSender();
~LogSender();
void Connect(const std::string & type, const std::string & name, const std::string & server);
void SendLogMessage(const LogMessage &);
void SetLevel(int level) { m_level = level; }
void SetLevel(const std::string & level) { SetLevel(Status::String2Level(level)); }
void SetErrLevel(int level) { m_errlevel = level; }
void SetErrLevel(const std::string & level) { SetErrLevel(Status::String2Level(level)); }
bool IsLogged(const std::string & level) { return Status::String2Level(level) >= m_level; }
private:
std::string m_name;
TransportClient * m_logclient;
int m_level;
int m_errlevel;
bool m_shownotconnected;
};
}
#endif // EUDAQ_INCLUDED_LogSender
| [
"jgrosse1@uni-goettingen.de"
] | jgrosse1@uni-goettingen.de |
d17e28b44bd53a2614adaacac3022a656d1b489e | 7710234d428e3e9b7a696ca8525f847f8df23402 | /SystemHelper.h | 91bbff32a2d6fd8cb67d7d6aff0b5e07bf82e711 | [] | no_license | xitaofeng/win32_cplusplus_code | b39e3baf6e922db20ec280c164c26b5781fee857 | a740af3637dddc8d1988e4139d1f48f1baf31766 | refs/heads/master | 2020-05-27T21:29:28.876620 | 2016-08-03T06:20:29 | 2016-08-03T06:20:29 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 6,320 | h | /**
* @file SystemHelper.h windows系统常用函数整理
*
* 日期 作者 描述
* 2016/07/20 gxl create
*/
#ifndef G_SYSTEMHELPER_H_
#define G_SYSTEMHELPER_H_
#include <string>
#include <windows.h>
#include <Tlhelp32.h>
using namespace std;
/**
* @brief windows系统常用函数帮助类
*/
class CSystemHelper
{
public:
/**
* @brief 检查当前程序互斥量
*
* @param cMutexName[in] 互斥量名称
*
* @return true-已运行 false-未运行
*
* @code
int main(int argc, char* argv[])
{
bool bRunning = CSystemHelper::CheckProcessMutex("Single.test");
if (bRunning){
cout << "yes" << endl;
} else {
cout << "no" << endl;
}
::system("pause");
return 0;
}
* @endcode
*/
static bool CheckProcessMutex(const char* cMutexName)
{
HANDLE hSingleton = CreateMutexA(NULL, FALSE, cMutexName);
if ((hSingleton != NULL) && (GetLastError() == ERROR_ALREADY_EXISTS))
{
return true;
}
return false;
}
/**
* @brief 检查进程是否存在
*
* @param cProcessName[in] 进程名称
*
* @return true-存在 false-不存在
*
* @code
int main(int argc, char* argv[])
{
bool bExist = CSystemHelper::CheckProcessExist("demo.exe");
if (bExist){
cout << "yes" << endl;
} else {
cout << "no" << endl;
}
::system("pause");
return 0;
}
* @endcode
*/
static bool CheckProcessExist(const char* cProcessName)
{
bool bRet = false;
HANDLE hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hProcessSnap == INVALID_HANDLE_VALUE)
{
return bRet;
}
PROCESSENTRY32 pe32;
pe32.dwSize = sizeof(PROCESSENTRY32);
BOOL bMore = Process32First(hProcessSnap, &pe32);
while (bMore)
{
if (strcmp(cProcessName, pe32.szExeFile) == 0 &&
pe32.th32ProcessID != GetCurrentProcessId())
{
bRet = true;
}
bMore = ::Process32Next(hProcessSnap, &pe32);
}
CloseHandle(hProcessSnap);
return bRet;
}
/**
* @brief 开启进程
*
* @param cProcessPath[in] 进程路径
*
* @code
int main(int argc, char* argv[])
{
CSystemHelper::OpenProcess("c:\\demo.exe");
::system("pause");
return 0;
}
* @endcode
*/
static void OpenProcess(char* cProcessPath)
{
PROCESS_INFORMATION processInfo;
STARTUPINFO startupInfo;
::ZeroMemory(&startupInfo, sizeof(startupInfo));
startupInfo.cb = sizeof(startupInfo);
::CreateProcess(NULL, cProcessPath, NULL, NULL, FALSE,
0, NULL, NULL, &startupInfo, &processInfo);
}
/**
* @brief 销毁进程
*
* @param cProcessName[in] 进程名称
*
* @code
int main(int argc, char* argv[])
{
CSystemHelper::DestoryProcess("demo.exe");
::system("pause");
return 0;
}
* @endcode
*/
static void DestoryProcess(const char* cProcessName)
{
PROCESSENTRY32 pe32;
pe32.dwSize = sizeof(pe32);
HANDLE hProcessSnap = ::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hProcessSnap == INVALID_HANDLE_VALUE)
{
return;
}
BOOL bMore = ::Process32First(hProcessSnap, &pe32);
while (bMore)
{
if (strcmp(cProcessName, pe32.szExeFile) == 0 &&
pe32.th32ProcessID != GetCurrentProcessId())
{
HANDLE hHandle = ::OpenProcess(PROCESS_ALL_ACCESS, FALSE, pe32.th32ProcessID);
if (hHandle)
{
::TerminateProcess(hHandle, 0);
::CloseHandle(hHandle);
}
}
bMore = ::Process32Next(hProcessSnap, &pe32);
}
CloseHandle(hProcessSnap);
}
/**
* @brief 开机自运行本程序
*
* @param cProcessName[in] 程序名称
*
* @code
int main(int argc, char* argv[])
{
CSystemHelper::SetAutoStartup("demo");
::system("pause");
return 0;
}
* @endcode
*/
static bool SetAutoStartup(const char* cProcessName)
{
char filename[MAX_PATH];
GetModuleFileName(NULL, filename, MAX_PATH);
//判断环境是否为WOW64
BOOL isWOW64;
REGSAM samDesired;
IsWow64Process(GetCurrentProcess(), &isWOW64);
samDesired = isWOW64 ? KEY_WRITE | KEY_WOW64_64KEY : KEY_WRITE;
HKEY hKey;
LONG lRet = RegCreateKeyEx(HKEY_LOCAL_MACHINE, TEXT("Software\\Microsoft\\Windows\\CurrentVersion\\Run"), 0, NULL, 0, samDesired, NULL, &hKey, NULL);
if (lRet != ERROR_SUCCESS)
{
return false;
}
lRet = RegSetValueEx(hKey, cProcessName, 0, REG_SZ, (BYTE*)filename, MAX_PATH);
if (lRet != ERROR_SUCCESS)
{
return false;
}
RegCloseKey(hKey);
return true;
}
/**
* @brief 取消开机自运行本程序
*
* @param cProcessName[in] 程序名称
*
* @code
int main(int argc, char* argv[])
{
CSystemHelper::CancelAutoStartup("测试程序");
::system("pause");
return 0;
}
* @endcode
*/
static bool CancelAutoStartup(const char* cProcessName)
{
//判断环境是否为WOW64
BOOL isWOW64;
REGSAM samDesired;
IsWow64Process(GetCurrentProcess(), &isWOW64);
samDesired = isWOW64 ? KEY_WRITE | KEY_WOW64_64KEY : KEY_WRITE;
HKEY hKey;
LONG lRet = RegOpenKeyEx(HKEY_LOCAL_MACHINE, TEXT("Software\\Microsoft\\Windows\\CurrentVersion\\Run"), 0, samDesired, &hKey);
if (lRet == ERROR_SUCCESS)
{
RegDeleteValue(hKey, cProcessName);
RegCloseKey(hKey);
return true;
}
return false;
}
/**
* @brief 重新运行一个本程序实例
*
* 可在异常退出时,重启本程序时使用。
*
* @code
int main(int argc, char* argv[])
{
CSystemHelper::ReStartProcess();
::system("pause");
return 0;
}
* @endcode
*/
static void ReStartProcess()
{
char szPath[MAX_PATH] = {0};
GetModuleFileName(NULL, szPath, MAX_PATH);
STARTUPINFO startupInfo;
PROCESS_INFORMATION procInfo;
memset(&startupInfo, 0x00, sizeof(STARTUPINFO));
startupInfo.cb = sizeof(STARTUPINFO);
::CreateProcess(szPath, NULL, NULL, NULL, FALSE, NORMAL_PRIORITY_CLASS, NULL, NULL, &startupInfo, &procInfo);
}
/**
* @brief 打开某个文件夹
*
* @param chPath[in] 文件夹路径
*
* @code
int main(int argc, char* argv[])
{
CSystemHelper::OpenFolder("c://");
::system("pause");
return 0;
}
* @endcode
*/
static void OpenFolder(const char* chPath)
{
ShellExecute(NULL, NULL, "explorer", chPath, NULL, SW_SHOW);
}
};
#endif // G_SYSTEMHELPER_H_ | [
"931047642@qq.com"
] | 931047642@qq.com |
8b33c6ada746f8fe1af64cc7412aa6e2e61f834f | 8a5c59b7650e5eb6032728bc7e956031741a6add | /visualisationsettingswidget.h | 0b8d226fa07f8461bc0a44475607a67c653c5be7 | [] | no_license | amezin/citnetvis2 | d5a6d1cb6334c74a6fc021234aeebca16718734f | cd5ef48bdb88767623ea965783801e6c7e51cd82 | refs/heads/master | 2020-04-13T03:07:53.765823 | 2013-06-05T06:06:47 | 2013-06-05T06:06:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 888 | h | #ifndef VISUALISATIONSETTINGSWIDGET_H
#define VISUALISATIONSETTINGSWIDGET_H
#include <QWidget>
#include <QDoubleSpinBox>
#include <QFormLayout>
#include <QSet>
#include "scene.h"
#include "persistentwidget.h"
class VisualisationSettingsWidget : public QWidget, public PersistentWidget
{
Q_OBJECT
public:
explicit VisualisationSettingsWidget(Scene *scene, QWidget *parent = 0);
virtual void saveState(QSettings *) const;
virtual void loadState(const QSettings *);
private slots:
void updateSceneParameters();
private:
void addSpinBox(Scene::Parameter, const QString &title,
double minValue, double maxValue, int prec = 1);
Scene *scene;
QDoubleSpinBox *spinBox[Scene::NParameters];
QFormLayout *layout;
bool blockUpdates;
QSet<int> changesColor, changesSize, changesLabel;
};
#endif // VISUALISATIONSETTINGSWIDGET_H
| [
"mezin.alexander@gmail.com"
] | mezin.alexander@gmail.com |
93d9909f8b5f849870b08bf4e5d3d5ab081f1d5b | 278a5c98068425520a1dedf47aba3dda09df0c8a | /src/yb/redisserver/cpp_redis/includes/cpp_redis/replies/array_reply.hpp | bc5475b72ea0a2810bf6c11731927b28bb993210 | [
"Apache-2.0",
"BSD-3-Clause",
"CC0-1.0",
"Unlicense",
"bzip2-1.0.6",
"dtoa",
"MIT",
"BSL-1.0",
"LicenseRef-scancode-public-domain"
] | permissive | jchristov/yugabyte-db | d5c76090e4ec0e11bd6698df1c5140cce28bd816 | 7a15f6441e781b51afc5fc6d7f0e6b9606637231 | refs/heads/master | 2020-03-16T16:16:02.627739 | 2017-12-11T19:49:31 | 2017-12-11T19:49:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 915 | hpp | #pragma once
#include <vector>
#include "cpp_redis/replies/reply.hpp"
namespace cpp_redis {
class reply;
namespace replies {
class array_reply : public reply {
public:
//! ctor & dtor
array_reply(const std::vector<cpp_redis::reply>& rows = {});
~array_reply(void) = default;
//! copy ctor & assignment operator
array_reply(const array_reply&) = default;
array_reply& operator=(const array_reply&) = default;
public:
//! getters
unsigned int size(void) const;
const std::vector<cpp_redis::reply>& get_rows(void) const;
const cpp_redis::reply& get(unsigned int idx) const;
const cpp_redis::reply& operator[](unsigned int idx) const;
//! setters
void set_rows(const std::vector<cpp_redis::reply>& rows);
void add_row(const cpp_redis::reply& row);
void operator<<(const cpp_redis::reply& row);
private:
std::vector<cpp_redis::reply> m_rows;
};
} //! replies
} //! cpp_redis
| [
"amitanandaiyer@users.noreply.github.com"
] | amitanandaiyer@users.noreply.github.com |
7586707fe3b50e9c579b72514013902326947b81 | f2bfe92bcb233798fc9c49ed22748d8c7571706a | /SkyEngine/old/DirectInputHadler.cpp | e80b1d55f8ef098f8aecd52105227f2c59a3af68 | [] | no_license | am17/SkyEngine | d5ed9064daa00151a3dec182cd328b2f369555eb | 5882ba9a267fbfb134e1eff44cb026a3ebd30302 | refs/heads/master | 2021-01-23T02:05:44.370183 | 2017-06-19T20:27:47 | 2017-06-19T20:27:47 | 92,908,018 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,047 | cpp | #include "stdafx.h"
#include "DirectInputHadler.h"
#include "Log.h"
namespace sky
{
DirectInputHandler::DirectInputHandler(HINSTANCE hInstance, HWND hwnd)
:defaultCommand(nullptr),
upArrowKeyPadCommand(nullptr),
downArrowKeyPadCommand(nullptr),
leftArrowKeyPadCommand(nullptr),
rightArrowKeyPadCommand(nullptr)
{
init(hInstance, hwnd);
}
DirectInputHandler::~DirectInputHandler()
{
if (defaultCommand)
{
delete defaultCommand;
defaultCommand = nullptr;
}
DIKeyboard->Unacquire();
DIMouse->Unacquire();
DirectInput->Release();
}
bool DirectInputHandler::init(HINSTANCE hInstance, HWND hwnd)
{
HRESULT hr = DirectInput8Create(hInstance, DIRECTINPUT_VERSION, IID_IDirectInput8, (void**)&DirectInput, nullptr);
hr = DirectInput->CreateDevice(GUID_SysKeyboard, &DIKeyboard, nullptr);
hr = DirectInput->CreateDevice(GUID_SysMouse, &DIMouse, nullptr);
hr = DIKeyboard->SetDataFormat(&c_dfDIKeyboard);
hr = DIKeyboard->SetCooperativeLevel(hwnd, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE);
hr = DIMouse->SetDataFormat(&c_dfDIMouse);
hr = DIMouse->SetCooperativeLevel(hwnd, DISCL_NONEXCLUSIVE | DISCL_NOWINKEY | DISCL_FOREGROUND);
defaultCommand = new DefaultCommand();
upArrowKeyPadCommand = defaultCommand;
downArrowKeyPadCommand = defaultCommand;
leftArrowKeyPadCommand = defaultCommand;
rightArrowKeyPadCommand = defaultCommand;
return true;
}
void DirectInputHandler::handleInput()
{
BYTE keyboardState[256];
DIKeyboard->Acquire();
HRESULT HR = DIKeyboard->GetDeviceState(sizeof(keyboardState), (LPVOID)&keyboardState);
if (keyboardState[DIK_ESCAPE] & 0x80)
{
//PostMessage(hwnd, WM_DESTROY, 0, 0);
}
if (keyboardState[DIK_LEFT] & 0x80)
{
leftArrowKeyPadCommand->execute(EKEYBOARD_COMMAND::EKC_ARROWLEFT);
}
if (keyboardState[DIK_RIGHT] & 0x80)
{
rightArrowKeyPadCommand->execute(EKEYBOARD_COMMAND::EKC_ARROWRIGHT);
}
if (keyboardState[DIK_UP] & 0x80)
{
upArrowKeyPadCommand->execute(EKEYBOARD_COMMAND::EKC_ARROWUP);
}
if (keyboardState[DIK_DOWN] & 0x80)
{
downArrowKeyPadCommand->execute(EKEYBOARD_COMMAND::EKC_ARROWDOWN);
}
DIMOUSESTATE mouseCurrState;
//mouse
DIMouse->Acquire();
DIMouse->GetDeviceState(sizeof(DIMOUSESTATE), &mouseCurrState);
if (mouseCurrState.lX != mouseLastState.lX)
{
//Log::write("MOUSEX");
}
if (mouseCurrState.lY != mouseLastState.lY)
{
//Log::write("MOUSEY");
}
mouseLastState = mouseCurrState;
}
void DirectInputHandler::bindKeyCommand(EKEYBOARD_COMMAND keyboardCommand, ICommand *command)
{
assert(command != nullptr);
switch (keyboardCommand)
{
case sky::EKEYBOARD_COMMAND::EKC_ARROWUP:
upArrowKeyPadCommand = command;
break;
case sky::EKEYBOARD_COMMAND::EKC_ARROWDOWN:
downArrowKeyPadCommand = command;
break;
case sky::EKEYBOARD_COMMAND::EKC_ARROWLEFT:
leftArrowKeyPadCommand = command;
break;
case sky::EKEYBOARD_COMMAND::EKC_ARROWRIGHT:
rightArrowKeyPadCommand = command;
break;
default:
break;
}
}
}
| [
"eugene.voronov@girngm.ru"
] | eugene.voronov@girngm.ru |
f87b0a88cc368e32425eb589bc21e458a43cba02 | d09945668f19bb4bc17087c0cb8ccbab2b2dd688 | /yuki/0001-1000/601-700/626.cpp | c7d5d4e49bc44505053864d0d5194bb08e619294 | [] | no_license | kmjp/procon | 27270f605f3ae5d80fbdb28708318a6557273a57 | 8083028ece4be1460150aa3f0e69bdb57e510b53 | refs/heads/master | 2023-09-04T11:01:09.452170 | 2023-09-03T15:25:21 | 2023-09-03T15:25:21 | 30,825,508 | 23 | 2 | null | 2023-08-18T14:02:07 | 2015-02-15T11:25:23 | C++ | UTF-8 | C++ | false | false | 1,388 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef signed long long ll;
#undef _P
#define _P(...) (void)printf(__VA_ARGS__)
#define FOR(x,to) for(x=0;x<(to);x++)
#define FORR(x,arr) for(auto& x:arr)
#define ITR(x,c) for(__typeof(c.begin()) x=c.begin();x!=c.end();x++)
#define ALL(a) (a.begin()),(a.end())
#define ZERO(a) memset(a,0,sizeof(a))
#define MINUS(a) memset(a,0xff,sizeof(a))
//-------------------------------------------------------
int N;
ll W;
pair<ll,ll> P[5050];
ll ma=0;
bool cmp(pair<ll,ll> L,pair<ll,ll> R) {
return L.first*1.0/L.second>R.first*1.0/R.second;
}
void solve() {
int i,j,k,l,r,x,y; string s;
cin>>N>>W;
FOR(i,N) {
cin>>P[i].first>>P[i].second;
}
sort(P,P+N,cmp);
vector<pair<ll,ll>> V;
V.push_back({0,0});
FOR(i,N) {
ll v=P[i].first,w=P[i].second;
vector<pair<ll,ll>> V2=V;
FORR(vv,V) if(vv.second+w<=W) V2.push_back({vv.first+v,vv.second+w});
V.clear();
sort(ALL(V2));
reverse(ALL(V2));
ll pre=W+1;
FORR(vv,V2) if(vv.second<pre) V.push_back(vv), pre=vv.second;
}
ll ma=0;
FORR(v,V) ma=max(ma,v.first);
cout<<ma<<endl;
}
int main(int argc,char** argv){
string s;int i;
if(argc==1) ios::sync_with_stdio(false), cin.tie(0);
FOR(i,argc-1) s+=argv[i+1],s+='\n'; FOR(i,s.size()) ungetc(s[s.size()-1-i],stdin);
cout.tie(0); solve(); return 0;
}
| [
"kmjp@users.noreply.github.com"
] | kmjp@users.noreply.github.com |
f6ab9f7a054f41256d39583659286569a6ecf60d | bd1fea86d862456a2ec9f56d57f8948456d55ee6 | /000/068/847/CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_int64_t_memmove_53a.cpp | e86c8fbd5ddea3d3ff2462db672464e07db6c1a9 | [] | no_license | CU-0xff/juliet-cpp | d62b8485104d8a9160f29213368324c946f38274 | d8586a217bc94cbcfeeec5d39b12d02e9c6045a2 | refs/heads/master | 2021-03-07T15:44:19.446957 | 2020-03-10T12:45:40 | 2020-03-10T12:45:40 | 246,275,244 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,389 | cpp | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_int64_t_memmove_53a.cpp
Label Definition File: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805.label.xml
Template File: sources-sink-53a.tmpl.cpp
*/
/*
* @description
* CWE: 122 Heap Based Buffer Overflow
* BadSource: Allocate using new[] and set data pointer to a small buffer
* GoodSource: Allocate using new[] and set data pointer to a large buffer
* Sink: memmove
* BadSink : Copy int64_t array to data using memmove
* Flow Variant: 53 Data flow: data passed as an argument from one function through two others to a fourth; all four functions are in different source files
*
* */
#include "std_testcase.h"
namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_int64_t_memmove_53
{
#ifndef OMITBAD
/* bad function declaration */
void badSink_b(int64_t * data);
void bad()
{
int64_t * data;
data = NULL;
/* FLAW: Allocate using new[] and point data to a small buffer that is smaller than the large buffer used in the sinks */
data = new int64_t[50];
badSink_b(data);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* good function declarations */
void goodG2BSink_b(int64_t * data);
/* goodG2B uses the GoodSource with the BadSink */
static void goodG2B()
{
int64_t * data;
data = NULL;
/* FIX: Allocate using new[] and point data to a large buffer that is at least as large as the large buffer used in the sink */
data = new int64_t[100];
goodG2BSink_b(data);
}
void good()
{
goodG2B();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
using namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_int64_t_memmove_53; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| [
"frank@fischer.com.mt"
] | frank@fischer.com.mt |
a158007f9d5f4e04917f51bb25852416b963f6bc | be22fc9c0814d6186400f97e7c47d3c359bd44ca | /3rd-party/ff/distributed/ff_dsender.hpp | 9a06cdbbedb694e2774b9b4ef96bf78daf870318 | [
"MIT"
] | permissive | taskflow/taskflow | 76258cc5c5c4549aacb84c5307837b810fbc42d1 | 9316d98937e992968f1fb3a5836bf3500f756df7 | refs/heads/master | 2023-07-05T06:27:08.883646 | 2023-06-13T11:38:21 | 2023-06-13T11:38:21 | 130,068,982 | 5,616 | 716 | NOASSERTION | 2023-09-12T23:32:21 | 2018-04-18T13:45:30 | C++ | UTF-8 | C++ | false | false | 17,827 | hpp | /* ***************************************************************************
*
* FastFlow is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License version 3 as
* published by the Free Software Foundation.
* Starting from version 3.0.1 FastFlow is dual licensed under the GNU LGPLv3
* or MIT License (https://github.com/ParaGroup/WindFlow/blob/vers3.x/LICENSE.MIT)
*
* 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 Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
****************************************************************************
*/
/* Authors:
* Nicolo' Tonci
* Massimo Torquati
*/
#ifndef FF_DSENDER_H
#define FF_DSENDER_H
#include <iostream>
#include <map>
#include <ff/ff.hpp>
#include <ff/distributed/ff_network.hpp>
#include <ff/distributed/ff_batchbuffer.hpp>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/uio.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <netdb.h>
#include <cmath>
#include <thread>
#include <cereal/cereal.hpp>
#include <cereal/archives/portable_binary.hpp>
#include <cereal/types/vector.hpp>
#include <cereal/types/polymorphic.hpp>
using namespace ff;
using precomputedRT_t = std::map<std::string, std::pair<std::vector<int>, ChannelType>>;
class ff_dsender: public ff_minode_t<message_t> {
protected:
size_t neos=0;
std::vector<std::pair<ChannelType, ff_endpoint>> dest_endpoints;
precomputedRT_t* precomputedRT;
std::map<std::pair<int, ChannelType>, int> dest2Socket;
std::vector<int> sockets;
int last_rr_socket = -1;
std::map<int, unsigned int> socketsCounters;
std::map<int, ff_batchBuffer> batchBuffers;
std::string gName;
int batchSize;
int messageOTF;
int coreid;
fd_set set, tmpset;
int fdmax = -1;
virtual int handshakeHandler(const int sck, ChannelType t){
size_t sz = htobe64(gName.size());
struct iovec iov[3];
iov[0].iov_base = &t;
iov[0].iov_len = sizeof(ChannelType);
iov[1].iov_base = &sz;
iov[1].iov_len = sizeof(sz);
iov[2].iov_base = (char*)(gName.c_str());
iov[2].iov_len = gName.size();
if (writevn(sck, iov, 3) < 0){
error("Error writing on socket\n");
return -1;
}
return 0;
}
int create_connect(const ff_endpoint& destination){
int socketFD;
#ifdef LOCAL
socketFD = socket(AF_LOCAL, SOCK_STREAM, 0);
if (socketFD < 0){
error("\nError creating socket \n");
return socketFD;
}
struct sockaddr_un serv_addr;
memset(&serv_addr, '0', sizeof(serv_addr));
serv_addr.sun_family = AF_LOCAL;
strncpy(serv_addr.sun_path, destination.address.c_str(), destination.address.size()+1);
if (connect(socketFD, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0){
close(socketFD);
return -1;
}
#endif
#ifdef REMOTE
struct addrinfo hints;
struct addrinfo *result, *rp;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
hints.ai_socktype = SOCK_STREAM; /* Stream socket */
hints.ai_flags = 0;
hints.ai_protocol = IPPROTO_TCP; /* Allow only TCP */
// resolve the address
if (getaddrinfo(destination.address.c_str() , std::to_string(destination.port).c_str() , &hints, &result) != 0)
return -1;
// try to connect to a possible one of the resolution results
for (rp = result; rp != NULL; rp = rp->ai_next) {
socketFD = socket(rp->ai_family, rp->ai_socktype,
rp->ai_protocol);
if (socketFD == -1)
continue;
if (connect(socketFD, rp->ai_addr, rp->ai_addrlen) != -1)
break; /* Success */
close(socketFD);
}
free(result);
if (rp == NULL) { /* No address succeeded */
return -1;
}
#endif
// receive the reachable destination from this sockets
return socketFD;
}
int tryConnect(const ff_endpoint &destination){
int fd = -1, retries = 0;
while((fd = this->create_connect(destination)) < 0 && ++retries < MAX_RETRIES)
if (retries < AGGRESSIVE_TRESHOLD)
std::this_thread::sleep_for(std::chrono::milliseconds(1));
else
std::this_thread::sleep_for(std::chrono::milliseconds(200));
//std::this_thread::sleep_for(std::chrono::milliseconds((long)std::pow(2, retries - AGGRESSIVE_TRESHOLD)));
return fd;
}
int sendToSck(int sck, message_t* task){
task->sender = htonl(task->sender);
task->chid = htonl(task->chid);
size_t sz = htobe64(task->data.getLen());
struct iovec iov[4];
iov[0].iov_base = &task->sender;
iov[0].iov_len = sizeof(task->sender);
iov[1].iov_base = &task->chid;
iov[1].iov_len = sizeof(task->chid);
iov[2].iov_base = &sz;
iov[2].iov_len = sizeof(sz);
iov[3].iov_base = task->data.getPtr();
iov[3].iov_len = task->data.getLen();
if (writevn(sck, iov, 4) < 0){
error("Error writing on socket\n");
return -1;
}
return 0;
}
int waitAckFrom(int sck){
while (socketsCounters[sck] == 0){
for(auto& [sck_, counter] : socketsCounters){
int r; ack_t a;
if ((r = recvnnb(sck_, reinterpret_cast<char*>(&a), sizeof(ack_t))) != sizeof(ack_t)){
if (errno == EWOULDBLOCK){
assert(r == -1);
continue;
}
perror("recvnnb ack");
return -1;
} else
counter++;
}
if (socketsCounters[sck] == 0){
tmpset = set;
if (select(fdmax + 1, &tmpset, NULL, NULL, NULL) == -1){
perror("select");
return -1;
}
}
}
return 1;
}
int getMostFilledBufferSck(bool feedback){
int sckMax = 0;
int sizeMax = 0;
for(auto& [sck, buffer] : batchBuffers){
if ((feedback && buffer.ct != ChannelType::FBK) || (!feedback && buffer.ct != ChannelType::FWD)) continue;
if (buffer.size > sizeMax) sckMax = sck;
}
if (sckMax > 0) return sckMax;
do {
last_rr_socket = (last_rr_socket + 1) % this->sockets.size();
} while (batchBuffers[sockets[last_rr_socket]].ct != (feedback ? ChannelType::FBK : ChannelType::FWD));
return sockets[last_rr_socket];
}
public:
ff_dsender(std::pair<ChannelType, ff_endpoint> dest_endpoint, precomputedRT_t* rt, std::string gName = "", int batchSize = DEFAULT_BATCH_SIZE, int messageOTF = DEFAULT_MESSAGE_OTF, int coreid=-1): precomputedRT(rt), gName(gName), batchSize(batchSize), messageOTF(messageOTF), coreid(coreid) {
this->dest_endpoints.push_back(std::move(dest_endpoint));
}
ff_dsender( std::vector<std::pair<ChannelType, ff_endpoint>> dest_endpoints_, precomputedRT_t* rt, std::string gName = "", int batchSize = DEFAULT_BATCH_SIZE, int messageOTF = DEFAULT_MESSAGE_OTF, int coreid=-1) : dest_endpoints(std::move(dest_endpoints_)), precomputedRT(rt), gName(gName), batchSize(batchSize), messageOTF(messageOTF), coreid(coreid) {}
int svc_init() {
if (coreid!=-1)
ff_mapThreadToCpu(coreid);
FD_ZERO(&set);
FD_ZERO(&tmpset);
//sockets.resize(dest_endpoints.size());
for(auto& [ct, ep] : this->dest_endpoints){
int sck = tryConnect(ep);
if (sck <= 0) return -1;
sockets.push_back(sck);
socketsCounters[sck] = messageOTF;
batchBuffers.emplace(std::piecewise_construct, std::forward_as_tuple(sck), std::forward_as_tuple(this->batchSize, ct, [this, sck](struct iovec* v, int size) -> bool {
if (this->socketsCounters[sck] == 0 && this->waitAckFrom(sck) == -1){
error("Errore waiting ack from socket inside the callback\n");
return false;
}
if (writevn(sck, v, size) < 0){
error("Error sending the iovector inside the callback!\n");
return false;
}
this->socketsCounters[sck]--;
return true;
}));
// compute the routing table!
for(int dest : precomputedRT->operator[](ep.groupName).first)
dest2Socket[std::make_pair(dest, ct)] = sck;
if (handshakeHandler(sck, ct) < 0) {
error("svc_init ff_dsender failed");
return -1;
}
FD_SET(sck, &set);
if (sck > fdmax) fdmax = sck;
}
// we can erase the list of endpoints
this->dest_endpoints.clear();
return 0;
}
message_t *svc(message_t* task) {
int sck;
//if (task->chid == -1) task->chid = 0;
if (task->chid != -1)
sck = dest2Socket[{task->chid, (task->feedback ? ChannelType::FBK : ChannelType::FWD)}];
else {
sck = getMostFilledBufferSck(task->feedback); // get the most filled buffer socket or a rr socket
}
if (batchBuffers[sck].push(task) == -1) {
return EOS;
}
return this->GO_ON;
}
void eosnotify(ssize_t id) {
for (const auto& sck : sockets)
batchBuffers[sck].push(new message_t(id, -2));
if (++neos >= this->get_num_inchannels()) {
// all input EOS received, now sending the EOS to all connections
for(const auto& sck : sockets) {
if (batchBuffers[sck].sendEOS()<0) {
error("sending EOS to external connections (ff_dsender)\n");
}
shutdown(sck, SHUT_WR);
}
}
}
void svc_end() {
// here we wait all acks from all connections
size_t totalack = sockets.size()*messageOTF;
size_t currentack = 0;
for(const auto& [_, counter] : socketsCounters)
currentack += counter;
ack_t a;
while(currentack<totalack) {
for(auto scit = socketsCounters.begin(); scit != socketsCounters.end();) {
auto sck = scit->first;
auto& counter = scit->second;
switch(recvnnb(sck, (char*)&a, sizeof(a))) {
case 0:
case -1:
if (errno==EWOULDBLOCK) { ++scit; continue; }
currentack += (messageOTF-counter);
socketsCounters.erase(scit++);
break;
default: {
currentack++;
counter++;
++scit;
}
}
}
}
for(auto& sck : sockets) close(sck);
}
};
class ff_dsenderH : public ff_dsender {
std::vector<int> internalSockets;
int last_rr_socket_Internal = -1;
int internalMessageOTF;
bool squareBoxEOS = false;
/*int getNextReadyInternal(){
for(size_t i = 0; i < this->internalSockets.size(); i++){
int actualSocketIndex = (last_rr_socket_Internal + 1 + i) % this->internalSockets.size();
int sck = internalSockets[actualSocketIndex];
if (socketsCounters[sck] > 0) {
last_rr_socket_Internal = actualSocketIndex;
return sck;
}
}
int sck;
decltype(internalSockets)::iterator it;
do {
sck = waitAckFromAny(); // FIX: error management!
if (sck < 0) {
error("waitAckFromAny failed in getNextReadyInternal");
return -1;
}
} while ((it = std::find(internalSockets.begin(), internalSockets.end(), sck)) != internalSockets.end());
last_rr_socket_Internal = it - internalSockets.begin();
return sck;
}*/
int getMostFilledInternalBufferSck(){
int sckMax = 0;
int sizeMax = 0;
for(int sck : internalSockets){
auto& b = batchBuffers[sck];
if (b.size > sizeMax) {
sckMax = sck;
sizeMax = b.size;
}
}
if (sckMax > 0) return sckMax;
last_rr_socket_Internal = (last_rr_socket_Internal + 1) % this->internalSockets.size();
return internalSockets[last_rr_socket_Internal];
}
public:
ff_dsenderH(std::pair<ChannelType, ff_endpoint> e, precomputedRT_t* rt, std::string gName = "", int batchSize = DEFAULT_BATCH_SIZE, int messageOTF = DEFAULT_MESSAGE_OTF, int internalMessageOTF = DEFAULT_INTERNALMSG_OTF, int coreid=-1) : ff_dsender(e, rt, gName, batchSize, messageOTF, coreid), internalMessageOTF(internalMessageOTF) {}
ff_dsenderH(std::vector<std::pair<ChannelType, ff_endpoint>> dest_endpoints_, precomputedRT_t* rt, std::string gName = "", int batchSize = DEFAULT_BATCH_SIZE, int messageOTF = DEFAULT_MESSAGE_OTF, int internalMessageOTF = DEFAULT_INTERNALMSG_OTF, int coreid=-1) : ff_dsender(dest_endpoints_, rt, gName, batchSize, messageOTF, coreid), internalMessageOTF(internalMessageOTF) {}
int svc_init() {
if (coreid!=-1)
ff_mapThreadToCpu(coreid);
FD_ZERO(&set);
FD_ZERO(&tmpset);
for(const auto& [ct, endpoint] : this->dest_endpoints){
int sck = tryConnect(endpoint);
if (sck <= 0) return -1;
bool isInternal = ct == ChannelType::INT;
if (isInternal) internalSockets.push_back(sck);
else sockets.push_back(sck);
socketsCounters[sck] = isInternal ? internalMessageOTF : messageOTF;
batchBuffers.emplace(std::piecewise_construct, std::forward_as_tuple(sck), std::forward_as_tuple(this->batchSize, ct, [this, sck](struct iovec* v, int size) -> bool {
if (this->socketsCounters[sck] == 0 && this->waitAckFrom(sck) == -1){
error("Errore waiting ack from socket inside the callback\n");
return false;
}
if (writevn(sck, v, size) < 0){
error("Error sending the iovector inside the callback (errno=%d) %s\n", errno);
return false;
}
this->socketsCounters[sck]--;
return true;
})); // change with the correct size
for(int dest : precomputedRT->operator[](endpoint.groupName).first)
dest2Socket[std::make_pair(dest, ct)] = sck;
if (handshakeHandler(sck, ct) < 0) return -1;
FD_SET(sck, &set);
if (sck > fdmax) fdmax = sck;
}
// we can erase the list of endpoints
this->dest_endpoints.clear();
return 0;
}
message_t *svc(message_t* task) {
if (this->get_channel_id() == (ssize_t)(this->get_num_inchannels() - 1)){
int sck;
// pick destination from the list of internal connections!
if (task->chid != -1){ // roundrobin over the destinations
sck = dest2Socket[{task->chid, ChannelType::INT}];
} else
sck = getMostFilledInternalBufferSck();
if (batchBuffers[sck].push(task) == -1) {
return EOS;
}
return this->GO_ON;
}
return ff_dsender::svc(task);
}
void eosnotify(ssize_t id) {
if (id == (ssize_t)(this->get_num_inchannels() - 1)){
// send the EOS to all the internal connections
if (squareBoxEOS) return;
squareBoxEOS = true;
for(const auto& sck : internalSockets) {
if (batchBuffers[sck].sendEOS()<0) {
error("sending EOS to internal connections\n");
}
shutdown(sck, SHUT_WR);
}
}
if (++neos >= this->get_num_inchannels()) {
// all input EOS received, now sending the EOS to all
// others connections
for(const auto& sck : sockets) {
if (batchBuffers[sck].sendEOS()<0) {
error("sending EOS to external connections (ff_dsenderH)\n");
}
shutdown(sck, SHUT_WR);
}
}
}
void svc_end() {
// here we wait all acks from all connections
size_t totalack = internalSockets.size()*internalMessageOTF;
totalack += sockets.size()*messageOTF;
size_t currentack = 0;
for(const auto& [sck, counter] : socketsCounters) {
currentack += counter;
}
ack_t a;
while(currentack<totalack) {
for(auto scit = socketsCounters.begin(); scit != socketsCounters.end();) {
auto sck = scit->first;
auto& counter = scit->second;
switch(recvnnb(sck, (char*)&a, sizeof(a))) {
case 0:
case -1: {
if (errno == EWOULDBLOCK) {
++scit;
continue;
}
decltype(internalSockets)::iterator it;
it = std::find(internalSockets.begin(), internalSockets.end(), sck);
if (it != internalSockets.end())
currentack += (internalMessageOTF-counter);
else
currentack += (messageOTF-counter);
socketsCounters.erase(scit++);
} break;
default: {
currentack++;
counter++;
++scit;
}
}
}
}
for(const auto& [sck, _] : socketsCounters) close(sck);
}
};
#endif
| [
"chchiu@pass-2.ece.utah.edu"
] | chchiu@pass-2.ece.utah.edu |
33f043cfbd1aab60c68950c16cc0c75e60dd4ea7 | baebe8a00a7b3aa662b8078bd000c424bb214cc6 | /src/texture/texture.cpp | c85820a512036d476b2835d007dd42180207e513 | [
"MIT"
] | permissive | jonike/lumen | 8ffd85f64018eba0d5adea401c44f740b6ea0032 | c35259f45a265d470afccb8b6282c8520eabdc95 | refs/heads/master | 2021-04-25T04:03:36.864204 | 2017-06-02T17:49:11 | 2017-07-15T00:10:37 | 115,495,859 | 2 | 0 | null | 2017-12-27T07:45:31 | 2017-12-27T07:45:31 | null | UTF-8 | C++ | false | false | 2,389 | cpp | #include <cmath>
#include <IL\il.h>
#include <IL\ilu.h>
#include <film.h>
#include <stdexcept>
#include <texture.h>
namespace lumen {
texture::texture(const std::string& file) :
texels(6),
width_(0),
height_(0)
{
if (!ilLoadImage(file.c_str())) {
throw std::invalid_argument(iluErrorString(ilGetError()));
}
ilConvertImage(IL_RGB, IL_FLOAT);
iluBuildMipmaps();
ILuint img = ilGetInteger(IL_CUR_IMAGE);
ILint width = ilGetInteger(IL_IMAGE_WIDTH);
ILint height = ilGetInteger(IL_IMAGE_HEIGHT);
ILint num_faces = ilGetInteger(IL_NUM_FACES);
std::unique_ptr<ILfloat[]> data(new ILfloat[width * height * 3]);
int stride = 3 * width;
for (ILint face = 0; face <= num_faces; ++face) {
ilBindImage(img);
ilActiveFace(face);
texels[face].reserve(width * height);
ilCopyPixels(0, 0, 0, width, height, 1, IL_RGB, IL_FLOAT, data.get());
for (ILint i = 0; i < height; ++i) {
for (ILint j = 0; j < width; ++j) {
int offset = i * stride + 3 * j;
// texture colors are already gamma corrected so each color
// needs to have the inverse gamma applied otherwise the image
// will gamma correct the colors a second time and saturate
// the textures
nex::color texel(
std::powf(data[offset + 0], GAMMA_VALUE),
std::powf(data[offset + 1], GAMMA_VALUE),
std::powf(data[offset + 2], GAMMA_VALUE),
1.0f);
texels[face].push_back(texel);
}
}
}
ilDeleteImages(1, &img);
width_ = width;
height_ = height;
}
nex::color texture::fetch_2d(int x, int y)
{
return texels[0][x + y * width_];
}
nex::color texture::fetch_cube(int face, int x, int y)
{
return texels[face][x + y * width_];
}
int texture::width() const
{
return width_;
}
int texture::height() const
{
return height_;
}
}
| [
"jeremy.adam.lukacs@gmail.com"
] | jeremy.adam.lukacs@gmail.com |
b5551a7b5c0e3a5e5b886e999322c4b6be13fb92 | dccaab4cb32470d58399750d457d89f3874a99e3 | /3rdparty/include/Poco/Net/MediaType.h | 6c841a435830848e8cd340517aad89ae2ca87c5a | [] | no_license | Pan-Rongtao/mycar | 44832b0b5fdbb6fb713fddff98afbbe90ced6415 | 05b1f0f52c309607c4c64a06b97580101e30d424 | refs/heads/master | 2020-07-15T20:31:28.183703 | 2019-12-20T07:45:00 | 2019-12-20T07:45:00 | 205,642,065 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,594 | h | //
// MediaType.h
//
// Library: Net
// Package: Messages
// Module: MediaType
//
// Definition of the MediaType class.
//
// Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#ifndef Net_MediaType_INCLUDED
#define Net_MediaType_INCLUDED
#include "Poco/Net/Net.h"
#include "Poco/Net/NameValueCollection.h"
namespace Poco {
namespace Net {
class Net_API MediaType
/// This class represents a MIME media type, consisting of
/// a top-level type, a subtype and an optional set of
/// parameters.
///
/// The implementation conforms with RFC 2045 and RFC 2046.
{
public:
MediaType(const std::string& mediaType);
/// Creates the MediaType from the given string, which
/// must have the format <type>/<subtype>{;<parameter>=<value>}.
MediaType(const std::string& type, const std::string& subType);
/// Creates the MediaType, using the given type and subtype.
MediaType(const MediaType& mediaType);
/// Creates a MediaType from another one.
~MediaType();
/// Destroys the MediaType.
MediaType& operator = (const MediaType& mediaType);
/// Assigns another media type.
MediaType& operator = (const std::string& mediaType);
/// Assigns another media type.
void swap(MediaType& mediaType);
/// Swaps the MediaType with another one.
void setType(const std::string& type);
/// Sets the top-level type.
const std::string& getType() const;
/// Returns the top-level type.
void setSubType(const std::string& subType);
/// Sets the sub type.
const std::string& getSubType() const;
/// Returns the sub type.
void setParameter(const std::string& name, const std::string& value);
/// Sets the parameter with the given name.
const std::string& getParameter(const std::string& name) const;
/// Returns the parameter with the given name.
///
/// Throws a NotFoundException if the parameter does not exist.
bool hasParameter(const std::string& name) const;
/// Returns true iff a parameter with the given name exists.
void removeParameter(const std::string& name);
/// Removes the parameter with the given name.
const NameValueCollection& parameters() const;
/// Returns the parameters.
std::string toString() const;
/// Returns the string representation of the media type
/// which is <type>/<subtype>{;<parameter>=<value>}
bool matches(const MediaType& mediaType) const;
/// Returns true iff the type and subtype match
/// the type and subtype of the given media type.
/// Matching is case insensitive.
bool matches(const std::string& type, const std::string& subType) const;
/// Returns true iff the type and subtype match
/// the given type and subtype.
/// Matching is case insensitive.
bool matches(const std::string& type) const;
/// Returns true iff the type matches the given type.
/// Matching is case insensitive.
bool matchesRange(const MediaType& mediaType) const;
/// Returns true if the type and subtype match
/// the type and subtype of the given media type.
/// If the MIME type is a range of types it matches
/// any media type within the range (e.g. "image/*" matches
/// any image media type, "*/*" matches anything).
/// Matching is case insensitive.
bool matchesRange(const std::string& type, const std::string& subType) const;
/// Returns true if the type and subtype match
/// the given type and subtype.
/// If the MIME type is a range of types it matches
/// any media type within the range (e.g. "image/*" matches
/// any image media type, "*/*" matches anything).
/// Matching is case insensitive.
bool matchesRange(const std::string& type) const;
/// Returns true if the type matches the given type or
/// the type is a range of types denoted by "*".
/// Matching is case insensitive.
protected:
void parse(const std::string& mediaType);
private:
MediaType();
std::string _type;
std::string _subType;
NameValueCollection _parameters;
};
//
// inlines
//
inline const std::string& MediaType::getType() const
{
return _type;
}
inline const std::string& MediaType::getSubType() const
{
return _subType;
}
inline const NameValueCollection& MediaType::parameters() const
{
return _parameters;
}
inline void swap(MediaType& m1, MediaType& m2)
{
m1.swap(m2);
}
} } // namespace Poco::Net
#endif // Net_MediaType_INCLUDED
| [
"Rongtao.Pan@desay-svautomotive.com"
] | Rongtao.Pan@desay-svautomotive.com |
bad5f72692e51c7c85bae20268c67e1c83e9026b | e68e8ef755fed83cf751b582f68999bcbb3ccbef | /Tests/Test_State.h | 1123a43808814b9cfa23372432beffd86e098427 | [] | no_license | Sketcher14/TortoiseStash | a161b68eeac89afab315736075d58c1905b16921 | db36d8afcafe6622447295092b474fc95897c192 | refs/heads/main | 2022-10-12T07:28:01.938051 | 2022-10-02T14:03:57 | 2022-10-02T14:03:57 | 190,795,224 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 219 | h | #pragma once
#include <QtTest>
class Test_State : public QObject
{
Q_OBJECT
private slots:
void Test_AddRoundKey();
void Test_SubstituteBytes();
void Test_ShiftRows();
void Test_MixColumns();
};
| [
"www.vitaliy_14@mail.ru"
] | www.vitaliy_14@mail.ru |
43fe69ad51df6d89beed75348bda058a0ca42613 | 0d9076293349241af62d00eff4c4107e51426ea5 | /coding interview guide/二叉树/在二叉树中找到一个节点的后继结点.cpp | 65d198da7322878c93dca8207909d616f07e4e6f | [] | no_license | zonasse/Algorithm | f6445616d0cde04e5ef5f475e7f9c8ec68638dd0 | cda4ba606b66040a54c44d95db51220a2df47414 | refs/heads/master | 2020-03-23T12:12:00.525247 | 2019-08-10T03:42:53 | 2019-08-10T03:42:53 | 141,543,243 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 686 | cpp | //
// Created by 钟奇龙 on 2019-05-03.
//
//
// Created by 钟奇龙 on 2019-05-01.
//
#include <iostream>
using namespace std;
class Node{
public:
int data;
Node *parent;
Node *left;
Node *right;
Node(int x):data(x),left(NULL),right(NULL),parent(NULL){}
};
Node* getNextNode(Node *root){
if(!root) return NULL;
if(root->right){
Node *right = root->right;
while(right->left){
right = right->left;
}
return right;
}else{
Node *parent = root->parent;
while(parent && parent->left != root){
root = parent;
parent = root->parent;
}
return parent;
}
} | [
"992903713@qq.com"
] | 992903713@qq.com |
04d311eddc6017991d14cd0674f8835d51d0f73d | b3439873c106d69b6ae8110c36bcd77264e8c5a7 | /server/Server/Skills/ImpactLogic/StdImpact040.cpp | 90b1063863814cfb56c81bf29ada97c23a7c318f | [] | no_license | cnsuhao/web-pap | b41356411dc8dad0e42a11e62a27a1b4336d91e2 | 7c9b1f49d9ba8d8e40f8fddae829c2e414ccfeca | refs/heads/master | 2021-05-28T01:01:18.122567 | 2013-11-19T06:49:41 | 2013-11-19T06:49:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,381 | cpp | #include "stdafx.h"
///////////////////////////////////////////////////////////////////////////////
// 文件名:StdImpact040.cpp
// 功能说明:效果--在一定时间内,增加效果所有者的移动速度,并且下一次打击驱散目标怒气
//
// 修改记录:
//
//
//
///////////////////////////////////////////////////////////////////////////////
#include "StdImpact040.h"
namespace Combat_Module
{
using namespace Combat_Module::Skill_Module;
namespace Impact_Module
{
BOOL StdImpact040_T::InitFromData(OWN_IMPACT& rImp, ImpactData_T const& rData) const
{
__ENTER_FUNCTION
SetActivateTimes(rImp, GetActivateTimesInTable(rImp));
return TRUE;
__LEAVE_FUNCTION
return FALSE;
}
VOID StdImpact040_T::MarkModifiedAttrDirty(OWN_IMPACT & rImp, Obj_Character & rMe) const
{
__ENTER_FUNCTION
if(0!=GetMoveSpeedRefix(rImp))
{
rMe.MarkMoveSpeedRefixDirtyFlag();
}
__LEAVE_FUNCTION
}
BOOL StdImpact040_T::GetIntAttrRefix(OWN_IMPACT & rImp, Obj_Character& rMe, CharIntAttrRefixs_T::Index_T nIdx, INT & rIntAttrRefix) const
{
__ENTER_FUNCTION
if(CharIntAttrRefixs_T::REFIX_MOVE_SPEED==nIdx)
{
if(0!=GetMoveSpeedRefix(rImp))
{
rIntAttrRefix += rMe.GetBaseMoveSpeed()*GetMoveSpeedRefix(rImp)/100;
return TRUE;
}
}
__LEAVE_FUNCTION
return FALSE;
}
VOID StdImpact040_T::OnHitTarget(OWN_IMPACT & rImp, Obj_Character & rMe, Obj_Character & rTar) const
{
__ENTER_FUNCTION
if(Obj::OBJ_TYPE_HUMAN==rTar.GetObjType())
{
INT nActivateTimes = GetActivateTimes(rImp);
if(0==nActivateTimes)
{
return;
}
INT nImpact = GetSubImpact(rImp);
g_ImpactCore.SendImpactToUnit(rTar, nImpact, rMe.GetID(), 500);
if(0<nActivateTimes)
{
--nActivateTimes;
SetActivateTimes(rImp, nActivateTimes);
}
}
__LEAVE_FUNCTION
}
};
};
| [
"viticm@126.com"
] | viticm@126.com |
bbde99aeda2b4fafde1176486f27529acf864e33 | 1d928c3f90d4a0a9a3919a804597aa0a4aab19a3 | /c++/dash/2017/12/blockchain.cpp | cf7307861281b0d3f1e2e49022925534931a55f1 | [] | no_license | rosoareslv/SED99 | d8b2ff5811e7f0ffc59be066a5a0349a92cbb845 | a062c118f12b93172e31e8ca115ce3f871b64461 | refs/heads/main | 2023-02-22T21:59:02.703005 | 2021-01-28T19:40:51 | 2021-01-28T19:40:51 | 306,497,459 | 1 | 1 | null | 2020-11-24T20:56:18 | 2020-10-23T01:18:07 | null | UTF-8 | C++ | false | false | 58,544 | cpp | // Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Copyright (c) 2014-2017 The Dash Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "amount.h"
#include "chain.h"
#include "chainparams.h"
#include "checkpoints.h"
#include "coins.h"
#include "consensus/validation.h"
#include "validation.h"
#include "policy/policy.h"
#include "primitives/transaction.h"
#include "rpc/server.h"
#include "streams.h"
#include "sync.h"
#include "txdb.h"
#include "txmempool.h"
#include "util.h"
#include "utilstrencodings.h"
#include "hash.h"
#include <stdint.h>
#include <univalue.h>
#include <boost/thread/thread.hpp> // boost::thread::interrupt
using namespace std;
extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, UniValue& entry);
void ScriptPubKeyToJSON(const CScript& scriptPubKey, UniValue& out, bool fIncludeHex);
double GetDifficulty(const CBlockIndex* blockindex)
{
// Floating point number that is a multiple of the minimum difficulty,
// minimum difficulty = 1.0.
if (blockindex == NULL)
{
if (chainActive.Tip() == NULL)
return 1.0;
else
blockindex = chainActive.Tip();
}
int nShift = (blockindex->nBits >> 24) & 0xff;
double dDiff =
(double)0x0000ffff / (double)(blockindex->nBits & 0x00ffffff);
while (nShift < 29)
{
dDiff *= 256.0;
nShift++;
}
while (nShift > 29)
{
dDiff /= 256.0;
nShift--;
}
return dDiff;
}
UniValue blockheaderToJSON(const CBlockIndex* blockindex)
{
UniValue result(UniValue::VOBJ);
result.push_back(Pair("hash", blockindex->GetBlockHash().GetHex()));
int confirmations = -1;
// Only report confirmations if the block is on the main chain
if (chainActive.Contains(blockindex))
confirmations = chainActive.Height() - blockindex->nHeight + 1;
result.push_back(Pair("confirmations", confirmations));
result.push_back(Pair("height", blockindex->nHeight));
result.push_back(Pair("version", blockindex->nVersion));
result.push_back(Pair("versionHex", strprintf("%08x", blockindex->nVersion)));
result.push_back(Pair("merkleroot", blockindex->hashMerkleRoot.GetHex()));
result.push_back(Pair("time", (int64_t)blockindex->nTime));
result.push_back(Pair("mediantime", (int64_t)blockindex->GetMedianTimePast()));
result.push_back(Pair("nonce", (uint64_t)blockindex->nNonce));
result.push_back(Pair("bits", strprintf("%08x", blockindex->nBits)));
result.push_back(Pair("difficulty", GetDifficulty(blockindex)));
result.push_back(Pair("chainwork", blockindex->nChainWork.GetHex()));
if (blockindex->pprev)
result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex()));
CBlockIndex *pnext = chainActive.Next(blockindex);
if (pnext)
result.push_back(Pair("nextblockhash", pnext->GetBlockHash().GetHex()));
return result;
}
UniValue blockToJSON(const CBlock& block, const CBlockIndex* blockindex, bool txDetails = false)
{
UniValue result(UniValue::VOBJ);
result.push_back(Pair("hash", blockindex->GetBlockHash().GetHex()));
int confirmations = -1;
// Only report confirmations if the block is on the main chain
if (chainActive.Contains(blockindex))
confirmations = chainActive.Height() - blockindex->nHeight + 1;
result.push_back(Pair("confirmations", confirmations));
result.push_back(Pair("size", (int)::GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION)));
result.push_back(Pair("height", blockindex->nHeight));
result.push_back(Pair("version", block.nVersion));
result.push_back(Pair("versionHex", strprintf("%08x", block.nVersion)));
result.push_back(Pair("merkleroot", block.hashMerkleRoot.GetHex()));
UniValue txs(UniValue::VARR);
BOOST_FOREACH(const CTransaction&tx, block.vtx)
{
if(txDetails)
{
UniValue objTx(UniValue::VOBJ);
TxToJSON(tx, uint256(), objTx);
txs.push_back(objTx);
}
else
txs.push_back(tx.GetHash().GetHex());
}
result.push_back(Pair("tx", txs));
result.push_back(Pair("time", block.GetBlockTime()));
result.push_back(Pair("mediantime", (int64_t)blockindex->GetMedianTimePast()));
result.push_back(Pair("nonce", (uint64_t)block.nNonce));
result.push_back(Pair("bits", strprintf("%08x", block.nBits)));
result.push_back(Pair("difficulty", GetDifficulty(blockindex)));
result.push_back(Pair("chainwork", blockindex->nChainWork.GetHex()));
if (blockindex->pprev)
result.push_back(Pair("previousblockhash", blockindex->pprev->GetBlockHash().GetHex()));
CBlockIndex *pnext = chainActive.Next(blockindex);
if (pnext)
result.push_back(Pair("nextblockhash", pnext->GetBlockHash().GetHex()));
return result;
}
UniValue getblockcount(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getblockcount\n"
"\nReturns the number of blocks in the longest block chain.\n"
"\nResult:\n"
"n (numeric) The current block count\n"
"\nExamples:\n"
+ HelpExampleCli("getblockcount", "")
+ HelpExampleRpc("getblockcount", "")
);
LOCK(cs_main);
return chainActive.Height();
}
UniValue getbestblockhash(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getbestblockhash\n"
"\nReturns the hash of the best (tip) block in the longest block chain.\n"
"\nResult\n"
"\"hex\" (string) the block hash hex encoded\n"
"\nExamples\n"
+ HelpExampleCli("getbestblockhash", "")
+ HelpExampleRpc("getbestblockhash", "")
);
LOCK(cs_main);
return chainActive.Tip()->GetBlockHash().GetHex();
}
UniValue getdifficulty(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getdifficulty\n"
"\nReturns the proof-of-work difficulty as a multiple of the minimum difficulty.\n"
"\nResult:\n"
"n.nnn (numeric) the proof-of-work difficulty as a multiple of the minimum difficulty.\n"
"\nExamples:\n"
+ HelpExampleCli("getdifficulty", "")
+ HelpExampleRpc("getdifficulty", "")
);
LOCK(cs_main);
return GetDifficulty();
}
std::string EntryDescriptionString()
{
return " \"size\" : n, (numeric) transaction size in bytes\n"
" \"fee\" : n, (numeric) transaction fee in " + CURRENCY_UNIT + "\n"
" \"modifiedfee\" : n, (numeric) transaction fee with fee deltas used for mining priority\n"
" \"time\" : n, (numeric) local time transaction entered pool in seconds since 1 Jan 1970 GMT\n"
" \"height\" : n, (numeric) block height when transaction entered pool\n"
" \"startingpriority\" : n, (numeric) priority when transaction entered pool\n"
" \"currentpriority\" : n, (numeric) transaction priority now\n"
" \"descendantcount\" : n, (numeric) number of in-mempool descendant transactions (including this one)\n"
" \"descendantsize\" : n, (numeric) size of in-mempool descendants (including this one)\n"
" \"descendantfees\" : n, (numeric) modified fees (see above) of in-mempool descendants (including this one)\n"
" \"ancestorcount\" : n, (numeric) number of in-mempool ancestor transactions (including this one)\n"
" \"ancestorsize\" : n, (numeric) size of in-mempool ancestors (including this one)\n"
" \"ancestorfees\" : n, (numeric) modified fees (see above) of in-mempool ancestors (including this one)\n"
" \"depends\" : [ (array) unconfirmed transactions used as inputs for this transaction\n"
" \"transactionid\", (string) parent transaction id\n"
" ... ]\n";
}
void entryToJSON(UniValue &info, const CTxMemPoolEntry &e)
{
AssertLockHeld(mempool.cs);
info.push_back(Pair("size", (int)e.GetTxSize()));
info.push_back(Pair("fee", ValueFromAmount(e.GetFee())));
info.push_back(Pair("modifiedfee", ValueFromAmount(e.GetModifiedFee())));
info.push_back(Pair("time", e.GetTime()));
info.push_back(Pair("height", (int)e.GetHeight()));
info.push_back(Pair("startingpriority", e.GetPriority(e.GetHeight())));
info.push_back(Pair("currentpriority", e.GetPriority(chainActive.Height())));
info.push_back(Pair("descendantcount", e.GetCountWithDescendants()));
info.push_back(Pair("descendantsize", e.GetSizeWithDescendants()));
info.push_back(Pair("descendantfees", e.GetModFeesWithDescendants()));
info.push_back(Pair("ancestorcount", e.GetCountWithAncestors()));
info.push_back(Pair("ancestorsize", e.GetSizeWithAncestors()));
info.push_back(Pair("ancestorfees", e.GetModFeesWithAncestors()));
const CTransaction& tx = e.GetTx();
set<string> setDepends;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
{
if (mempool.exists(txin.prevout.hash))
setDepends.insert(txin.prevout.hash.ToString());
}
UniValue depends(UniValue::VARR);
BOOST_FOREACH(const string& dep, setDepends)
{
depends.push_back(dep);
}
info.push_back(Pair("depends", depends));
}
UniValue mempoolToJSON(bool fVerbose = false)
{
if (fVerbose)
{
LOCK(mempool.cs);
UniValue o(UniValue::VOBJ);
BOOST_FOREACH(const CTxMemPoolEntry& e, mempool.mapTx)
{
const uint256& hash = e.GetTx().GetHash();
UniValue info(UniValue::VOBJ);
entryToJSON(info, e);
o.push_back(Pair(hash.ToString(), info));
}
return o;
}
else
{
vector<uint256> vtxid;
mempool.queryHashes(vtxid);
UniValue a(UniValue::VARR);
BOOST_FOREACH(const uint256& hash, vtxid)
a.push_back(hash.ToString());
return a;
}
}
UniValue getrawmempool(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getrawmempool ( verbose )\n"
"\nReturns all transaction ids in memory pool as a json array of string transaction ids.\n"
"\nArguments:\n"
"1. verbose (boolean, optional, default=false) true for a json object, false for array of transaction ids\n"
"\nResult: (for verbose = false):\n"
"[ (json array of string)\n"
" \"transactionid\" (string) The transaction id\n"
" ,...\n"
"]\n"
"\nResult: (for verbose = true):\n"
"{ (json object)\n"
" \"transactionid\" : { (json object)\n"
+ EntryDescriptionString()
+ " }, ...\n"
"}\n"
"\nExamples\n"
+ HelpExampleCli("getrawmempool", "true")
+ HelpExampleRpc("getrawmempool", "true")
);
bool fVerbose = false;
if (params.size() > 0)
fVerbose = params[0].get_bool();
return mempoolToJSON(fVerbose);
}
UniValue getmempoolancestors(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2) {
throw runtime_error(
"getmempoolancestors txid (verbose)\n"
"\nIf txid is in the mempool, returns all in-mempool ancestors.\n"
"\nArguments:\n"
"1. \"txid\" (string, required) The transaction id (must be in mempool)\n"
"2. verbose (boolean, optional, default=false) true for a json object, false for array of transaction ids\n"
"\nResult (for verbose=false):\n"
"[ (json array of strings)\n"
" \"transactionid\" (string) The transaction id of an in-mempool ancestor transaction\n"
" ,...\n"
"]\n"
"\nResult (for verbose=true):\n"
"{ (json object)\n"
" \"transactionid\" : { (json object)\n"
+ EntryDescriptionString()
+ " }, ...\n"
"}\n"
"\nExamples\n"
+ HelpExampleCli("getmempoolancestors", "\"mytxid\"")
+ HelpExampleRpc("getmempoolancestors", "\"mytxid\"")
);
}
bool fVerbose = false;
if (params.size() > 1)
fVerbose = params[1].get_bool();
uint256 hash = ParseHashV(params[0], "parameter 1");
LOCK(mempool.cs);
CTxMemPool::txiter it = mempool.mapTx.find(hash);
if (it == mempool.mapTx.end()) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not in mempool");
}
CTxMemPool::setEntries setAncestors;
uint64_t noLimit = std::numeric_limits<uint64_t>::max();
std::string dummy;
mempool.CalculateMemPoolAncestors(*it, setAncestors, noLimit, noLimit, noLimit, noLimit, dummy, false);
if (!fVerbose) {
UniValue o(UniValue::VARR);
BOOST_FOREACH(CTxMemPool::txiter ancestorIt, setAncestors) {
o.push_back(ancestorIt->GetTx().GetHash().ToString());
}
return o;
} else {
UniValue o(UniValue::VOBJ);
BOOST_FOREACH(CTxMemPool::txiter ancestorIt, setAncestors) {
const CTxMemPoolEntry &e = *ancestorIt;
const uint256& hash = e.GetTx().GetHash();
UniValue info(UniValue::VOBJ);
entryToJSON(info, e);
o.push_back(Pair(hash.ToString(), info));
}
return o;
}
}
UniValue getmempooldescendants(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2) {
throw runtime_error(
"getmempooldescendants txid (verbose)\n"
"\nIf txid is in the mempool, returns all in-mempool descendants.\n"
"\nArguments:\n"
"1. \"txid\" (string, required) The transaction id (must be in mempool)\n"
"2. verbose (boolean, optional, default=false) true for a json object, false for array of transaction ids\n"
"\nResult (for verbose=false):\n"
"[ (json array of strings)\n"
" \"transactionid\" (string) The transaction id of an in-mempool descendant transaction\n"
" ,...\n"
"]\n"
"\nResult (for verbose=true):\n"
"{ (json object)\n"
" \"transactionid\" : { (json object)\n"
+ EntryDescriptionString()
+ " }, ...\n"
"}\n"
"\nExamples\n"
+ HelpExampleCli("getmempooldescendants", "\"mytxid\"")
+ HelpExampleRpc("getmempooldescendants", "\"mytxid\"")
);
}
bool fVerbose = false;
if (params.size() > 1)
fVerbose = params[1].get_bool();
uint256 hash = ParseHashV(params[0], "parameter 1");
LOCK(mempool.cs);
CTxMemPool::txiter it = mempool.mapTx.find(hash);
if (it == mempool.mapTx.end()) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not in mempool");
}
CTxMemPool::setEntries setDescendants;
mempool.CalculateDescendants(it, setDescendants);
// CTxMemPool::CalculateDescendants will include the given tx
setDescendants.erase(it);
if (!fVerbose) {
UniValue o(UniValue::VARR);
BOOST_FOREACH(CTxMemPool::txiter descendantIt, setDescendants) {
o.push_back(descendantIt->GetTx().GetHash().ToString());
}
return o;
} else {
UniValue o(UniValue::VOBJ);
BOOST_FOREACH(CTxMemPool::txiter descendantIt, setDescendants) {
const CTxMemPoolEntry &e = *descendantIt;
const uint256& hash = e.GetTx().GetHash();
UniValue info(UniValue::VOBJ);
entryToJSON(info, e);
o.push_back(Pair(hash.ToString(), info));
}
return o;
}
}
UniValue getmempoolentry(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1) {
throw runtime_error(
"getmempoolentry txid\n"
"\nReturns mempool data for given transaction\n"
"\nArguments:\n"
"1. \"txid\" (string, required) The transaction id (must be in mempool)\n"
"\nResult:\n"
"{ (json object)\n"
+ EntryDescriptionString()
+ "}\n"
"\nExamples\n"
+ HelpExampleCli("getmempoolentry", "\"mytxid\"")
+ HelpExampleRpc("getmempoolentry", "\"mytxid\"")
);
}
uint256 hash = ParseHashV(params[0], "parameter 1");
LOCK(mempool.cs);
CTxMemPool::txiter it = mempool.mapTx.find(hash);
if (it == mempool.mapTx.end()) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction not in mempool");
}
const CTxMemPoolEntry &e = *it;
UniValue info(UniValue::VOBJ);
entryToJSON(info, e);
return info;
}
UniValue getblockhashes(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 2)
throw runtime_error(
"getblockhashes timestamp\n"
"\nReturns array of hashes of blocks within the timestamp range provided.\n"
"\nArguments:\n"
"1. high (numeric, required) The newer block timestamp\n"
"2. low (numeric, required) The older block timestamp\n"
"\nResult:\n"
"[\n"
" \"hash\" (string) The block hash\n"
"]\n"
"\nExamples:\n"
+ HelpExampleCli("getblockhashes", "1231614698 1231024505")
+ HelpExampleRpc("getblockhashes", "1231614698, 1231024505")
);
unsigned int high = params[0].get_int();
unsigned int low = params[1].get_int();
std::vector<uint256> blockHashes;
if (!GetTimestampIndex(high, low, blockHashes)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available for block hashes");
}
UniValue result(UniValue::VARR);
for (std::vector<uint256>::const_iterator it=blockHashes.begin(); it!=blockHashes.end(); it++) {
result.push_back(it->GetHex());
}
return result;
}
UniValue getblockhash(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getblockhash index\n"
"\nReturns hash of block in best-block-chain at index provided.\n"
"\nArguments:\n"
"1. index (numeric, required) The block index\n"
"\nResult:\n"
"\"hash\" (string) The block hash\n"
"\nExamples:\n"
+ HelpExampleCli("getblockhash", "1000")
+ HelpExampleRpc("getblockhash", "1000")
);
LOCK(cs_main);
int nHeight = params[0].get_int();
if (nHeight < 0 || nHeight > chainActive.Height())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Block height out of range");
CBlockIndex* pblockindex = chainActive[nHeight];
return pblockindex->GetBlockHash().GetHex();
}
UniValue getblockheader(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getblockheader \"hash\" ( verbose )\n"
"\nIf verbose is false, returns a string that is serialized, hex-encoded data for blockheader 'hash'.\n"
"If verbose is true, returns an Object with information about blockheader <hash>.\n"
"\nArguments:\n"
"1. \"hash\" (string, required) The block hash\n"
"2. verbose (boolean, optional, default=true) true for a json object, false for the hex encoded data\n"
"\nResult (for verbose = true):\n"
"{\n"
" \"hash\" : \"hash\", (string) the block hash (same as provided)\n"
" \"confirmations\" : n, (numeric) The number of confirmations, or -1 if the block is not on the main chain\n"
" \"height\" : n, (numeric) The block height or index\n"
" \"version\" : n, (numeric) The block version\n"
" \"versionHex\" : \"00000000\", (string) The block version formatted in hexadecimal\n"
" \"merkleroot\" : \"xxxx\", (string) The merkle root\n"
" \"time\" : ttt, (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n"
" \"mediantime\" : ttt, (numeric) The median block time in seconds since epoch (Jan 1 1970 GMT)\n"
" \"nonce\" : n, (numeric) The nonce\n"
" \"bits\" : \"1d00ffff\", (string) The bits\n"
" \"difficulty\" : x.xxx, (numeric) The difficulty\n"
" \"chainwork\" : \"0000...1f3\" (string) Expected number of hashes required to produce the current chain (in hex)\n"
" \"previousblockhash\" : \"hash\", (string) The hash of the previous block\n"
" \"nextblockhash\" : \"hash\", (string) The hash of the next block\n"
"}\n"
"\nResult (for verbose=false):\n"
"\"data\" (string) A string that is serialized, hex-encoded data for block 'hash'.\n"
"\nExamples:\n"
+ HelpExampleCli("getblockheader", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
+ HelpExampleRpc("getblockheader", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\"")
);
LOCK(cs_main);
std::string strHash = params[0].get_str();
uint256 hash(uint256S(strHash));
bool fVerbose = true;
if (params.size() > 1)
fVerbose = params[1].get_bool();
if (mapBlockIndex.count(hash) == 0)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
CBlockIndex* pblockindex = mapBlockIndex[hash];
if (!fVerbose)
{
CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION);
ssBlock << pblockindex->GetBlockHeader();
std::string strHex = HexStr(ssBlock.begin(), ssBlock.end());
return strHex;
}
return blockheaderToJSON(pblockindex);
}
UniValue getblockheaders(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 3)
throw runtime_error(
"getblockheaders \"hash\" ( count verbose )\n"
"\nReturns an array of items with information about <count> blockheaders starting from <hash>.\n"
"\nIf verbose is false, each item is a string that is serialized, hex-encoded data for a single blockheader.\n"
"If verbose is true, each item is an Object with information about a single blockheader.\n"
"\nArguments:\n"
"1. \"hash\" (string, required) The block hash\n"
"2. count (numeric, optional, default/max=" + strprintf("%s", MAX_HEADERS_RESULTS) +")\n"
"3. verbose (boolean, optional, default=true) true for a json object, false for the hex encoded data\n"
"\nResult (for verbose = true):\n"
"[ {\n"
" \"hash\" : \"hash\", (string) The block hash\n"
" \"confirmations\" : n, (numeric) The number of confirmations, or -1 if the block is not on the main chain\n"
" \"height\" : n, (numeric) The block height or index\n"
" \"version\" : n, (numeric) The block version\n"
" \"merkleroot\" : \"xxxx\", (string) The merkle root\n"
" \"time\" : ttt, (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n"
" \"mediantime\" : ttt, (numeric) The median block time in seconds since epoch (Jan 1 1970 GMT)\n"
" \"nonce\" : n, (numeric) The nonce\n"
" \"bits\" : \"1d00ffff\", (string) The bits\n"
" \"difficulty\" : x.xxx, (numeric) The difficulty\n"
" \"chainwork\" : \"0000...1f3\" (string) Expected number of hashes required to produce the current chain (in hex)\n"
" \"previousblockhash\" : \"hash\", (string) The hash of the previous block\n"
" \"nextblockhash\" : \"hash\", (string) The hash of the next block\n"
"}, {\n"
" ...\n"
" },\n"
"...\n"
"]\n"
"\nResult (for verbose=false):\n"
"[\n"
" \"data\", (string) A string that is serialized, hex-encoded data for block header.\n"
" ...\n"
"]\n"
"\nExamples:\n"
+ HelpExampleCli("getblockheaders", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\" 2000")
+ HelpExampleRpc("getblockheaders", "\"00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09\" 2000")
);
LOCK(cs_main);
std::string strHash = params[0].get_str();
uint256 hash(uint256S(strHash));
if (mapBlockIndex.count(hash) == 0)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
int nCount = MAX_HEADERS_RESULTS;
if (params.size() > 1)
nCount = params[1].get_int();
if (nCount <= 0 || nCount > (int)MAX_HEADERS_RESULTS)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Count is out of range");
bool fVerbose = true;
if (params.size() > 2)
fVerbose = params[2].get_bool();
CBlockIndex* pblockindex = mapBlockIndex[hash];
UniValue arrHeaders(UniValue::VARR);
if (!fVerbose)
{
for (; pblockindex; pblockindex = chainActive.Next(pblockindex))
{
CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION);
ssBlock << pblockindex->GetBlockHeader();
std::string strHex = HexStr(ssBlock.begin(), ssBlock.end());
arrHeaders.push_back(strHex);
if (--nCount <= 0)
break;
}
return arrHeaders;
}
for (; pblockindex; pblockindex = chainActive.Next(pblockindex))
{
arrHeaders.push_back(blockheaderToJSON(pblockindex));
if (--nCount <= 0)
break;
}
return arrHeaders;
}
UniValue getblock(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getblock \"hash\" ( verbose )\n"
"\nIf verbose is false, returns a string that is serialized, hex-encoded data for block 'hash'.\n"
"If verbose is true, returns an Object with information about block <hash>.\n"
"\nArguments:\n"
"1. \"hash\" (string, required) The block hash\n"
"2. verbose (boolean, optional, default=true) true for a json object, false for the hex encoded data\n"
"\nResult (for verbose = true):\n"
"{\n"
" \"hash\" : \"hash\", (string) the block hash (same as provided)\n"
" \"confirmations\" : n, (numeric) The number of confirmations, or -1 if the block is not on the main chain\n"
" \"size\" : n, (numeric) The block size\n"
" \"height\" : n, (numeric) The block height or index\n"
" \"version\" : n, (numeric) The block version\n"
" \"versionHex\" : \"00000000\", (string) The block version formatted in hexadecimal\n"
" \"merkleroot\" : \"xxxx\", (string) The merkle root\n"
" \"tx\" : [ (array of string) The transaction ids\n"
" \"transactionid\" (string) The transaction id\n"
" ,...\n"
" ],\n"
" \"time\" : ttt, (numeric) The block time in seconds since epoch (Jan 1 1970 GMT)\n"
" \"mediantime\" : ttt, (numeric) The median block time in seconds since epoch (Jan 1 1970 GMT)\n"
" \"nonce\" : n, (numeric) The nonce\n"
" \"bits\" : \"1d00ffff\", (string) The bits\n"
" \"difficulty\" : x.xxx, (numeric) The difficulty\n"
" \"chainwork\" : \"xxxx\", (string) Expected number of hashes required to produce the chain up to this block (in hex)\n"
" \"previousblockhash\" : \"hash\", (string) The hash of the previous block\n"
" \"nextblockhash\" : \"hash\" (string) The hash of the next block\n"
"}\n"
"\nResult (for verbose=false):\n"
"\"data\" (string) A string that is serialized, hex-encoded data for block 'hash'.\n"
"\nExamples:\n"
+ HelpExampleCli("getblock", "\"00000000000fd08c2fb661d2fcb0d49abb3a91e5f27082ce64feed3b4dede2e2\"")
+ HelpExampleRpc("getblock", "\"00000000000fd08c2fb661d2fcb0d49abb3a91e5f27082ce64feed3b4dede2e2\"")
);
LOCK(cs_main);
std::string strHash = params[0].get_str();
uint256 hash(uint256S(strHash));
bool fVerbose = true;
if (params.size() > 1)
fVerbose = params[1].get_bool();
if (mapBlockIndex.count(hash) == 0)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
CBlock block;
CBlockIndex* pblockindex = mapBlockIndex[hash];
if (fHavePruned && !(pblockindex->nStatus & BLOCK_HAVE_DATA) && pblockindex->nTx > 0)
throw JSONRPCError(RPC_INTERNAL_ERROR, "Block not available (pruned data)");
if(!ReadBlockFromDisk(block, pblockindex, Params().GetConsensus()))
throw JSONRPCError(RPC_INTERNAL_ERROR, "Can't read block from disk");
if (!fVerbose)
{
CDataStream ssBlock(SER_NETWORK, PROTOCOL_VERSION);
ssBlock << block;
std::string strHex = HexStr(ssBlock.begin(), ssBlock.end());
return strHex;
}
return blockToJSON(block, pblockindex);
}
struct CCoinsStats
{
int nHeight;
uint256 hashBlock;
uint64_t nTransactions;
uint64_t nTransactionOutputs;
uint256 hashSerialized;
uint64_t nDiskSize;
CAmount nTotalAmount;
CCoinsStats() : nHeight(0), nTransactions(0), nTransactionOutputs(0), nTotalAmount(0) {}
};
static void ApplyStats(CCoinsStats &stats, CHashWriter& ss, const uint256& hash, const std::map<uint32_t, Coin>& outputs)
{
assert(!outputs.empty());
ss << hash;
ss << VARINT(outputs.begin()->second.nHeight * 2 + outputs.begin()->second.fCoinBase);
stats.nTransactions++;
for (const auto output : outputs) {
ss << VARINT(output.first + 1);
ss << *(const CScriptBase*)(&output.second.out.scriptPubKey);
ss << VARINT(output.second.out.nValue);
stats.nTransactionOutputs++;
stats.nTotalAmount += output.second.out.nValue;
}
ss << VARINT(0);
}
//! Calculate statistics about the unspent transaction output set
static bool GetUTXOStats(CCoinsView *view, CCoinsStats &stats)
{
boost::scoped_ptr<CCoinsViewCursor> pcursor(view->Cursor());
CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION);
stats.hashBlock = pcursor->GetBestBlock();
{
LOCK(cs_main);
stats.nHeight = mapBlockIndex.find(stats.hashBlock)->second->nHeight;
}
ss << stats.hashBlock;
uint256 prevkey;
std::map<uint32_t, Coin> outputs;
while (pcursor->Valid()) {
boost::this_thread::interruption_point();
COutPoint key;
Coin coin;
if (pcursor->GetKey(key) && pcursor->GetValue(coin)) {
if (!outputs.empty() && key.hash != prevkey) {
ApplyStats(stats, ss, prevkey, outputs);
outputs.clear();
}
prevkey = key.hash;
outputs[key.n] = std::move(coin);
} else {
return error("%s: unable to read value", __func__);
}
pcursor->Next();
}
if (!outputs.empty()) {
ApplyStats(stats, ss, prevkey, outputs);
}
stats.hashSerialized = ss.GetHash();
stats.nDiskSize = view->EstimateSize();
return true;
}
UniValue gettxoutsetinfo(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"gettxoutsetinfo\n"
"\nReturns statistics about the unspent transaction output set.\n"
"Note this call may take some time.\n"
"\nResult:\n"
"{\n"
" \"height\":n, (numeric) The current block height (index)\n"
" \"bestblock\": \"hex\", (string) the best block hash hex\n"
" \"transactions\": n, (numeric) The number of transactions\n"
" \"txouts\": n, (numeric) The number of output transactions\n"
" \"hash_serialized\": \"hash\", (string) The serialized hash\n"
" \"disk_size\": n, (numeric) The estimated size of the chainstate on disk\n"
" \"total_amount\": x.xxx (numeric) The total amount\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("gettxoutsetinfo", "")
+ HelpExampleRpc("gettxoutsetinfo", "")
);
UniValue ret(UniValue::VOBJ);
CCoinsStats stats;
FlushStateToDisk();
if (GetUTXOStats(pcoinsdbview, stats)) {
ret.push_back(Pair("height", (int64_t)stats.nHeight));
ret.push_back(Pair("bestblock", stats.hashBlock.GetHex()));
ret.push_back(Pair("transactions", (int64_t)stats.nTransactions));
ret.push_back(Pair("txouts", (int64_t)stats.nTransactionOutputs));
ret.push_back(Pair("hash_serialized_2", stats.hashSerialized.GetHex()));
ret.push_back(Pair("disk_size", stats.nDiskSize));
ret.push_back(Pair("total_amount", ValueFromAmount(stats.nTotalAmount)));
}
return ret;
}
UniValue gettxout(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 3)
throw runtime_error(
"gettxout \"txid\" n ( includemempool )\n"
"\nReturns details about an unspent transaction output.\n"
"\nArguments:\n"
"1. \"txid\" (string, required) The transaction id\n"
"2. n (numeric, required) vout number\n"
"3. includemempool (boolean, optional) Whether to include the mem pool\n"
"\nResult:\n"
"{\n"
" \"bestblock\" : \"hash\", (string) the block hash\n"
" \"confirmations\" : n, (numeric) The number of confirmations\n"
" \"value\" : x.xxx, (numeric) The transaction value in " + CURRENCY_UNIT + "\n"
" \"scriptPubKey\" : { (json object)\n"
" \"asm\" : \"code\", (string) \n"
" \"hex\" : \"hex\", (string) \n"
" \"reqSigs\" : n, (numeric) Number of required signatures\n"
" \"type\" : \"pubkeyhash\", (string) The type, eg pubkeyhash\n"
" \"addresses\" : [ (array of string) array of dash addresses\n"
" \"dashaddress\" (string) dash address\n"
" ,...\n"
" ]\n"
" },\n"
" \"version\" : n, (numeric) The version\n"
" \"coinbase\" : true|false (boolean) Coinbase or not\n"
"}\n"
"\nExamples:\n"
"\nGet unspent transactions\n"
+ HelpExampleCli("listunspent", "") +
"\nView the details\n"
+ HelpExampleCli("gettxout", "\"txid\" 1") +
"\nAs a json rpc call\n"
+ HelpExampleRpc("gettxout", "\"txid\", 1")
);
LOCK(cs_main);
UniValue ret(UniValue::VOBJ);
std::string strHash = params[0].get_str();
uint256 hash(uint256S(strHash));
int n = params[1].get_int();
COutPoint out(hash, n);
bool fMempool = true;
if (params.size() > 2)
fMempool = params[2].get_bool();
Coin coin;
if (fMempool) {
LOCK(mempool.cs);
CCoinsViewMemPool view(pcoinsTip, mempool);
if (!view.GetCoin(out, coin) || mempool.isSpent(out)) { // TODO: filtering spent coins should be done by the CCoinsViewMemPool
return NullUniValue;
}
} else {
if (!pcoinsTip->GetCoin(out, coin)) {
return NullUniValue;
}
}
BlockMap::iterator it = mapBlockIndex.find(pcoinsTip->GetBestBlock());
CBlockIndex *pindex = it->second;
ret.push_back(Pair("bestblock", pindex->GetBlockHash().GetHex()));
if (coin.nHeight == MEMPOOL_HEIGHT) {
ret.push_back(Pair("confirmations", 0));
} else {
ret.push_back(Pair("confirmations", (int64_t)(pindex->nHeight - coin.nHeight + 1)));
}
ret.push_back(Pair("value", ValueFromAmount(coin.out.nValue)));
UniValue o(UniValue::VOBJ);
ScriptPubKeyToJSON(coin.out.scriptPubKey, o, true);
ret.push_back(Pair("scriptPubKey", o));
ret.push_back(Pair("coinbase", (bool)coin.fCoinBase));
return ret;
}
UniValue verifychain(const UniValue& params, bool fHelp)
{
int nCheckLevel = GetArg("-checklevel", DEFAULT_CHECKLEVEL);
int nCheckDepth = GetArg("-checkblocks", DEFAULT_CHECKBLOCKS);
if (fHelp || params.size() > 2)
throw runtime_error(
"verifychain ( checklevel numblocks )\n"
"\nVerifies blockchain database.\n"
"\nArguments:\n"
"1. checklevel (numeric, optional, 0-4, default=" + strprintf("%d", nCheckLevel) + ") How thorough the block verification is.\n"
"2. numblocks (numeric, optional, default=" + strprintf("%d", nCheckDepth) + ", 0=all) The number of blocks to check.\n"
"\nResult:\n"
"true|false (boolean) Verified or not\n"
"\nExamples:\n"
+ HelpExampleCli("verifychain", "")
+ HelpExampleRpc("verifychain", "")
);
LOCK(cs_main);
if (params.size() > 0)
nCheckLevel = params[0].get_int();
if (params.size() > 1)
nCheckDepth = params[1].get_int();
return CVerifyDB().VerifyDB(Params(), pcoinsTip, nCheckLevel, nCheckDepth);
}
/** Implementation of IsSuperMajority with better feedback */
static UniValue SoftForkMajorityDesc(int minVersion, CBlockIndex* pindex, int nRequired, const Consensus::Params& consensusParams)
{
int nFound = 0;
CBlockIndex* pstart = pindex;
for (int i = 0; i < consensusParams.nMajorityWindow && pstart != NULL; i++)
{
if (pstart->nVersion >= minVersion)
++nFound;
pstart = pstart->pprev;
}
UniValue rv(UniValue::VOBJ);
rv.push_back(Pair("status", nFound >= nRequired));
rv.push_back(Pair("found", nFound));
rv.push_back(Pair("required", nRequired));
rv.push_back(Pair("window", consensusParams.nMajorityWindow));
return rv;
}
static UniValue SoftForkDesc(const std::string &name, int version, CBlockIndex* pindex, const Consensus::Params& consensusParams)
{
UniValue rv(UniValue::VOBJ);
rv.push_back(Pair("id", name));
rv.push_back(Pair("version", version));
rv.push_back(Pair("enforce", SoftForkMajorityDesc(version, pindex, consensusParams.nMajorityEnforceBlockUpgrade, consensusParams)));
rv.push_back(Pair("reject", SoftForkMajorityDesc(version, pindex, consensusParams.nMajorityRejectBlockOutdated, consensusParams)));
return rv;
}
static UniValue BIP9SoftForkDesc(const Consensus::Params& consensusParams, Consensus::DeploymentPos id)
{
UniValue rv(UniValue::VOBJ);
const ThresholdState thresholdState = VersionBitsTipState(consensusParams, id);
switch (thresholdState) {
case THRESHOLD_DEFINED: rv.push_back(Pair("status", "defined")); break;
case THRESHOLD_STARTED: rv.push_back(Pair("status", "started")); break;
case THRESHOLD_LOCKED_IN: rv.push_back(Pair("status", "locked_in")); break;
case THRESHOLD_ACTIVE: rv.push_back(Pair("status", "active")); break;
case THRESHOLD_FAILED: rv.push_back(Pair("status", "failed")); break;
}
if (THRESHOLD_STARTED == thresholdState)
{
rv.push_back(Pair("bit", consensusParams.vDeployments[id].bit));
}
rv.push_back(Pair("startTime", consensusParams.vDeployments[id].nStartTime));
rv.push_back(Pair("timeout", consensusParams.vDeployments[id].nTimeout));
return rv;
}
void BIP9SoftForkDescPushBack(UniValue& bip9_softforks, const std::string &name, const Consensus::Params& consensusParams, Consensus::DeploymentPos id)
{
// Deployments with timeout value of 0 are hidden.
// A timeout value of 0 guarantees a softfork will never be activated.
// This is used when softfork codes are merged without specifying the deployment schedule.
if (consensusParams.vDeployments[id].nTimeout > 0)
bip9_softforks.push_back(Pair(name, BIP9SoftForkDesc(consensusParams, id)));
}
UniValue getblockchaininfo(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getblockchaininfo\n"
"Returns an object containing various state info regarding block chain processing.\n"
"\nResult:\n"
"{\n"
" \"chain\": \"xxxx\", (string) current network name as defined in BIP70 (main, test, regtest)\n"
" \"blocks\": xxxxxx, (numeric) the current number of blocks processed in the server\n"
" \"headers\": xxxxxx, (numeric) the current number of headers we have validated\n"
" \"bestblockhash\": \"...\", (string) the hash of the currently best block\n"
" \"difficulty\": xxxxxx, (numeric) the current difficulty\n"
" \"mediantime\": xxxxxx, (numeric) median time for the current best block\n"
" \"verificationprogress\": xxxx, (numeric) estimate of verification progress [0..1]\n"
" \"chainwork\": \"xxxx\" (string) total amount of work in active chain, in hexadecimal\n"
" \"pruned\": xx, (boolean) if the blocks are subject to pruning\n"
" \"pruneheight\": xxxxxx, (numeric) heighest block available\n"
" \"softforks\": [ (array) status of softforks in progress\n"
" {\n"
" \"id\": \"xxxx\", (string) name of softfork\n"
" \"version\": xx, (numeric) block version\n"
" \"enforce\": { (object) progress toward enforcing the softfork rules for new-version blocks\n"
" \"status\": xx, (boolean) true if threshold reached\n"
" \"found\": xx, (numeric) number of blocks with the new version found\n"
" \"required\": xx, (numeric) number of blocks required to trigger\n"
" \"window\": xx, (numeric) maximum size of examined window of recent blocks\n"
" },\n"
" \"reject\": { ... } (object) progress toward rejecting pre-softfork blocks (same fields as \"enforce\")\n"
" }, ...\n"
" ],\n"
" \"bip9_softforks\": { (object) status of BIP9 softforks in progress\n"
" \"xxxx\" : { (string) name of the softfork\n"
" \"status\": \"xxxx\", (string) one of \"defined\", \"started\", \"locked_in\", \"active\", \"failed\"\n"
" \"bit\": xx, (numeric) the bit (0-28) in the block version field used to signal this softfork (only for \"started\" status)\n"
" \"startTime\": xx, (numeric) the minimum median time past of a block at which the bit gains its meaning\n"
" \"timeout\": xx (numeric) the median time past of a block at which the deployment is considered failed if not yet locked in\n"
" }\n"
" }\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("getblockchaininfo", "")
+ HelpExampleRpc("getblockchaininfo", "")
);
LOCK(cs_main);
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("chain", Params().NetworkIDString()));
obj.push_back(Pair("blocks", (int)chainActive.Height()));
obj.push_back(Pair("headers", pindexBestHeader ? pindexBestHeader->nHeight : -1));
obj.push_back(Pair("bestblockhash", chainActive.Tip()->GetBlockHash().GetHex()));
obj.push_back(Pair("difficulty", (double)GetDifficulty()));
obj.push_back(Pair("mediantime", (int64_t)chainActive.Tip()->GetMedianTimePast()));
obj.push_back(Pair("verificationprogress", Checkpoints::GuessVerificationProgress(Params().Checkpoints(), chainActive.Tip())));
obj.push_back(Pair("chainwork", chainActive.Tip()->nChainWork.GetHex()));
obj.push_back(Pair("pruned", fPruneMode));
const Consensus::Params& consensusParams = Params().GetConsensus();
CBlockIndex* tip = chainActive.Tip();
UniValue softforks(UniValue::VARR);
UniValue bip9_softforks(UniValue::VOBJ);
softforks.push_back(SoftForkDesc("bip34", 2, tip, consensusParams));
softforks.push_back(SoftForkDesc("bip66", 3, tip, consensusParams));
softforks.push_back(SoftForkDesc("bip65", 4, tip, consensusParams));
BIP9SoftForkDescPushBack(bip9_softforks, "csv", consensusParams, Consensus::DEPLOYMENT_CSV);
BIP9SoftForkDescPushBack(bip9_softforks, "dip0001", consensusParams, Consensus::DEPLOYMENT_DIP0001);
obj.push_back(Pair("softforks", softforks));
obj.push_back(Pair("bip9_softforks", bip9_softforks));
if (fPruneMode)
{
CBlockIndex *block = chainActive.Tip();
while (block && block->pprev && (block->pprev->nStatus & BLOCK_HAVE_DATA))
block = block->pprev;
obj.push_back(Pair("pruneheight", block->nHeight));
}
return obj;
}
/** Comparison function for sorting the getchaintips heads. */
struct CompareBlocksByHeight
{
bool operator()(const CBlockIndex* a, const CBlockIndex* b) const
{
/* Make sure that unequal blocks with the same height do not compare
equal. Use the pointers themselves to make a distinction. */
if (a->nHeight != b->nHeight)
return (a->nHeight > b->nHeight);
return a < b;
}
};
UniValue getchaintips(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"getchaintips ( count branchlen )\n"
"Return information about all known tips in the block tree,"
" including the main chain as well as orphaned branches.\n"
"\nArguments:\n"
"1. count (numeric, optional) only show this much of latest tips\n"
"2. branchlen (numeric, optional) only show tips that have equal or greater length of branch\n"
"\nResult:\n"
"[\n"
" {\n"
" \"height\": xxxx, (numeric) height of the chain tip\n"
" \"hash\": \"xxxx\", (string) block hash of the tip\n"
" \"difficulty\" : x.xxx, (numeric) The difficulty\n"
" \"chainwork\" : \"0000...1f3\" (string) Expected number of hashes required to produce the current chain (in hex)\n"
" \"branchlen\": 0 (numeric) zero for main chain\n"
" \"status\": \"active\" (string) \"active\" for the main chain\n"
" },\n"
" {\n"
" \"height\": xxxx,\n"
" \"hash\": \"xxxx\",\n"
" \"difficulty\" : x.xxx,\n"
" \"chainwork\" : \"0000...1f3\"\n"
" \"branchlen\": 1 (numeric) length of branch connecting the tip to the main chain\n"
" \"status\": \"xxxx\" (string) status of the chain (active, valid-fork, valid-headers, headers-only, invalid)\n"
" }\n"
"]\n"
"Possible values for status:\n"
"1. \"invalid\" This branch contains at least one invalid block\n"
"2. \"headers-only\" Not all blocks for this branch are available, but the headers are valid\n"
"3. \"valid-headers\" All blocks are available for this branch, but they were never fully validated\n"
"4. \"valid-fork\" This branch is not part of the active chain, but is fully validated\n"
"5. \"active\" This is the tip of the active main chain, which is certainly valid\n"
"\nExamples:\n"
+ HelpExampleCli("getchaintips", "")
+ HelpExampleRpc("getchaintips", "")
);
LOCK(cs_main);
/*
* Idea: the set of chain tips is chainActive.tip, plus orphan blocks which do not have another orphan building off of them.
* Algorithm:
* - Make one pass through mapBlockIndex, picking out the orphan blocks, and also storing a set of the orphan block's pprev pointers.
* - Iterate through the orphan blocks. If the block isn't pointed to by another orphan, it is a chain tip.
* - add chainActive.Tip()
*/
std::set<const CBlockIndex*, CompareBlocksByHeight> setTips;
std::set<const CBlockIndex*> setOrphans;
std::set<const CBlockIndex*> setPrevs;
BOOST_FOREACH(const PAIRTYPE(const uint256, CBlockIndex*)& item, mapBlockIndex)
{
if (!chainActive.Contains(item.second)) {
setOrphans.insert(item.second);
setPrevs.insert(item.second->pprev);
}
}
for (std::set<const CBlockIndex*>::iterator it = setOrphans.begin(); it != setOrphans.end(); ++it)
{
if (setPrevs.erase(*it) == 0) {
setTips.insert(*it);
}
}
// Always report the currently active tip.
setTips.insert(chainActive.Tip());
int nBranchMin = -1;
int nCountMax = INT_MAX;
if(params.size() >= 1)
nCountMax = params[0].get_int();
if(params.size() == 2)
nBranchMin = params[1].get_int();
/* Construct the output array. */
UniValue res(UniValue::VARR);
BOOST_FOREACH(const CBlockIndex* block, setTips)
{
const int branchLen = block->nHeight - chainActive.FindFork(block)->nHeight;
if(branchLen < nBranchMin) continue;
if(nCountMax-- < 1) break;
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("height", block->nHeight));
obj.push_back(Pair("hash", block->phashBlock->GetHex()));
obj.push_back(Pair("difficulty", GetDifficulty(block)));
obj.push_back(Pair("chainwork", block->nChainWork.GetHex()));
obj.push_back(Pair("branchlen", branchLen));
string status;
if (chainActive.Contains(block)) {
// This block is part of the currently active chain.
status = "active";
} else if (block->nStatus & BLOCK_FAILED_MASK) {
// This block or one of its ancestors is invalid.
status = "invalid";
} else if (block->nChainTx == 0) {
// This block cannot be connected because full block data for it or one of its parents is missing.
status = "headers-only";
} else if (block->IsValid(BLOCK_VALID_SCRIPTS)) {
// This block is fully validated, but no longer part of the active chain. It was probably the active block once, but was reorganized.
status = "valid-fork";
} else if (block->IsValid(BLOCK_VALID_TREE)) {
// The headers for this block are valid, but it has not been validated. It was probably never part of the most-work chain.
status = "valid-headers";
} else {
// No clue.
status = "unknown";
}
obj.push_back(Pair("status", status));
res.push_back(obj);
}
return res;
}
UniValue mempoolInfoToJSON()
{
UniValue ret(UniValue::VOBJ);
ret.push_back(Pair("size", (int64_t) mempool.size()));
ret.push_back(Pair("bytes", (int64_t) mempool.GetTotalTxSize()));
ret.push_back(Pair("usage", (int64_t) mempool.DynamicMemoryUsage()));
size_t maxmempool = GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
ret.push_back(Pair("maxmempool", (int64_t) maxmempool));
ret.push_back(Pair("mempoolminfee", ValueFromAmount(mempool.GetMinFee(maxmempool).GetFeePerK())));
return ret;
}
UniValue getmempoolinfo(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getmempoolinfo\n"
"\nReturns details on the active state of the TX memory pool.\n"
"\nResult:\n"
"{\n"
" \"size\": xxxxx, (numeric) Current tx count\n"
" \"bytes\": xxxxx, (numeric) Sum of all tx sizes\n"
" \"usage\": xxxxx, (numeric) Total memory usage for the mempool\n"
" \"maxmempool\": xxxxx, (numeric) Maximum memory usage for the mempool\n"
" \"mempoolminfee\": xxxxx (numeric) Minimum fee for tx to be accepted\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("getmempoolinfo", "")
+ HelpExampleRpc("getmempoolinfo", "")
);
return mempoolInfoToJSON();
}
UniValue invalidateblock(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"invalidateblock \"hash\"\n"
"\nPermanently marks a block as invalid, as if it violated a consensus rule.\n"
"\nArguments:\n"
"1. hash (string, required) the hash of the block to mark as invalid\n"
"\nResult:\n"
"\nExamples:\n"
+ HelpExampleCli("invalidateblock", "\"blockhash\"")
+ HelpExampleRpc("invalidateblock", "\"blockhash\"")
);
std::string strHash = params[0].get_str();
uint256 hash(uint256S(strHash));
CValidationState state;
{
LOCK(cs_main);
if (mapBlockIndex.count(hash) == 0)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
CBlockIndex* pblockindex = mapBlockIndex[hash];
InvalidateBlock(state, Params(), pblockindex);
}
if (state.IsValid()) {
ActivateBestChain(state, Params(), NULL);
}
if (!state.IsValid()) {
throw JSONRPCError(RPC_DATABASE_ERROR, state.GetRejectReason());
}
return NullUniValue;
}
UniValue reconsiderblock(const UniValue& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"reconsiderblock \"hash\"\n"
"\nRemoves invalidity status of a block and its descendants, reconsider them for activation.\n"
"This can be used to undo the effects of invalidateblock.\n"
"\nArguments:\n"
"1. hash (string, required) the hash of the block to reconsider\n"
"\nResult:\n"
"\nExamples:\n"
+ HelpExampleCli("reconsiderblock", "\"blockhash\"")
+ HelpExampleRpc("reconsiderblock", "\"blockhash\"")
);
std::string strHash = params[0].get_str();
uint256 hash(uint256S(strHash));
{
LOCK(cs_main);
if (mapBlockIndex.count(hash) == 0)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found");
CBlockIndex* pblockindex = mapBlockIndex[hash];
ResetBlockFailureFlags(pblockindex);
}
CValidationState state;
ActivateBestChain(state, Params(), NULL);
if (!state.IsValid()) {
throw JSONRPCError(RPC_DATABASE_ERROR, state.GetRejectReason());
}
return NullUniValue;
}
static const CRPCCommand commands[] =
{ // category name actor (function) okSafeMode
// --------------------- ------------------------ ----------------------- ----------
{ "blockchain", "getblockchaininfo", &getblockchaininfo, true },
{ "blockchain", "getbestblockhash", &getbestblockhash, true },
{ "blockchain", "getblockcount", &getblockcount, true },
{ "blockchain", "getblock", &getblock, true },
{ "blockchain", "getblockhashes", &getblockhashes, true },
{ "blockchain", "getblockhash", &getblockhash, true },
{ "blockchain", "getblockheader", &getblockheader, true },
{ "blockchain", "getblockheaders", &getblockheaders, true },
{ "blockchain", "getchaintips", &getchaintips, true },
{ "blockchain", "getdifficulty", &getdifficulty, true },
{ "blockchain", "getmempoolancestors", &getmempoolancestors, true },
{ "blockchain", "getmempooldescendants", &getmempooldescendants, true },
{ "blockchain", "getmempoolentry", &getmempoolentry, true },
{ "blockchain", "getmempoolinfo", &getmempoolinfo, true },
{ "blockchain", "getrawmempool", &getrawmempool, true },
{ "blockchain", "gettxout", &gettxout, true },
{ "blockchain", "gettxoutsetinfo", &gettxoutsetinfo, true },
{ "blockchain", "verifychain", &verifychain, true },
/* Not shown in help */
{ "hidden", "invalidateblock", &invalidateblock, true },
{ "hidden", "reconsiderblock", &reconsiderblock, true },
};
void RegisterBlockchainRPCCommands(CRPCTable &tableRPC)
{
for (unsigned int vcidx = 0; vcidx < ARRAYLEN(commands); vcidx++)
tableRPC.appendCommand(commands[vcidx].name, &commands[vcidx]);
}
| [
"rodrigosoaresilva@gmail.com"
] | rodrigosoaresilva@gmail.com |
756cd563fa1759e4bbfb23c662bb6e0ec0247a99 | 27ae6b58577f38891e12fa5665548803e86df08b | /Mincho/UI.cpp | 34e13aa0e6321da1809f1e201cc0c6f042ba497c | [] | no_license | DaLae37/RiotOfMincho | 194eaea462fe65e2d0965ebc6a344aaa7d619e00 | e0702c9e9c6d2fdc112257c56ac9d8477fbfad1c | refs/heads/master | 2023-05-01T09:27:24.793458 | 2023-04-20T03:57:00 | 2023-04-20T03:57:00 | 99,400,643 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,079 | cpp | #include "stdafx.h"
#include "UI.h"
UI::UI()
{
player1Index = 0;
player2Index = 1;
player1 = new ZeroSprite("Resource/UI/player1.png");
player1->SetPos(0, 20);
PushScene(player1);
player2 = new ZeroSprite("Resource/UI/player2.png");
player2->SetPos(1000, 20);
PushScene(player2);
for (int i = 0; i < 3; i++) {
if (i < 2) {
P1isDone[i] = false;
P2isDone[i] = false;
for (int j = 0; j < 2; j++) {
CircleP1[i][j] = new ZeroSprite("Resource/UI/Circle%d.png", j);
CircleP1[i][j]->SetPos(45 + 100 * i, 500);
CircleP2[i][j] = new ZeroSprite("Resource/UI/Circle%d.png", j);
CircleP2[i][j]->SetPos(1045+ 100 * i, 500);
}
}
player1Heart[i] = new ZeroSprite("Resource/UI/Heart.png");
player1Heart[i]->SetPos(i * 95, 115);
player2Heart[i] = new ZeroSprite("Resource/UI/Heart.png");
player2Heart[i]->SetPos(1190 - i * 95, 115);
character[i] = new ZeroSprite("Resource/UI/Character%d.png", i+1);
player1HeartRender[i] = true;
player2HeartRender[i] = true;
}
for (int i = 0; i < 15; i++) {
for (int j = 0; j < 15; j++) {
if ((new Def)->map[i][j]) {
Tile[i][j] = new ZeroSprite("Resource/Background/enableTile.png");
}
else {
Tile[i][j] = new ZeroSprite("Resource/Background/unableTile.png");
}
Tile[i][j]->SetPos(280 + j * MAP_SIZE, 0 + i * MAP_SIZE);
}
}
}
UI::~UI()
{
}
void UI::Render() {
ZeroIScene::Render();
for (int i = 0; i < 15; i++) {
for (int j = 0; j < 15; j++) {
Tile[i][j]->Render();
}
}
player1->Render();
player2->Render();
for (int i = 0; i < 3; i++) {
if (i < 2) {
CircleP1[i][(int)P1isDone[i]]->Render();
CircleP2[i][(int)P2isDone[i]]->Render();
}
if (player1Index == i) {
character[player1Index]->SetPos(5,210);
character[player1Index]->Render();
}
else if (player2Index == i) {
character[player2Index]->SetPos(1005,210);
character[player2Index]->Render();
}
if(player1HeartRender[i])
player1Heart[i]->Render();
if(player2HeartRender[i])
player2Heart[i]->Render();
}
}
void UI::Update(float eTime) {
ZeroIScene::Update(eTime);
} | [
"dalae37@gmail.com"
] | dalae37@gmail.com |
9a0f79338a9018dd5684d6c79b0c620466698b4e | 7a81be09ee6f278b7061eeb83f408d822a617dde | /cpp/datastructures/schaumDS/SODSWCPP/Pr0602.cpp | 3ef3034614bb51edf6126f1380a3e788e8922a56 | [] | no_license | amithjkamath/codesamples | dba2ef77abc3b2604b8202ed67ef516bbc971a76 | d3147d743ba9431d42423d0fa78b0e1048922458 | refs/heads/master | 2022-03-23T23:25:35.171973 | 2022-02-28T21:22:23 | 2022-02-28T21:22:23 | 67,352,584 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 967 | cpp | // Data Structures with C++ by John R. Hubbard
// Copyright McGraw-Hill, 2000
// Example 6.2 page 121
// Testing reverse() function for queues
#include <iostream>
#include <queue>
#include <stack>
using namespace std;
template <class T> void print(queue<T>);
template <class T> void reverse(queue<T>&);
int main()
{ queue<char> q;
q.push('A');
q.push('B');
q.push('C');
q.push('D');
q.push('E');
print(q);
reverse(q);
print(q);
}
template <class T>
void print(queue<T> q)
{ cout << "size=" << q.size();
if (q.size()>0)
{ cout << ",\tfront=" << q.front() << ":\t(" << q.front();
q.pop();
while (!q.empty())
{ cout << "," << q.front();
q.pop();
}
cout << ")";
}
cout << "\n";
}
template <class T> void reverse(queue<T>& q)
{ stack<T> s;
while (!q.empty())
{ s.push(q.front());
q.pop();
}
while (!s.empty())
{ q.push(s.top());
s.pop();
}
}
| [
"kamath.quaero@gmail.com"
] | kamath.quaero@gmail.com |
444a6c436cf83f38fc6a6c1cdd9ab80aca4c2b4d | adecc7f08d1a16947f3a3d134822d8ff955cab04 | /src/compressor.cpp | e3e9b182e8c1bec811ea42e3c2be8c3fad6bc43e | [
"MIT"
] | permissive | NodeZeroCoin/nodezerocore | 75af6bb7a3bb94207deb18c6ca2d9d377ed406e2 | 852034254f8ebc5611f8ffe12104628b27207100 | refs/heads/master | 2021-02-11T11:17:44.408776 | 2020-05-12T22:51:21 | 2020-05-12T22:51:21 | 244,486,535 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,139 | cpp | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2017-2018 The PIVX developers
// Copyright (c) 2019 The CryptoDev developers
// Copyright (c) 2019 The NodeZero developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "compressor.h"
#include "hash.h"
#include "pubkey.h"
#include "script/standard.h"
bool CScriptCompressor::IsToKeyID(CKeyID& hash) const
{
if (script.size() == 25 && script[0] == OP_DUP && script[1] == OP_HASH160 && script[2] == 20 && script[23] == OP_EQUALVERIFY && script[24] == OP_CHECKSIG) {
memcpy(&hash, &script[3], 20);
return true;
}
return false;
}
bool CScriptCompressor::IsToScriptID(CScriptID& hash) const
{
if (script.size() == 23 && script[0] == OP_HASH160 && script[1] == 20 && script[22] == OP_EQUAL) {
memcpy(&hash, &script[2], 20);
return true;
}
return false;
}
bool CScriptCompressor::IsToPubKey(CPubKey& pubkey) const
{
if (script.size() == 35 && script[0] == 33 && script[34] == OP_CHECKSIG && (script[1] == 0x02 || script[1] == 0x03)) {
pubkey.Set(&script[1], &script[34]);
return true;
}
if (script.size() == 67 && script[0] == 65 && script[66] == OP_CHECKSIG && script[1] == 0x04) {
pubkey.Set(&script[1], &script[66]);
return pubkey.IsFullyValid(); // if not fully valid, a case that would not be compressible
}
return false;
}
bool CScriptCompressor::Compress(std::vector<unsigned char>& out) const
{
CKeyID keyID;
if (IsToKeyID(keyID)) {
out.resize(21);
out[0] = 0x00;
memcpy(&out[1], &keyID, 20);
return true;
}
CScriptID scriptID;
if (IsToScriptID(scriptID)) {
out.resize(21);
out[0] = 0x01;
memcpy(&out[1], &scriptID, 20);
return true;
}
CPubKey pubkey;
if (IsToPubKey(pubkey)) {
out.resize(33);
memcpy(&out[1], &pubkey[1], 32);
if (pubkey[0] == 0x02 || pubkey[0] == 0x03) {
out[0] = pubkey[0];
return true;
} else if (pubkey[0] == 0x04) {
out[0] = 0x04 | (pubkey[64] & 0x01);
return true;
}
}
return false;
}
unsigned int CScriptCompressor::GetSpecialSize(unsigned int nSize) const
{
if (nSize == 0 || nSize == 1)
return 20;
if (nSize == 2 || nSize == 3 || nSize == 4 || nSize == 5)
return 32;
return 0;
}
bool CScriptCompressor::Decompress(unsigned int nSize, const std::vector<unsigned char>& in)
{
switch (nSize) {
case 0x00:
script.resize(25);
script[0] = OP_DUP;
script[1] = OP_HASH160;
script[2] = 20;
memcpy(&script[3], &in[0], 20);
script[23] = OP_EQUALVERIFY;
script[24] = OP_CHECKSIG;
return true;
case 0x01:
script.resize(23);
script[0] = OP_HASH160;
script[1] = 20;
memcpy(&script[2], &in[0], 20);
script[22] = OP_EQUAL;
return true;
case 0x02:
case 0x03:
script.resize(35);
script[0] = 33;
script[1] = nSize;
memcpy(&script[2], &in[0], 32);
script[34] = OP_CHECKSIG;
return true;
case 0x04:
case 0x05:
unsigned char vch[33] = {};
vch[0] = nSize - 2;
memcpy(&vch[1], &in[0], 32);
CPubKey pubkey(&vch[0], &vch[33]);
if (!pubkey.Decompress())
return false;
assert(pubkey.size() == 65);
script.resize(67);
script[0] = 65;
memcpy(&script[1], pubkey.begin(), 65);
script[66] = OP_CHECKSIG;
return true;
}
return false;
}
// Amount compression:
// * If the amount is 0, output 0
// * first, divide the amount (in base units) by the largest power of 10 possible; call the exponent e (e is max 9)
// * if e<9, the last digit of the resulting number cannot be 0; store it as d, and drop it (divide by 10)
// * call the result n
// * output 1 + 10*(9*n + d - 1) + e
// * if e==9, we only know the resulting number is not zero, so output 1 + 10*(n - 1) + 9
// (this is decodable, as d is in [1-9] and e is in [0-9])
uint64_t CTxOutCompressor::CompressAmount(uint64_t n)
{
if (n == 0)
return 0;
int e = 0;
while (((n % 10) == 0) && e < 9) {
n /= 10;
e++;
}
if (e < 9) {
int d = (n % 10);
assert(d >= 1 && d <= 9);
n /= 10;
return 1 + (n * 9 + d - 1) * 10 + e;
} else {
return 1 + (n - 1) * 10 + 9;
}
}
uint64_t CTxOutCompressor::DecompressAmount(uint64_t x)
{
// x = 0 OR x = 1+10*(9*n + d - 1) + e OR x = 1+10*(n - 1) + 9
if (x == 0)
return 0;
x--;
// x = 10*(9*n + d - 1) + e
int e = x % 10;
x /= 10;
uint64_t n = 0;
if (e < 9) {
// x = 9*n + d - 1
int d = (x % 9) + 1;
x /= 9;
// x = n
n = x * 10 + d;
} else {
n = x + 1;
}
while (e) {
n *= 10;
e--;
}
return n;
}
| [
"61714747+NodeZeroCoin@users.noreply.github.com"
] | 61714747+NodeZeroCoin@users.noreply.github.com |
17093e4a8f4d50d82480a93a3535008494f8ee4f | 68336b429ac97a617956792f7377a61d19080a7b | /c++/Complexity/Complexity2.cpp | 69ed947ed4f8badcbe69df83b47d6b08c2ee8047 | [] | no_license | ibrahimisad8/algorithm-implementations | 8e2da60a756b2e252fe2b7536584fcfa00cc6ace | 5dcc95f101cd53162f7de2e9a49d7dd1e8f96944 | refs/heads/master | 2020-04-10T08:52:53.624728 | 2019-01-03T14:28:08 | 2019-01-03T14:28:08 | 160,918,255 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 364 | cpp | // you can use includes, for example:
// #include <algorithm>
#include <algorithm>
#include <functional>
#include <numeric>
// you can write to stdout for debugging purposes, e.g.
// cout << "this is a debug message" << endl;
int solution(vector<int> &A)
{
return std::accumulate(A.begin(), A.end(), (A.size()+1) * (A.size()+2) / 2, std::minus<int>());
} | [
"ibrahimisa.d8@gmail.com"
] | ibrahimisa.d8@gmail.com |
fa89713a838dae0e7a66f61003266ed0273a4940 | 1f184676c51ff1f621ce2e867608b10770ad6f03 | /signal/linux_signal_manager.h | 6ea60fe70ae305aecaee2880eb20b40adfdcc913 | [
"MIT"
] | permissive | swarupkotikalapudi/chat-app-linux | 6b2406443eb4a1310794b58cf53adb9782643331 | 18f3d3116893f1f499b2bc7c6492371afa438c4e | refs/heads/master | 2021-01-10T03:09:38.803839 | 2016-01-17T17:04:42 | 2016-01-17T17:04:42 | 49,811,843 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 850 | h | #ifndef _LINUX_SIGNAL_MANAGER_H
#define _LINUX_SIGNAL_MANAGER_H
#include<iosfwd>
#include<set>
#include<algorithm>
#include<memory>
class IsignalListner;
/* this class is used by source where some event(e.g. signal) happened, these event need to be informed to subscriber */
class linuxSignalManager
{
private:
typedef void(*fptrSignalHandler)(int);
fptrSignalHandler m_SignalHandler;
std::set<std::shared_ptr<IsignalListner>> m_listners;
protected:
public:
linuxSignalManager();
~linuxSignalManager();
virtual int registerSignalListner(std::shared_ptr<IsignalListner> p_listen);
virtual int unregisterSignalListner(std::shared_ptr<IsignalListner> p_listen);
virtual void informSignalListner(int sig = 0);
virtual int registerSignalHandler(fptrSignalHandler sigHandler);
};
#endif /* _LINUX_SIGNAL_MANAGER_H */
| [
"swarupkotikalapudi@gmail.com"
] | swarupkotikalapudi@gmail.com |
f98d98f961850a1b80cb13aee34a412148983d14 | 8c79fbda535452688910f6ef34d9902a8e08070f | /src/main.cpp | c90f0cf6fc71ddf4c9a86e1e86830f0d38c11ff3 | [] | no_license | tetraoxygen/KnightsTour | ebc5dde72d0df69455d31936c1265764d2c5a4a1 | 89cbe96720f82fca282183bcdf2c3f783d6076d0 | refs/heads/master | 2023-03-18T01:27:08.459358 | 2021-03-15T05:07:26 | 2021-03-15T05:07:26 | 347,785,732 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,885 | cpp | /** ---------------------------
* @file main.cpp
* @author Charlie Welsh
* @version 1.0
*
* CS162-01 - Assignment 5.1
* The Knight's Tour assignment
*
* --------------------------- */
#include <iostream>
#include <iomanip>
const int BOARD_SIZE = 5;
struct Board {
int array [BOARD_SIZE][BOARD_SIZE] = {{0}};
};
/**
* Recursively solves the knights tour using brute force
* Prints any solutions it finds.
*
* @param board - the board we’re working with (contains all moves-to-date)
* @param row - the row we’re going to attempt to place the knight on this move (zero-indexed).
* @param col - the column we’re going to attempt place the knight on this move (zero-indexed).
* @param currentMoveNumber - the move number we’re making (1 = first move)
*
* @return The number of solutions the given board and move leads to
*
*/
int solveKnightsTour(Board board, int row, int col, int currentMoveNum = 1);
/**
* Prints the contents of a Board object.
*
* @param board - the board we’re working with (contains all moves-to-date)
*
*/
void printBoard(Board board);
int main() {
Board board;
std::cout << solveKnightsTour(board, 2, 2) << " solutions found" << std::endl;
}
// -------------------
void printBoard(Board board) {
for (int col = 0; col < BOARD_SIZE; col++) {
for (int row = 0; row < BOARD_SIZE; row++) {
std::cout << std::setfill('0') << std::setw(2) << board.array[row][col] << " ";
}
std::cout << '\n';
}
std::cout << std::endl;
}
// -------------------
int solveKnightsTour(Board board, int row, int col, int currentMoveNum) {
const int startCol = col;
const int startRow = row;
bool shortHorizontal = false;
int solutions = 0;
board.array[row][col] = currentMoveNum;
if (currentMoveNum != BOARD_SIZE * BOARD_SIZE) {
for (int rotation = 0; rotation < 4; rotation++) {
switch(rotation) {
case 0:
col = startCol + 2;
shortHorizontal = true;
break;
case 1:
row = startRow + 2;
shortHorizontal = false;
break;
case 2:
col = startCol - 2;
shortHorizontal = true;
break;
case 3:
row = startRow - 2;
shortHorizontal = false;
break;
}
for (int direction = 0; direction < 2; direction++) {
if (shortHorizontal) {
switch (direction) {
case 0:
row = startRow - 1;
break;
case 1:
row = startRow + 1;
break;
}
} else {
switch (direction) {
case 0:
col = startCol - 1;
break;
case 1:
col = startCol + 1;
break;
}
}
if (
row < BOARD_SIZE &&
row >= 0 &&
col < BOARD_SIZE &&
col >= 0 &&
board.array[row][col] == 0
) {
solutions = solutions + solveKnightsTour(board, row, col, currentMoveNum + 1);
}
}
}
} else {
printBoard(board);
solutions = 1;
}
return solutions;
} | [
"charlie@allotrope.xyz"
] | charlie@allotrope.xyz |
fe7ea14fd2d79e7da9ec5ca98613081d3c3e0a49 | f5bab0feb337491bb9d6c1a7658818238f87f690 | /apps/netpipe/hosted/src/netpipe.cc | a50e98ba9ee706d380ad67648b14b452256dc21a | [] | no_license | jimcadden/ebbrt-contrib | 0cb18653a396e59bc894556f394537de0f82b57a | 76a1fe0c96a7fccc4958ad6cc5916d7923b6f7a4 | refs/heads/master | 2021-09-20T03:37:38.826638 | 2018-08-02T23:00:38 | 2018-08-02T23:00:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,142 | cc | // Copyright Boston University SESA Group 2013 - 2016.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <signal.h>
#include <boost/filesystem.hpp>
#include <ebbrt/Context.h>
#include <ebbrt/ContextActivation.h>
#include <ebbrt/GlobalIdMap.h>
#include <ebbrt/StaticIds.h>
#include <ebbrt/NodeAllocator.h>
#include <ebbrt/Runtime.h>
#include "Printer.h"
int main(int argc, char** argv) {
auto bindir = boost::filesystem::system_complete(argv[0]).parent_path() /
"/bm/netpipe.elf32";
ebbrt::Runtime runtime;
ebbrt::Context c(runtime);
boost::asio::signal_set sig(c.io_service_, SIGINT);
{
ebbrt::ContextActivation activation(c);
// ensure clean quit on ctrl-c
sig.async_wait([&c](const boost::system::error_code& ec,
int signal_number) { c.io_service_.stop(); });
Printer::Init().Then([bindir](ebbrt::Future<void> f) {
f.Get();
ebbrt::node_allocator->AllocateNode(bindir.string(), 1);
});
}
c.Run();
return 0;
}
| [
"jmcadden@bu.edu"
] | jmcadden@bu.edu |
13d251596a3fae6c8075e1d94805ad098f83dbcc | 4365cdadad0026cabdf008bb46cacbaa397122f3 | /Taewoo/problem_solving/personal/self/miro.cpp | 0f3368e28e48190664547eb8ce7926d7cf20ced1 | [] | no_license | thalals/Algorithm_Study | 31e124df727fb0af9bf9d4905f3eade35a722813 | 3d067442e5e0d6ca6896a0b0c8e58a0dc41e717e | refs/heads/main | 2023-07-06T05:52:04.679220 | 2021-08-19T06:11:56 | 2021-08-19T06:11:56 | 331,019,217 | 1 | 1 | null | 2021-01-19T15:10:19 | 2021-01-19T15:10:18 | null | UTF-8 | C++ | false | false | 1,207 | cpp | #include<bits/stdc++.h>
using namespace std;
int N, M;
int graph[201][201];
int visited[201][201];
int dx[4] = {0, 0, 1, -1};
int dy[4] = {1, -1, 0, 0};
void bfs(int x, int y) {
queue<pair<int, int>> q;
q.push({x, y});
visited[x][y] = 1;
bool flag = false;
while(!q.empty()) {
pair<int, int> p = q.front(); q.pop();
for(int i = 0; i < 4; i++) {
int X = p.first + dx[i];
int Y = p.second + dy[i];
if(X < 0 || X == N || Y < 0 || Y == M) continue;
if(!graph[X][Y] || visited[X][Y]) continue;
q.push({X, Y});
visited[X][Y] = visited[p.first][p.second] + 1;
if(X == N - 1 && Y == M - 1) {
flag = true;
break;
}
}
if(flag) break;
}
}
int main() {
cin >> N >> M;
for(int i = 0; i < N; i++)
for(int j = 0; j < M; j++)
scanf("%1d", &graph[i][j]);
memset(visited, 0, sizeof(visited));
bfs(0, 0);
for(int i = 0; i < N; i++){
for(int j = 0; j < M; j++){
cout << visited[i][j] << ' ';
}cout << '\n';
}
cout << visited[N-1][M-1] << '\n';
} | [
"skaxodn97@gmail.com"
] | skaxodn97@gmail.com |
89fbcf507920f2b30fb05a0c221d7e1276c7f74c | a26fef3708b8f5308827cc9d8d25a520faf7a24c | /ManipulatorMain.ino | 29455008a1ce6ff6b18c12d1a830d13ec1648929 | [
"MIT"
] | permissive | igorgrebenev/ManipulatorMain | c3b44a2c75fc7e4814c7c26cdeb4b68e80d13bc1 | df22b016b0d2a58a74b840336a2191664df5c49b | refs/heads/master | 2020-04-10T23:15:14.387259 | 2019-02-13T01:05:25 | 2019-02-13T01:05:25 | 161,346,399 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,359 | ino | // Maksim Grebenev 2018
#import "SGServo.h"
#import "ROT3U6DOF.h"
void setup() {
setupROT3U6DOF(0, 0); // 500-900Initialize servos ROT3U6DOF_SERVO_COUNT/ROT3U6DOF_SERVO_START_PORT
resetROT3U6DOF(); // установим кутяплю в исходное положение
delay(6000); // подождем 1 мин для прогрева потенцииометра
}
void loop() {
int positions00[] = {27, 65, 120, 180, 15, 20};
performAllServos(positions00);
int positions01[] = {UNDEFINED, 64, UNDEFINED, 131, UNDEFINED, UNDEFINED};
performAllServos(positions01);
int positions02[] = {UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, 70};
performAllServos(positions02);
int positions03[] = {UNDEFINED, 90, 45, UNDEFINED, UNDEFINED, UNDEFINED};
performAllServos(positions03);
int positions04[] = {142, 0, 102, 0, 0, UNDEFINED};
performAllServos(positions04);
// бросить шарик
int positions05[] = {UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, UNDEFINED, 20};
performAllServos(positions05);
// подготовка у подъему манипулятора
int positions06a[] = {UNDEFINED, UNDEFINED, 0, 0, UNDEFINED, UNDEFINED};
performAllServos(positions06a);
int positions06[] = {UNDEFINED, 90, 45, 20, UNDEFINED, UNDEFINED};
performAllServos(positions06);
delay(3000);
}
| [
"igor.grebenev@quantumsoft.ru"
] | igor.grebenev@quantumsoft.ru |
4c1e9a8982abfc3f5073c40e6244f3157026d16d | e05ecd8947dc56f1c16e6882124cd53646aa84ed | /src/EKF_learning/KF/test/kalam_roll_pich_test_01.cpp | 8b8537ebc0cbbf82a0b94a243950807dfba0bc0a | [] | no_license | xiazhenyu555/msckf_mono | 2a8195d65393fcc0012691365168d25f09c97e00 | 37013fdd9ccd1a14d433e287961d7392d3b57fe8 | refs/heads/master | 2023-05-13T13:35:24.475342 | 2019-04-06T13:41:48 | 2019-04-06T13:41:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 154 | cpp | #include <iostream>
#include "imu_data_reader.h"
#include <cmath>
using namespace std;
int main(int argc, char *argv[])
{
/**/
return 0;
}
| [
"xinliangzhong@foxmail.com"
] | xinliangzhong@foxmail.com |
c30fb82b959ad04f11150ea262c6efa199487142 | ecd866fe9df43a2d7d9f286d72f23b113491564c | /algorithms/algorithms/robot.cpp | fa45104f2450ef664c54b2028538dbecdd053a7e | [] | no_license | LeeBoHyoung/algorithm | c8f58eb118bb63bb62117a2a8cb11287507020bf | c6255d229bfb550b38fe4e951fdbc614a9e57dfd | refs/heads/master | 2021-06-21T08:53:56.681106 | 2021-04-24T03:35:23 | 2021-04-24T03:35:23 | 206,602,984 | 1 | 0 | null | null | null | null | UHC | C++ | false | false | 1,785 | cpp | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct robot {
int dir;
int r;
int c;
};
int n, m;
int map[50][50];
bool visited[50][50];
int dr[4] = { -1, 0, 0, 1 };
int dc[4] = { 0, -1, 1, 0 }; //북 서 남 동
int ans = 1;
pair<int, int> route(int dir, int r, int c) {
int nr, nc;
if (dir == 0) { // 북
nr = r + dr[1];
nc = c + dc[1];
}
else if (dir == 1) { // 동
nr = r + dr[0];
nc = c + dc[0];
}
else if (dir == 2) { // 남
nr = r + dr[2];
nc = c + dc[2];
}
else if (dir == 3) { // 서
nr = r + dr[3];
nc = c + dc[3];
}
return make_pair(nr, nc);
}
pair<int, int> direct(int dir, int r, int c) {
if (dir == 0)
return make_pair(r - 1, c);
else if (dir == 1)
return make_pair(r, c + 1);
else if (dir == 2)
return make_pair(r + 1, c);
else if (dir == 3)
return make_pair(r, c - 1);
}
int nr, nc;
void dfs(int r, int c, int dir) {
visited[r][c] = true;
pair<int, int> next;
int check = 0;
for (int i = 0; i < 4; i++) {
//dir = (dir + i) % 4;
next = route(dir, r, c);
dir = (dir + 3) % 4;
nr = next.first; nc = next.second;
if (nr >= 0 && nr < n && nc >= 0 && nc < m) {
if (visited[nr][nc] == false && map[nr][nc] == 0) {
check = 1;
ans++;
dfs(nr, nc, dir);
return;
}
}
}
if (check == 0) {
pair<int, int> back = direct((dir + 2) % 4, r, c);
if (map[back.first][back.second] == 1 || !(back.first >= 0 && back.first < n && back.second >= 0 && back.second < m))
return;
else {
dfs(back.first, back.second, dir);
}
}
}
int main() {
robot init;
cin >> n >> m;
cin >> init.r;
cin >> init.c;
cin >> init.dir;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> map[i][j];
}
}
dfs(init.r, init.c, init.dir);
cout << ans;
} | [
"dlqhgud11@naver.com"
] | dlqhgud11@naver.com |
e988b195f3a55f2edcb4b978a4c459cfcf323261 | cc126b413c764161648e00e61c3a32c92ce65572 | /tests/mt_session_unittest.cpp | 61c4d0de9e524b8588449e979be1d8ccf07ac546 | [] | no_license | LiKun-8/sthread | 6b5fc6ebe3377d6b85aa37e524179584d352d9a6 | 64766a692c17228d29a366a3f585bfbdf963d5af | refs/heads/master | 2020-07-11T23:42:33.511576 | 2019-05-11T09:51:10 | 2019-05-11T09:51:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 272 | cpp | #include "gtest/googletest/include/gtest/gtest.h"
#include "../include/mt_ext.h"
MTHREAD_NAMESPACE_USING
TEST(SessionTest, session)
{
}
// 测试所有的功能
int main(int argc, char* argv[])
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} | [
"zhoulv2000@163.com"
] | zhoulv2000@163.com |
76c4fe80c1c6de89d32606babba8040acba5af8a | 7f2e3ef75e6ab9ff292d0df3673faf5d044c2bd6 | /TitanEngine/SDK/Samples/Unpackers/x86/C/Dynamic unpackers/ExeFog 1.x/RL!deExeFog/unpacker.cpp | e5086ec9df771495a67ece72d648e92484c48e45 | [] | no_license | 0xFF1E071F/fuu | 53929f5fe5c312b58f3879914cd992c79e6b9e13 | 696a819e23808d3e4711d3a73122a317785ad3da | refs/heads/master | 2021-05-29T23:33:42.855092 | 2015-04-27T15:51:28 | 2015-04-27T15:51:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,730 | cpp | #include "unpacker.h"
#include <cstdio>
#include <cstring>
#include <cstdarg>
cUnpacker cUnpacker::lInstance;
HWND cUnpacker::Window = NULL;
void (*cUnpacker::LogCallback)(const char*) = &cUnpacker::DefLogCallback;
char cUnpacker::lPath[MAX_PATH], cUnpacker::lOut[MAX_PATH];
PROCESS_INFORMATION* cUnpacker::lProcess;
bool cUnpacker::lRealign, cUnpacker::lCopyOverlay;
PE32Struct cUnpacker::lPEInfo;
ULONG_PTR cUnpacker::lEP;
ULONG_PTR cUnpacker::SFXSectionVA;
DWORD cUnpacker::SFXSectionSize;
void cUnpacker::Log(const char* pFormat, ...)
{
va_list ArgList;
char Buffer[iMaxString];
va_start(ArgList, pFormat);
vsprintf_s(Buffer, sizeof Buffer, pFormat, ArgList);
va_end(ArgList);
LogCallback(Buffer);
}
void cUnpacker::Abort()
{
StopDebug();
Log("[Fatal Error] Unpacking has been aborted.");
}
bool cUnpacker::Unpack(const char* pPath, bool pRealign, bool pCopyOverlay)
{
HANDLE HFile, HMap;
DWORD FileSize;
ULONG_PTR MapVA;
bool Return = false;
lRealign = pRealign;
lCopyOverlay = pCopyOverlay;
strncpy(lPath, pPath, sizeof lPath - 1);
lPath[sizeof lPath - 1] = '\0';
char* ExtChar = strrchr(lPath, '.');
if(ExtChar)
{
*ExtChar = '\0';
sprintf_s(lOut, MAX_PATH, "%s.unpacked.%s", lPath, ExtChar+1);
*ExtChar = '.';
}
else
{
sprintf_s(lOut, MAX_PATH, "%s.unpacked", lPath);
}
DeleteFileA(lOut);
Log("-> Unpack started...");
if(StaticFileLoad(lPath, UE_ACCESS_READ, false, &HFile, &FileSize, &HMap, &MapVA))
{
if(GetPE32DataFromMappedFileEx(MapVA, &lPEInfo))
{
lEP = lPEInfo.ImageBase + lPEInfo.OriginalEntryPoint;
WORD SFXSectionIndex = GetPE32SectionNumberFromVA(MapVA, lEP);
SFXSectionVA = lPEInfo.ImageBase + GetPE32DataFromMappedFile(MapVA, SFXSectionIndex, UE_SECTIONVIRTUALOFFSET);
SFXSectionSize = GetPE32DataFromMappedFile(MapVA, SFXSectionIndex, UE_SECTIONVIRTUALSIZE);
lProcess = (PROCESS_INFORMATION*)InitDebugEx(lPath, 0, 0, &OnEp);
if(lProcess)
{
DebugLoop();
ImporterCleanup();
Return = true;
}
else Log("[Error] Engine initialization failed!");
}
else Log("[Error] Selected file is not a valid PE32 file!");
StaticFileUnload(lPath, false, HFile, FileSize, HMap, MapVA);
}
else Log("[Error] Can't open selected file!");
Log("-> Unpack ended...");
return Return;
}
void __stdcall cUnpacker::OnEp()
{
BYTE WildCard = 0xFF;
const BYTE DecryptPattern[] = {0x90, 0xEB, 0x04, 0x01, 0x07, 0x01, 0x07, 0xBB, 0xFF, 0xFF, 0xFF, 0xFF, 0xB9, 0xC8, 0x03, 0x00, 0x00, 0xB0, 0xFF, 0x30, 0x04, 0x0B, 0x8A, 0x04, 0x0B, 0xE2, 0xF8};
/*
NOP
JMP @SKIP
ADD DWORD PTR DS:[EDI],EAX
ADD DWORD PTR DS:[EDI],EAX
SKIP:
MOV EBX, XXXXXXXX ; code after LOOPD
MOV ECX, 3C8 ; constant value
MOV AL, XX
@DECRYPT:
XOR BYTE PTR DS:[EBX+ECX],AL
MOV AL,BYTE PTR DS:[EBX+ECX]
LOOPD DECRYPT
*/
ImporterInit(iImporterSize, lPEInfo.ImageBase);
ULONG_PTR DecryptCode = Find((void*)lEP, SFXSectionVA+SFXSectionSize-lEP, (void*)DecryptPattern, sizeof DecryptPattern, &WildCard);
if(!DecryptCode)
{
Log("[Error] Cannot find decryption code, probably not packed with a supported version?");
Abort();
return;
}
if(!SetHardwareBreakPoint(DecryptCode + sizeof DecryptPattern, NULL, UE_HARDWARE_EXECUTE, UE_HARDWARE_SIZE_1, &OnDecrypted))
{
Log("[Error] Unable to set breakpoint on decryption code.");
Abort();
}
}
void __stdcall cUnpacker::OnDecrypted()
{
BYTE WildCard = 0xEE;
const BYTE LoadLibraryAPattern[] = {0xB9, 0xEE, 0xEE, 0xEE, 0xEE, 0x01, 0xE9, 0x83, 0x79, 0x0C, 0x00, 0x0F, 0x84, 0xEE, 0xEE, 0xEE, 0xEE, 0x8B, 0x59, 0x0C, 0x01, 0xEB, 0x51, 0x53, 0xFF, 0xD7, 0x59, 0x85, 0xC0};
/*
MOV ECX, XXXXXXXX
ADD ECX,EBP
CMP DWORD PTR DS:[ECX+C],0
JE XXXXXXXX
MOV EBX,DWORD PTR DS:[ECX+C]
0ADD EBX,EBP
PUSH ECX
PUSH EBX
CALL EDI
POP ECX
TEST EAX,EAX
*/
const BYTE GetProcAddressPattern[] = {0x8B, 0x07, 0x83, 0xC7, 0x04, 0xA9, 0x00, 0x00, 0x00, 0x80, 0x74, 0x08, 0x25, 0xFF, 0xFF, 0x00, 0x00, 0x50, 0xEB, 0x06, 0x01, 0xE8, 0x83, 0xC0, 0x02, 0x50, 0x53, 0xFF, 0xD6, 0x5A, 0x59, 0x85, 0xC0};
/*
MOV EAX,DWORD PTR DS:[EDI]
ADD EDI,4
TEST EAX,80000000
JE SHORT Nag_exeF.00404491
AND EAX,0FFFF
PUSH EAX
JMP SHORT Nag_exeF.00404497
ADD EAX,EBP
ADD EAX,2
PUSH EAX
PUSH EBX
CALL ESI
POP EDX
POP ECX
TEST EAX,EAX
*/
const size_t LoadLibraryABreakpointOffset = 24;
const size_t GetProcAddressBreakpointOffset = 27;
const BYTE OepPattern[] = {0x01, 0x2C, 0x24, 0xC3, 0x13, 0x13, 0x13, 0x13};
/*
ADD DWORD PTR SS:[ESP],EBP
RETN
ADC EDX,DWORD PTR DS:[EBX]
ADC EDX,DWORD PTR DS:[EBX]
*/
ULONG_PTR DecryptedCode = GetContextData(UE_CIP);
ULONG_PTR LoadLibraryACode = Find((void*)DecryptedCode, SFXSectionVA+SFXSectionSize-DecryptedCode, (void*)LoadLibraryAPattern, sizeof LoadLibraryAPattern, &WildCard);
ULONG_PTR GetProcAddressCode = Find((void*)DecryptedCode, SFXSectionVA+SFXSectionSize-DecryptedCode, (void*)GetProcAddressPattern, sizeof GetProcAddressPattern, NULL);
if(!LoadLibraryACode || !GetProcAddressCode)
{
Log("[Error] Cannot find imports handling code, probably not packed with a supported version?");
Abort();
return;
}
SetBPX(LoadLibraryACode + LoadLibraryABreakpointOffset, UE_BREAKPOINT, &OnLoadLibraryACall);
SetBPX(GetProcAddressCode + GetProcAddressBreakpointOffset, UE_BREAKPOINT, &OnGetProcAddressCall);
ULONG_PTR OepCode = Find((void*)DecryptedCode, SFXSectionVA+SFXSectionSize-DecryptedCode, (void*)OepPattern, sizeof OepPattern, NULL);
if(!OepCode)
{
Log("[Error] Cannot find OEP code, probably not packed with a supported version?");
Abort();
return;
}
SetBPX(OepCode, UE_BREAKPOINT, &OnOepCode);
}
void __stdcall cUnpacker::OnLoadLibraryACall()
{
/*
We're currently on the call to LoadLibraryA
To get the parameter pushed to the API, we need to decrease the index we pass to GetFunctionParameter by 1
This is because the return address has not yet been pushed to the stack and parameters are set off by one DWORD
*/
// Get name param pushed to LoadLibraryA
char* DLLName = (char*)GetFunctionParameter(lProcess->hProcess, UE_FUNCTION_STDCALL, 0, UE_PARAMETER_STRING);
// Add Dll (next call to ImporterAddNew[Ordinal]API sets first thunk)
ImporterAddNewDll(DLLName, NULL);
Log("[i] Imported DLL: %s", DLLName);
}
void __stdcall cUnpacker::OnGetProcAddressCall()
{
char APIName[iMaxString];
/*
Get second parameter pushed to GetProcAddress (API name or ordinal)
See OnGetModuleHandleACall as to why we use 1 instead of 2 for the index
*/
ULONG_PTR APIParam = GetFunctionParameter(lProcess->hProcess, UE_FUNCTION_STDCALL, 1, UE_PARAMETER_DWORD);
// Get address of IAT thunk for this API
// It is located at [ESP+8], we can use GetFunctionParameter to easily get its value
// since effectively it's the 3rd param
ULONG_PTR ThunkAddr = GetFunctionParameter(lProcess->hProcess, UE_FUNCTION_STDCALL, 2, UE_PARAMETER_DWORD);
if(!HIWORD(APIParam)) // Is this an ordinal API?
{
// Add ordinal API (pushed value = ordinal #)
ImporterAddNewOrdinalAPI(APIParam, ThunkAddr);
Log(" + [%08X]: #%d", ThunkAddr, APIParam);
}
else
{
// Add API name (pushed value = address to string)
GetRemoteString(lProcess->hProcess, (void*)APIParam, APIName, sizeof APIName);
ImporterAddNewAPI(APIName, ThunkAddr);
Log(" + [%08X]: %s", ThunkAddr, APIName);
}
}
void __stdcall cUnpacker::OnOepCode()
{
RemoveAllBreakPoints(UE_OPTION_REMOVEALL);
// Lazy man's way of getting the value at [ESP]
ULONG_PTR OEP = lPEInfo.ImageBase + GetFunctionParameter(lProcess->hProcess, UE_FUNCTION_STDCALL, 0, UE_PARAMETER_DWORD);
Log("[x] Reached OEP: %08X.", OEP);
// Dump the unpacked module to disk
if(!DumpProcess(lProcess->hProcess, (void*)lPEInfo.ImageBase, lOut, OEP))
{
Log("[Error] Cannot dump process.");
Abort();
return;
}
Log("[x] Dumping process.");
// Create a new import table from the data added through ImporterAddNewDll + ImporterAddNew[Ordinal]API
if(!ImporterExportIATEx(lOut, ".revlabs"))
{
Log("[Error] Cannot fix imports.");
Abort();
return;
}
Log("[x] Fixing imports.");
if(lRealign)
{
// Realign sections, shrink file size
if(!RealignPEEx(lOut, NULL, NULL))
{
Log("[Error] Realigning failed.");
Abort();
return;
}
Log("[x] Realigning file.");
}
if(lCopyOverlay)
{
// Copy overlay from the original file to the dump
if(CopyOverlay(lPath, lOut))
Log("[x] Copying overlay.");
else
Log("[x] No overlay found.");
}
StopDebug();
Log("[x] File successfully unpacked to %s.", lOut);
}
| [
"safin@smartdec.ru"
] | safin@smartdec.ru |
f96475a3d34bb906414217396da8d46db9dad585 | 947a4b48f592700a06cb332758ef8406a3808809 | /banking_system_step7_v0.7/Account.h | 2110055cae1ce2bed64eccec40c79533528d8947 | [] | no_license | 95kim1/banking-system | b5da741a6aa4f11164c326ff1d76da01e9f23da3 | 78d79969840310a04e97f3a771efea2ef670e0e7 | refs/heads/main | 2023-08-01T11:36:57.642701 | 2021-09-06T14:01:56 | 2021-09-06T14:01:56 | 401,977,902 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 825 | h | /*
* 파일이름: Account.h
* 작성자: sh.kim
* 업데이트 정보: [2021, 09, 04] 파일버전 0.7
*/
#ifndef __ACCOUNT_H__
#define __ACCOUNT_H__
/*
* 클래스명: Account
* 유형: Entity class
*/
class Account
{
int mId; // 계좌번호
unsigned long long mBalance; // 계좌잔액
char* mName; // 고객이름
public:
Account(const int id, const unsigned long long balance, const char* name);
Account(const Account& accunt);
~Account();
int GetId() const;
unsigned long long GetBalance() const;
char* GetName() const;
void SetId(const int id);
void SetBalance(const unsigned long long balance);
void SetName(const char* name);
virtual void DepositeMoney(const unsigned long long money);
void WithdrawMoney(const unsigned long long money);
virtual void ShowInfo();
};
#endif
| [
"95kim1@naver.com"
] | 95kim1@naver.com |
c0b385007402bfbd470ddb3986bccbd6c6a7ef6f | f530448ab4c5ea4dc76e7303825fbd27957c514c | /AntibodyV4-CodeBlocks/WeaponPlNinjaStar.h | eb97cea1b394a9e9c27e54dfe1f32ea839a59a31 | [] | no_license | joeaoregan/LIT-Yr3-Project-Antibody | 677c038e0688bb96125c2687025d1e505837be6b | 22135f4fdb1e0dc2faa5691492ebd6e11011a9d6 | refs/heads/master | 2020-04-21T16:48:26.317244 | 2019-02-13T20:27:36 | 2019-02-13T20:27:36 | 169,714,493 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,188 | h | /* ---------------------------------------------------------------------------------------------------------------------
- Name: WeaponPlNinjaStar.h
- Description: Header file for the Weapon Player Ninja Star class.
- Information: Ninja stars are rotating objects, and they have a slower speed than Lasers but a higher
points value. Like lasers the player automatically has unlimited ninja stars. Ninja stars
can be used to cut Enemy Virus in two. Each player has a differnt colour ninja star, and
sound effect.
- Log:
2017/03/18 Added the Ninja Stars texture to the texture map in Texture class
Ninja star rotations are updated in the move() function instead of setRotatingAngle() in Game class
A texture ID has been added for both Player 1 and Player 2 types of ninja star
And the angle of rotation is now assigned to the Ninja Star class instead of the Texture class
Destroy function is inherited from Game Object base class
2017/03/04 Moved smaller class files functionality into their headers
2017/02/10 Fixed velocity for ninja star after spawning, ninja stars are no longer static
2017/01/30 Added rotation angle to constructors for Textures that rotate
2017/01/25 Fixed Ninja Star scoring for Player 2
2017/01/20 Fixed problem for ninja stars only scoring for Player 1
2017/01/17 Added collision detection for Ninja Stars
2017/01/09 Ninja Star Weapon
Added spawnNinjaStar() function to create ninja star weapon
2017/02/21 Added check so only Ninja Stars and Saws split viruses
2017/01/30 Added rotation angle to constructors for Textures that rotate
2017/01/17 Added player decision to spawnNinjaStar() function - determines player to spawn for and their coords
2017/01/09 Add Ninja Star weapon class
2017/03/18 Rendering functionality has been moved back to class
----------------------------------------------------------------------------------------------------------------------*/
#ifndef NINJA_STAR_H
#define NINJA_STAR_H
#include "Weapon.h"
class WeaponPlNinjaStar : public Weapon {
public:
/*
Ninja Star Constructor
Initializes the variables
The ninja star name, texture ID, sub-type, type, angle of rotation, and assigned player are set
Along with dimensions, velocity on X axis, collider width and height, and the object is set alive.
*/
WeaponPlNinjaStar(int player) {
if (player == PLAYER1) {
setName("Ninja Star P1"); // 2017/03/18 Name of Ninja Star for info / error messages
setTextureID("nsP1ID"); // 2017/03/18 Texture ID for Player 1 Ninja Star
setSubType(NINJA_STAR_P1); // The sub-type of weapon
}
else if (player == PLAYER2) {
setName("Ninja Star P2"); // 2017/03/18 Name of Ninja Star for info / error messages
setTextureID("nsP2ID"); // 2017/03/18 Texture ID for Player 2 Ninja Star
setSubType(NINJA_STAR_P2); // The sub-type of weapon
}
setType(PLAYER_WEAPON); // The type of game object is Player Weapon
setAngle(5); // 2017/03/18 Angle of rotation for Ninja Stars, rotates clockwise 5 degrees each frame
setPlayer(player); // 2017/01/17 Set the player the laser belongs too
setWidth(25); // Set width for texture and collider
setHeight(25); // Set Height for texture and collider
setVelX(10); // Set velocity on X axis as 10 --- NOT WORKING HERE???
setColliderWidth(getWidth());
setColliderHeight(getHeight());
setAlive(true);
/*
// Older variables set elsewhere e.g. velocity set in spawn function in Game class
std::cout << "NinjaStar constuctor called.\n";
if (player == PLAYER1) setSubType(NINJA_STAR_P1);
else if (player == PLAYER2) setSubType(NINJA_STAR_P2);
setVelocity(10); // The speed the object moves at
*/
};
// Ninja Star Destructor
~WeaponPlNinjaStar() {
std::cout << "NinjaStar destructor called." << std::endl;
};
/*
Ninja stars have basic movement, inherited move function from Game Object base class
The ninja star rotation is updated as it moves across the screen, similar to Blood Cells
*/
virtual void move(int x = 0, int y = 0) {
GameObject::move(); // Movement is inherited from Game Object base class
setAngle(getAngle() + 5); // 2017/03/18 The angle of rotation is set, similar to Blood Cell, functionality moved from Game class
};
/*
Ninja Stars are destroyed when they move off screen
This functionality is inherited from the Game Object base class
*/
virtual void destroy() {
GameObject::destroy(); // 2017/03/18 destroy method inherited from Game Object base class
};
/*
2017/03/18 Render Ninja Stars
The Ninja Stars texture is loaded from the texture map using the stored ID
Ninja Stars rotate similar to Blood Cells but in only one direction
*/
virtual void render() {
SDL_Rect renderQuad = { getX(), getY(), getWidth(), getHeight() }; // Set rendering space and render to screen
// Similar to Blood Cell rotation but rotating in only one direction
SDL_RenderCopyEx(Game::Instance()->getRenderer(), Texture::Instance()->getTexture(getTextureID()), NULL, &renderQuad, getAngle(), NULL, SDL_FLIP_NONE); // Render to screen
}
};
#endif | [
"k00203642@student.lit.ie"
] | k00203642@student.lit.ie |
c1a9202af8e5412d41bbb57ba8d2809acea262ed | 1afb5e6cf8d6638a43e352a941fdb51161494c83 | /Assignment2/HighScoreManager.h | 6e346eb51249e5f342f70d41b24f300a94697a02 | [] | no_license | Sukhmanbir/Assignment2 | 4064271a7132b1c27ce93910840b766f1d5ff34a | 1dc57ff03ab31426fad348ee71178c633d485193 | refs/heads/master | 2021-01-09T20:40:03.472621 | 2016-07-19T01:36:08 | 2016-07-19T01:36:08 | 63,277,343 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 238 | h | #pragma once
#include <string>
using namespace std;
class HighScoreManager {
public:
void createHighScore();
void updateHighScore();
void printHighScore();
private:
struct user {
string username;
int score;
string date;
};
}; | [
"code@douglasbrunner.name"
] | code@douglasbrunner.name |
07f40104e025217a721eb5dffa9222e3c851b1bf | a73d4adcd66759fa67bc9e55c770b56b3ab5471b | /tutes/tute01/extra-q2.cpp | 2db6fb86f15073aa767490ef0b064495d210a960 | [] | no_license | patrick-forks/cs6771 | 1695d0ee530a782ffc4c5683ba469291966aade8 | f70373b71da44faf169521bc8068847cc76ab91c | refs/heads/master | 2023-04-09T02:35:38.456908 | 2016-10-31T12:44:56 | 2016-10-31T12:44:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 200 | cpp | #include <iostream>
int i;
int f() { return i++; }
int g() { return i == 1 ? i + 3 : i - 1; }
int h() { return i == 2 ? i - 3 : i + 2; }
int main() {
std::cout << f() + g() * h() << std::endl;
}
| [
"jessqnnguyen@gmail.com"
] | jessqnnguyen@gmail.com |
33e844320b7c9866b0432e6148f6d63ec959bd4a | 0da071c412415402b669bc3733e36058f4fd1877 | /src/ListViewGroups.h | a509f082a83c87e2f0fc8af21d65e2c467dfd1fb | [
"MIT"
] | permissive | Michael-prog/ExplorerListView | 3d50d4e09bfdff06e06b9b80f62075a942b07644 | 8bc0299b7d58def5393527f518fd857f5122b42d | refs/heads/master | 2022-01-25T09:02:24.411107 | 2019-02-27T19:43:42 | 2019-02-27T19:43:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,208 | h | //////////////////////////////////////////////////////////////////////
/// \class ListViewGroups
/// \author Timo "TimoSoft" Kunze
/// \brief <em>Manages a collection of \c ListViewGroup objects</em>
///
/// This class provides easy access to collections of \c ListViewGroup objects. A \c ListViewGroups
/// object is used to group the control's groups.
///
/// \remarks Requires comctl32.dll version 6.0 or higher.
///
/// \if UNICODE
/// \sa ExLVwLibU::IListViewGroups, ListViewGroup, ExplorerListView
/// \else
/// \sa ExLVwLibA::IListViewGroups, ListViewGroup, ExplorerListView
/// \endif
//////////////////////////////////////////////////////////////////////
#pragma once
#include "res/resource.h"
#ifdef UNICODE
#include "ExLVwU.h"
#else
#include "ExLVwA.h"
#endif
#include "_IListViewGroupsEvents_CP.h"
#include "helpers.h"
#include "ExplorerListView.h"
#include "ListViewGroup.h"
class ATL_NO_VTABLE ListViewGroups :
public CComObjectRootEx<CComSingleThreadModel>,
public CComCoClass<ListViewGroups, &CLSID_ListViewGroups>,
public ISupportErrorInfo,
public IConnectionPointContainerImpl<ListViewGroups>,
public Proxy_IListViewGroupsEvents<ListViewGroups>,
public IEnumVARIANT,
#ifdef UNICODE
public IDispatchImpl<IListViewGroups, &IID_IListViewGroups, &LIBID_ExLVwLibU, /*wMajor =*/ VERSION_MAJOR, /*wMinor =*/ VERSION_MINOR>
#else
public IDispatchImpl<IListViewGroups, &IID_IListViewGroups, &LIBID_ExLVwLibA, /*wMajor =*/ VERSION_MAJOR, /*wMinor =*/ VERSION_MINOR>
#endif
{
friend class ExplorerListView;
friend class ClassFactory;
public:
#ifndef DOXYGEN_SHOULD_SKIP_THIS
DECLARE_REGISTRY_RESOURCEID(IDR_LISTVIEWGROUPS)
BEGIN_COM_MAP(ListViewGroups)
COM_INTERFACE_ENTRY(IListViewGroups)
COM_INTERFACE_ENTRY(IDispatch)
COM_INTERFACE_ENTRY(ISupportErrorInfo)
COM_INTERFACE_ENTRY(IConnectionPointContainer)
COM_INTERFACE_ENTRY(IEnumVARIANT)
END_COM_MAP()
BEGIN_CONNECTION_POINT_MAP(ListViewGroups)
CONNECTION_POINT_ENTRY(__uuidof(_IListViewGroupsEvents))
END_CONNECTION_POINT_MAP()
DECLARE_PROTECT_FINAL_CONSTRUCT()
#endif
//////////////////////////////////////////////////////////////////////
/// \name Implementation of ISupportErrorInfo
///
//@{
/// \brief <em>Retrieves whether an interface supports the \c IErrorInfo interface</em>
///
/// \param[in] interfaceToCheck The IID of the interface to check.
///
/// \return \c S_OK if the interface identified by \c interfaceToCheck supports \c IErrorInfo;
/// otherwise \c S_FALSE.
///
/// \sa <a href="https://msdn.microsoft.com/en-us/library/ms221233.aspx">IErrorInfo</a>
virtual HRESULT STDMETHODCALLTYPE InterfaceSupportsErrorInfo(REFIID interfaceToCheck);
//@}
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// \name Implementation of IEnumVARIANT
///
//@{
/// \brief <em>Clones the \c VARIANT iterator used to iterate the groups</em>
///
/// Clones the \c VARIANT iterator including its current state. This iterator is used to iterate
/// the \c ListViewGroup objects managed by this collection object.
///
/// \param[out] ppEnumerator Receives the clone's \c IEnumVARIANT implementation.
///
/// \return An \c HRESULT error code.
///
/// \sa Next, Reset, Skip,
/// <a href="https://msdn.microsoft.com/en-us/library/ms221053.aspx">IEnumVARIANT</a>,
/// <a href="https://msdn.microsoft.com/en-us/library/ms690336.aspx">IEnumXXXX::Clone</a>
virtual HRESULT STDMETHODCALLTYPE Clone(IEnumVARIANT** ppEnumerator);
/// \brief <em>Retrieves the next x groups</em>
///
/// Retrieves the next \c numberOfMaxItems groups from the iterator.
///
/// \param[in] numberOfMaxItems The maximum number of groups the array identified by \c pItems can
/// contain.
/// \param[in,out] pItems An array of \c VARIANT values. On return, each \c VARIANT will contain
/// the pointer to a group's \c IListViewGroup implementation.
/// \param[out] pNumberOfItemsReturned The number of groups that actually were copied to the array
/// identified by \c pItems.
///
/// \return An \c HRESULT error code.
///
/// \sa Clone, Reset, Skip, ListViewGroup,
/// <a href="https://msdn.microsoft.com/en-us/library/ms695273.aspx">IEnumXXXX::Next</a>
virtual HRESULT STDMETHODCALLTYPE Next(ULONG numberOfMaxItems, VARIANT* pItems, ULONG* pNumberOfItemsReturned);
/// \brief <em>Resets the \c VARIANT iterator</em>
///
/// Resets the \c VARIANT iterator so that the next call of \c Next or \c Skip starts at the first
/// group in the collection.
///
/// \return An \c HRESULT error code.
///
/// \sa Clone, Next, Skip,
/// <a href="https://msdn.microsoft.com/en-us/library/ms693414.aspx">IEnumXXXX::Reset</a>
virtual HRESULT STDMETHODCALLTYPE Reset(void);
/// \brief <em>Skips the next x groups</em>
///
/// Instructs the \c VARIANT iterator to skip the next \c numberOfItemsToSkip groups.
///
/// \param[in] numberOfItemsToSkip The number of groups to skip.
///
/// \return An \c HRESULT error code.
///
/// \sa Clone, Next, Reset,
/// <a href="https://msdn.microsoft.com/en-us/library/ms690392.aspx">IEnumXXXX::Skip</a>
virtual HRESULT STDMETHODCALLTYPE Skip(ULONG numberOfItemsToSkip);
//@}
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// \name Implementation of IListViewGroups
///
//@{
/// \brief <em>Retrieves a \c ListViewGroup object from the collection</em>
///
/// Retrieves a \c ListViewGroup object from the collection that wraps the listview group identified
/// by \c groupIdentifier.
///
/// \param[in] groupIdentifier A value that identifies the listview group to be retrieved.
/// \param[in] groupIdentifierType A value specifying the meaning of \c groupIdentifier. Any of the
/// values defined by the \c GroupIdentifierTypeConstants enumeration is valid.
/// \param[out] ppGroup Receives the group's \c IListViewGroup implementation.
///
/// \return An \c HRESULT error code.
///
/// \remarks This property is read-only.
///
/// \if UNICODE
/// \sa ListViewGroup, Add, Remove, Contains, ExLVwLibU::GroupIdentifierTypeConstants
/// \else
/// \sa ListViewGroup, Add, Remove, Contains, ExLVwLibA::GroupIdentifierTypeConstants
/// \endif
virtual HRESULT STDMETHODCALLTYPE get_Item(LONG groupIdentifier, GroupIdentifierTypeConstants groupIdentifierType = gitID, IListViewGroup** ppGroup = NULL);
/// \brief <em>Retrieves a \c VARIANT enumerator</em>
///
/// Retrieves a \c VARIANT enumerator that may be used to iterate the \c ListViewGroup objects
/// managed by this collection object. This iterator is used by Visual Basic's \c For...Each
/// construct.
///
/// \param[out] ppEnumerator Receives the iterator's \c IEnumVARIANT implementation.
///
/// \return An \c HRESULT error code.
///
/// \remarks This property is read-only and hidden.
///
/// \sa <a href="https://msdn.microsoft.com/en-us/library/ms221053.aspx">IEnumVARIANT</a>
virtual HRESULT STDMETHODCALLTYPE get__NewEnum(IUnknown** ppEnumerator);
/// \brief <em>Adds a group to the listview</em>
///
/// Adds a group with the specified properties at the specified position in the control and returns a
/// \c ListViewGroup object wrapping the inserted group.
///
/// \param[in] groupHeaderText The new group's header text. The number of characters in this text
/// is not limited.
/// \param[in] groupID The new group's ID. It must be unique and can't be set to -1.
/// \param[in] insertAt The new group's zero-based index. If set to -1, the group will be inserted
/// as the last group.
/// \param[in] virtualItemCount If the listview control is in virtual mode, this parameter specifies
/// the number of items in the new group.
/// \param[in] headerAlignment The alignment of the new group's header text. Any of the values
/// defined by the \c AlignmentConstants enumeration is valid.
/// \param[in] iconIndex The zero-based index of the new group's header icon in the control's
/// \c ilGroups imagelist. If set to -1, the group header doesn't contain an icon.
/// \param[in] collapsible If \c VARIANT_TRUE, the new group can be collapsed by the user.
/// \param[in] collapsed If \c VARIANT_TRUE, the new group is collapsed.
/// \param[in] groupFooterText The new group's footer text. The number of characters in this text
/// is not limited.
/// \param[in] footerAlignment The alignment of the new group's footer text. Any of the values
/// defined by the \c AlignmentConstants enumeration is valid.
/// \param[in] subTitleText The new group's subtitle text. The maximum number of characters in this
/// text is defined by \c MAX_GROUPSUBTITLETEXTLENGTH.
/// \param[in] taskText The new group's task link text. The maximum number of characters in this
/// text is defined by \c MAX_GROUPTASKTEXTLENGTH.
/// \param[in] subsetLinkText The text displayed as a link below the new group if not all items of the
/// group are displayed. The maximum number of characters in this text is defined by
/// \c MAX_GROUPSUBSETLINKTEXTLENGTH.
/// \param[in] subseted If \c VARIANT_TRUE, the control displays only a subset of the new group's items
/// if the control is not large enough to display all items without scrolling.
/// \param[in] showHeader If \c VARIANT_FALSE, the new group's header is not displayed.
/// \param[out] ppAddedGroup Receives the added group's \c IListViewGroup implementation.
///
/// \return An \c HRESULT error code.
///
/// \remarks The \c virtualItemCount, \c iconIndex, \c collapsible, \c collapsed, \c groupFooterText,
/// \c footerAlignment, \c subTitleText, \c taskText, \c subsetLinkText, \c subseted and
/// \c showHeader parameters are ignored if comctl32.dll is used in a version older than 6.10.\n
/// The \c virtualItemCount parameter is ignored if the control is not in virtual mode.
///
/// \if UNICODE
/// \sa Count, Remove, RemoveAll, ListViewGroup::get_Text, ListViewGroup::get_ID,
/// ListViewGroup::get_Position, ListViewGroup::get_ItemCount, ExplorerListView::get_VirtualMode,
/// ListViewGroup::get_Alignment, ExLVwLibU::AlignmentConstants, ListViewGroup::get_IconIndex,
/// ExplorerListView::get_hImageList, ExLVwLibU::ImageListConstants,
/// ListViewGroup::get_Collapsible, ListViewGroup::get_Collapsed, ListViewGroup::get_SubtitleText,
/// ListViewGroup::get_TaskText, ListViewGroup::get_SubsetLinkText, ListViewGroup::get_Subseted,
/// ListViewGroup::get_ShowHeader
/// \else
/// \sa Count, Remove, RemoveAll, ListViewGroup::get_Text, ListViewGroup::get_ID,
/// ListViewGroup::get_Position, ListViewGroup::get_ItemCount, ExplorerListView::get_VirtualMode,
/// ListViewGroup::get_Alignment, ExLVwLibA::AlignmentConstants ListViewGroup::get_IconIndex,
/// ExplorerListView::get_hImageList, ExLVwLibA::ImageListConstants,
/// ListViewGroup::get_Collapsible, ListViewGroup::get_Collapsed, ListViewGroup::get_SubtitleText,
/// ListViewGroup::get_TaskText, ListViewGroup::get_SubsetLinkText, ListViewGroup::get_Subseted,
/// ListViewGroup::get_ShowHeader
/// \endif
virtual HRESULT STDMETHODCALLTYPE Add(BSTR groupHeaderText, LONG groupID, LONG insertAt = -1, LONG virtualItemCount = 1, AlignmentConstants headerAlignment = alLeft, LONG iconIndex = -1, VARIANT_BOOL collapsible = VARIANT_FALSE, VARIANT_BOOL collapsed = VARIANT_FALSE, BSTR groupFooterText = L"", AlignmentConstants footerAlignment = alLeft, BSTR subTitleText = L"", BSTR taskText = L"", BSTR subsetLinkText = L"", VARIANT_BOOL subseted = VARIANT_FALSE, VARIANT_BOOL showHeader = VARIANT_TRUE, IListViewGroup** ppAddedGroup = NULL);
/// \brief <em>Retrieves whether the specified group is part of the group collection</em>
///
/// \param[in] groupIdentifier A value that identifies the group to be checked.
/// \param[in] groupIdentifierType A value specifying the meaning of \c groupIdentifier. Any of the
/// values defined by the \c GroupIdentifierTypeConstants enumeration is valid.
/// \param[out] pValue \c VARIANT_TRUE, if the group is part of the collection; otherwise
/// \c VARIANT_FALSE.
///
/// \return An \c HRESULT error code.
///
/// \if UNICODE
/// \sa Add, Remove, ExLVwLibU::GroupIdentifierTypeConstants
/// \else
/// \sa Add, Remove, ExLVwLibA::GroupIdentifierTypeConstants
/// \endif
virtual HRESULT STDMETHODCALLTYPE Contains(LONG groupIdentifier, GroupIdentifierTypeConstants groupIdentifierType = gitID, VARIANT_BOOL* pValue = NULL);
/// \brief <em>Counts the groups in the collection</em>
///
/// Retrieves the number of \c ListViewGroup objects in the collection.
///
/// \param[out] pValue The number of elements in the collection.
///
/// \return An \c HRESULT error code.
///
/// \sa Add, Remove, RemoveAll
virtual HRESULT STDMETHODCALLTYPE Count(LONG* pValue);
/// \brief <em>Removes the specified group in the collection from the listview</em>
///
/// \param[in] groupIdentifier A value that identifies the listview group to be removed.
/// \param[in] groupIdentifierType A value specifying the meaning of \c groupIdentifier. Any of the
/// values defined by the \c GroupIdentifierTypeConstants enumeration is valid.
///
/// \return An \c HRESULT error code.
///
/// \if UNICODE
/// \sa Add, Count, RemoveAll, Contains, ExLVwLibU::GroupIdentifierTypeConstants
/// \else
/// \sa Add, Count, RemoveAll, Contains, ExLVwLibA::GroupIdentifierTypeConstants
/// \endif
virtual HRESULT STDMETHODCALLTYPE Remove(LONG groupIdentifier, GroupIdentifierTypeConstants groupIdentifierType = gitID);
/// \brief <em>Removes all groups in the collection from the listview</em>
///
/// \return An \c HRESULT error code.
///
/// \sa Add, Count, Remove
virtual HRESULT STDMETHODCALLTYPE RemoveAll(void);
//@}
//////////////////////////////////////////////////////////////////////
/// \brief <em>Sets the owner of this collection</em>
///
/// \param[in] pOwner The owner to set.
///
/// \sa Properties::pOwnerExLvw
void SetOwner(__in_opt ExplorerListView* pOwner);
protected:
/// \brief <em>Holds the object's properties' settings</em>
struct Properties
{
/// \brief <em>The \c ExplorerListView object that owns this collection</em>
///
/// \sa SetOwner
ExplorerListView* pOwnerExLvw;
/// \brief <em>Holds the position index of the next enumerated group</em>
int nextEnumeratedGroup;
Properties()
{
pOwnerExLvw = NULL;
nextEnumeratedGroup = 0;
}
~Properties();
/// \brief <em>Retrieves the owning listview's window handle</em>
///
/// \return The window handle of the listview that contains the groups in this collection.
///
/// \sa pOwnerExLvw
HWND GetExLvwHWnd(void);
} properties;
}; // ListViewGroups
OBJECT_ENTRY_AUTO(__uuidof(ListViewGroups), ListViewGroups) | [
"tkunze71216@gmx.de"
] | tkunze71216@gmx.de |
01f79fbab6e5b6605209beeb2e399a8e059e1b82 | f71fe728904863239420d52a11f6972240166c11 | /Lib/src/tim.cpp | 75ffc031971b5c88431229d645fa69ea34846bf8 | [
"Apache-2.0"
] | permissive | joson1/thunderlib32-AC6 | 1ccc3bd1ec2e7f3b6d1e2c7b2d69335e7be61d54 | d3e551eb3d4aada0bfdd0a129349e25dd7400584 | refs/heads/master | 2020-04-17T14:46:07.515133 | 2019-04-15T13:58:32 | 2019-04-15T13:58:32 | 166,671,006 | 6 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,749 | cpp | #include "tim.h"
#include "STDDEF.H"
void (*TIM2_update_Irq)() = NULL;
void (*TIM3_update_Irq)() = NULL;
void (*TIM4_update_Irq)() = NULL;
void (*TIM5_update_Irq)() = NULL;
void (*TIM6_update_Irq)() = NULL;
void (*TIM7_update_Irq)() = NULL;
TIM::TIM(TIM_TypeDef* TIMn)
{
}
TIM::TIM()
{
}
TIM::~TIM()
{
}
void TIM::set_Remap(uint16_t Remap)
{
if((uint32_t)this->TIMn<(uint32_t)APB2PERIPH_BASE)
{
uint8_t timx = ((uint32_t)this->TIMn - (uint32_t)0x40000000) >>10;
switch (timx)
{
case 0:
AFIO->MAPR &= ~(Remap<<8);
AFIO->MAPR |= (Remap<<8);
break;
case 1:
AFIO->MAPR &= ~(Remap<<10);
AFIO->MAPR |= (Remap<<10);
break;
case 2:
AFIO->MAPR &= ~(Remap<<12);
AFIO->MAPR |= (Remap<<12);
break;
case 3:
AFIO->MAPR &= ~(Remap<<16);
AFIO->MAPR |= (Remap<<16);
break;
default:
break;
}
}else
{
AFIO->MAPR &= ~(Remap<<6);
AFIO->MAPR |= (Remap<<6);
}
}
void TIM::set_Remap(TIM_TypeDef* TIMn,uint16_t Remap)
{
if((uint32_t)TIMn<(uint32_t)APB2PERIPH_BASE)
{
uint8_t timx = ((uint32_t)TIMn - (uint32_t)0x40000000) >>10;
switch (timx)
{
case 0:
AFIO->MAPR &= ~(Remap<<8);
AFIO->MAPR |= (Remap<<8);
break;
case 1:
AFIO->MAPR &= ~(Remap<<10);
AFIO->MAPR |= (Remap<<10);
break;
case 2:
AFIO->MAPR &= ~(Remap<<12);
AFIO->MAPR |= (Remap<<12);
break;
case 3:
AFIO->MAPR &= ~(Remap<<16);
AFIO->MAPR |= (Remap<<16);
break;
default:
break;
}
}else
{
AFIO->MAPR &= ~(Remap<<6);
AFIO->MAPR |= (Remap<<6);
}
}
extern "C"{
void TIM2_IRQHandler()
{
if((TIM2->SR)&0X0001)
{
(*TIM2_update_Irq)();
}
TIM2->SR &= 0XFFFE;
}
void TIM3_IRQHandler()
{
if(TIM3->SR&0x0001)
{
(*TIM3_update_Irq)();
}
TIM3->SR &= 0XFFFE;
}
void TIM4_IRQHandler()
{
if(TIM4->SR & 0x0001)
{
(*TIM4_update_Irq)();
}
TIM4->SR &= 0XFFFE;
}
void TIM5_IRQHandler()
{
if(TIM5->SR&0x0001)
{
(*TIM5_update_Irq)();
}
TIM5->SR &= 0XFFFE;
}
void TIM6_IRQHandler()
{
if(TIM6->SR & 0x0001)
{
(*TIM6_update_Irq)();
}
TIM6->SR &= 0XFFFE;
}
void TIM7_IRQHandler()
{
if(TIM7->SR & 0x0001)
{
(*TIM7_update_Irq)();
}
TIM7->SR &= 0XFFFE;
}
}
| [
"wjy1063896722@outlook.com"
] | wjy1063896722@outlook.com |
a41de61a403a4e956df0e02fe0676cc65a4e3816 | 897ef84932251c57a790b75b1410a147b9b64792 | /sysexevent.cpp | db0df88841ea5efb02e5a9677b74b12651df66eb | [] | no_license | erophames/CamX | a92b789d758e514d43e6fd676dbb9eed1b7b3468 | 56b08ed02d976621f538feca10e1aaa58926aa5a | refs/heads/master | 2021-06-21T21:14:27.776691 | 2017-07-22T11:46:09 | 2017-07-22T11:46:09 | 98,467,657 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,404 | cpp | Seq_Event *SysEx::CloneNewAndSortToPattern(MidiPattern *p)
{
SysEx *newsys=(SysEx *)CloneNew();
if(newsys)
{
p->AddSortEvent(newsys);
if(sysexend.pattern)
{
p->AddSortVirtual(&newsys->sysexend);
newsys->sysexend.pattern=p;
}
}
return newsys;
}
Seq_Event *SysEx::CloneNewAndSortToPattern(MidiPattern *p,long diff)
{
SysEx *newsys=(SysEx *)CloneNew();
if(newsys)
{
newsys->objectstart+=diff;
newsys->sysexend.objectstart+=diff;
newsys->staticstartposition+=diff;
newsys->sysexend.staticstartposition+=diff;
p->AddSortEvent(newsys);
if(sysexend.pattern)
{
p->AddSortVirtual(&newsys->sysexend);
newsys->sysexend.pattern=p;
}
}
return newsys;
}
void SysEx::DeleteFromPattern()
{
pattern->events.DeleteObject(this); // Remove from Event list
if(sysexend.pattern)
{
pattern->DeleteVirtual(&sysexend);
sysexend.pattern=0;
}
}
void SysEx::CalcSysTicks()
{
if(data && length && mainmidi.baudrate)
{
double h=mainmidi.baudrate;
double h2=length;
// start/stopbits ->bytes/sec
h/=10;
h/=h2;
// h2=ms
ticklength=mainvar.ConvertMilliSecToTicks(h);
}
else
ticklength=0;
}
void SysEx::CheckSysExEnd()
{
if(ticklength>=16) // add virtual 0xF7
{
pattern->AddSortVirtual(&sysexend,objectstart+ticklength);
}
else
{
if(sysexend.pattern)
{
pattern->DeleteVirtual(&sysexend);
sysexend.pattern=0;
}
}
}
| [
"matthieu.brucher@gmail.com"
] | matthieu.brucher@gmail.com |
6f910ff0e839dfd20098818417cf896a999e2fb6 | 2fa54a1de361602fae80fa8a76ff2052f238223c | /squarefactory.cpp | aa040aad0d73fb5fa03499bc740a10ddcc55b0f0 | [] | no_license | rlmaso2/Shape_Factory | 660d656e9ca959265a742bbc49916d4d8937409f | e740a7ef8a94428b003ac67106314d018d0a3f57 | refs/heads/master | 2020-04-05T23:45:42.940631 | 2015-07-15T19:49:26 | 2015-07-15T19:49:26 | 39,095,950 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 388 | cpp | #include "squarefactory.h"
#include <cassert>
static SquareFactory squareFactory;
SquareFactory::SquareFactory() {
ShapeFactory::registerShape("square", this);
}
Square* SquareFactory::createShape(const QDomElement& element) const {
assert(!element.isNull());
assert(element.tagName()=="square");
Square* square = new Square(element);
return square;
} | [
"Ricky.Mason@BionicInnovations.com"
] | Ricky.Mason@BionicInnovations.com |
acb8419ba3aad88c0deddb8a4c73928eb5d2b817 | ba8689a6e4f0e4f6e78c1864e6a1f448b9d04aef | /Calculator/src/ReversePolishNotation.cpp | c5f103b6dcd84f6d28f6c240c220f0597c2895a4 | [] | no_license | YlmzCmlttn/Calculator | 591ffd109a3f9e3f3cd05d17f1c919fa27f7e103 | ba4dcad575abf3931c608ba088982358373d4666 | refs/heads/main | 2023-04-30T06:35:17.043533 | 2021-05-07T00:46:57 | 2021-05-07T00:46:57 | 363,385,391 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,705 | cpp | #include "ReversePolishNotation.h"
#include <stack>
#include <iostream>
namespace ReversePolishNotation
{
bool isLeftAssociative(std::string str) {
return g_BinaryFunctions[str].m_Left;
}
// get function precedence
short getPrecedence(std::string str) {
if (isContain<std::string>(keys(g_BinaryFunctions), str)) {
return g_BinaryFunctions[str].m_Precendence;
}
return 0;
}
bool isNumber(char c,bool decimal, bool negative){
if (c >= '0' && c <= '9') {
return true;
}
else if ((!decimal) && c == '.') {
return true;
}
else if (!negative && c == '-') {
return true;
}
return false;
}
std::string findElement(const int& index, const std::string& equation, std::vector<std::string> list){
for (std::string item : list) {
int n = (int)item.size();
if (equation.substr(index, n) == item) {
return item;
}
}
return "";
}
RPN reversePolishNotation(const std::string& equation){
std::vector<std::string> queue;
std::stack<std::string> stack;
std::string element = "";
std::pair<TokenTypes,TokenTypes> types = std::make_pair<TokenTypes,TokenTypes>(TokenTypes::UNKNOW,TokenTypes::UNKNOW);
bool isDecimal = false;
bool isNegative =false;
const int equationLength = equation.size();
for (int i = 0; i < equationLength; i++)
{
bool condition = true;
char c = equation[i];
if(isNumber(c)){
types.first = TokenTypes::CONSTANT;
if(c == '.'){
isDecimal = true;
}else if(c == '-'){
isNegative = true;
if((types.second == TokenTypes::CONSTANT || types.second == TokenTypes::UNKNOW) && i != 0){
condition = false;
}
}
int startIndex = i;
if(i<equationLength-1){
if(condition){
while(isNumber(equation[i+1],isDecimal,isNegative)){
if(equation[i+1]=='-'){
break;
}
i++;
if(i == equationLength-1){
break;
}
}
}
}
element = equation.substr(startIndex,i-startIndex+1);
if(element=="-"){
types.first = TokenTypes::OPERATOR;
}
types.second = types.first;
}else{
element = findElement(i,equation,g_FunctionNames);
if(element != ""){
types.first = isContain<char>(g_Operators,element[0]) ? TokenTypes::OPERATOR : TokenTypes::FUNCTION;
}
else{
element = findElement(i,equation,g_ConstantNames);
if(element != ""){
types.first = TokenTypes::CONSTANT;
}else{
if(isContain<char>(g_LeftBrackets,equation[i])){
types.first = TokenTypes::LEFTPARANTESIS;
element = "(";
}else if(isContain<char>(g_RightBrackets,equation[i])){
types.first = TokenTypes::RIGHTPARANTESIS;
element = ")";
}else{
types.first = TokenTypes::UNKNOW;
}
}
}
i += element.size()-1;
}
std::string last_stack = (stack.size() > 0) ? stack.top() : "";
switch (types.first)
{
case TokenTypes::CONSTANT:
queue.push_back(element);
break;
case TokenTypes::FUNCTION:
stack.push(element);
break;
case TokenTypes::OPERATOR:
if(stack.size()!=0){
while((
(isContain<std::string>(g_FunctionNames, last_stack) && !isContain<char>(g_Operators, last_stack.c_str()[0])) ||
getPrecedence(last_stack) > getPrecedence(element) || ((getPrecedence(last_stack) == getPrecedence(element)) && isLeftAssociative(last_stack))) &&
!isContain<char>(g_LeftBrackets, last_stack.c_str()[0])
){
queue.push_back(stack.top());
stack.pop();
if(stack.size()==0){
break;
}
last_stack = stack.top();
}
}
stack.push(element);
break;
case TokenTypes::LEFTPARANTESIS:
stack.push(element);
break;
case TokenTypes::RIGHTPARANTESIS:
while(last_stack[0] != '('){
queue.push_back(stack.top());
stack.pop();
last_stack = stack.top();
}
stack.pop();
break;
default:
return queue;
}
types.second = types.first;
}
while(stack.size()>0){
queue.push_back(stack.top());
stack.pop();
}
return queue;
}
std::map<std::string, Function> g_UnaryFunctions = {
{"sin",Function(static_cast<double(*)(double)>(std::sin))}
};
std::map<std::string, Function> g_BinaryFunctions = {
{ "+", Function([](double x, double y) -> double { return x + y; }, TokenTypes::OPERATOR, 2) },
{ "-", Function([](double x, double y) -> double { return x - y; }, TokenTypes::OPERATOR, 2) },
{ "*", Function([](double x, double y) -> double { return x * y; }, TokenTypes::OPERATOR, 3) },
{ "/", Function([](double x, double y) -> double { return x / y; }, TokenTypes::OPERATOR, 3) },
{ "^", Function(static_cast<double(*)(double,double)>(std::pow), TokenTypes::OPERATOR, 4, false) }
};
std::vector<std::string> g_FunctionNames = keys<Function>(g_UnaryFunctions, g_BinaryFunctions);
// constants
std::map<std::string, double> g_Constants = {
{ "pi", std::atan(1) * 4 },
{ "e", std::exp(1) }
};
std::vector<std::string> g_ConstantNames = keys<double>(g_Constants);
} // namespace ReversePolishNotation
//256+874159+878745sadasd+sad5589741-8895478-
//3+4*2/(1-5)^2^3 | [
"ylmzcmlttn@gmail.com"
] | ylmzcmlttn@gmail.com |
55f7426e010878ebaa36c45ded778ae5fcbf818e | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/mutt/gumtree/mutt_repos_function_1997_mutt-1.7.2.cpp | 38734f00eac107895199bc6aeedd12f2b6c3abbf | [] | 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 | 220 | cpp | void imap_munge_mbox_name (IMAP_DATA *idata, char *dest, size_t dlen, const char *src)
{
char *buf;
buf = safe_strdup (src);
imap_utf_encode (idata, &buf);
imap_quote_string (dest, dlen, buf);
FREE (&buf);
} | [
"993273596@qq.com"
] | 993273596@qq.com |
5daa0379d5e5e0f6af70d792b79b7a7478c595c9 | c9908e7759720601dc72f76dbc7f4627b2fabb21 | /inject2.cxx | 96ee9e0664d72c1e82741146f64dcafb0b9fe7bf | [] | no_license | seanbaxter/long_demo | 78243ec90372f98b79bfe84cceb1e716ed1fee1e | 6268fa0e49a46ca14d89020043cc544e746cbbeb | refs/heads/master | 2020-09-13T13:48:33.647926 | 2020-03-01T21:49:58 | 2020-03-01T21:49:58 | 222,804,755 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 900 | cxx | #include <cstdio>
#include <fstream>
#include <iostream>
#include "json.hpp"
const char* inject_filename = "json_data/inject1.json";
@meta printf("Opening resource %s\n", inject_filename);
@meta std::ifstream json_file(inject_filename);
@meta nlohmann::json j;
@meta json_file>> j;
// Record the function names in this array.
@meta std::vector<std::string> function_names;
@meta for(auto& item : j.items()) {
@meta std::string name = item.value()["name"];
@meta std::string definition = item.value()["definition"];
@meta printf("Injecting function '%s' = '%s'\n",
name.c_str(), definition.c_str());
double @(name)(double x) {
return @expression(definition);
}
@meta function_names.push_back(std::move(name));
}
int main() {
double x = 15;
@meta for(const std::string& name : function_names)
printf("%s(%f) -> %f\n", @string(name), x, @(name)(x));
return 0;
}
| [
"lightborn@gmail.com"
] | lightborn@gmail.com |
03003e8014899fe5903ade8629d30b869c3c3df9 | 87ff77a23c76065db79b12687926024be6d086ab | /jrTest12/InitDataManager.cpp | 741fc4d4646aa28da8d0542d67d149ed134e9bf5 | [] | no_license | lesbox/jrTest12_2.10.0 | b3030e7a250ad419190afa2acd1f4568635b44f3 | ece8f2d903e2e73870d4c4393f2ae3db258d2c77 | refs/heads/master | 2021-01-19T19:02:18.041612 | 2017-04-18T07:21:49 | 2017-04-18T07:21:49 | 88,393,490 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 5,644 | cpp | #include "InitDataManager.h"
MiniShipCard::MiniShipCard() {
this->cid = 0;
this->type = 0;
this->evoCid = 0;
this->evoToCid = 0;
this->repairOilModulus = 0;
this->repairSteelModulus = 0;
this->repairTime = 0;
}
MiniShipCard::~MiniShipCard() {
}
bool MiniShipCard::fromQJsonObject(QJsonObject data, ErrorManager & errorManager) {
int flagTemp;
int valueTemp;
this->cid = (int)getDoubleFromQJsonObject(data, "cid", flagTemp);
if (flagTemp != 0) {
errorManager.pushErrorInfo("cid");
return false;
}
this->type = (int)getDoubleFromQJsonObject(data, "type", flagTemp);
if (flagTemp != 0) {
errorManager.pushErrorInfo("type");
return false;
}
this->dismantle.clear();
if (data.contains("dismantle")) {
QJsonObject dismantle = data["dismantle"].toObject();
bool flagTemp1;
int valueTemp1;
for each(QString key in dismantle.keys()) {
valueTemp1 = key.toInt(&flagTemp1);
if (flagTemp1 == false) {
errorManager.pushErrorInfo(key);
errorManager.pushErrorInfo("dismantle");
return false;
}
valueTemp = (int)getDoubleFromQJsonObject(dismantle, key, flagTemp);
if (flagTemp != 0) {
errorManager.pushErrorInfo(key);
errorManager.pushErrorInfo("dismantle");
return false;
}
this->dismantle.insert(valueTemp1, valueTemp);
}
}
this->evoCid = (int)getDoubleFromQJsonObject(data, "evoCid", flagTemp);
if (flagTemp == 1) {
errorManager.pushErrorInfo("evoCid");
return false;
}
this->evoToCid = (int)getDoubleFromQJsonObject(data, "evoToCid", flagTemp);
if (flagTemp == 1) {
errorManager.pushErrorInfo("evoToCid");
return false;
}
this->repairOilModulus = getDoubleFromQJsonObject(data, "repairOilModulus", flagTemp);
if (flagTemp == 1) {
errorManager.pushErrorInfo("repairOilModulus");
return false;
}
this->repairSteelModulus = getDoubleFromQJsonObject(data, "repairSteelModulus", flagTemp);
if (flagTemp == 1) {
errorManager.pushErrorInfo("repairSteelModulus");
return false;
}
this->repairTime = getDoubleFromQJsonObject(data, "repairTime", flagTemp);
if (flagTemp == 1) {
errorManager.pushErrorInfo("repairTime");
return false;
}
return true;
}
MiniGlobalConfig::MiniGlobalConfig() {
}
MiniGlobalConfig::~MiniGlobalConfig() {
}
bool MiniGlobalConfig::fromQJsonObject(QJsonObject data, ErrorManager & errorManager) {
int flagTemp;
int valueTemp;
this->resourceRecoveryTime.clear();
if (!data.contains("resourceRecoveryTime") || !data["resourceRecoveryTime"].isArray()) {
errorManager.pushErrorInfo("resourceRecoveryTime");
return false;
}
else {
QJsonArray resourceRecoveryTime = data["resourceRecoveryTime"].toArray();
for (int count = 0; count < resourceRecoveryTime.size(); count++) {
valueTemp = (int)getDoubleFromQJsonValueRef(resourceRecoveryTime[count], flagTemp);
if (flagTemp != 0) {
return false;
}
this->resourceRecoveryTime.append(valueTemp);
}
}
this->resourceRecoveryNum.clear();
if (!data.contains("resourceRecoveryNum") || !data["resourceRecoveryNum"].isArray()) {
errorManager.errorInfo = "resourceRecoveryNum";
return false;
}
else {
QJsonArray resourceRecoveryNum = data["resourceRecoveryNum"].toArray();
for (int count = 0; count < resourceRecoveryNum.size(); count++) {
valueTemp = (int)getDoubleFromQJsonValueRef(resourceRecoveryNum[count], flagTemp);
if (flagTemp != 0) {
errorManager.pushErrorInfo(QString::number(count));
errorManager.pushErrorInfo("resourceRecoveryNum/");
return false;
}
this->resourceRecoveryNum.append(valueTemp);
}
}
return true;
}
MiniInitDataManager::MiniInitDataManager() {
}
MiniInitDataManager::~MiniInitDataManager() {
}
bool MiniInitDataManager::fromQJsonObject(QJsonObject data, ErrorManager & errorManager) {
int flagTemp;
int valueTemp;
this->shipCard.clear();
if (!data.contains("shipCard") || !data["shipCard"].isArray()) {
errorManager.errorInfo = "shipCard";
return false;
}
else {
QJsonArray shipCard = data["shipCard"].toArray();
MiniShipCard shipCardTemp;
for (int count = 0; count < shipCard.size(); count++) {
if (!shipCard[count].isObject()) {
errorManager.pushErrorInfo(QString::number(count));
errorManager.pushErrorInfo("shipCard");
return false;
}
if (false == shipCardTemp.fromQJsonObject(shipCard[count].toObject(), errorManager)) {
errorManager.pushErrorInfo(QString::number(count));
errorManager.pushErrorInfo("shipCard");
return false;
}
this->shipCard.insert(shipCardTemp.cid, shipCardTemp);
}
}
if (!data.contains("globalConfig") || !data["globalConfig"].isObject()) {
errorManager.pushErrorInfo("globalConfig");
return false;
}
else {
if (false == this->globalConfig.fromQJsonObject(data["globalConfig"].toObject(), errorManager)) {
errorManager.pushErrorInfo("globalConfig");
return false;
}
}
this->errorCode.clear();
if (!data.contains("errorCode") || !data["errorCode"].isObject()) {
errorManager.errorInfo = "errorCode";
return false;
}
else {
QJsonObject errorCode = data["errorCode"].toObject();
int keyValueTemp;
QString stringValueTemp;
bool flagTemp1;
for each(QString key in errorCode.keys()) {
keyValueTemp = key.toInt(&flagTemp1);
if (flagTemp1 == false) {
errorManager.pushErrorInfo(key);
errorManager.pushErrorInfo("errorCode");
return false;
}
stringValueTemp = getStringFromQJsonObject(errorCode, key, flagTemp);
if (flagTemp != 0) {
errorManager.pushErrorInfo(key);
errorManager.pushErrorInfo("errorCode");
return false;
}
this->errorCode.insert(keyValueTemp, stringValueTemp);
}
}
return true;
} | [
"pwwndg@gmail.com"
] | pwwndg@gmail.com |
2612c32c5f3617bd9c4909a7667b39c03395ec79 | 52bd63e7c5f1730485e80008181dde512ad1a313 | /pstade/egg/is_bind_expression.hpp | 1cd6dcfb85eba4d11eee42f78a1542830e63c78c | [
"BSL-1.0"
] | permissive | fpelliccioni/pstade | 09df122a8cada6bd809512507b1eff9543d22cb1 | ffb52f2bf187c8f001588e6c5c007a4a3aa9a5e8 | refs/heads/master | 2016-09-11T02:06:23.972758 | 2013-09-26T15:13:05 | 2013-09-26T15:13:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,481 | hpp | #ifndef PSTADE_EGG_IS_BIND_EXPRESSION_HPP
#define PSTADE_EGG_IS_BIND_EXPRESSION_HPP
#include "./detail/prefix.hpp"
// PStade.Egg
//
// Copyright Shunsuke Sogame 2007.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <boost/mpl/bool.hpp>
#include <pstade/enable_if.hpp>
#include "./bll/functor_fwd.hpp"
namespace boost { namespace _bi {
template<class R, class F, class L>
class bind_t;
} }
namespace pstade { namespace egg {
template<class X, class EnableIf>
struct is_bind_expression_base :
boost::mpl::false_
{ };
template<class X>
struct is_bind_expression :
is_bind_expression_base<X, enabler>
{ };
template<class X>
struct is_bind_expression<X const> :
is_bind_expression<X>
{ };
template<class X>
struct is_bind_expression<X volatile> :
is_bind_expression<X>
{ };
template<class X>
struct is_bind_expression<X const volatile> :
is_bind_expression<X>
{ };
template<class T>
struct is_bind_expression< boost::lambda::lambda_functor<T> > :
boost::mpl::true_
{ };
template<class R, class F, class L>
struct is_bind_expression< boost::_bi::bind_t<R, F, L> > :
boost::mpl::true_
{ };
} } // namespace pstade::egg
#endif
| [
"fpelliccioni@gmail.com"
] | fpelliccioni@gmail.com |
6ab49fe29655583a2e7bff96344b2cb5bbff279a | 370c147753310d348fef4e16ae4b31ee07be0acd | /src/test/test_common.h | 79d419dd64b6e024e55351ebb85f1776ed55c229 | [] | no_license | rushad/filetransfer | c4971de66a4e2d78135c7641e2696963068815df | 13ded7c6444daf5a0f3cb1c3569c73f4f6ffc321 | refs/heads/master | 2020-05-15T19:56:09.089811 | 2014-02-07T12:20:24 | 2014-02-07T12:20:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,741 | h | #pragma once
#include "../observer.h"
#include "../progress_calculator.h"
#include "../queue.h"
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/thread/thread.hpp>
#include <string>
namespace FileTransfer
{
namespace Test
{
using boost::posix_time::ptime;
using boost::posix_time::millisec;
const size_t CHUNK_SIZE = 100;
const unsigned CHUNK_DELAY = 2;
const unsigned CHUNK_NUMBER = 10;
static ptime CurrentTime()
{
return boost::posix_time::microsec_clock::universal_time();
}
static void usleep(unsigned ms)
{
boost::this_thread::sleep_for(boost::chrono::milliseconds(ms));
}
static Queue::Chunk MakeChunk(const std::string& str)
{
Queue::Chunk chunk(str.size());
chunk.assign(str.data(), str.data() + str.size());
return chunk;
}
static Queue::Chunk MakeChunk(const Queue::Chunk& chunk1, const Queue::Chunk& chunk2)
{
Queue::Chunk chunk(chunk1);
chunk.insert(chunk.end(), chunk2.begin(), chunk2.end());
return chunk;
}
class FakeObserver : public Observer
{
public:
virtual void UpdateProgress(const unsigned dlPerc, const unsigned ulPerc)
{
DlProgress = dlPerc;
UlProgress = ulPerc;
}
unsigned DlProgress;
unsigned UlProgress;
typedef boost::shared_ptr<FakeObserver> Ptr;
};
class FakeProgressCalculator : public ProgressCalculator
{
public:
FakeProgressCalculator()
: Calls(0)
{
}
virtual void Calculate()
{
++Calls;
}
public:
unsigned Calls;
};
}
} | [
"rushad@bk.ru"
] | rushad@bk.ru |
ccf7cddae0777f71ab212647d4379f1e8d383234 | e2cd39b6bff42bdfaf861e2f152af8781f2be7eb | /ShadowMultiplayer/RoboCat/Inc/ShadowFactory.hpp | d28cb3e3596fda4c65e8f2d87818b485413bd4a3 | [] | no_license | cjjb95/ConorByrneCharlieDuffCA3Multiplayer | 7cb5b797579fdd54ed57805034b7621abc05b8f0 | ec341bbbe8ccb872f2aeebf9368b68f15783a8d6 | refs/heads/master | 2022-07-14T22:09:38.009275 | 2020-05-15T20:58:17 | 2020-05-15T20:58:17 | 262,842,342 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 573 | hpp | // Written by: Ronan
#ifndef SHADOWFACTORY_HPP
#define SHADOWFACTORY_HPP
class ShadowFactory
{
public:
static void StaticInit();
static std::unique_ptr<ShadowFactory> sInstance;
std::vector<sf::VertexArray> getShadows(sf::Vector2f playerPosition, sf::Color color, sf::FloatRect p_bounds);
bool load();
bool doesCollideWithWorld(sf::FloatRect p_bounds);
private:
std::vector<sf::FloatRect> shadowCasters;
sf::Vector2f m_worldSize;
std::vector<Line> getShadowLines();
void optimizeShadowCasters();
bool doesExitWithMapBounds(sf::FloatRect p_bounds);
};
#endif | [
"cjjb95@gmail.com"
] | cjjb95@gmail.com |
032a8999f007ffe9fb2f89e437deb26c341dc2b4 | fa8a73511234afbb06469f9b38e17b65b5e6072c | /src/basic/INIT3-Cuda.cpp | 1f5409a4f72538d2e6a4ec171ff964c26fdbcf13 | [] | no_license | him-28/RAJAPerf | 5c6b3e6bb49dce22c827b7ae856b3f7c02b60e33 | a8f669c1ad01d51132a4e3d9d6aa8b2cabc9eff0 | refs/heads/master | 2020-04-01T21:39:11.737238 | 2018-09-28T16:37:07 | 2018-09-28T16:37:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,813 | cpp | //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Copyright (c) 2017-18, Lawrence Livermore National Security, LLC.
//
// Produced at the Lawrence Livermore National Laboratory
//
// LLNL-CODE-738930
//
// All rights reserved.
//
// This file is part of the RAJA Performance Suite.
//
// For details about use and distribution, please read RAJAPerf/LICENSE.
//
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
#include "INIT3.hpp"
#include "RAJA/RAJA.hpp"
#if defined(RAJA_ENABLE_CUDA)
#include "common/CudaDataUtils.hpp"
#include <iostream>
namespace rajaperf
{
namespace basic
{
//
// Define thread block size for CUDA execution
//
const size_t block_size = 256;
#define INIT3_DATA_SETUP_CUDA \
Real_ptr out1; \
Real_ptr out2; \
Real_ptr out3; \
Real_ptr in1; \
Real_ptr in2; \
\
allocAndInitCudaDeviceData(out1, m_out1, iend); \
allocAndInitCudaDeviceData(out2, m_out2, iend); \
allocAndInitCudaDeviceData(out3, m_out3, iend); \
allocAndInitCudaDeviceData(in1, m_in1, iend); \
allocAndInitCudaDeviceData(in2, m_in2, iend);
#define INIT3_DATA_TEARDOWN_CUDA \
getCudaDeviceData(m_out1, out1, iend); \
getCudaDeviceData(m_out2, out2, iend); \
getCudaDeviceData(m_out3, out3, iend); \
deallocCudaDeviceData(out1); \
deallocCudaDeviceData(out2); \
deallocCudaDeviceData(out3); \
deallocCudaDeviceData(in1); \
deallocCudaDeviceData(in2);
__global__ void init3(Real_ptr out1, Real_ptr out2, Real_ptr out3,
Real_ptr in1, Real_ptr in2,
Index_type iend)
{
Index_type i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < iend) {
INIT3_BODY;
}
}
void INIT3::runCudaVariant(VariantID vid)
{
const Index_type run_reps = getRunReps();
const Index_type ibegin = 0;
const Index_type iend = getRunSize();
if ( vid == Base_CUDA ) {
INIT3_DATA_SETUP_CUDA;
startTimer();
for (RepIndex_type irep = 0; irep < run_reps; ++irep) {
const size_t grid_size = RAJA_DIVIDE_CEILING_INT(iend, block_size);
init3<<<grid_size, block_size>>>( out1, out2, out3, in1, in2,
iend );
}
stopTimer();
INIT3_DATA_TEARDOWN_CUDA;
} else if ( vid == RAJA_CUDA ) {
INIT3_DATA_SETUP_CUDA;
startTimer();
for (RepIndex_type irep = 0; irep < run_reps; ++irep) {
RAJA::forall< RAJA::cuda_exec<block_size, true /*async*/> >(
RAJA::RangeSegment(ibegin, iend), [=] __device__ (Index_type i) {
INIT3_BODY;
});
}
stopTimer();
INIT3_DATA_TEARDOWN_CUDA;
} else {
std::cout << "\n INIT3 : Unknown Cuda variant id = " << vid << std::endl;
}
}
} // end namespace basic
} // end namespace rajaperf
#endif // RAJA_ENABLE_CUDA
| [
"hornung1@llnl.gov"
] | hornung1@llnl.gov |
ada34e001b2f4c91cafe4258d59a6436f8fceb87 | 487d3cf6209e32b0d8f8b84976a66a74910ff676 | /src/rpcmining.cpp | 82a33b9bbbc0da0e5a46b4c5e270bc2546815017 | [
"MIT"
] | permissive | eonagen/eonagenEONA | 1040e3ff4b3879ccbd122f5cfe6687286faef770 | 606898a77b43ec8c7de664987bb88ceaa3d94ffe | refs/heads/master | 2020-04-15T17:09:37.826304 | 2019-01-09T12:58:25 | 2019-01-09T12:58:25 | 162,619,789 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 22,998 | cpp | // Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "rpcserver.h"
#include "chainparams.h"
#include "main.h"
#include "db.h"
#include "txdb.h"
#include "init.h"
#include "miner.h"
#include "kernel.h"
#include <boost/assign/list_of.hpp>
using namespace json_spirit;
using namespace std;
using namespace boost::assign;
// Key used by getwork/getblocktemplate miners.
// Allocated in InitRPCMining, free'd in ShutdownRPCMining
static CReserveKey* pMiningKey = NULL;
void InitRPCMining()
{
if (!pwalletMain)
return;
// getwork/getblocktemplate mining rewards paid here:
pMiningKey = new CReserveKey(pwalletMain);
}
void ShutdownRPCMining()
{
if (!pMiningKey)
return;
delete pMiningKey; pMiningKey = NULL;
}
Value getsubsidy(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getsubsidy [nTarget]\n"
"Returns proof-of-work subsidy value for the specified value of target.");
return (uint64_t)GetProofOfWorkReward(pindexBest->nHeight, 0);
}
Value getstakesubsidy(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getstakesubsidy <hex string>\n"
"Returns proof-of-stake subsidy value for the specified coinstake.");
RPCTypeCheck(params, list_of(str_type));
vector<unsigned char> txData(ParseHex(params[0].get_str()));
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
CTransaction tx;
try {
ssData >> tx;
}
catch (std::exception &e) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
}
uint64_t nCoinAge;
CTxDB txdb("r");
if (!tx.GetCoinAge(txdb, pindexBest, nCoinAge))
throw JSONRPCError(RPC_MISC_ERROR, "GetCoinAge failed");
return (uint64_t)GetProofOfStakeReward(pindexBest, nCoinAge, 0);
}
Value getmininginfo(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getmininginfo\n"
"Returns an object containing mining-related information.");
uint64_t nWeight = 0;
if (pwalletMain)
nWeight = pwalletMain->GetStakeWeight();
Object obj, diff, weight;
obj.push_back(Pair("blocks", (int)nBestHeight));
obj.push_back(Pair("currentblocksize",(uint64_t)nLastBlockSize));
obj.push_back(Pair("currentblocktx",(uint64_t)nLastBlockTx));
diff.push_back(Pair("proof-of-work", GetDifficulty()));
diff.push_back(Pair("proof-of-stake", GetDifficulty(GetLastBlockIndex(pindexBest, true))));
diff.push_back(Pair("search-interval", (int)nLastCoinStakeSearchInterval));
obj.push_back(Pair("difficulty", diff));
obj.push_back(Pair("blockvalue", (uint64_t)GetProofOfWorkReward(pindexBest->nHeight, 0)));
obj.push_back(Pair("netmhashps", GetPoWMHashPS()));
obj.push_back(Pair("netstakeweight", GetPoSKernelPS()));
obj.push_back(Pair("errors", GetWarnings("statusbar")));
obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
weight.push_back(Pair("minimum", (uint64_t)nWeight));
weight.push_back(Pair("maximum", (uint64_t)0));
weight.push_back(Pair("combined", (uint64_t)nWeight));
obj.push_back(Pair("stakeweight", weight));
obj.push_back(Pair("testnet", TestNet()));
return obj;
}
Value getstakinginfo(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getstakinginfo\n"
"Returns an object containing staking-related information.");
uint64_t nWeight = 0;
uint64_t nExpectedTime = 0;
if (pwalletMain)
nWeight = pwalletMain->GetStakeWeight();
uint64_t nNetworkWeight = GetPoSKernelPS();
bool staking = nLastCoinStakeSearchInterval && nWeight;
nExpectedTime = staking ? (TARGET_SPACING * nNetworkWeight / nWeight) : 0;
Object obj;
obj.push_back(Pair("enabled", GetBoolArg("-staking", true)));
obj.push_back(Pair("staking", staking));
obj.push_back(Pair("errors", GetWarnings("statusbar")));
obj.push_back(Pair("currentblocksize", (uint64_t)nLastBlockSize));
obj.push_back(Pair("currentblocktx", (uint64_t)nLastBlockTx));
obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
obj.push_back(Pair("difficulty", GetDifficulty(GetLastBlockIndex(pindexBest, true))));
obj.push_back(Pair("search-interval", (int)nLastCoinStakeSearchInterval));
obj.push_back(Pair("weight", (uint64_t)nWeight));
obj.push_back(Pair("netstakeweight", (uint64_t)nNetworkWeight));
obj.push_back(Pair("expectedtime", nExpectedTime));
return obj;
}
Value checkkernel(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"checkkernel [{\"txid\":txid,\"vout\":n},...] [createblocktemplate=false]\n"
"Check if one of given inputs is a kernel input at the moment.\n"
);
RPCTypeCheck(params, list_of(array_type)(bool_type));
Array inputs = params[0].get_array();
bool fCreateBlockTemplate = params.size() > 1 ? params[1].get_bool() : false;
if (vNodes.empty())
throw JSONRPCError(-9, "eonagen is not connected!");
if (IsInitialBlockDownload())
throw JSONRPCError(-10, "eonagen is downloading blocks...");
COutPoint kernel;
CBlockIndex* pindexPrev = pindexBest;
unsigned int nBits = GetNextTargetRequired(pindexPrev, true);
int64_t nTime = GetAdjustedTime();
nTime &= ~STAKE_TIMESTAMP_MASK;
BOOST_FOREACH(Value& input, inputs)
{
const Object& o = input.get_obj();
const Value& txid_v = find_value(o, "txid");
if (txid_v.type() != str_type)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing txid key");
string txid = txid_v.get_str();
if (!IsHex(txid))
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected hex txid");
const Value& vout_v = find_value(o, "vout");
if (vout_v.type() != int_type)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing vout key");
int nOutput = vout_v.get_int();
if (nOutput < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive");
COutPoint cInput(uint256(txid), nOutput);
if (CheckKernel(pindexPrev, nBits, nTime, cInput))
{
kernel = cInput;
break;
}
}
Object result;
result.push_back(Pair("found", !kernel.IsNull()));
if (kernel.IsNull())
return result;
Object oKernel;
oKernel.push_back(Pair("txid", kernel.hash.GetHex()));
oKernel.push_back(Pair("vout", (int64_t)kernel.n));
oKernel.push_back(Pair("time", nTime));
result.push_back(Pair("kernel", oKernel));
if (!fCreateBlockTemplate)
return result;
int64_t nFees;
auto_ptr<CBlock> pblock(CreateNewBlock(*pMiningKey, true, &nFees));
pblock->nTime = pblock->vtx[0].nTime = nTime;
CDataStream ss(SER_DISK, PROTOCOL_VERSION);
ss << *pblock;
result.push_back(Pair("blocktemplate", HexStr(ss.begin(), ss.end())));
result.push_back(Pair("blocktemplatefees", nFees));
CPubKey pubkey;
if (!pMiningKey->GetReservedKey(pubkey))
throw JSONRPCError(RPC_MISC_ERROR, "GetReservedKey failed");
result.push_back(Pair("blocktemplatesignkey", HexStr(pubkey)));
return result;
}
Value getworkex(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"getworkex [data, coinbase]\n"
"If [data, coinbase] is not specified, returns extended work data.\n"
);
if (vNodes.empty())
throw JSONRPCError(-9, "eonagen is not connected!");
if (IsInitialBlockDownload())
throw JSONRPCError(-10, "eonagen is downloading blocks...");
typedef map<uint256, pair<CBlock*, CScript> > maEONAwBlock_t;
static maEONAwBlock_t maEONAwBlock;
static vector<CBlock*> vNewBlock;
if (params.size() == 0)
{
// Update block
static unsigned int nTransactionsUpdatedLast;
static CBlockIndex* pindexPrev;
static int64_t nStart;
static CBlock* pblock;
if (pindexPrev != pindexBest ||
(mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60))
{
if (pindexPrev != pindexBest)
{
// Deallocate old blocks since they're obsolete now
maEONAwBlock.clear();
BOOST_FOREACH(CBlock* pblock, vNewBlock)
delete pblock;
vNewBlock.clear();
}
nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
pindexPrev = pindexBest;
nStart = GetTime();
// Create new block
pblock = CreateNewBlock(*pMiningKey);
if (!pblock)
throw JSONRPCError(-7, "Out of memory");
vNewBlock.push_back(pblock);
}
// Update nTime
pblock->nTime = max(pindexPrev->GetPastTimeLimit()+1, GetAdjustedTime());
pblock->nNonce = 0;
// Update nExtraNonce
static unsigned int nExtraNonce = 0;
IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
// Save
maEONAwBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
// Prebuild hash buffers
char pmidstate[32];
char pdata[128];
char phash1[64];
FormatHashBuffers(pblock, pmidstate, pdata, phash1);
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
CTransaction coinbaseTx = pblock->vtx[0];
std::vector<uint256> merkle = pblock->GetMerkleBranch(0);
Object result;
result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
ssTx << coinbaseTx;
result.push_back(Pair("coinbase", HexStr(ssTx.begin(), ssTx.end())));
Array merkle_arr;
BOOST_FOREACH(uint256 merkleh, merkle) {
merkle_arr.push_back(HexStr(BEGIN(merkleh), END(merkleh)));
}
result.push_back(Pair("merkle", merkle_arr));
return result;
}
else
{
// Parse parameters
vector<unsigned char> vchData = ParseHex(params[0].get_str());
vector<unsigned char> coinbase;
if(params.size() == 2)
coinbase = ParseHex(params[1].get_str());
if (vchData.size() != 128)
throw JSONRPCError(-8, "Invalid parameter");
CBlock* pdata = (CBlock*)&vchData[0];
// Byte reverse
for (int i = 0; i < 128/4; i++)
((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
// Get saved block
if (!maEONAwBlock.count(pdata->hashMerkleRoot))
return false;
CBlock* pblock = maEONAwBlock[pdata->hashMerkleRoot].first;
pblock->nTime = pdata->nTime;
pblock->nNonce = pdata->nNonce;
if(coinbase.size() == 0)
pblock->vtx[0].vin[0].scriptSig = maEONAwBlock[pdata->hashMerkleRoot].second;
else
CDataStream(coinbase, SER_NETWORK, PROTOCOL_VERSION) >> pblock->vtx[0]; // FIXME - HACK!
pblock->hashMerkleRoot = pblock->BuildMerkleTree();
assert(pwalletMain != NULL);
return CheckWork(pblock, *pwalletMain, *pMiningKey);
}
}
Value getwork(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getwork [data]\n"
"If [data] is not specified, returns formatted hash data to work on:\n"
" \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated
" \"data\" : block data\n"
" \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated
" \"target\" : little endian hash target\n"
"If [data] is specified, tries to solve the block and returns true if it was successful.");
if (vNodes.empty())
throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "eonagen is not connected!");
if (IsInitialBlockDownload())
throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "eonagen is downloading blocks...");
typedef map<uint256, pair<CBlock*, CScript> > maEONAwBlock_t;
static maEONAwBlock_t maEONAwBlock; // FIXME: thread safety
static vector<CBlock*> vNewBlock;
if (params.size() == 0)
{
// Update block
static unsigned int nTransactionsUpdatedLast;
static CBlockIndex* pindexPrev;
static int64_t nStart;
static CBlock* pblock;
if (pindexPrev != pindexBest ||
(mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60))
{
if (pindexPrev != pindexBest)
{
// Deallocate old blocks since they're obsolete now
maEONAwBlock.clear();
BOOST_FOREACH(CBlock* pblock, vNewBlock)
delete pblock;
vNewBlock.clear();
}
// Clear pindexPrev so future getworks make a new block, despite any failures from here on
pindexPrev = NULL;
// Store the pindexBest used before CreateNewBlock, to avoid races
nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
CBlockIndex* pindexPrevNew = pindexBest;
nStart = GetTime();
// Create new block
pblock = CreateNewBlock(*pMiningKey);
if (!pblock)
throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
vNewBlock.push_back(pblock);
// Need to update only after we know CreateNewBlock succeeded
pindexPrev = pindexPrevNew;
}
// Update nTime
pblock->UpdateTime(pindexPrev);
pblock->nNonce = 0;
// Update nExtraNonce
static unsigned int nExtraNonce = 0;
IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
// Save
maEONAwBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
// Pre-build hash buffers
char pmidstate[32];
char pdata[128];
char phash1[64];
FormatHashBuffers(pblock, pmidstate, pdata, phash1);
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
Object result;
result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated
result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated
result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
return result;
}
else
{
// Parse parameters
vector<unsigned char> vchData = ParseHex(params[0].get_str());
if (vchData.size() != 128)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
CBlock* pdata = (CBlock*)&vchData[0];
// Byte reverse
for (int i = 0; i < 128/4; i++)
((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
// Get saved block
if (!maEONAwBlock.count(pdata->hashMerkleRoot))
return false;
CBlock* pblock = maEONAwBlock[pdata->hashMerkleRoot].first;
pblock->nTime = pdata->nTime;
pblock->nNonce = pdata->nNonce;
pblock->vtx[0].vin[0].scriptSig = maEONAwBlock[pdata->hashMerkleRoot].second;
pblock->hashMerkleRoot = pblock->BuildMerkleTree();
assert(pwalletMain != NULL);
return CheckWork(pblock, *pwalletMain, *pMiningKey);
}
}
Value getblocktemplate(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getblocktemplate [params]\n"
"Returns data needed to construct a block to work on:\n"
" \"version\" : block version\n"
" \"previousblockhash\" : hash of current highest block\n"
" \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n"
" \"coinbaseaux\" : data that should be included in coinbase\n"
" \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n"
" \"target\" : hash target\n"
" \"mintime\" : minimum timestamp appropriate for next block\n"
" \"curtime\" : current timestamp\n"
" \"mutable\" : list of ways the block template may be changed\n"
" \"noncerange\" : range of valid nonces\n"
" \"sigoplimit\" : limit of sigops in blocks\n"
" \"sizelimit\" : limit of block size\n"
" \"bits\" : compressed target of next block\n"
" \"height\" : height of the next block\n"
"See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
std::string strMode = "template";
if (params.size() > 0)
{
const Object& oparam = params[0].get_obj();
const Value& modeval = find_value(oparam, "mode");
if (modeval.type() == str_type)
strMode = modeval.get_str();
else if (modeval.type() == null_type)
{
/* Do nothing */
}
else
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
}
if (strMode != "template")
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
if (vNodes.empty())
throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "eonagen is not connected!");
//if (IsInitialBlockDownload())
// throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "eonagen is downloading blocks...");
// Update block
static unsigned int nTransactionsUpdatedLast;
static CBlockIndex* pindexPrev;
static int64_t nStart;
static CBlock* pblock;
if (pindexPrev != pindexBest ||
(mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 5))
{
// Clear pindexPrev so future calls make a new block, despite any failures from here on
pindexPrev = NULL;
// Store the pindexBest used before CreateNewBlock, to avoid races
nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
CBlockIndex* pindexPrevNew = pindexBest;
nStart = GetTime();
// Create new block
if(pblock)
{
delete pblock;
pblock = NULL;
}
pblock = CreateNewBlock(*pMiningKey);
if (!pblock)
throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
// Need to update only after we know CreateNewBlock succeeded
pindexPrev = pindexPrevNew;
}
// Update nTime
pblock->UpdateTime(pindexPrev);
pblock->nNonce = 0;
Array transactions;
map<uint256, int64_t> setTxIndex;
int i = 0;
CTxDB txdb("r");
BOOST_FOREACH (CTransaction& tx, pblock->vtx)
{
uint256 txHash = tx.GetHash();
setTxIndex[txHash] = i++;
if (tx.IsCoinBase() || tx.IsCoinStake())
continue;
Object entry;
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
ssTx << tx;
entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end())));
entry.push_back(Pair("hash", txHash.GetHex()));
MapPrevTx mapInputs;
map<uint256, CTxIndex> mapUnused;
bool fInvalid = false;
if (tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
{
entry.push_back(Pair("fee", (int64_t)(tx.GetValueIn(mapInputs) - tx.GetValueOut())));
Array deps;
BOOST_FOREACH (MapPrevTx::value_type& inp, mapInputs)
{
if (setTxIndex.count(inp.first))
deps.push_back(setTxIndex[inp.first]);
}
entry.push_back(Pair("depends", deps));
int64_t nSigOps = GetLegacySigOpCount(tx);
nSigOps += GetP2SHSigOpCount(tx, mapInputs);
entry.push_back(Pair("sigops", nSigOps));
}
transactions.push_back(entry);
}
Object aux;
aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
static Array aMutable;
if (aMutable.empty())
{
aMutable.push_back("time");
aMutable.push_back("transactions");
aMutable.push_back("prevblock");
}
Object result;
result.push_back(Pair("version", pblock->nVersion));
result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
result.push_back(Pair("transactions", transactions));
result.push_back(Pair("coinbaseaux", aux));
result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
result.push_back(Pair("target", hashTarget.GetHex()));
result.push_back(Pair("mintime", (int64_t)pindexPrev->GetPastTimeLimit()+1));
result.push_back(Pair("mutable", aMutable));
result.push_back(Pair("noncerange", "00000000ffffffff"));
result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
result.push_back(Pair("curtime", (int64_t)pblock->nTime));
result.push_back(Pair("bits", strprintf("%08x", pblock->nBits)));
result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
return result;
}
Value submitblock(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"submitblock <hex data> [optional-params-obj]\n"
"[optional-params-obj] parameter is currently ignored.\n"
"Attempts to submit new block to network.\n"
"See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
vector<unsigned char> blockData(ParseHex(params[0].get_str()));
CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
CBlock block;
try {
ssBlock >> block;
}
catch (std::exception &e) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
}
bool fAccepted = ProcessBlock(NULL, &block);
if (!fAccepted)
return "rejected";
return Value::null;
}
| [
"45151553+Pinecoin-Developer@users.noreply.github.com"
] | 45151553+Pinecoin-Developer@users.noreply.github.com |
8333538f0787aa08cc4aee9d32c85c4238163e96 | 202443d103d4777cc8976185233d9da587da75fc | /r_dump_basic.h | 0b0b7d621d39479610042052f493506726da2824 | [] | no_license | pts/pts-contestcc | 3e0cb2ac36924b17c2862ddc23c9a797e3c4bf57 | dde2f4bddffaf5ecddda0957140bad728431f0cd | refs/heads/master | 2021-01-01T05:47:15.028723 | 2014-04-24T21:25:30 | 2014-04-24T21:27:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 522 | h | #ifndef R_DUMP_BASIC_H
#define R_DUMP_BASIC_H 1
#ifndef __cplusplus
#error This is a C++ header.
#endif
#include <stdint.h>
#include <string.h>
#include <string>
#include "r_strpiece.h"
namespace r {
void wrdump_low(char v, std::string *out);
void wrdump_low(const StrPiece &v, std::string *out);
void wrdump_low(const std::string &v, std::string *out);
void wrdump_low(const char *v, uintptr_t size, std::string *out);
void wrdump_low(const char *v, std::string *out);
} // namespace r
#endif // R_DUMP_BASIC_H
| [
"pts@fazekas.hu"
] | pts@fazekas.hu |
0c2abfd3f1765fe99a9159ee9056367b524ad45d | 89dedd7f3c7acc81d12e2bcb2e716f9af9e5fa04 | /third_party/WebKit/Source/core/events/KeyboardEvent.cpp | d0c4eacd48da6436775c31f64985494acdbcab5b | [
"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 | bino7/chromium | 8d26f84a1b6e38a73d1b97fea6057c634eff68cb | 4666a6bb6fdcb1114afecf77bdaa239d9787b752 | refs/heads/master | 2022-12-22T14:31:53.913081 | 2016-09-06T10:05:11 | 2016-09-06T10:05:11 | 67,410,510 | 1 | 3 | BSD-3-Clause | 2022-12-17T03:08:52 | 2016-09-05T10:11:59 | null | UTF-8 | C++ | false | false | 6,875 | cpp | /**
* Copyright (C) 2001 Peter Kelly (pmk@post.com)
* Copyright (C) 2001 Tobias Anton (anton@stud.fbi.fh-darmstadt.de)
* Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
* Copyright (C) 2003, 2005, 2006, 2007 Apple Inc. 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 "core/events/KeyboardEvent.h"
#include "bindings/core/v8/DOMWrapperWorld.h"
#include "bindings/core/v8/ScriptState.h"
#include "platform/WindowsKeyboardCodes.h"
#include "public/platform/Platform.h"
#include "public/platform/WebInputEvent.h"
#include "wtf/PtrUtil.h"
namespace blink {
static inline const AtomicString& eventTypeForKeyboardEventType(WebInputEvent::Type type)
{
switch (type) {
case WebInputEvent::KeyUp:
return EventTypeNames::keyup;
case WebInputEvent::RawKeyDown:
return EventTypeNames::keydown;
case WebInputEvent::Char:
return EventTypeNames::keypress;
case WebInputEvent::KeyDown:
// The caller should disambiguate the combined event into RawKeyDown or Char events.
break;
default:
break;
}
NOTREACHED();
return EventTypeNames::keydown;
}
static inline KeyboardEvent::KeyLocationCode keyLocationCode(const WebInputEvent& key)
{
if (key.modifiers & WebInputEvent::IsKeyPad)
return KeyboardEvent::kDomKeyLocationNumpad;
if (key.modifiers & WebInputEvent::IsLeft)
return KeyboardEvent::kDomKeyLocationLeft;
if (key.modifiers & WebInputEvent::IsRight)
return KeyboardEvent::kDomKeyLocationRight;
return KeyboardEvent::kDomKeyLocationStandard;
}
KeyboardEvent* KeyboardEvent::create(ScriptState* scriptState, const AtomicString& type, const KeyboardEventInit& initializer)
{
if (scriptState->world().isIsolatedWorld())
UIEventWithKeyState::didCreateEventInIsolatedWorld(initializer.ctrlKey(), initializer.altKey(), initializer.shiftKey(), initializer.metaKey());
return new KeyboardEvent(type, initializer);
}
KeyboardEvent::KeyboardEvent()
: m_location(kDomKeyLocationStandard)
{
}
KeyboardEvent::KeyboardEvent(const WebKeyboardEvent& key, AbstractView* view)
: UIEventWithKeyState(eventTypeForKeyboardEventType(key.type), true, true, view, 0, static_cast<PlatformEvent::Modifiers>(key.modifiers), key.timeStampSeconds, InputDeviceCapabilities::doesntFireTouchEventsSourceCapabilities())
, m_keyEvent(wrapUnique(new WebKeyboardEvent(key)))
// TODO: BUG482880 Fix this initialization to lazy initialization.
, m_code(Platform::current()->domCodeStringFromEnum(key.domCode))
, m_key(Platform::current()->domKeyStringFromEnum(key.domKey))
, m_location(keyLocationCode(key))
{
initLocationModifiers(m_location);
}
KeyboardEvent::KeyboardEvent(const AtomicString& eventType, const KeyboardEventInit& initializer)
: UIEventWithKeyState(eventType, initializer)
, m_code(initializer.code())
, m_key(initializer.key())
, m_location(initializer.location())
{
if (initializer.repeat())
m_modifiers |= PlatformEvent::IsAutoRepeat;
initLocationModifiers(initializer.location());
}
KeyboardEvent::KeyboardEvent(const AtomicString& eventType, bool canBubble, bool cancelable, AbstractView* view,
const String& code, const String& key, unsigned location, PlatformEvent::Modifiers modifiers,
double plaformTimeStamp)
: UIEventWithKeyState(eventType, canBubble, cancelable, view, 0, modifiers, plaformTimeStamp, InputDeviceCapabilities::doesntFireTouchEventsSourceCapabilities())
, m_code(code)
, m_key(key)
, m_location(location)
{
initLocationModifiers(location);
}
KeyboardEvent::~KeyboardEvent()
{
}
void KeyboardEvent::initKeyboardEvent(ScriptState* scriptState, const AtomicString& type, bool canBubble, bool cancelable, AbstractView* view,
const String& keyIdentifier, unsigned location, bool ctrlKey, bool altKey, bool shiftKey, bool metaKey)
{
if (isBeingDispatched())
return;
if (scriptState->world().isIsolatedWorld())
UIEventWithKeyState::didCreateEventInIsolatedWorld(ctrlKey, altKey, shiftKey, metaKey);
initUIEvent(type, canBubble, cancelable, view, 0);
m_location = location;
initModifiers(ctrlKey, altKey, shiftKey, metaKey);
initLocationModifiers(location);
}
int KeyboardEvent::keyCode() const
{
// IE: virtual key code for keyup/keydown, character code for keypress
// Firefox: virtual key code for keyup/keydown, zero for keypress
// We match IE.
if (!m_keyEvent)
return 0;
#if OS(ANDROID)
// FIXME: Check to see if this applies to other OS.
// If the key event belongs to IME composition then propagate to JS.
if (m_keyEvent->nativeKeyCode == 0xE5) // VKEY_PROCESSKEY
return m_keyEvent->nativeKeyCode;
#endif
if (type() == EventTypeNames::keydown || type() == EventTypeNames::keyup)
return m_keyEvent->windowsKeyCode;
return charCode();
}
int KeyboardEvent::charCode() const
{
// IE: not supported
// Firefox: 0 for keydown/keyup events, character code for keypress
// We match Firefox
if (!m_keyEvent || (type() != EventTypeNames::keypress))
return 0;
return m_keyEvent->text[0];
}
const AtomicString& KeyboardEvent::interfaceName() const
{
return EventNames::KeyboardEvent;
}
bool KeyboardEvent::isKeyboardEvent() const
{
return true;
}
int KeyboardEvent::which() const
{
// Netscape's "which" returns a virtual key code for keydown and keyup, and a character code for keypress.
// That's exactly what IE's "keyCode" returns. So they are the same for keyboard events.
return keyCode();
}
void KeyboardEvent::initLocationModifiers(unsigned location)
{
switch (location) {
case KeyboardEvent::kDomKeyLocationNumpad:
m_modifiers |= PlatformEvent::IsKeyPad;
break;
case KeyboardEvent::kDomKeyLocationLeft:
m_modifiers |= PlatformEvent::IsLeft;
break;
case KeyboardEvent::kDomKeyLocationRight:
m_modifiers |= PlatformEvent::IsRight;
break;
}
}
DEFINE_TRACE(KeyboardEvent)
{
UIEventWithKeyState::trace(visitor);
}
} // namespace blink
| [
"bino.zh@gmail.com"
] | bino.zh@gmail.com |
62116b593a5ab11f4af26892e342fad6c0e42dab | 22641cf13e595060a9e1849829952a90ba4b82ea | /MushroomSpawner.h | ce1d2b9d1658054888ccc22742f38f821d00c121 | [] | no_license | nkowales/FundComp2Project | ca48f852686a225b36f11fc51d2b9da74c58cc7c | ea7d1104b4d5aa78351ed952aa51c04b095ad297 | refs/heads/master | 2020-05-16T00:37:21.429617 | 2015-04-30T02:36:13 | 2015-04-30T02:36:13 | 30,984,299 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 665 | h | /*
* MushrooomSpawner.h
*
* Created on: Apr 29, 2015
* Author: naiello
*/
#ifndef MUSHROOMSPAWNER_H_
#define MUSHROOMSPAWNER_H_
#include "WorldObject.h"
#include "HealthMushroom.h"
#define MSPAWN_SPEED 100
class MushroomSpawner : public WorldObject
{
public:
MushroomSpawner(Uint32);
void init(ContentManager*);
void update(Uint32);
bool canCollideWith(const WorldObject*);
void handleCollision(WorldObject*, const SDL_Rect&);
WorldInput resolveInput(string);
void spawn();
void enable(WorldObject* = NULL, string = "");
private:
bool enabled = false;
double timer = 0.;
double spawnInterval = 15.;
};
#endif /* MUSHROOMSPAWNER_H_ */
| [
"naiello@nd.edu"
] | naiello@nd.edu |
744314d79dd303587a72122ae62612f697846687 | 157fd7fe5e541c8ef7559b212078eb7a6dbf51c6 | /TRiAS/Framework/LPict42/pictinlc.cpp | 4e8685221fd80c69514f92eff342b1eb42e67191 | [] | no_license | 15831944/TRiAS | d2bab6fd129a86fc2f06f2103d8bcd08237c49af | 840946b85dcefb34efc219446240e21f51d2c60d | refs/heads/master | 2020-09-05T05:56:39.624150 | 2012-11-11T02:24:49 | 2012-11-11T02:24:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 682 | cpp | #include "stdafx.h"
#include "LPictImpl.h"
#ifdef LAFX_PICT_SEG
#pragma code_seg(LAFX_PICT_SEG)
#endif
/////////////////////////////////////////////////////////////////////////////
#ifdef _DEBUG
#undef THIS_FILE
static char BASED_CODE THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
#define new DEBUG_NEW
#ifndef _AFX_ENABLE_INLINES // _DEBUG is defined
#ifdef AFX_DBG1_SEG
#pragma code_seg(AFX_DBG1_SEG)
#endif
static char BASED_CODE _szAfxInl[] = __FILE__;
#undef THIS_FILE
#define THIS_FILE _szAfxInl
#define _AFX_INLINE
#include "lpict/PictCod.inl"
#endif //!_AFX_ENABLE_INLINES
| [
"Windows Live ID\\hkaiser@cct.lsu.edu"
] | Windows Live ID\hkaiser@cct.lsu.edu |
0abd8118bd63240512bc970cc21e0dc812df3880 | 1a29e3fc23318be40f27339a749bbc3bdc59c0c3 | /codeforces/gym/102021/j.cpp | 6bc53c4ff11306abd16f672095ddf0b818318398 | [] | no_license | wdzeng/cp-solutions | 6c2ac554f6d291774929bc6ad612c4c2e3966c9f | 8d39fcbda812a1db7e03988654cd20042cf4f854 | refs/heads/master | 2023-03-23T17:23:08.809526 | 2020-12-05T00:29:21 | 2020-12-05T00:29:21 | 177,706,525 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,043 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<double, double> pdd;
const double PI = acos(-1);
#define x first
#define y second
#define iter(c) c.begin(), c.end()
#define ms(a) memset(a, 0, sizeof(a))
#define mss(a) memset(a, -1, sizeof(a))
#define mp(e, f) make_pair(e, f)
inline void foul() {
cout << "impossible\n";
exit(0);
}
struct puzzle {
const int index;
int top, left, bottom, right;
puzzle *nextline = NULL, *next = NULL;
puzzle(int i, int t, int l, int b, int r) : index(i), top(t), left(l), bottom(b), right(r) {}
inline void rotate() {
int tmp = top;
top = right;
right = bottom;
bottom = left;
left = tmp;
}
inline void concat_right(puzzle* pz) {
while (pz->left != right) pz->rotate();
next = pz;
}
inline void concat_bottom(puzzle* pz) {
while (pz->top != bottom) pz->rotate();
nextline = pz;
}
};
const int maxn = 3e5 + 10;
bitset<maxn> vis;
vector<puzzle*> puzzles;
vector<pii> edges;
int N, R = 0, C;
puzzle* root = NULL;
inline void add_edge(int e, int i) {
if (e == 0) return;
if (e >= edges.size()) foul();
(edges[e].x == -1 ? edges[e].x : edges[e].y) = i;
}
void set_root_if_valid(puzzle* pz) {
for (int j = 0; j < 3; j++) {
if (pz->left == 0 && pz->top == 0) {
root = pz;
vis[pz->index] = 1;
break;
}
pz->rotate();
}
}
void get_input() {
cin >> N;
edges.assign(N * 2, {-1, -1});
for (int i = 0; i < N; i++) {
int a, b, c, d;
cin >> a >> b >> c >> d;
puzzle* pz = new puzzle(i, a, b, c, d);
add_edge(a, i);
add_edge(b, i);
add_edge(c, i);
add_edge(d, i);
puzzles.push_back(pz);
if (root == NULL) set_root_if_valid(pz);
}
}
void assemble_puzzles() {
auto linkright = [&](puzzle* src) -> puzzle* {
int e = src->right;
if (!e) return NULL;
auto& e2 = edges[e];
if (vis[e2.x] && vis[e2.y]) foul();
int v = vis[e2.x] ? e2.y : e2.x;
vis[v] = 1;
src->concat_right(puzzles[v]);
return src->next;
};
auto linkbottom = [&](puzzle* src) -> puzzle* {
int e = src->bottom;
if (!e) return NULL;
auto& e2 = edges[e];
if (vis[e2.x] && vis[e2.y]) foul();
int v = vis[e2.x] ? e2.y : e2.x;
vis[v] = 1;
src->concat_bottom(puzzles[v]);
return src->nextline;
};
auto topleft = root;
while (topleft) {
if (topleft->left != 0) foul();
R++;
auto bottomright = topleft;
int counter = 1;
while (bottomright = linkright(bottomright)) {
if (topleft == root && bottomright->top != 0) foul();
counter++;
}
if (topleft == root) C = counter;
if (C != counter) foul();
topleft = linkbottom(topleft);
}
if (R * C != N) foul();
}
void check_edges() {
puzzle* upper = root;
puzzle* lower;
while (upper) {
lower = upper->nextline;
puzzle* r1 = upper;
puzzle* r2 = lower;
while (r1) {
if (r2) {
if (r1->bottom == 0) foul();
if (r1->bottom != r2->top) foul();
r2 = r2->next;
} //
else {
if (r1->bottom != 0) foul();
}
r1 = r1->next;
}
upper = lower;
}
}
void print_puzzles() {
cout << R << ' ' << C << '\n';
auto topleft = root;
while (topleft) {
auto bottomright = topleft;
while (bottomright) {
cout << bottomright->index + 1 << ' ';
bottomright = bottomright->next;
}
cout << '\n';
topleft = topleft->nextline;
}
}
int main() {
cin.tie(0), ios::sync_with_stdio(0);
get_input();
assemble_puzzles();
check_edges();
print_puzzles();
return 0;
} | [
"hyperbola.cs07@gmail.com"
] | hyperbola.cs07@gmail.com |
3c87077334db1cd165fcebda4119b1ab9a5cecee | 5ae928266943657b0734e377c165f82edb36a52c | /src/Config/ConfigDataParser.h | a7647ff2b7f887e60964f99f35c19bf7a698fa5b | [] | no_license | jmatta1/ORCHIDReader | 47e28de753f4cb855772481cc0000bbc9ea5adc7 | c3430439a5942dff89d49444ed60138717d3b575 | refs/heads/master | 2021-01-19T11:49:22.077658 | 2018-03-02T16:14:11 | 2018-03-02T16:14:11 | 80,251,124 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,050 | h | /***************************************************************************//**
********************************************************************************
**
** @file ConfigDataParser.h
** @author James Till Matta
** @date 21 Jan, 2017
** @brief
**
** @copyright Copyright (C) 2016 James Till Matta
**
** 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.
**
** @details holds the grammar necessary to parse the first level input file
**
********************************************************************************
*******************************************************************************/
#ifndef ORCHIDREADER_SRC_CONFIG_CONFIGDATAPARSER_H
#define ORCHIDREADER_SRC_CONFIG_CONFIGDATAPARSER_H
// includes for C system headers
// includes for C++ system headers
#include<iostream>
// includes from other libraries
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>
#include <boost/spirit/include/phoenix_object.hpp>
#include <boost/phoenix/bind/bind_member_function.hpp>
// includes from ORCHIDReader
#include"ConfigData.h"
#include"UtilityParsers.h"
namespace InputParser
{
namespace Parsing
{
namespace qi = boost::spirit::qi;
// the main gammar
template <typename Iterator>
struct ConfigDataGrammar : qi::grammar<Iterator>
{
public:
ConfigDataGrammar(ConfigData* cd) : ConfigDataGrammar::base_type(startRule), ptr(cd)
{
namespace phoenix = boost::phoenix;
using qi::skip;
using qi::blank;
using qi::lexeme;
using qi::float_;
using qi::int_;
using Utility::eol_;
using Utility::boolSymbols_;
using qi::fail;
using qi::on_error;
using Utility::separator;
//define the rules to parse the parameters
listFilePath = (lexeme["ListFilePath"] >> '=' > quotedString [phoenix::bind(&ConfigData::listFilePathSet, ptr, qi::_1)] > separator);
rootFilePath = (lexeme["RootFilePath"] >> '=' > quotedString [phoenix::bind(&ConfigData::rootFilePathSet, ptr, qi::_1)] > separator);
arrayDataPath = (lexeme["ArrayDataPath"] >> '=' > quotedString [phoenix::bind(&ConfigData::arrayDataPathSet, ptr, qi::_1)] > separator);
runCsvPath = (lexeme["RunCsvPath"] >> '=' > quotedString [phoenix::bind(&ConfigData::runCsvPathSet, ptr, qi::_1)] > separator);
detMetaDataPath = (lexeme["DetMetaDataPath"] >> '=' > quotedString [phoenix::bind(&ConfigData::detMetaDataPathSet, ptr, qi::_1)] > separator);
batchMetaDataPath = (lexeme["BatchMetaDataPath"] >> '=' > quotedString [phoenix::bind(&ConfigData::batchMetaDataPathSet, ptr, qi::_1)] > separator);
histIntegrationTime = (lexeme["HistIntegrationTime"] >> '=' > float_ [phoenix::bind(&ConfigData::histIntegrationTimeSet, ptr, qi::_1)] > separator);
arrayXPos = (lexeme["ArrayXPosition"] >> '=' > float_ [phoenix::bind(&ConfigData::arrayXPosSet, ptr, qi::_1)] > separator);
arrayYPos = (lexeme["ArrayYPosition"] >> '=' > float_ [phoenix::bind(&ConfigData::arrayYPosSet, ptr, qi::_1)] > separator);
procFirstBuff = (lexeme["ProcessFirstBuffer"] >> '=' > boolSymbols_ [phoenix::bind(&ConfigData::processFirstBufferSet, ptr, qi::_1)] > separator);
genRootTree = (lexeme["GenerateRootTree"] >> '=' > boolSymbols_ [phoenix::bind(&ConfigData::generateRootTreeSet, ptr, qi::_1)] > separator);
rootTreeFilePath = (lexeme["RootTreeFilePath"] >> '=' > quotedString [phoenix::bind(&ConfigData::rootTreeFilePathSet, ptr, qi::_1)] > separator);
bufferLength = (lexeme["BufferLength"] >> '=' > '[' >> int_ [phoenix::bind(&ConfigData::bufferLengthAdd, ptr, qi::_1)] >> +(',' >> int_ [phoenix::bind(&ConfigData::bufferLengthAdd, ptr, qi::_1)]) >> ']' > separator);
// define the start rule which holds the whole monstrosity and set the rule to skip blanks
// if we skipped spaces we could not parse newlines as separators
startRule = skip(blank) [configDataRule];
configDataRule = *eol_ >> lexeme["[StartConfig]"] >> *eol_
> (
listFilePath ^ histIntegrationTime ^ arrayDataPath ^
arrayXPos ^ arrayYPos ^ rootFilePath ^ runCsvPath ^
detMetaDataPath ^ batchMetaDataPath ^ procFirstBuff ^
genRootTree ^ rootTreeFilePath ^ bufferLength
) > lexeme["[EndConfig]"];
on_error<fail>(startRule,
std::cout << phoenix::val("Error! Expecting ")
<< qi::_4 // what failed?
<< phoenix::val(" here: \n\"")
<< phoenix::construct<std::string>(qi::_3, qi::_2) // iterators to error-pos, end
<< phoenix::val("\"")
<< std::endl);
}
private:
//base rules for the file
qi::rule<Iterator> startRule;
qi::rule<Iterator, qi::blank_type> configDataRule;
// special sub grammars
Utility::QuotedString<Iterator> quotedString;
// parameters
qi::rule<Iterator, qi::blank_type> listFilePath, histIntegrationTime;
qi::rule<Iterator, qi::blank_type> arrayDataPath, arrayXPos;
qi::rule<Iterator, qi::blank_type> arrayYPos, rootFilePath;
qi::rule<Iterator, qi::blank_type> runCsvPath, detMetaDataPath;
qi::rule<Iterator, qi::blank_type> batchMetaDataPath, procFirstBuff;
qi::rule<Iterator, qi::blank_type> genRootTree, rootTreeFilePath;
qi::rule<Iterator, qi::blank_type> bufferLength;
// hold the pointer that we are going to bind to
ConfigData* ptr;
};
}
}
#endif //ORCHIDREADER_SRC_CONFIG_CONFIGDATAPARSER_H
| [
"jamesmatta@gmail.com"
] | jamesmatta@gmail.com |
e0d9f27c9916c1e463b3996300d49e45d298ccea | 5d83739af703fb400857cecc69aadaf02e07f8d1 | /Archive2/67/9e06c1d7609ea2/main.cpp | d84f86a9b4fd674ca3b421d159be980bae2ca582 | [] | no_license | WhiZTiM/coliru | 3a6c4c0bdac566d1aa1c21818118ba70479b0f40 | 2c72c048846c082f943e6c7f9fa8d94aee76979f | refs/heads/master | 2021-01-01T05:10:33.812560 | 2015-08-24T19:09:22 | 2015-08-24T19:09:22 | 56,789,706 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 176 | cpp | #include <iostream>
int main()
{
const char * UserName = "Vasia";
printf("C String %s can be located by pointer %p", UserName, UserName);
} | [
"francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df"
] | francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df |
6fac978491b24aa2336915bffa1b2d7b8911ea1c | 005339a7ad587359b9fbf657b61afa5364741c71 | /src/taskevad.cpp | 08a2b4d439ca6f910666af561479f9c597aa9c69 | [
"MIT"
] | permissive | taskeva/Taskeva-core | f81bb26e18b87b87ccc780ab6207d6a6941f254f | d88a5f8983617bc7a8e179e7187818be1c5e92f3 | refs/heads/master | 2020-05-07T18:56:38.113460 | 2019-04-11T12:42:33 | 2019-04-11T12:42:33 | 179,446,988 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,074 | 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 PIVX Developers
// Copyright (c) 2018-2019 The Taskeva Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "clientversion.h"
#include "init.h"
#include "main.h"
#include "masternodeconfig.h"
#include "noui.h"
#include "rpcserver.h"
#include "ui_interface.h"
#include "util.h"
#include <boost/algorithm/string/predicate.hpp>
#include <boost/filesystem.hpp>
#include <boost/thread.hpp>
/* Introduction text for doxygen: */
/*! \mainpage Developer documentation
*
* \section intro_sec Introduction
*
* This is the developer documentation of the reference client for an experimental new digital currency called Taskeva (http://www.taskeva.io),
* which enables instant payments to anyone, anywhere in the world. Taskeva uses peer-to-peer technology to operate
* with no central authority: managing transactions and issuing money are carried out collectively by the network.
*
* The software is a community-driven open source project, released under the MIT license.
*
* \section Navigation
* Use the buttons <code>Namespaces</code>, <code>Classes</code> or <code>Files</code> at the top of the page to start navigating the code.
*/
static bool fDaemon;
void DetectShutdownThread(boost::thread_group* threadGroup)
{
bool fShutdown = ShutdownRequested();
// Tell the main threads to shutdown.
while (!fShutdown) {
MilliSleep(200);
fShutdown = ShutdownRequested();
}
if (threadGroup) {
threadGroup->interrupt_all();
threadGroup->join_all();
}
}
//////////////////////////////////////////////////////////////////////////////
//
// Start
//
bool AppInit(int argc, char* argv[])
{
boost::thread_group threadGroup;
boost::thread* detectShutdownThread = NULL;
bool fRet = false;
//
// Parameters
//
// If Qt is used, parameters/taskeva.conf are parsed in qt/taskeva.cpp's main()
ParseParameters(argc, argv);
// Process help and version before taking care about datadir
if (mapArgs.count("-?") || mapArgs.count("-help") || mapArgs.count("-version")) {
std::string strUsage = _("Taskeva Core Daemon") + " " + _("version") + " " + FormatFullVersion() + "\n";
if (mapArgs.count("-version")) {
strUsage += LicenseInfo();
} else {
strUsage += "\n" + _("Usage:") + "\n" +
" taskevad [options] " + _("Start Taskeva Core Daemon") + "\n";
strUsage += "\n" + HelpMessage(HMM_BITCOIND);
}
fprintf(stdout, "%s", strUsage.c_str());
return false;
}
try {
if (!boost::filesystem::is_directory(GetDataDir(false))) {
fprintf(stderr, "Error: Specified data directory \"%s\" does not exist.\n", mapArgs["-datadir"].c_str());
return false;
}
try {
ReadConfigFile(mapArgs, mapMultiArgs);
} catch (std::exception& e) {
fprintf(stderr, "Error reading configuration file: %s\n", e.what());
return false;
}
// Check for -testnet or -regtest parameter (Params() calls are only valid after this clause)
if (!SelectParamsFromCommandLine()) {
fprintf(stderr, "Error: Invalid combination of -regtest and -testnet.\n");
return false;
}
// parse masternode.conf
std::string strErr;
if (!masternodeConfig.read(strErr)) {
fprintf(stderr, "Error reading masternode configuration file: %s\n", strErr.c_str());
return false;
}
// Command-line RPC
bool fCommandLine = false;
for (int i = 1; i < argc; i++)
if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], "taskeva:"))
fCommandLine = true;
if (fCommandLine) {
fprintf(stderr, "Error: There is no RPC client functionality in taskevad anymore. Use the taskeva-cli utility instead.\n");
exit(1);
}
#ifndef WIN32
fDaemon = GetBoolArg("-daemon", false);
if (fDaemon) {
fprintf(stdout, "Taskeva server starting\n");
// Daemonize
pid_t pid = fork();
if (pid < 0) {
fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
return false;
}
if (pid > 0) // Parent process, pid is child process id
{
return true;
}
// Child process falls through to rest of initialization
pid_t sid = setsid();
if (sid < 0)
fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
}
#endif
SoftSetBoolArg("-server", true);
detectShutdownThread = new boost::thread(boost::bind(&DetectShutdownThread, &threadGroup));
fRet = AppInit2(threadGroup);
} catch (std::exception& e) {
PrintExceptionContinue(&e, "AppInit()");
} catch (...) {
PrintExceptionContinue(NULL, "AppInit()");
}
if (!fRet) {
if (detectShutdownThread)
detectShutdownThread->interrupt();
threadGroup.interrupt_all();
// threadGroup.join_all(); was left out intentionally here, because we didn't re-test all of
// the startup-failure cases to make sure they don't result in a hang due to some
// thread-blocking-waiting-for-another-thread-during-startup case
}
if (detectShutdownThread) {
detectShutdownThread->join();
delete detectShutdownThread;
detectShutdownThread = NULL;
}
Shutdown();
return fRet;
}
int main(int argc, char* argv[])
{
SetupEnvironment();
// Connect taskevad signal handlers
noui_connect();
return (AppInit(argc, argv) ? 0 : 1);
}
| [
"xnkennyh@mail.com"
] | xnkennyh@mail.com |
3e4c083a8d7faa96bfa58d8f01904634588f3841 | 2fc6ab0fdcd34c4c8516f61638bba16bf4045b0a | /player/openBookGenerator/tableGenerator/gentable.cpp | 02166f34d5389d87627c11123118ead3c92ec119 | [] | no_license | FoteiniAthina/Leiserchess---MIT-6.172-Fall16-Final-Project | 7c534f4f79a155326584b6e2dde681a4c67f609d | e32f2e9db5155f7de1a0b2b4ec7f72f4e0388f86 | refs/heads/master | 2020-08-13T02:55:08.296021 | 2016-12-22T06:42:45 | 2016-12-22T06:42:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,432 | cpp | #include <cstdlib>
#include <cstdio>
#include <iostream>
#include <cmath>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#include <cstring>
#include <cassert>
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
#define SIZE(x) (int((x).size()))
#define rep(i,l,r) for (int i=(l); i<=(r); i++)
#define repd(i,r,l) for (int i=(r); i>=(l); i--)
#define rept(i,c) for (__typeof((c).begin()) i=(c).begin(); i!=(c).end(); i++)
#ifndef ONLINE_JUDGE
#define debug(x) { cerr<<#x<<" = "<<(x)<<endl; }
#else
#define debug(x) {}
#endif
char buf1[10000], buf2[10000];
struct node
{
string result;
map<string, node*> child;
node() {}
};
node *root;
void insert(string s, string val)
{
string t="";
int i=0;
node *cur=root;
while (i<s.length())
{
while (s[i]!=' ') t+=s[i], i++;
if (!cur->child.count(t))
cur->child[t]=new node();
cur=cur->child[t];
t="";
i++;
}
cur->result=val;
}
string moves[1000000], result[1000000];
int leftc[1000000], rightc[1000000];
node *q[1000000];
void lemon()
{
root=new node();
root->result="h4g5";
int cnt=0;
while (1)
{
if (!gets(buf1)) break;
if (!gets(buf2)) break;
string s1=buf1;
assert(s1[s1.length()-1]!=' ');
s1=s1+" ";
string s2=buf2;
//assert(3<=s2.length() && s2.length()<=4);
insert(s1,s2);
cnt++;
}
fprintf(stderr,"%d states processed\n",cnt);
int head=1, tail=2;
q[head]=root; moves[head]="";
while (head<tail)
{
node *cur=q[head];
leftc[head]=tail;
rept(it,cur->child)
{
q[tail]=it->second;
moves[tail]=it->first;
tail++;
}
rightc[head]=tail;
head++;
}
printf("const char* const moves[] = {\n ");
rep(i,1,tail-1)
{
printf("\"%s\"",moves[i].c_str());
if (i<tail-1) printf(",");
if (i%10==0) printf("\n ");
}
printf("\n};\n\n");
printf("const int childrange[][2] = {\n ");
int maxb=0;
rep(i,1,tail-1)
{
printf("{%d,%d}",leftc[i]-1,rightc[i]-1);
if (rightc[i]-leftc[i]>maxb) maxb=rightc[i]-leftc[i];
if (i<tail-1) printf(",");
if (i%5==0) printf("\n ");
}
printf("\n};\n\n");
printf("const char* const results[] = {\n ");
rep(i,1,tail-1)
{
printf("\"%s\"",q[i]->result.c_str());
if (i<tail-1) printf(",");
if (i%10==0) printf("\n ");
}
printf("\n};\n\n");
fprintf(stderr,"max branch = %d\n",maxb);
}
int main()
{
ios::sync_with_stdio(true);
#ifndef ONLINE_JUDGE
freopen("D.txt","r",stdin);
#endif
lemon();
return 0;
}
| [
"haoranxu510@gmail.com"
] | haoranxu510@gmail.com |
ab7799b0ac23261cd567425d3e9f8f01768fe963 | 4beae9d121cced388d2295d1cbc436b80b4a25f2 | /src/test/test_mocha.h | 933bb810c9db23d7f2af2502248bf3a4cd4091d4 | [
"MIT"
] | permissive | volbil/newmocha | 8e5e5e3cbb51d05a330e7ad05d3bed4a3632ded6 | 809c90fbb6bc72364af2ed0ba6f97abac9d23e22 | refs/heads/master | 2022-06-11T09:37:03.595755 | 2020-04-27T02:35:06 | 2020-04-27T02:35:06 | 260,594,664 | 0 | 0 | null | 2020-05-02T01:50:46 | 2020-05-02T01:50:45 | null | UTF-8 | C++ | false | false | 4,531 | h | // Copyright (c) 2015 The Bitcoin Core developers
// Copyright (c) 2014-2019 The Mocha Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_TEST_TEST_DASH_H
#define BITCOIN_TEST_TEST_DASH_H
#include "chainparamsbase.h"
#include "fs.h"
#include "key.h"
#include "pubkey.h"
#include "random.h"
#include "scheduler.h"
#include "txdb.h"
#include "txmempool.h"
#include <boost/thread.hpp>
extern uint256 insecure_rand_seed;
extern FastRandomContext insecure_rand_ctx;
static inline void SeedInsecureRand(bool fDeterministic = false)
{
if (fDeterministic) {
insecure_rand_seed = uint256();
} else {
insecure_rand_seed = GetRandHash();
}
insecure_rand_ctx = FastRandomContext(insecure_rand_seed);
}
static inline uint32_t InsecureRand32() { return insecure_rand_ctx.rand32(); }
static inline uint256 InsecureRand256() { return insecure_rand_ctx.rand256(); }
static inline uint64_t InsecureRandBits(int bits) { return insecure_rand_ctx.randbits(bits); }
static inline uint64_t InsecureRandRange(uint64_t range) { return insecure_rand_ctx.randrange(range); }
static inline bool InsecureRandBool() { return insecure_rand_ctx.randbool(); }
/** Basic testing setup.
* This just configures logging and chain parameters.
*/
struct BasicTestingSetup {
ECCVerifyHandle globalVerifyHandle;
BasicTestingSetup(const std::string& chainName = CBaseChainParams::MAIN);
~BasicTestingSetup();
};
/** Testing setup that configures a complete environment.
* Included are data directory, coins database, script check threads setup.
*/
class CConnman;
class CNode;
struct CConnmanTest {
static void AddNode(CNode& node);
static void ClearNodes();
};
class PeerLogicValidation;
struct TestingSetup: public BasicTestingSetup {
CCoinsViewDB *pcoinsdbview;
fs::path pathTemp;
boost::thread_group threadGroup;
CConnman* connman;
CScheduler scheduler;
std::unique_ptr<PeerLogicValidation> peerLogic;
TestingSetup(const std::string& chainName = CBaseChainParams::MAIN);
~TestingSetup();
};
class CBlock;
struct CMutableTransaction;
class CScript;
struct TestChainSetup : public TestingSetup
{
TestChainSetup(int blockCount);
~TestChainSetup();
// Create a new block with just given transactions, coinbase paying to
// scriptPubKey, and try to add it to the current chain.
CBlock CreateAndProcessBlock(const std::vector<CMutableTransaction>& txns,
const CScript& scriptPubKey);
CBlock CreateAndProcessBlock(const std::vector<CMutableTransaction>& txns,
const CKey& scriptKey);
CBlock CreateBlock(const std::vector<CMutableTransaction>& txns,
const CScript& scriptPubKey);
CBlock CreateBlock(const std::vector<CMutableTransaction>& txns,
const CKey& scriptKey);
std::vector<CTransaction> coinbaseTxns; // For convenience, coinbase transactions
CKey coinbaseKey; // private/public key needed to spend coinbase transactions
};
//
// Testing fixture that pre-creates a
// 100-block REGTEST-mode block chain
//
struct TestChain100Setup : public TestChainSetup {
TestChain100Setup() : TestChainSetup(100) {}
};
struct TestChainDIP3Setup : public TestChainSetup
{
TestChainDIP3Setup() : TestChainSetup(431) {}
};
struct TestChainDIP3BeforeActivationSetup : public TestChainSetup
{
TestChainDIP3BeforeActivationSetup() : TestChainSetup(430) {}
};
class CTxMemPoolEntry;
struct TestMemPoolEntryHelper
{
// Default values
CAmount nFee;
int64_t nTime;
unsigned int nHeight;
bool spendsCoinbase;
unsigned int sigOpCount;
LockPoints lp;
TestMemPoolEntryHelper() :
nFee(0), nTime(0), nHeight(1),
spendsCoinbase(false), sigOpCount(4) { }
CTxMemPoolEntry FromTx(const CMutableTransaction &tx);
CTxMemPoolEntry FromTx(const CTransaction &tx);
// Change the default value
TestMemPoolEntryHelper &Fee(CAmount _fee) { nFee = _fee; return *this; }
TestMemPoolEntryHelper &Time(int64_t _time) { nTime = _time; return *this; }
TestMemPoolEntryHelper &Height(unsigned int _height) { nHeight = _height; return *this; }
TestMemPoolEntryHelper &SpendsCoinbase(bool _flag) { spendsCoinbase = _flag; return *this; }
TestMemPoolEntryHelper &SigOps(unsigned int _sigops) { sigOpCount = _sigops; return *this; }
};
#endif
| [
"whoffman1031@gmail.com"
] | whoffman1031@gmail.com |
97bef332a39ede576ecfb6cf6cc8382d71be668b | 69f8736d82d85b53282d9e8d750987c4fa587ed8 | /mainwindow.h | 1756b3ceb08e00123513c2189e10b3e904ec78e9 | [] | no_license | dridk/sampleIDViewer | 0673304ccf5d26f8ca82ca283fac125945a4baf8 | 46d9b173539da6c01f4984cf79d1337a2e43fcdc | refs/heads/master | 2021-01-16T21:23:27.926793 | 2015-07-10T15:00:00 | 2015-07-10T15:00:00 | 38,535,818 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 895 | h | #ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include "sampleidlistwidget.h"
#include "fsaplot.h"
#include "fsainfowidget.h"
#include "sampleidinfowidget.h"
#include "filebrowserwidget.h"
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
public slots:
void open();
void setStatus(const QString& message);
protected:
void createToolBar(const QList<QAction*>& actionsList);
private:
Ui::MainWindow *ui;
SampleIDListWidget * mListWidget;
FsaPlot * mPlot;
QTabWidget * mTabWidget;
QSplitter * mSplitter;
SampleIDInfoWidget * mSampleIdInfoWidget;
FsaInfoWidget * mFsaInfoWidget;
FileBrowserWidget * mBrowserWidget;
QLabel * mAnimLabel;
};
#endif // MAINWINDOW_H
| [
"sacha@labsquare.org"
] | sacha@labsquare.org |
1004b63ada7fa3a1789bd709b3ef9eee444c007f | 6ad4557321bf8e3fddb06501382b8af02b92e7e4 | /ARA/reconstruction3.cpp | aa7de6d17dfbed9d83de5651849eebd88e8a1388 | [] | no_license | RomLei/EC-RSF | e21ba198774f4c518f579b5313c40adb45c091a3 | aca0e5dc4818c23a93ab1d81bef293b0a5d45c7d | refs/heads/master | 2020-07-11T08:24:36.489384 | 2019-08-26T14:09:08 | 2019-08-26T14:14:34 | 204,488,970 | 1 | 1 | null | null | null | null | GB18030 | C++ | false | false | 296 | cpp | #include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<iostream>
#include<iomanip>
#include<vector>
#include"ARA.h"
using namespace std;
bool reconstruction3(vector<node> &rnode, vector<vector<int>> &G, vector<vector<int>> &Gbackup)//对剩余的节点进行完全重建
{
return true;
} | [
"ronglei1994@126.com"
] | ronglei1994@126.com |
97a5dd6652370e48639bc89bf66800d45e2e3c5a | 37d905bbb10ea00eaadd47dc41989461fa213aea | /Virtual_Memory_Management/TLB.cpp | 499871fcdbcd8092866e2b6c4fbb4969269db86e | [] | no_license | cmarch314/Virtual_Memory | d36ebe6d1a8792d50805643a0c86d0afe484ad17 | 8ab078898d0cdfca21fd73869030588f6e45a93c | refs/heads/master | 2021-01-10T13:10:42.650548 | 2016-03-16T02:20:11 | 2016-03-16T02:20:11 | 53,989,228 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,162 | cpp | #include "TLB.h"
TLB::TLB()
{
table = new int*[4];
init();
}
void TLB::init()
{
for (int i = 0; i < 4; i++)
{
table[i] = new int[4];
table[i][0] = -1;
table[i][1] = -1;
table[i][2] = -1;
table[i][3] = -1;
}
}
TLB::~TLB()
{
delete[] table;
}
int TLB::find(int s, int p) // works as pop?
{
for (int i = 0; i < 4; i++)
{
if ((table[i][1] == s) && (table[i][2] == p))
{
return i;
}
}
return -1;
}
int TLB::update(int index, int s, int p, int f)
{
if (index == -1)//miss case
{
for (int i = 0; i < 4; i++)
{
if (table[i][0] == -1)//find empty spot (least latest acessed.)
{
index = i;
break;
}
}
if (index == -1)//if all occupied
{
for (int i = 0; i < 4; i++)
{
if (table[i][0] == 0)//find lowest priority (least latest acessed.)
{
index = i;
break;
}
}
}
table[index][0] = 0;//all shall fall by this index
table[index][1] = s;
table[index][2] = p;
table[index][3] = f;
}
for (int i = 0; i < 4; i++)
{
if (table[i][0] > table[index][0])
{
table[i][0]--;
}
}
table[index][0] = 3;
return index;
}
int TLB::get_f(int index)
{
return table[index][3];
} | [
"cmarch314@gmail.com"
] | cmarch314@gmail.com |
70b13cdc2d2a9e5217cea89f5f4284e0ad894fbf | 4f8bb0eaafafaf5b857824397604538e36f86915 | /课件/计算几何/计算几何_陈海丰/计算几何代码/pku_1389_矩形相交.cpp | ef0069449dd296a17ffe39e671b46587beef9713 | [] | no_license | programmingduo/ACMsteps | c61b622131132e49c0e82ad0007227d125eb5023 | 9c7036a272a5fc0ff6660a263daed8f16c5bfe84 | refs/heads/master | 2020-04-12T05:40:56.194077 | 2018-05-10T03:06:08 | 2018-05-10T03:06:08 | 63,032,134 | 1 | 2 | null | null | null | null | GB18030 | C++ | false | false | 2,188 | cpp | /*
大牛的思想
题目给出 n 个矩形,要求它们的面积并。具体做法是离散化。
先把 2n 个 x 坐标排序去重,然后再把所有水平线段(
要记录是矩形上边还是下边)按 y 坐标排序。
最后对于每一小段区间 (x[i], x[i + 1]) 扫描所有的水平线段,
求出这些水平线段在小区间内覆盖的面积。总的时间复杂度是 O(n^2)。
利用线段树,可以优化到 O(nlogn)。
*/
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#define up 1
#define down -1
typedef struct TSeg
{
double l, r;
double y;
int UpOrDown;
}TSeg;
TSeg seg[4000];
int segn;
double x[4000];
int xn;
int cmp1(const void *a, const void *b)
{
if(*(double *)a < *(double *)b) return -1;
else return 1;
}
int cmp2(const void *a, const void *b)
{
TSeg *c = (TSeg *)a;
TSeg *d = (TSeg *)b;
if(c->y < d->y) return -1;
else return 1;
}
void movex(int t, int &xn)
{
int i;
for(i = t;i <= xn - 1;i++){
x[i] = x[i + 1];
}
xn--;
}
int main()
{
//freopen("in.in", "r", stdin);
//freopen("out.out", "w", stdout);
int n, i, j, cnt;
double x1, y1, x2, y2, ylow, area;
while(1){
scanf("%lf%lf%lf%lf", &x1, &y1, &x2, &y2);
if(x1 == -1 && x2 == -1 && y1 == -1 && y2 == -1) break;
xn = 0;
segn = 0;
while(1){
if(xn != 0) {
scanf("%lf%lf%lf%lf", &x1, &y1, &x2, &y2);
if(x1 == -1 && x2 == -1 && y1 == -1 && y2 == -1) break;
}
x[xn++] = x1;
x[xn++] = x2;
seg[segn].l = x1;
seg[segn].r = x2;
seg[segn].y = y1;
seg[segn++].UpOrDown = down;
seg[segn].l = x1;
seg[segn].r = x2;
seg[segn].y = y2;
seg[segn++].UpOrDown = up;
}
qsort(x, xn, sizeof(x[0]), cmp1);
/*除掉重复的x*/
for(i = 1;i < xn;){
if(x[i] == x[i - 1]) movex(i, xn);
else i++;
}
qsort(seg, segn, sizeof(seg[0]), cmp2);
area = 0.0;
for(i = 0;i < xn - 1;i++){
cnt = 0;
for(j = 0;j < segn;j++){
if(seg[j].l <= x[i] && seg[j].r >= x[i + 1]){
if(cnt == 0) ylow = seg[j].y;
if(seg[j].UpOrDown == down) cnt++;
else cnt--;
if(cnt == 0) area += (x[i + 1] - x[i]) * (seg[j].y - ylow);
}
}
}
printf("%.0lf\n", area);
}
return 0;
}
| [
"wuduotju@163.com"
] | wuduotju@163.com |
d5dbbde70832c05ac77cb0ad6df6708744168394 | 8e8f31a13efeb173bea12c3a4e674cc80a92f20b | /victor/catkin_ws/src/camera/src/listener3.cpp | 9445a580d9529b8093324d198d652c19c1b38aa4 | [] | no_license | emotionrobots/students | a2a7e31cb082de04be4d94c0cc1f852bf7409583 | f4e70117236bccb8b13091c8395348b575cb36e6 | refs/heads/master | 2021-09-27T08:16:13.793474 | 2018-08-05T20:29:10 | 2018-08-05T20:29:10 | 67,504,742 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,231 | cpp | #include <iostream>
#include <ros/ros.h>
#include <sensor_msgs/PointCloud2.h>
#include <pcl_conversions/pcl_conversions.h>
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <fstream>
#define mp make_pair
#define pb push_back
using namespace std;
using namespace pcl;
using namespace sensor_msgs;
using namespace cv;
const int HEIGHT = 480, WIDTH = 640;
Point3d xyz[480][640];
Mat src(HEIGHT, WIDTH, CV_8UC3);
bool hasRead = false;
vector<Point> corners;
bool cmp(const Point& p1, const Point& p2) {
return p1.x == p2.x ? p1.y < p2.y : p1.x < p2.x;
}
void call_back(const sensor_msgs::PointCloud2ConstPtr& cloud) {
pcl::PointCloud<pcl::PointXYZRGB> PointCloudXYZRGB;
pcl::fromROSMsg(*cloud, PointCloudXYZRGB);
int max_i = cloud->height * cloud->width;
for (int i = 0; i < max_i; i++) {
int r = i / cloud->width, c = i % cloud->width;
PointXYZRGB p = PointCloudXYZRGB.points[i];
float z = p.z;
xyz[r][c] = Point3d(p.x, -p.y, p.z);
src.at<Vec3b>(Point(c, r)) = Vec3b(p.b, p.g, p.r);
}
hasRead = true;
}
void read() {
hasRead = false;
while (!hasRead) {
ros::spinOnce();
}
}
void show() {
for (int i = 0; i < corners.size(); i++) {
// cout << '(' << corners[i].first << ", " << corners[i].second << ')' << endl;
circle(src, Point(corners[i].x, corners[i].y), 5, Scalar(0, 0, 255), -1);
}
imshow("show1", src);
}
void compress_lines(vector<Vec2f>& lines) {
vector<double> weights(lines.size(), 1);
for (int i = 0; i < lines.size(); i++) {
double total_r = lines[i][0], total_a = lines[i][1];
for (int j = lines.size() - 1; j > i; j--) {
double diff_a = abs(lines[i][1] - lines[j][1]);
if (abs(lines[i][0] - lines[j][0]) < 50) {
if (diff_a < .2) {
total_r += lines[j][0];
total_a += lines[j][1];
weights[i] += weights[j];
lines.erase(lines.begin() + j);
} else if (diff_a > CV_PI - .2) {
total_r += lines[j][0];
total_a += lines[j][1] > CV_PI / 2 ? lines[j][1] - CV_PI : lines[j][1];
weights[i] += weights[j];
lines.erase(lines.begin() + j);
}
}
}
lines[i][0] = total_r / weights[i];
lines[i][1] = total_a / weights[i];
if (lines[i][1] < 0) lines[i][1] += CV_PI;
}
}
vector<Point> inter(const vector<Vec2f>& lines) {
vector<Point> points;
for (int i = 0; i < lines.size(); i++) {
double r1 = lines[i][0], a1 = lines[i][1];
// cout << r1 << ' ' << a1 << endl;
for (int j = i + 1; j < lines.size(); j++) {
double r2 = lines[j][0], a2 = lines[j][1];
double x = (r1 / sin(a1) - r2 / sin(a2)) / (cos(a1) / sin(a1) - cos(a2) / sin(a2));
double y = (-cos(a1) / sin(a1)) * x + r1 / sin(a1);
if (-1 < x && x < 640 && -1 < y && y < 480 && abs(a1 - a2) > .2 && abs(a1 - a2) < CV_PI - .2) {
points.pb(Point(x, y));
}
}
}
return points;
}
Point3d trans(const Point3d& p, double h, double a, double d) {
double x1 = p.x, y1 = p.y, z1 = p.z;
double x2 = x1, y2 = y1*sin(a) - z1*cos(a) + h, z2 = y1*cos(a) + z1*sin(a);
double x3 = d - z2, y3 = x2, z3 = y2;
return Point3d(x3, y3, z3);
}
vector<Point> compress_points(const vector<Point>& points) {
vector<pair<pair<double, double>, int>> cluster;
for (int i = 0; i < points.size(); i++) {
cluster.pb(mp(mp(points[i].x, points[i].y), 1));
}
while (cluster.size() > 4) {
int i1 = 0, i2 = 1;
pair<double, double> c1 = cluster[0].first, c2 = cluster[1].first;
double dist = hypot(c1.first - c2.first, c1.second - c2.second);
for (int i = 0; i < cluster.size(); i++) {
pair<double, double> c3 = cluster[i].first;
for (int j = i + 1; j < cluster.size(); j++) {
pair<double, double> c4 = cluster[j].first;
double dist2 = hypot(c3.first - c4.first, c3.second - c4.second);
if (dist2 < dist) {
c1 = c3;
c2 = c4;
dist = dist2;
i1 = i;
i2 = j;
}
}
}
double xsum1 = cluster[i1].first.first * cluster[i1].second;
double ysum1 = cluster[i1].first.second * cluster[i1].second;
double xsum2 = cluster[i2].first.first * cluster[i2].second;
double ysum2 = cluster[i2].first.second * cluster[i2].second;
int total = cluster[i1].second + cluster[i2].second;
cluster.erase(cluster.begin() + i2);
cluster.erase(cluster.begin() + i1);
cluster.pb(mp(mp((xsum1 + xsum2) / total, (ysum1 + ysum2) / total), total));
}
vector<Point> points2;
for (int i = 0; i < cluster.size(); i++) {
points2.pb(Point(cvRound(cluster[i].first.first), cluster[i].first.second));
}
return points2;
}
bool get_corners() {
Mat dst, cdst;
Canny(src, dst, 150, 450, 3);
cvtColor(dst, cdst, CV_GRAY2BGR);
// cout << "d1" << endl;
vector<Vec2f> lines;
HoughLines(dst, lines, 1, CV_PI/180, 65, 0, 0 );
// cout << "lines " << lines.size() << endl;
compress_lines(lines);
cout << "lines " << lines.size() << endl;
for (int i = 0; i < lines.size(); i++) {
float rho = lines[i][0], theta = lines[i][1];
Point pt1, pt2;
double a = cos(theta), b = sin(theta);
double x0 = a*rho, y0 = b*rho;
pt1.x = cvRound(x0 + 1000*(-b));
pt1.y = cvRound(y0 + 1000*(a));
pt2.x = cvRound(x0 - 1000*(-b));
pt2.y = cvRound(y0 - 1000*(a));
line(cdst, pt1, pt2, Scalar(0,0,255), 3, CV_AA);
}
if (lines.size() > 100) return false;
/*
23
14
*/
vector<Point> points = inter(lines);
corners = compress_points(points);
sort(corners.begin(), corners.end(), cmp);
for (int i = 0; i < corners.size(); i++) {
Point p = corners[i];
cout << p.x << ' ' << p.y << endl;
cout << xyz[p.y][p.x].x << ' ' << xyz[p.y][p.x].y << ' ' << xyz[p.y][p.x].z << endl;
}
cout << "----------------------------" << endl;
imshow("show1", dst);
if (waitKey(700) != -1) exit(0);
imshow("show1", cdst);
if (waitKey(700) != -1) exit(0);
return true;
}
int main(int argc, char** argv) {
ros::init(argc, argv, "listener");
ros::NodeHandle n;
ros::Rate loop_rate(30);
ros::Subscriber sub;
sub = n.subscribe("/camera/depth_registered/points", 1, call_back);
namedWindow("show1", CV_WINDOW_AUTOSIZE);
//
while (true) {
// cout << 'a' << endl;
// src = imread(argv[1], 0);
// cout << 'b' << endl;
do {
read();
} while (!get_corners());
// cout << 'c' << endl;
show();
// cout << 'd' << endl;
if (waitKey(700) != -1) break;
}
return 0;
}m | [
"larrylisky@gmail.com"
] | larrylisky@gmail.com |
a050f872e308cdf1ee33c8c7ca816320f02be07c | 90af0fa8944c9bcb677178774d4c2c7bfe2b6e79 | /Library/Include/Graphics/Graphics.cpp | f29970971e24e480f86f93bffa9a765b953b216d | [
"MIT"
] | permissive | OiC-SysDev-Game/WonderWolfGirl | 33a5db5e7bde89bb49a90fc32950d66662a6fd52 | 6118d47fea259ec7437d5b9a7c3f967fe2eb4fa0 | refs/heads/main | 2023-07-05T11:23:24.258746 | 2021-07-30T05:41:13 | 2021-07-30T05:41:13 | 381,572,812 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 4,727 | cpp | #include "Graphics.h"
#include "../Common/Common.h"
#include "../Utility/GraphicsUtilities.h"
bool u22::graphics::Graphics::Setup(void) {
if (!::glfwInit()) {
return false;
} // if
::glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE);
::glfwWindowHint(GLFW_SAMPLES, 0);
::glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
::glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 5);
::glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
::glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
::glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE);
// font
if (::FT_Init_FreeType(&_font)) {
return false;
} // if
return true;
}
bool u22::graphics::Graphics::LoadShader(void) {
bool ret = false;
{
auto shader = std::make_shared<u22::graphics::EffectShader>();
ret = shader->Load("../Resource/shader/sprite.vert", "../Resource/shader/sprite.frag");
if (!ret) {
ret = shader->Load("Resource/shader/sprite.vert", "Resource/shader/sprite.frag");
if (!ret) {
return false;
} // if
} // if
_shader_map.emplace(u22::graphics::EffectShaderType::Sprite, shader);
}
{
auto shader = std::make_shared<u22::graphics::EffectShader>();
ret = shader->Load("../Resource/shader/circle.vert", "../Resource/shader/circle.frag");
if (!ret) {
ret = shader->Load("Resource/shader/circle.vert", "Resource/shader/circle.frag");
if (!ret) {
return false;
} // if
} // if
_shader_map.emplace(u22::graphics::EffectShaderType::Circle, shader);
}
{
auto shader = std::make_shared<u22::graphics::EffectShader>();
ret = shader->Load("../Resource/shader/rectangle.vert", "../Resource/shader/rectangle.frag");
if (!ret) {
ret = shader->Load("Resource/shader/rectangle.vert", "Resource/shader/rectangle.frag");
if (!ret) {
return false;
} // if
} // if
_shader_map.emplace(u22::graphics::EffectShaderType::Rectangle, shader);
}
u22::utility::GraphicsUtilities::Setup();
return true;
}
bool u22::graphics::Graphics::ReleaseShader(void) {
for (auto& shader : _shader_map) {
if (!shader.second->Release()) {
return false;
} // if
} // for
_shader_map.clear();
return true;
}
u22::graphics::Graphics::Graphics() :
_initialized(false),
_shader_map(),
_font() {
bool setup = this->Setup();
_ASSERT_EXPR(setup, L"グラフィックスのセットアップでエラーが起きました");
}
u22::graphics::Graphics::~Graphics() {
}
FT_Library u22::graphics::Graphics::GetFontPtr(void) const {
return this->_font;
}
std::shared_ptr<u22::graphics::EffectShader> u22::graphics::Graphics::GetEffectShader(u22::graphics::EffectShaderType type) const {
return this->_shader_map.at(type);
}
void u22::graphics::Graphics::ClearTarget(const u22::math::Vector4F& color, float depth, float stencil) {
// クリア
auto& c = color;
::glClearColor(c.r, c.g, c.b, c.a);
::glClearDepth(depth);
::glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
}
void u22::graphics::Graphics::RenderStart(void) {
// 2d depth stencil = disable
// culling = disable
// デフォルトのフレームバッファに対しての操作
::glDisable(GL_DEPTH);
//::glEnable(GL_DEPTH);
::glDisable(GL_CULL_FACE);
//::glEnable(GL_CULL_FACE);
//::glFrontFace(GL_CCW); // default
//::glCullFace(GL_BACK); // default
::glEnable(GL_BLEND);
::glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}
bool u22::graphics::Graphics::Initialize(const std::shared_ptr<u22::Window>& window) {
_initialized = false;
// OpenGL拡張機能チュートリアル
// https://www.opengl.org/sdk/docs/tutorials/ClockworkCoders/extensions.php
auto error = ::glewInit();
if (error != GLEW_OK) {
//std::cout << "error : " << reinterpret_cast<const char*>(::glewGetErrorString(error)) << "\n";
::glfwTerminate();
return false;
} // if
if (!GLEW_ARB_vertex_program) {
return false;
} // if
if (!this->LoadShader()) {
return false;
} // if
_initialized = true;
return _initialized;
}
bool u22::graphics::Graphics::Release(void) {
u22::utility::GraphicsUtilities::Cleanup();
::FT_Done_FreeType(_font);
_font = nullptr;
if (!this->ReleaseShader()) {
return false;
} // if
if (!_initialized) {
return false;
} // if
::glfwTerminate();
return true;
} | [
"towa.k100@icloud.com"
] | towa.k100@icloud.com |
91f68a3b383a6f6f28dd62bf0a07442cf062890e | 0fc70d8a4494e8e3ac7e41874119a79c5e99e255 | /pthread_handle.h | a68ca938ecefa23e1509b9df50225100e426e2fe | [] | no_license | zrj12345/jpush_server | 420f6b1e6fa4a077e9ae04547ed5954fa7ed32df | 5706fdcbdf8c1ad96dcd36f27cc17f1d50cb2bd7 | refs/heads/master | 2021-01-18T15:08:25.305221 | 2015-12-23T22:51:05 | 2015-12-23T22:51:05 | 48,404,980 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 808 | h | #ifndef _PTHREAD_HANDLE_H_
#define _PTHREAD_HANDLE_H_
#include "files.h"
#include "DbPool.h"
#include "redisclient.h"
#include <pthread.h>
#include <list>
typedef void *(*event_deal)(void *arg);
class pthread_handle{
public:
struct func_arg{
event_deal func_pointer;
void* arg;
};
~pthread_handle();
pthread_handle(int thread_num = 4):max_thread_num(thread_num){};
void pool_event_init(int thread_num);
int thread_run();
int pool_destroy();
int pool_event_add(event_deal func,void *arg);
static void* thread_event(void *arg);
private:
pthread_cond_t queue_ready;
pthread_mutex_t queue_lock;
list<func_arg> event_list;
void *event_arg;
pthread_t *threadid;
int max_thread_num;
bool shutdown;
};
#endif | [
"qzhangrongjie@163.com"
] | qzhangrongjie@163.com |
a2a39e41c3b13e548d5919b5d01430c4002017d9 | 3b74df8a933fbcb3ee3f7a2202aacdc240b939b7 | /libraries/fc/vendor/websocketpp/websocketpp/transport/asio/security/none.hpp | 2dde03a59962371243c8f73377fd98f299e0f967 | [
"Zlib",
"BSD-3-Clause",
"MIT"
] | permissive | techsharesteam/techshares | 746111254c29d18376ddaddedcb6b3b66aa085ec | 47c58630a578204147057b7504e571e19546444f | refs/heads/master | 2021-01-21T14:43:23.261812 | 2017-04-23T13:03:31 | 2017-04-23T13:03:31 | 58,311,014 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,688 | hpp | /*
* Copyright (c) 2015, Peter Thorson. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the WebSocket++ Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL PETER THORSON 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.
*
*/
#ifndef WEBSOCKETPP_TRANSPORT_SECURITY_NONE_HPP
#define WEBSOCKETPP_TRANSPORT_SECURITY_NONE_HPP
#include <websocketpp/uri.hpp>
#include <websocketpp/transport/asio/security/base.hpp>
#include <websocketpp/common/asio.hpp>
#include <websocketpp/common/memory.hpp>
#include <sstream>
#include <string>
namespace websocketpp {
namespace transport {
namespace asio {
/// A socket policy for the asio transport that implements a plain, unencrypted
/// socket
namespace basic_socket {
/// The signature of the socket init handler for this socket policy
typedef lib::function<void(connection_hdl,lib::asio::ip::tcp::socket&)>
socket_init_handler;
/// Basic Asio connection socket component
/**
* transport::asio::basic_socket::connection implements a connection socket
* component using Asio ip::tcp::socket.
*/
class connection : public lib::enable_shared_from_this<connection> {
public:
/// Type of this connection socket component
typedef connection type;
/// Type of a shared pointer to this connection socket component
typedef lib::shared_ptr<type> ptr;
/// Type of a pointer to the Asio io_service being used
typedef lib::asio::io_service* io_service_ptr;
/// Type of a pointer to the Asio io_service strand being used
typedef lib::shared_ptr<lib::asio::io_service::strand> strand_ptr;
/// Type of the ASIO socket being used
typedef lib::asio::ip::tcp::socket socket_type;
/// Type of a shared pointer to the socket being used.
typedef lib::shared_ptr<socket_type> socket_ptr;
explicit connection() : m_state(UNINITIALIZED) {
//std::cout << "transport::asio::basic_socket::connection constructor"
// << std::endl;
}
/// Get a shared pointer to this component
ptr get_shared() {
return shared_from_this();
}
/// Check whether or not this connection is secure
/**
* @return Whether or not this connection is secure
*/
bool is_secure() const {
return false;
}
/// Set the socket initialization handler
/**
* The socket initialization handler is called after the socket object is
* created but before it is used. This gives the application a chance to
* set any Asio socket options it needs.
*
* @param h The new socket_init_handler
*/
void set_socket_init_handler(socket_init_handler h) {
m_socket_init_handler = h;
}
/// Retrieve a pointer to the underlying socket
/**
* This is used internally. It can also be used to set socket options, etc
*/
lib::asio::ip::tcp::socket & get_socket() {
return *m_socket;
}
/// Retrieve a pointer to the underlying socket
/**
* This is used internally.
*/
lib::asio::ip::tcp::socket & get_next_layer() {
return *m_socket;
}
/// Retrieve a pointer to the underlying socket
/**
* This is used internally. It can also be used to set socket options, etc
*/
lib::asio::ip::tcp::socket & get_raw_socket() {
return *m_socket;
}
/// Get the remote endpoint address
/**
* The iostream transport has no information about the ultimate remote
* endpoint. It will return the string "iostream transport". To indicate
* this.
*
* TODO: allow user settable remote endpoint addresses if this seems useful
*
* @return A string identifying the address of the remote endpoint
*/
std::string get_remote_endpoint(lib::error_code & ec) const {
std::stringstream s;
lib::asio::error_code aec;
lib::asio::ip::tcp::endpoint ep = m_socket->remote_endpoint(aec);
if (aec) {
ec = error::make_error_code(error::pass_through);
s << "Error getting remote endpoint: " << aec
<< " (" << aec.message() << ")";
return s.str();
} else {
ec = lib::error_code();
s << ep;
return s.str();
}
}
protected:
/// Perform one time initializations
/**
* init_asio is called once immediately after construction to initialize
* Asio components to the io_service
*
* @param service A pointer to the endpoint's io_service
* @param strand A shared pointer to the connection's asio strand
* @param is_server Whether or not the endpoint is a server or not.
*/
lib::error_code init_asio (io_service_ptr service, strand_ptr, bool)
{
if (m_state != UNINITIALIZED) {
return socket::make_error_code(socket::error::invalid_state);
}
m_socket = lib::make_shared<lib::asio::ip::tcp::socket>(
lib::ref(*service));
m_state = READY;
return lib::error_code();
}
/// Set uri hook
/**
* Called by the transport as a connection is being established to provide
* the uri being connected to to the security/socket layer.
*
* This socket policy doesn't use the uri so it is ignored.
*
* @since 0.6.0
*
* @param u The uri to set
*/
void set_uri(uri_ptr) {}
/// Pre-initialize security policy
/**
* Called by the transport after a new connection is created to initialize
* the socket component of the connection. This method is not allowed to
* write any bytes to the wire. This initialization happens before any
* proxies or other intermediate wrappers are negotiated.
*
* @param callback Handler to call back with completion information
*/
void pre_init(init_handler callback) {
if (m_state != READY) {
callback(socket::make_error_code(socket::error::invalid_state));
return;
}
if (m_socket_init_handler) {
m_socket_init_handler(m_hdl,*m_socket);
}
m_state = READING;
callback(lib::error_code());
}
/// Post-initialize security policy
/**
* Called by the transport after all intermediate proxies have been
* negotiated. This gives the security policy the chance to talk with the
* real remote endpoint for a bit before the websocket handshake.
*
* @param callback Handler to call back with completion information
*/
void post_init(init_handler callback) {
callback(lib::error_code());
}
/// Sets the connection handle
/**
* The connection handle is passed to any handlers to identify the
* connection
*
* @param hdl The new handle
*/
void set_handle(connection_hdl hdl) {
m_hdl = hdl;
}
/// Cancel all async operations on this socket
void cancel_socket() {
m_socket->cancel();
}
void async_shutdown(socket_shutdown_handler h) {
lib::asio::error_code ec;
m_socket->shutdown(lib::asio::ip::tcp::socket::shutdown_both, ec);
h(ec);
}
lib::error_code get_ec() const {
return lib::error_code();
}
/// Translate any security policy specific information about an error code
/**
* Translate_ec takes a boost error code and attempts to convert its value
* to an appropriate websocketpp error code. The plain socket policy does
* not presently provide any additional information so all errors will be
* reported as the generic transport pass_through error.
*
* @since 0.3.0
*
* @param ec The error code to translate_ec
* @return The translated error code
*/
lib::error_code translate_ec(lib::asio::error_code) {
// We don't know any more information about this error so pass through
return make_error_code(transport::error::pass_through);
}
private:
enum state {
UNINITIALIZED = 0,
READY = 1,
READING = 2
};
socket_ptr m_socket;
state m_state;
connection_hdl m_hdl;
socket_init_handler m_socket_init_handler;
};
/// Basic ASIO endpoint socket component
/**
* transport::asio::basic_socket::endpoint implements an endpoint socket
* component that uses Boost ASIO's ip::tcp::socket.
*/
class endpoint {
public:
/// The type of this endpoint socket component
typedef endpoint type;
/// The type of the corresponding connection socket component
typedef connection socket_con_type;
/// The type of a shared pointer to the corresponding connection socket
/// component.
typedef socket_con_type::ptr socket_con_ptr;
explicit endpoint() {}
/// Checks whether the endpoint creates secure connections
/**
* @return Whether or not the endpoint creates secure connections
*/
bool is_secure() const {
return false;
}
/// Set socket init handler
/**
* The socket init handler is called after a connection's socket is created
* but before it is used. This gives the end application an opportunity to
* set asio socket specific parameters.
*
* @param h The new socket_init_handler
*/
void set_socket_init_handler(socket_init_handler h) {
m_socket_init_handler = h;
}
protected:
/// Initialize a connection
/**
* Called by the transport after a new connection is created to initialize
* the socket component of the connection.
*
* @param scon Pointer to the socket component of the connection
*
* @return Error code (empty on success)
*/
lib::error_code init(socket_con_ptr scon) {
scon->set_socket_init_handler(m_socket_init_handler);
return lib::error_code();
}
private:
socket_init_handler m_socket_init_handler;
};
} // namespace basic_socket
} // namespace asio
} // namespace transport
} // namespace websocketpp
#endif // WEBSOCKETPP_TRANSPORT_SECURITY_NONE_HPP
| [
"thsgroupteamcontact@gmail.com"
] | thsgroupteamcontact@gmail.com |
66b14cffc882ea7cc123bf57981f1ba3dc1f7b50 | 3fc56a21137af2376ff0a0f784f6ed78d8d69973 | /DLib Attacher/ResPacker.cpp | 41fb4543259e5283285730864695dd357a95ec79 | [] | no_license | asdlei99/DLib-Attacher | c524d0cdc9f3fffcc88ccd6f9037d9dba6d977d6 | bb522c6c3863caac04acec8be2feb99563ffadb8 | refs/heads/master | 2020-12-24T03:38:14.949362 | 2014-01-15T16:51:36 | 2014-01-15T16:51:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,437 | cpp | #include "stdafx.h"
#include "ResPacker.h"
// ======================= CResPacker :: PUBLIC =======================
CResPacker::CResPacker() : _guid(0)
{
}
CResPacker::~CResPacker()
{
Clear();
}
UINT CResPacker::Add(PVOID buffer, UINT size)
{
_ResFrame frame;
if (size < 1) {
return RES_INVALID_ID;
}
frame.id = GetGuid();
frame.pdata = calloc(size, 1);
frame.size = size;
if (!frame.pdata) {
return RES_INVALID_ID;
}
memcpy(frame.pdata, buffer, size);
_res.push_back(frame);
return frame.id;
}
BOOL CResPacker::Edit(UINT id, PVOID buffer, UINT size)
{
std::list<_ResFrame>::iterator frame = GetResFrame(id);
if (frame == _res.end() || size < 1) {
return false;
}
free(frame->pdata);
frame->pdata = calloc(size, 1);
frame->size = size;
if (!frame->pdata) {
return false;
}
memcpy(frame->pdata, buffer, size);
return true;
}
BOOL CResPacker::Resize(UINT id, UINT size)
{
std::list<_ResFrame>::iterator frame = GetResFrame(id);
if (frame == _res.end() || size < 1) {
return false;
}
if (size == frame->size) {
return true;
}
frame->pdata = realloc(frame->pdata, size);
frame->size = size;
return true;
}
BOOL CResPacker::Delete(UINT id)
{
std::list<_ResFrame>::iterator frame = GetResFrame(id);
if (frame == _res.end()) {
return false;
}
free(frame->pdata);
_res.erase(frame);
return true;
}
void CResPacker::Clear()
{
std::list<_ResFrame>::iterator it = _res.begin();
while (it != _res.end()) {
free(it->pdata);
it++;
}
_res.clear();
}
PVOID CResPacker::GetDataPtr(UINT id, PUINT psize)
{
std::list<_ResFrame>::iterator frame = GetResFrame(id);
if (frame == _res.end()) {
return NULL;
}
if (psize) {
*psize = frame->size;
}
return frame->pdata;
}
DWORD CResPacker::GetResOffset(UINT id)
{
std::list<_ResFrame>::iterator it = _res.begin();
UINT offset = 0;
while (it != _res.end()) {
if (it->id == id) {
return offset + sizeof(UINT) + sizeof(UINT);//offset + header(id_var + size_var)
}
offset += it->size + sizeof(UINT) + sizeof(UINT);//buffer + id_var + size_var
it++;
}
return RES_INVALID_ID;
}
UINT CResPacker::GetTotalSize()
{
std::list<_ResFrame>::iterator it = _res.begin();
UINT total_size = 0;
while (it != _res.end()) {
total_size += it->size + sizeof(UINT) + sizeof(UINT);//buffer + id_var + size_var
it++;
}
return total_size;
}
BOOL CResPacker::Compile(PVOID output, UINT buff_size, PUINT pcomp_size)
{
std::list<_ResFrame>::iterator it = _res.begin();
DWORD offset = 0;
*pcomp_size = GetTotalSize();
if (*pcomp_size > buff_size) {
return false;
}
while (it != _res.end()) {
*(UINT *)((UINT)output + offset) = it->id;
offset += sizeof(UINT);
*(UINT *)((UINT)output + offset) = it->size;
offset += sizeof(UINT);
memcpy((PVOID)((UINT)output + offset), it->pdata, it->size);
offset += it->size;
it++;
}
return true;
}
BOOL CResPacker::Decompile(PVOID input, UINT buff_size, PUINT pcount)
{
DWORD added = 0, offset = 0;
UINT guid = 0;
_ResFrame frame;
Clear();
while (true) {
if (offset + (sizeof(UINT) * 2) > buff_size) {
break;
}
frame.id = *(UINT *)((UINT)input + offset);
offset += sizeof(UINT);
frame.size = *(UINT *)((UINT)input + offset);
offset += sizeof(UINT);
if (offset + frame.size > buff_size) {
break;
}
if (!frame.id && !frame.size) {
break;
}
if (frame.id > guid) {
guid = frame.id;
}
if (GetDataPtr(frame.id, NULL)) {
Clear();
return false;
}
frame.pdata = calloc(frame.size, 1);
if (!frame.pdata) {
Clear();
return false;
}
memcpy(frame.pdata, (PVOID)((UINT)input + offset), frame.size);
_res.push_back(frame);
offset += frame.size;
added++;
if (offset == buff_size) {
break;
}
}
_guid = ++guid;
if (pcount) {
*pcount = added;
}
return true;
}
UINT CResPacker::Count()
{
return _res.size();
}
// ======================= CResPacker :: PRIVATE =======================
UINT CResPacker::GetGuid()
{
return _guid++;
}
std::list<_ResFrame>::iterator CResPacker::GetResFrame(UINT id)
{
std::list<_ResFrame>::iterator it = _res.begin();
while (it != _res.end()) {
if (it->id == id) {
return it;
}
it++;
}
return _res.end();
}
| [
"8bit.dosninja@gmail.com"
] | 8bit.dosninja@gmail.com |
15988d290412b98a7ed49573e21ef3adfd110956 | b4ba3bc2725c8ff84cd80803c8b53afbe5e95e07 | /Medusa/MedusaCore/Core/Chrono/ProfileNode.h | e22a385b9e2a1e3e99b2640814ef6ae2a52e76fb | [
"MIT"
] | permissive | xueliuxing28/Medusa | c4be1ed32c2914ff58bf02593f41cf16e42cc293 | 15b0a59d7ecc5ba839d66461f62d10d6dbafef7b | refs/heads/master | 2021-06-06T08:27:41.655517 | 2016-10-08T09:49:54 | 2016-10-08T09:49:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,892 | h | // Copyright (c) 2015 fjz13. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
#pragma once
#include "MedusaCorePreDeclares.h"
#include "Core/Collection/List.h"
#include "Core/String/StringRef.h"
#include "Core/Collection/List.h"
#include "Core/Chrono/StopWatch.h"
MEDUSA_BEGIN;
class ProfileNode
{
public:
ProfileNode(const StringRef& name, ProfileNode* parent, size_t count = 1, size_t logCount = 0);
ProfileNode();
~ProfileNode();
public:
void Begin();
bool End();
bool End(StopWatch::TimePoint timeStamp);
bool Count(StopWatch::Duration elapsedTime);
void Reset();
void Stop();
ProfileNode* FindOrCreateChildNode(const StringRef& name, size_t count = 1, size_t logCount = 0);
void PrintResult(const StringRef& totalPrefix, const StringRef& perPrefix)const;
public:
const StringRef& Name() const { return mName; }
ProfileNode* Parent() const { return mParent; }
StopWatch::Duration AverageTime()const { return mTotalCount!=0?mTotalTime / mTotalCount / mCount: StopWatch::Duration(0); }
StopWatch::Duration MinTime()const { return mTotalCount != 0 ? mMinTime / mCount : StopWatch::Duration(0); }
StopWatch::Duration MaxTime()const { return mTotalCount != 0 ? mMaxTime / mCount : StopWatch::Duration(0); }
StopWatch::Duration ElapsedTime()const { return mElapsedTime / mCount; }
private:
StringRef mName;
ProfileNode* mParent = nullptr;
List<ProfileNode*> mChildren;
size_t mCount = 1; //each run count
size_t mTotalCount = 0;
StopWatch::Duration mTotalTime{ 0 };
StopWatch::TimePoint mStartTime;
StopWatch::TimePoint mEndTime;
StopWatch::Duration mElapsedTime{ 0 };
int mRecursionCounter = 0;
List<int64> mTimeLogs;
size_t mMinLogIndex = 0;
size_t mMaxLogIndex = 0;
StopWatch::Duration mMinTime{ Math::UIntMaxValue };
StopWatch::Duration mMaxTime{ 0 };
};
MEDUSA_END; | [
"fjz13@live.cn"
] | fjz13@live.cn |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.