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
75a2d8a245446f0a01a4b542b468acf9de16d3fd
96187cb1b203d621ff20abe0f13a5ece35c7de15
/Codechef/June Long Challenge/LENTMO.cpp
663b73f97944d565c10833657bdd86f7a28b7c6c
[]
no_license
shadabshaikh0/Competitive-Programming
7faa248513338f0af8b0ce651536dbe0b18aafe7
56d0723e69c750ac287feb76e1cf60e646910a83
refs/heads/master
2020-07-04T04:27:28.498903
2020-01-05T02:28:18
2020-01-05T02:28:18
202,155,410
1
0
null
null
null
null
UTF-8
C++
false
false
400
cpp
#include<bits/stdc++.h> #define ll long long int #define RD(v,n) for(ll i =0;i<n;i++ ) cin>>v[i] #define bolt ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); using namespace std; int main() { bolt; ll t; cin>>t; while(t--){ ll n; cin>>n; vector<ll> v(n); RD(v,n); ll k,x; cin>>k>>x; for( ll i=0;i<n;i++ ){ } } return 0; }
[ "pictcanteen1983@gmail.com" ]
pictcanteen1983@gmail.com
061b69e543ecff07570d34bc6a36024f666676ce
f155c5738f71d7039c8308e56bab485f2264af27
/QT-Projects-9ffde45272023ece2f312d9e52dfeeb4ea44e85e/dia2/widgetmeshrenderer.cpp
efe8fa5990ef515306d1a5c44ac4533c9668c385
[]
no_license
albertllopart/QT-Projects
6c372924cb93ecc112300077863218ec40599884
32d9f9378d70f63e1c36fed11637e49ded6d7a5d
refs/heads/master
2020-04-22T10:21:27.917518
2019-06-13T17:33:03
2019-06-13T17:33:03
170,302,603
0
0
null
null
null
null
UTF-8
C++
false
false
5,092
cpp
#include "widgetmeshrenderer.h" #include "ui_widgetmeshrenderer.h" #include "meshrenderer.h" #include "scene.h" #include "resourcemanager.h" #include <QDebug> #include "mesh.h" #include "submesh.h" #include "texture.h" WidgetMeshRenderer::WidgetMeshRenderer(Scene* scene, MeshRenderer* mesh, QWidget *parent) : QWidget(parent), ui(new Ui::WidgetMeshRenderer) { ui->setupUi(this); this->scene = scene; this->meshRenderer = mesh; bool hasMesh = false; int indexToSelect = 0; ui->ComboMesh->addItem("No Mesh..."); for (int i = 0; i < scene->resourceManager->GetCountResources(ResourceType::RMesh); i++) { Resource* r = scene->resourceManager->GetResource(i, ResourceType::RMesh); ui->ComboMesh->addItem(r->GetName()); if (this->meshRenderer->GetMesh() != nullptr) { std::string name1 = r->GetName(); std::string name2 = this->meshRenderer->GetMesh()->GetName(); if(name1 == name2) { indexToSelect = i + 1; hasMesh = true; } } } if(hasMesh) { ui->ComboMesh->setCurrentIndex(indexToSelect); if (ui->Textures->itemAt(0) != nullptr) { ChangeMesh(ui->Textures); } if(mesh == nullptr) { ConnectSignalsSlots(); return; } AddTexturesLayout(this->meshRenderer->GetMesh()); } //ui->ComboMaterial->addItem("No Texture..."); ConnectSignalsSlots(); } WidgetMeshRenderer::~WidgetMeshRenderer() { delete ui; } void WidgetMeshRenderer::ConnectSignalsSlots() { connect(ui->ComboMesh, SIGNAL(currentIndexChanged(int)), this, SLOT(UpdateMeshRenderer())); //connect(ui->ComboMaterial, SIGNAL(currentIndexChanged(int)), this, SLOT(UpdateTexture())); } void WidgetMeshRenderer::UpdateMeshRenderer() { Mesh* mesh = (Mesh*)scene->resourceManager->GetResourceObject(ui->ComboMesh->currentIndex() - 1, ResourceType::RMesh); if(mesh != nullptr) { qInfo() << "okey........................"; meshRenderer->SetMesh(mesh); } else { meshRenderer->SetMesh(nullptr); } if (ui->Textures->itemAt(0) != nullptr) { ChangeMesh(ui->Textures); } if(mesh == nullptr) { emit InspectorUpdate(); return; } AddTexturesLayout(mesh); emit InspectorUpdate(); } void WidgetMeshRenderer::AddTexturesLayout(Mesh* mesh) { int index = 0; bool hasMesh = false; int indexToSelect = 0; foreach (SubMesh* sub, mesh->meshes) { qInfo() << "UPDATEEEEEEE"; QHBoxLayout* box = new QHBoxLayout(); const char* name = sub->meshName.c_str(); QLabel* la = new QLabel(QString(name)); la->setStyleSheet("font-style: normal"); QComboBox* combo = new QComboBox(); combo->setObjectName(QString::number(index)); combo->addItem("Select Texture..."); for (int i = 0; i < scene->resourceManager->GetCountResources(ResourceType::RTexture); i++) { Resource* r = scene->resourceManager->GetResource(i, ResourceType::RTexture); combo->addItem(r->GetName()); std::string name1 = r->GetName(); std::string name2 = sub->texture->GetName(); if(name1 == name2) { hasMesh = true; indexToSelect = i + 1; } } if(hasMesh) combo->setCurrentIndex(indexToSelect); std::string temp = name; box->addWidget(la); box->addWidget(combo); connect(combo, SIGNAL(currentIndexChanged(const QString&)), this, SLOT(UpdateTexture(const QString&))); ui->Textures->addLayout(box); index++; } } void WidgetMeshRenderer::ChangeMesh(QLayout* layout) { QLayoutItem* child; while (layout->count() != 0) { child = layout->takeAt(0); if (child->layout() != nullptr) { ChangeMesh(child->layout()); } else if (child->widget() != nullptr) { delete child->widget(); } delete child; } } void WidgetMeshRenderer::UpdateTexture(const QString& nameSubmesh) { //qInfo() << "Texture NULL" <<sender(); //qInfo() << "Texture NULL" << sender()->objectName().toStdString(); //qInfo() << "Texture NULL" <<; int index = std::stoi(sender()->objectName().toStdString()); Texture* newTexture = (Texture*)scene->resourceManager->GetResource(nameSubmesh.toStdString()); if(newTexture == nullptr) { qInfo() << "Texture NULL"; meshRenderer->GetMesh()->meshes[index]->texture = (Texture*)scene->resourceManager->GetResource(0, ResourceType::RTexture); } else { meshRenderer->GetMesh()->meshes[index]->texture = newTexture; } //meshRenderer->SetMaterial((Material*)scene->resourceManager->GetResource(ui->ComboMesh->currentIndex() - 1, ResourceType::RMaterial)); emit InspectorUpdate(); }
[ "elliot.jimenez1@gmail.com" ]
elliot.jimenez1@gmail.com
fae8db118dd6302389a3dc57a041df4ffe6fd638
e7c199a533caa9ea7122165dc5cbc0bceebb5c5c
/20201121/test.cpp
8748d4d41020c794e4b2117f58935d0f7ee28584
[]
no_license
bit-zll/nowcoder
34929c52f0f1bb05310109043747c0519cd306c0
f52227a6db9a4b85c6aa5d61e5cf1b34c051b25e
refs/heads/master
2023-01-15T11:14:11.907569
2020-12-05T12:45:44
2020-12-05T12:45:44
260,662,831
0
0
null
null
null
null
GB18030
C++
false
false
1,733
cpp
#define _CRT_SECURE_NO_WARNINGS #include <iostream> using namespace std; //数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。 //由于数字2在数组中出现了5次,超过数组长度的一半,因此输出2。如果不存在则输出0。 #include <vector> #if 0 class Solution { public: int MoreThanHalfNum_Solution(vector<int> numbers) { int half = numbers.size() / 2; int count = 1; int num; for (int i = 0; i < numbers.size(); i++) { num = numbers[i]; for (int j = i + 1; j < numbers.size(); j++) { if (num == numbers[j]) count++; } if (count > half) return num; count = 1; } return 0; } }; #endif #if 0 //杨辉三角 class Solution { public: vector<vector<int>> generate(int numRows) { vector<vector<int>> vv; vv.resize(numRows); for (size_t i = 1; i <= numRows; ++i) { vv[i - 1].resize(i, 0); vv[i - 1][0] = 1; vv[i - 1][i - 1] = 1; } for (size_t i = 0; i < vv.size(); ++i) { for (size_t j = 0; j < vv[i].size(); ++j) { if (vv[i][j] == 0) { vv[i][j] = vv[i - 1][j - 1] + vv[i - 1][j]; } } } return vv; } }; #endif #if 0 //只出现一次数字 class Solution { public: int singleNumber(vector<int>& nums) { int value = 0; for (auto e : nums) value ^= e; return value; } }; #endif //连续子数最大和 class Solution { public: int FindGreatestSumOfSubArray(vector<int> array) { int sz = array.size(); vector<int> dp(sz + 1, 0); int ret = array[0]; for (int i = 1; i <= sz; i++) { dp[i] = max(array[i - 1], dp[i - 1] + array[i - 1]); ret = max(dp[i], ret); } return ret; } };
[ "524183259@qq.com" ]
524183259@qq.com
5836b66aa8b69f6699c37603ebc23cef6df2814f
2eba3b3b3f979c401de3f45667461c41f9b3537a
/root/io/prefetching/atlasFlushed/Trk__HepSymMatrix_p1.h
dfd8a2feee2913ec92ac4ef93b048097185adbd4
[]
no_license
root-project/roottest
a8e36a09f019fa557b4ebe3dd72cf633ca0e4c08
134508460915282a5d82d6cbbb6e6afa14653413
refs/heads/master
2023-09-04T08:09:33.456746
2023-08-28T12:36:17
2023-08-29T07:02:27
50,793,033
41
105
null
2023-09-06T10:55:45
2016-01-31T20:15:51
C++
UTF-8
C++
false
false
790
h
////////////////////////////////////////////////////////// // This class has been generated by TFile::MakeProject // (Tue Jun 14 15:33:00 2011 by ROOT version 5.31/01) // from the StreamerInfo in file http://root.cern.ch/files/atlasFlushed.root ////////////////////////////////////////////////////////// #ifndef Trk__HepSymMatrix_p1_h #define Trk__HepSymMatrix_p1_h namespace Trk { class HepSymMatrix_p1; } // end of namespace. #include "Riostream.h" #include <vector> namespace Trk { class HepSymMatrix_p1 { public: // Nested classes declaration. public: // Data Members. vector<float> m_matrix_val; // int m_nrow; // HepSymMatrix_p1(); HepSymMatrix_p1(const HepSymMatrix_p1 & ); virtual ~HepSymMatrix_p1(); }; } // namespace #endif
[ "pcanal@fnal.gov" ]
pcanal@fnal.gov
a478ba8aa219e32b4b300e9ab034a9ab1d408150
26b8f7f2d80c36bb8c88d8f21667ac906d31178a
/lightem.cpp
ca63ff0c54881a89a142927730dcf478458198fa
[ "MIT" ]
permissive
sjaeckel/lightem
a0aad7e4e45c763bb611128f70a89c13d0dab309
99367482ac38fa4fc7513548a3b218702218c576
refs/heads/master
2020-05-14T08:22:32.038513
2014-07-05T22:57:17
2014-07-05T22:57:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,982
cpp
/* * lightem - light 'em up! a library to control RGB LED's */ #include <string.h> #include <stdlib.h> #include <stdio.h> #include "lightem.h" #define min(a,b) \ ({ __typeof__ (a) _a = (a); \ __typeof__ (b) _b = (b); \ _a < _b ? _a : _b; }) #define STORE32(x, y) \ do { (y)[3] = (uint8_t)(((x)>>24)&255); (y)[2] = (uint8_t)(((x)>>16)&255); \ (y)[1] = (uint8_t)(((x)>>8)&255); (y)[0] = (uint8_t)((x)&255); } while(0) #define LOAD32(x, y) \ do { x = ((uint32_t)((y)[3] & 255)<<24) | \ ((uint32_t)((y)[2] & 255)<<16) | \ ((uint32_t)((y)[1] & 255)<<8) | \ ((uint32_t)((y)[0] & 255)); } while(0) typedef struct __attribute__ ((__packed__)) _lightem_t { uint8_t type; uint8_t addr; uint8_t data[4]; uint8_t csum; } st_lightem_t; typedef enum _type_t { type_cmd = 254, type_data = 255 } en_type_t; lightem::lightem(void) { } lightem::~lightem() { } uint8_t lightem::_csum(uint8_t* p) { uint8_t *pe, csum = 0; if (!p) return 0xff; pe = p + (sizeof(st_lightem_t)-1); while (p != pe) { csum -= *p; ++p; } return csum; } void lightem::createCsum(void) { st_lightem_t* p = (st_lightem_t*)frame; p->csum = _csum(frame); } int lightem::isPixelValue(void) { st_lightem_t* p = (st_lightem_t*)frame; return p->type == type_data; } int lightem::isValid(void) { st_lightem_t* p = (st_lightem_t*)frame; return (_csum(frame) == p->csum); } uint32_t lightem::color(uint8_t r, uint8_t g, uint8_t b) { return ((uint32_t)r << 16) | ((uint32_t)g << 8) | b; } void lightem::setColor(uint32_t color) { st_lightem_t* p = (st_lightem_t*)frame; p->type = type_data; STORE32(color, p->data); } uint32_t lightem::getColor(void) { st_lightem_t* p = (st_lightem_t*)frame; uint32_t c; LOAD32(c, p->data); return c; } void lightem::setAddr(int addr) { st_lightem_t* p = (st_lightem_t*)frame; p->addr = addr; } int lightem::getAddr(void) { st_lightem_t* p = (st_lightem_t*)frame; return p->addr; } uint8_t* lightem::getAddr(size_t* psz) { st_lightem_t* p = (st_lightem_t*)frame; uint8_t* r = 0; if (psz) { size_t sz; if (p->addr == 0xff) { sz = 128; } else if ((p->addr & 0x90) == 0x90) { sz = 8; } else if ((p->addr & 0x80) == 0x80) { sz = 16; } else { sz = 1; } r = (uint8_t*)malloc(sz * sizeof(uint8_t)); if (r) { *psz = sz; if (p->addr == 0xff) { for (size_t i = 0; i < sz; ++i) { r[i] = i; } } else if ((p->addr & 0x90) == 0x90) { uint8_t a = p->addr & 0x0F; for (size_t i = 0; i < sz; ++i) { r[i] = ((uint8_t)i << 4) | a; } } else if ((p->addr & 0x80) == 0x80) { uint8_t a = (p->addr & 0x07) << 4; for (size_t i = 0; i < sz; ++i) { r[i] = a + i; } } else { *r = p->addr; } } } return r; } int lightem::setFrame(const void* f) { if (f) { memcpy(frame, f, sizeof(frame)); return isValid(); } return 0; } void* lightem::getFrame(size_t *psz) { size_t sz = 0; void* f = malloc(sizeof(frame)); if (f) { createCsum(); memcpy(f, frame, sizeof(frame)); sz = sizeof(frame); } if (psz) *psz = sz; return f; } extern "C" { void* lightem_c (int addr, uint8_t r, uint8_t g, uint8_t b, size_t *psz) { lightem l; l.setAddr(addr); l.setColor(r, g, b); return l.getFrame(psz); } }
[ "s@jaeckel.eu" ]
s@jaeckel.eu
2b6bf2264fed98cfdbcbbc6716a9a9c96ad425b5
0904cc7f2bac0acbe1d9041261e8753a509e0f2f
/recursion/taylor.cpp
bd6b32fae3c37a4de2881b78c3c892ad714ed8d7
[]
no_license
khushboosinghrecs/Data_Structure
a2add748621e2c4473aa8e73dd2f112cd2d6966e
2b5d866d7887bd8493d6b5aa79e03c59970ebf02
refs/heads/master
2023-04-06T16:26:12.315217
2021-04-07T08:41:22
2021-04-07T08:41:22
329,708,142
0
0
null
null
null
null
UTF-8
C++
false
false
289
cpp
#include<iostream> using namespace std; double taylor(int x, int n) { static double p=1, f=1; double r; if(n==0) { return 1; } else { r=taylor(x, n-1); p=p*x; f=f*n; return r+p/f; } } int main() { cout<< taylor(4, 10)<<'\n'; cout<< taylor(1, 10)<<'\n'; cout<< taylor(0, 10); return 0; }
[ "9919khush@gmail.com" ]
9919khush@gmail.com
d6da6d650a038c2f1f10d615e23b87943f6649c3
7f6edd2e2634d3c8eba2d16ec49dd0eb21a5622f
/CreationPatterns/SimplePrototype/SimplePrototype.cpp
3b99d7b5d5e5d56745a4bdb88157c2aadc06d9fa
[]
no_license
clintonvanry/DesignPatternsInCPP
6e5a57a84f275da972b8d6c2b4d815cc0c03bcb6
f3d0c0a1228e7090e720365b11ac8a9933721e83
refs/heads/master
2020-09-11T23:49:07.413992
2020-01-05T12:32:05
2020-01-05T12:32:05
222,229,806
0
0
null
null
null
null
UTF-8
C++
false
false
556
cpp
#include <iostream> #include "Contact.h" #include "EmployeeFactory.h" int main() { std::cout << "Hello World!\n"; //Contact john{"John Doe", new Address{"123 East Dr","London",10}}; ////Contact jane{ "Jane Smith", new Address{"123 East Dr","London",20} }; // auto jane = john; //jane.setName("Jane Smith"); //jane.setSuite(15); auto john = EmployeeFactory::NewMainOfficeEmployee("John Doe", 10); auto jane = EmployeeFactory::NewAuxOfficeEmployee("Jane Smith", 15); std::cout << *john << std::endl; std::cout << *jane << std::endl; }
[ "clinton.vanry@gmail.com" ]
clinton.vanry@gmail.com
4137cd8e6cf113b17dd8c502c24914d20ba142d5
bf1f45e565451d514e2ec698a2ae5eb835ebe056
/SnakeComponents.h
9d319a8a4199c87e7046dafe416eb8708a9f71e1
[]
no_license
MrHause/sdl_snake
fa3a0225103a60cec12bc26fedc0051b36bbd86c
d2746ae0865173cf7b9ef6f1657bb5d04f915f59
refs/heads/master
2023-06-23T23:20:48.074576
2021-07-18T11:02:53
2021-07-18T11:02:53
371,417,155
0
0
null
null
null
null
UTF-8
C++
false
false
357
h
#pragma once #include "ECS/Components.h" #include "SDL.h" class SnakeComponents { private: Entity snakeHead; Entity food; Manager manager; std::vector<std::unique_ptr<Entity>> snakeTail; public: SnakeComponents(); SnakeComponents(int xpos, int ypos); ~SnakeComponents(){} void draw(); void refresh(); void update(); void addTailComponent(); };
[ "mrhause90@gmail.com" ]
mrhause90@gmail.com
d49323a582390f2f3faec296265405c66cf65ad4
47e458101f543cecee59b27d27f67e8944930d3a
/Chapter_03/Task_12/inc/printBinary.h
850cacce62fc322d43ad186ffe4d229242e63487
[]
no_license
callmeFilip/Thinking-in-CPP-Volume-1-2nd-Edition
f1bb1c9e7edef1e9ca4eadb7758f80e08ee68bba
95db8120d67423c35728bd8b216393e9e869371d
refs/heads/master
2023-03-27T00:31:56.940278
2021-03-25T17:12:34
2021-03-25T17:12:34
312,387,460
0
0
null
null
null
null
UTF-8
C++
false
false
134
h
#pragma once #include <iostream> // : C03:printBinary.h // Display a byte in binary void printBinary(const unsigned char val); ///:~
[ "filip_andonow@abv.bg" ]
filip_andonow@abv.bg
f915429ed23b049ff57bdbb154ef68fcce3fc2b0
7540cadabdc5a8accff4808fab99bf2bb308606e
/preprocessing/preprocessing.h
7804edcf695065f252742e1c8c2e2700cc70c9b8
[]
no_license
maiafelipe/LucyCV
a239a7a7741709a5385cfc3e7c35dabb8c5465c4
18664fffce6ee05c7c4c0533496544d7cfc0076e
refs/heads/master
2020-04-26T03:29:03.275093
2013-07-16T14:13:31
2013-07-16T14:13:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,094
h
#ifndef __PREPROC_H__ #define __PREPROC_H__ #include <iostream> #include <cmath> #include "opencv2/imgproc/imgproc_c.h" #include "opencv2/legacy/legacy.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv2/opencv.hpp" using namespace std; // using namespace cv; template <class Type> class PreProcessing { private: Type* norMinimum; Type* norDiference; Type* norMean; Type* norStdDev; cv::PCA* objPca; bool initNorMinimum; bool initNorDiference; bool initNorMean; bool initNorStdDev; bool initObjPca; public: PreProcessing(); ~PreProcessing(); Type** normalize(Type** in, int n_patt, int n_att, bool relative = false); Type** normalize_mean(Type** in, int n_patt, int n_att, bool relative = false); Type** pca(Type** in, int n_patt, int n_att, int max_att, bool relative = false); int detectFace(Type** in, Type** desired, int n_patt, int n_att, int n_class, int origHeight, int origWidth, int newHeight, int newWidth); IplImage* detectAFace(cv::Mat& img, CascadeClassifier& cascade, double scale, bool tryflip, IplImage* src ); }; template <class Type> PreProcessing<Type>::PreProcessing() { initNorDiference = false; initNorMinimum = false; initNorMean = false; initNorStdDev = false; initObjPca = false; } template <class Type> PreProcessing<Type>::~PreProcessing() { if(initNorMinimum) { delete[] norMinimum; } if(initNorDiference) { delete[] norDiference; } if(initNorMean) { delete[] norMean; } if(initNorStdDev) { delete[] norStdDev; } if(initObjPca) { delete objPca; } } template <class Type> Type** PreProcessing<Type>::normalize(Type** in, int n_patt, int n_att, bool relative) { int lines = n_patt; int columns = n_att; // cout<<n_patt<<endl; if(!relative) { if(initNorMinimum) { delete[] norMinimum; initNorMinimum = false; } norMinimum = new Type[columns]; initNorMinimum = true; if(initNorDiference) { delete[] norDiference; initNorDiference = false; } norDiference = new Type[columns]; initNorDiference = true; for (int j = 0; j < columns; j++) { norMinimum[j] = INFINITE; Type maximum = 0; for (int i = 0; i < lines; i++) { // cout<<i<<endl; if (in[i][j] < norMinimum[j]) norMinimum[j] = in[i][j]; if (in[i][j] > maximum) maximum = in[i][j]; } norDiference[j] = maximum - norMinimum[j]; } } Type** outData = new Type*[n_patt]; for (int i = 0; i < lines; i++) { outData[i] = new Type[n_att]; for (int j = 0; j < columns; j++) { outData[i][j] = (in[i][j] - norMinimum[j]) /norDiference[j]; } } return outData; } template <class Type> Type** PreProcessing<Type>::normalize_mean(Type** in, int n_patt, int n_att, bool relative) { if(!relative) { if(initNorMean) { delete[] norMean; initNorMean = false; } norMean = new Type[n_att]; initNorMean = true; if(initNorStdDev) { delete[] norStdDev; initNorStdDev = false; } norStdDev = new Type[n_att]; initNorStdDev = true; for (int att = 0; att < n_att; att++) { Type mean = 0; for (int patt = 0; patt < n_patt; patt++) { mean += in[patt][att]; } norMean[att] = mean/n_patt; Type var = 0; for (int patt = 0; patt < n_patt; patt++) { var += ((in[patt][att] - norMean[att]) * (in[patt][att] - norMean[att])); } norStdDev[att] = sqrt(var/n_patt); } } Type** outData = new Type*[n_patt]; for (int patt = 0; patt < n_patt; patt++) { outData[patt] = new Type[n_att]; for (int att = 0; att < n_att; att++) { outData[patt][att] = (in[patt][att] - norMean[att])/norStdDev[att]; } } return outData; } template <class Type> Type** PreProcessing<Type>::pca(Type** in, int numInputs, int numAttributes, int max_att, bool relative) { cv::Mat inMatrix(numInputs, numAttributes, CV_64F); for(int i = 0; i < numInputs; i++) { for(int j = 0; j < numAttributes; j++) { inMatrix.col(j).row(i) = in[i][j]; } } if(!relative) { if(initObjPca) { delete objPca; initObjPca = false; } objPca = new cv::PCA(inMatrix, Mat(), CV_PCA_DATA_AS_ROW, max_att); initObjPca = true; } if(!objPca) { return NULL; } //projetar o training cv::Mat projection; objPca->project(inMatrix, projection); Type **buffet = new Type* [numInputs]; for(int i = 0; i < numInputs; i++) { buffet[i] = projection.ptr<double>(i); } Type** outData = new Type*[numInputs]; for(int i = 0; i < numInputs; i++) { outData[i] = new Type[numAttributes]; for(int j = 0; j < numAttributes; j++) { outData[i][j] = buffet[i][j]; } } return outData; } template <class Type> int PreProcessing<Type>::detectFace(Type** in, Type** desired, int n_patt, int n_att, int n_class, int origHeight, int origWidth, int newHeight, int newWidth) { int count = 0; Type** resultIn = new Type*[n_patt]; Type** resultDesired = new Type*[n_patt]; for (int patt = 0; patt < n_patt; patt++) { resultIn[patt] = new Type[newHeight*newWidth]; resultDesired[patt] = new Type[n_class]; for (int cl = 0; cl < n_class; cl++) { resultDesired[patt][cl] = 0; } } int numColors = 1; for (int patt = 0; patt < n_patt; patt++) { // cout<<"patt "<<patt<<endl; int att = 0; Mat imag(origHeight, origWidth, CV_8UC1); for (int h = 0; h < origHeight; h++) { for (int w = 0; w < origWidth; w++) { imag.col(w).row(h) = in[patt][att]; // cout<<imag.col(w).row(h)<<" "; att++; } // cout<<endl; } // cout<<"v1"<<endl; // cout<<endl<<endl; // cout<<patt<<endl; // namedWindow( "Display window", CV_WINDOW_AUTOSIZE );// Create a window for display. // imshow( "Display window", imag ); // waitKey(0); IplImage imagIPL = imag; char nome[50]; // sprintf(nome, "Janela %d", patt); // cvShowImage(nome, &imagIPL); CascadeClassifier cascade; string cascadeName = "haarcascades/haarcascade_frontalface_alt.xml"; if( !cascade.load(cascadeName) ) { cerr << "ERROR: Could not load classifier cascade" << endl; return 0; } // cout<<"v2"<<endl; IplImage* face = NULL; face = detectAFace(imag, cascade, 1, false, &imagIPL); // cout<<"v3"<<endl; IplImage *rface = cvCreateImage( cvSize(newWidth, newHeight), imagIPL.depth, imagIPL.nChannels ); // cout<<"v4"<<endl; if(face){ cvResize(face, rface); // sprintf(nome, "Janela %d 2", patt); // cvShowImage(nome, rface); // waitKey(0); count++; // cout<<"2"<<endl; }else{ string cascadeName = "haarcascades/haarcascade_frontalface_default.xml"; if( !cascade.load(cascadeName) ) { cerr << "ERROR: Could not load classifier cascade" << endl; return 0; } IplImage* face = NULL; face = detectAFace(imag, cascade, 1, false, &imagIPL); if(face){ cvResize(face, rface); // sprintf(nome, "Janela %d 2", patt); // cvShowImage(nome, rface); // waitKey(0); count++; // cout<<"3"<<endl; }else{ string cascadeName = "haarcascades/haarcascade_frontalface_alt2.xml"; if( !cascade.load(cascadeName) ) { cerr << "ERROR: Could not load classifier cascade" << endl; return 0; } IplImage* face = NULL; face = detectAFace(imag, cascade, 1, false, &imagIPL); if(face){ cvResize(face, rface); // sprintf(nome, "Janela %d 2", patt); // cvShowImage(nome, rface); // waitKey(0); count++; // cout<<"4"<<endl; }else{ string cascadeName = "haarcascades/haarcascade_profileface.xml"; if( !cascade.load(cascadeName) ) { cerr << "ERROR: Could not load classifier cascade" << endl; return 0; } IplImage* face = NULL; face = detectAFace(imag, cascade, 1, false, &imagIPL); if(face){ cvResize(face, rface); // sprintf(nome, "Janela %d 2", patt); // cvShowImage(nome, rface); // waitKey(0); count++; // cout<<"5"<<endl; } } } } if(face){ // cout<<"detec: 1"<<endl; int j = 0; for(int h = 0; h < newHeight; h++){ for(int w = 0; w < newWidth; w++){ CvScalar pont = cvGet2D(rface,h,w); for(int c = 0; c < numColors; c++){ resultIn[count-1][j] = pont.val[c]; j++; } // cout<<h<<" "<<w<<" "<<j<<" "<<rface->height<<" "<<rface->width<<endl; } } // cout<<"detec: 2"<<endl; for (int cl = 0; cl < n_class; cl++) { resultDesired[count-1][cl] = desired[patt][cl]; } // cout<<"detec: 3"<<endl; }else{ // int j = 0; // for(int h = 0; h < newHeight; h++){ // for(int w = 0; w < newWidth; w++){ // for(int c = 0; c < numColors; c++){ // resultIn[patt][j] = 0; // j++; // } // } // } } } in = resultIn; desired = resultDesired; cout<<count<<"/"<<n_patt<<endl; return count; } template <class Type> IplImage* PreProcessing<Type>::detectAFace( Mat& img, CascadeClassifier& cascade, double scale, bool tryflip, IplImage* src ) { int i = 0; double t = 0; vector<Rect> faces, faces2; Mat gray, smallImg( cvRound (img.rows/scale), cvRound(img.cols/scale), CV_8UC1 ); // cvtColor( img, gray, CV_BGR2GRAY ); gray = img; resize( gray, smallImg, smallImg.size(), 0, 0, INTER_LINEAR ); equalizeHist( smallImg, smallImg ); t = (double)cvGetTickCount(); cascade.detectMultiScale( smallImg, faces, 1.1, 2, 0 //|CV_HAAR_FIND_BIGGEST_OBJECT //|CV_HAAR_DO_ROUGH_SEARCH |CV_HAAR_SCALE_IMAGE , Size(30, 30) ); if( tryflip ) { flip(smallImg, smallImg, 1); cascade.detectMultiScale( smallImg, faces2, 1.1, 2, 0 //|CV_HAAR_FIND_BIGGEST_OBJECT //|CV_HAAR_DO_ROUGH_SEARCH |CV_HAAR_SCALE_IMAGE , Size(30, 30) ); for( vector<Rect>::const_iterator r = faces2.begin(); r != faces2.end(); r++ ) { faces.push_back(Rect(smallImg.cols - r->x - r->width, r->y, r->width, r->height)); } } t = (double)cvGetTickCount() - t; // printf( "detection time = %g ms\n", t/((double)cvGetTickFrequency()*1000.) ); if(faces.size() == 0) return NULL; for( vector<Rect>::const_iterator r = faces.begin(); r != faces.end(); r++, i++ ) { IplImage* cropped = cvCreateImage(cvSize(r->width*scale,r->height*scale), src->depth, src->nChannels ) ; cvSetImageROI( src, cvRect( r->x*scale,r->y*scale , r->width*scale,r->height*scale) ); // Do the copy cvCopy( src, cropped ); cvResetImageROI( src ); char nome[50]; // sprintf(nome, "Janela %d", i); // cvShowImage(nome, cropped ); //cvSaveImage("test.jpg", cropped); return cropped; } return NULL; } #endif
[ "felipe.ja.maia@gmail.com" ]
felipe.ja.maia@gmail.com
1a97e1f297160f584363f75899fe1ab3ab2304ea
7feae995490942cf150efa245cb6dbbe99046f67
/00001-00500/SRM485/Div2/AfraidOfEven.h
04a089704a5e22500c42ff29ad8914333b4a2665
[]
no_license
y42sora/soraSRM
98cd155efafd6dd0d169b424d7eaf1b1472db2d8
843f6f505b92f2b8e0233a9e05cf64969f85ee37
refs/heads/master
2020-06-29T01:47:27.623056
2013-03-09T14:13:21
2013-03-09T14:13:21
1,360,695
0
0
null
null
null
null
UTF-8
C++
false
false
1,275
h
//include //------------------------------------------ #include <vector> #include <list> #include <map> #include <set> #include <deque> #include <stack> #include <bitset> #include <algorithm> #include <functional> #include <numeric> #include <utility> #include <sstream> #include <iostream> #include <iomanip> #include <cstdio> #include <cmath> #include <cstdlib> #include <cctype> #include <string> #include <cstring> #include <ctime> using namespace std; //repetition //------------------------------------------ #define FOR(i,a,b) for(int i=(a);i<(b);++i) #define REP(i,n) FOR(i,0,n) class AfraidOfEven { int isAr(vector<int> seq){ int x = seq[1] - seq[0]; FOR(i,1,seq.size()) if(seq[i-1] + x != seq[i]) return i; return -1; } public: vector<int> restoreProgression(vector<int> seq) { vector<int> temp; FOR(i,0,seq.size()) temp.push_back(seq[i]); int two = seq[1]; int i = isAr(temp); while(i != -1){ int x = temp[1] - temp[0]; if(temp[i] <= temp[i-1] + x) temp[i] = temp[i] * 2; else{ seq[1] = seq[1] * 2; if(1000 < seq[1]){ seq[1] = two; seq[0] = seq[0] * 2; } temp.clear(); FOR(i,0,seq.size()) temp.push_back(seq[i]); } i = isAr(temp); } return vector<int>(temp); } };
[ "desktop@example.com" ]
desktop@example.com
6eaaffe68426eb06c0b505535132db34ed4f8d9d
41ec0ccf925ca4aea2b8688e247ca0cfa3f7a37b
/common/include/pcl/cloud_properties.h
fc344a6522314ae9cb1ba9a75b484d9682028c7c
[ "BSD-3-Clause" ]
permissive
0000duck/PCL-1
3a46d1ec48c772a82d0cc886cd8fbb1df153964a
7b828f3f4319f6c15e6a063d881be098d9ddef0e
refs/heads/master
2021-12-02T11:54:13.877225
2012-02-15T23:38:58
2012-02-15T23:38:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,117
h
/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2010-2011, Willow Garage, Inc. * * 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 Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * $Id$ * */ #ifndef PCL_CLOUD_PROPERTIES_H_ #define PCL_CLOUD_PROPERTIES_H_ namespace pcl { /** \brief CloudProperties stores a list of \b optional point cloud properties such as: * * - acquisition time * - the origin and orientation of the sensor when the data was acquired * - optional user parameters * * <b>This part of the API is for advanced users only, and constitutes a transition to the 2.0 API!</b> * * \author Radu B. Rusu */ class CloudProperties { public: /** \brief Default constructor. Sets: * * - \ref acquisition_time to 0 * - \ref sensor_origin to {0, 0, 0} * - \ref sensor_orientation to {1, 0, 0, 0} */ CloudProperties () : acquisition_time (0), sensor_origin (Eigen::Vector4f::Zero ()), sensor_orientation (Eigen::Quaternionf::Identity ()) { } /** \brief Data acquisition time. */ uint64_t acquisition_time; /** \brief Sensor acquisition pose (origin/translation in the cloud data coordinate system). */ Eigen::Vector4f sensor_origin; /** \brief Sensor acquisition pose (rotation in the cloud data coordinate system). * \note the data is stored in (w, x, y, z) format. */ Eigen::Quaternionf sensor_orientation; }; } #endif // PCL_CLOUD_PROPERTIES_H_
[ "rusu@a9d63959-f2ad-4865-b262-bf0e56cfafb6" ]
rusu@a9d63959-f2ad-4865-b262-bf0e56cfafb6
d2a07d0913d9765a8ce8864657b5d775d9c723a0
33035c05aad9bca0b0cefd67529bdd70399a9e04
/src/boost_fusion_sequence_comparison_equal_to.hpp
aede19bebef2025d433365c92bd970cd74a809aa
[ "LicenseRef-scancode-unknown-license-reference", "BSL-1.0" ]
permissive
elvisbugs/BoostForArduino
7e2427ded5fd030231918524f6a91554085a8e64
b8c912bf671868e2182aa703ed34076c59acf474
refs/heads/master
2023-03-25T13:11:58.527671
2021-03-27T02:37:29
2021-03-27T02:37:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
57
hpp
#include <boost/fusion/sequence/comparison/equal_to.hpp>
[ "k@kekyo.net" ]
k@kekyo.net
67523e3cdbb3f96d95853b64639a686269a3715b
dcfb571b8246b3f2750c614f2b2dd2e5cc2322ec
/src/rpc/server.cpp
c2c6aa34b676d3239b6654b17d8acbd5203e659a
[ "MIT" ]
permissive
ElCrebel/Merebel
59e58ed0e17e13740cefbc20fbe16a6f0b218d79
307f870adf14ec46d46f3f7b5c02d892da53eb2a
refs/heads/master
2021-08-18T05:48:32.561466
2020-04-06T02:47:44
2020-04-06T02:47:44
154,519,483
8
1
null
null
null
null
UTF-8
C++
false
false
27,944
cpp
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2019 The MEREBEL developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "rpc/server.h" #include "base58.h" #include "init.h" #include "main.h" #include "random.h" #include "sync.h" #include "guiinterface.h" #include "util.h" #include "utilstrencodings.h" #include <boost/bind.hpp> #include <boost/filesystem.hpp> #include <boost/iostreams/concepts.hpp> #include <boost/iostreams/stream.hpp> #include <boost/shared_ptr.hpp> #include <boost/signals2/signal.hpp> #include <boost/thread.hpp> #include <boost/algorithm/string/case_conv.hpp> // for to_upper() #include <univalue.h> static bool fRPCRunning = false; static bool fRPCInWarmup = true; static std::string rpcWarmupStatus("RPC server started"); static CCriticalSection cs_rpcWarmup; /* Timer-creating functions */ static RPCTimerInterface* timerInterface = NULL; /* Map of name to timer. * @note Can be changed to std::unique_ptr when C++11 */ static std::map<std::string, boost::shared_ptr<RPCTimerBase> > deadlineTimers; static struct CRPCSignals { boost::signals2::signal<void ()> Started; boost::signals2::signal<void ()> Stopped; boost::signals2::signal<void (const CRPCCommand&)> PreCommand; boost::signals2::signal<void (const CRPCCommand&)> PostCommand; } g_rpcSignals; void RPCServer::OnStarted(boost::function<void ()> slot) { g_rpcSignals.Started.connect(slot); } void RPCServer::OnStopped(boost::function<void ()> slot) { g_rpcSignals.Stopped.connect(slot); } void RPCServer::OnPreCommand(boost::function<void (const CRPCCommand&)> slot) { g_rpcSignals.PreCommand.connect(boost::bind(slot, _1)); } void RPCServer::OnPostCommand(boost::function<void (const CRPCCommand&)> slot) { g_rpcSignals.PostCommand.connect(boost::bind(slot, _1)); } void RPCTypeCheck(const UniValue& params, const std::list<UniValue::VType>& typesExpected, bool fAllowNull) { unsigned int i = 0; for (UniValue::VType t : typesExpected) { if (params.size() <= i) break; const UniValue& v = params[i]; if (!((v.type() == t) || (fAllowNull && (v.isNull())))) { std::string err = strprintf("Expected type %s, got %s", uvTypeName(t), uvTypeName(v.type())); throw JSONRPCError(RPC_TYPE_ERROR, err); } i++; } } void RPCTypeCheckObj(const UniValue& o, const std::map<std::string, UniValue::VType>& typesExpected, bool fAllowNull) { for (const PAIRTYPE(std::string, UniValue::VType)& t : typesExpected) { const UniValue& v = find_value(o, t.first); if (!fAllowNull && v.isNull()) throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing %s", t.first)); if (!((v.type() == t.second) || (fAllowNull && (v.isNull())))) { std::string err = strprintf("Expected type %s for %s, got %s", uvTypeName(t.second), t.first, uvTypeName(v.type())); throw JSONRPCError(RPC_TYPE_ERROR, err); } } } static inline int64_t roundint64(double d) { return (int64_t)(d > 0 ? d + 0.5 : d - 0.5); } CAmount AmountFromValue(const UniValue& value) { if (!value.isNum()) throw JSONRPCError(RPC_TYPE_ERROR, "Amount is not a number"); double dAmount = value.get_real(); if (dAmount <= 0.0 || dAmount > 21000000.0) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount"); CAmount nAmount = roundint64(dAmount * COIN); if (!MoneyRange(nAmount)) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount"); return nAmount; } UniValue ValueFromAmount(const CAmount& amount) { bool sign = amount < 0; int64_t n_abs = (sign ? -amount : amount); int64_t quotient = n_abs / COIN; int64_t remainder = n_abs % COIN; return UniValue(UniValue::VNUM, strprintf("%s%d.%08d", sign ? "-" : "", quotient, remainder)); } uint256 ParseHashV(const UniValue& v, std::string strName) { std::string strHex; if (v.isStr()) strHex = v.get_str(); if (!IsHex(strHex)) // Note: IsHex("") is false throw JSONRPCError(RPC_INVALID_PARAMETER, strName + " must be hexadecimal string (not '" + strHex + "')"); if (64 != strHex.length()) throw JSONRPCError(RPC_INVALID_PARAMETER, strprintf("%s must be of length %d (not %d)", strName, 64, strHex.length())); uint256 result; result.SetHex(strHex); return result; } uint256 ParseHashO(const UniValue& o, std::string strKey) { return ParseHashV(find_value(o, strKey), strKey); } std::vector<unsigned char> ParseHexV(const UniValue& v, std::string strName) { std::string strHex; if (v.isStr()) strHex = v.get_str(); if (!IsHex(strHex)) throw JSONRPCError(RPC_INVALID_PARAMETER, strName + " must be hexadecimal string (not '" + strHex + "')"); return ParseHex(strHex); } std::vector<unsigned char> ParseHexO(const UniValue& o, std::string strKey) { return ParseHexV(find_value(o, strKey), strKey); } int ParseInt(const UniValue& o, std::string strKey) { const UniValue& v = find_value(o, strKey); if (v.isNum()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, " + strKey + "is not an int"); return v.get_int(); } bool ParseBool(const UniValue& o, std::string strKey) { const UniValue& v = find_value(o, strKey); if (v.isBool()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, " + strKey + "is not a bool"); return v.get_bool(); } /** * Note: This interface may still be subject to change. */ std::string CRPCTable::help(std::string strCommand) const { std::string strRet; std::string category; std::set<rpcfn_type> setDone; std::vector<std::pair<std::string, const CRPCCommand*> > vCommands; for (std::map<std::string, const CRPCCommand*>::const_iterator mi = mapCommands.begin(); mi != mapCommands.end(); ++mi) vCommands.push_back(std::make_pair(mi->second->category + mi->first, mi->second)); std::sort(vCommands.begin(), vCommands.end()); for (const PAIRTYPE(std::string, const CRPCCommand*) & command : vCommands) { const CRPCCommand* pcmd = command.second; std::string strMethod = pcmd->name; // We already filter duplicates, but these deprecated screw up the sort order if (strMethod.find("label") != std::string::npos) continue; if ((strCommand != "" || pcmd->category == "hidden") && strMethod != strCommand) continue; #ifdef ENABLE_WALLET if (pcmd->reqWallet && !pwalletMain) continue; #endif try { UniValue params; rpcfn_type pfn = pcmd->actor; if (setDone.insert(pfn).second) (*pfn)(params, true); } catch (std::exception& e) { // Help text is returned in an exception std::string strHelp = std::string(e.what()); if (strCommand == "") { if (strHelp.find('\n') != std::string::npos) strHelp = strHelp.substr(0, strHelp.find('\n')); if (category != pcmd->category) { if (!category.empty()) strRet += "\n"; category = pcmd->category; std::string firstLetter = category.substr(0, 1); boost::to_upper(firstLetter); strRet += "== " + firstLetter + category.substr(1) + " ==\n"; } } strRet += strHelp + "\n"; } } if (strRet == "") strRet = strprintf("help: unknown command: %s\n", strCommand); strRet = strRet.substr(0, strRet.size() - 1); return strRet; } UniValue help(const UniValue& params, bool fHelp) { if (fHelp || params.size() > 1) throw std::runtime_error( "help ( \"command\" )\n" "\nList all commands, or get help for a specified command.\n" "\nArguments:\n" "1. \"command\" (string, optional) The command to get help on\n" "\nResult:\n" "\"text\" (string) The help text\n"); std::string strCommand; if (params.size() > 0) strCommand = params[0].get_str(); return tableRPC.help(strCommand); } UniValue stop(const UniValue& params, bool fHelp) { // Accept the deprecated and ignored 'detach' boolean argument if (fHelp || params.size() > 1) throw std::runtime_error( "stop\n" "\nStop MEREBEL server."); // Event loop will exit after current HTTP requests have been handled, so // this reply will get back to the client. StartShutdown(); return "MEREBEL server stopping"; } /** * Call Table */ static const CRPCCommand vRPCCommands[] = { // category name actor (function) okSafeMode threadSafe reqWallet // --------------------- ------------------------ ----------------------- ---------- ---------- --------- /* Overall control/query calls */ {"control", "getinfo", &getinfo, true, false, false}, /* uses wallet if enabled */ {"control", "help", &help, true, true, false}, {"control", "stop", &stop, true, true, false}, /* P2P networking */ {"network", "getnetworkinfo", &getnetworkinfo, true, false, false}, {"network", "addnode", &addnode, true, true, false}, {"network", "disconnectnode", &disconnectnode, true, true, false}, {"network", "getaddednodeinfo", &getaddednodeinfo, true, true, false}, {"network", "getconnectioncount", &getconnectioncount, true, false, false}, {"network", "getnettotals", &getnettotals, true, true, false}, {"network", "getpeerinfo", &getpeerinfo, true, false, false}, {"network", "ping", &ping, true, false, false}, {"network", "setban", &setban, true, false, false}, {"network", "listbanned", &listbanned, true, false, false}, {"network", "clearbanned", &clearbanned, true, false, false}, /* Block chain and UTXO */ {"blockchain", "findserial", &findserial, true, false, false}, {"blockchain", "getaccumulatorvalues", &getaccumulatorvalues, true, false, false}, {"blockchain", "getaccumulatorwitness", &getaccumulatorwitness, true, false, false}, {"blockchain", "getblockindexstats", &getblockindexstats, true, false, false}, {"blockchain", "getmintsinblocks", &getmintsinblocks, true, false, false}, {"blockchain", "getserials", &getserials, true, false, false}, {"blockchain", "getblockchaininfo", &getblockchaininfo, true, false, false}, {"blockchain", "getbestblockhash", &getbestblockhash, true, false, false}, {"blockchain", "getblockcount", &getblockcount, true, false, false}, {"blockchain", "getblock", &getblock, true, false, false}, {"blockchain", "getblockhash", &getblockhash, true, false, false}, {"blockchain", "getblockheader", &getblockheader, false, false, false}, {"blockchain", "getchaintips", &getchaintips, true, false, false}, {"blockchain", "getchecksumblock", &getchecksumblock, false, false, false}, {"blockchain", "getdifficulty", &getdifficulty, true, false, false}, {"blockchain", "getfeeinfo", &getfeeinfo, true, false, false}, {"blockchain", "getmempoolinfo", &getmempoolinfo, true, true, false}, {"blockchain", "getrawmempool", &getrawmempool, true, false, false}, {"blockchain", "gettxout", &gettxout, true, false, false}, {"blockchain", "gettxoutsetinfo", &gettxoutsetinfo, true, false, false}, {"blockchain", "invalidateblock", &invalidateblock, true, true, false}, {"blockchain", "reconsiderblock", &reconsiderblock, true, true, false}, {"blockchain", "verifychain", &verifychain, true, false, false}, /* Mining */ {"mining", "getblocktemplate", &getblocktemplate, true, false, false}, {"mining", "getmininginfo", &getmininginfo, true, false, false}, {"mining", "getnetworkhashps", &getnetworkhashps, true, false, false}, {"mining", "prioritisetransaction", &prioritisetransaction, true, false, false}, {"mining", "submitblock", &submitblock, true, true, false}, {"mining", "reservebalance", &reservebalance, true, true, false}, #ifdef ENABLE_WALLET /* Coin generation */ {"generating", "getgenerate", &getgenerate, true, false, false}, {"generating", "gethashespersec", &gethashespersec, true, false, false}, {"generating", "setgenerate", &setgenerate, true, true, false}, {"generating", "generate", &generate, true, true, false}, #endif /* Raw transactions */ {"rawtransactions", "createrawtransaction", &createrawtransaction, true, false, false}, {"rawtransactions", "decoderawtransaction", &decoderawtransaction, true, false, false}, {"rawtransactions", "decodescript", &decodescript, true, false, false}, {"rawtransactions", "getrawtransaction", &getrawtransaction, true, false, false}, {"rawtransactions", "sendrawtransaction", &sendrawtransaction, false, false, false}, {"rawtransactions", "signrawtransaction", &signrawtransaction, false, false, false}, /* uses wallet if enabled */ /* Utility functions */ {"util", "createmultisig", &createmultisig, true, true, false}, {"util", "validateaddress", &validateaddress, true, false, false}, /* uses wallet if enabled */ {"util", "verifymessage", &verifymessage, true, false, false}, {"util", "estimatefee", &estimatefee, true, true, false}, {"util", "estimatepriority", &estimatepriority, true, true, false}, /* Not shown in help */ {"hidden", "invalidateblock", &invalidateblock, true, true, false}, {"hidden", "reconsiderblock", &reconsiderblock, true, true, false}, {"hidden", "setmocktime", &setmocktime, true, false, false}, { "hidden", "waitfornewblock", &waitfornewblock, true, true, false }, { "hidden", "waitforblock", &waitforblock, true, true, false }, { "hidden", "waitforblockheight", &waitforblockheight, true, true, false }, /* MEREBEL features */ {"Merebel", "listmasternodes", &listmasternodes, true, true, false}, {"Merebel", "getmasternodecount", &getmasternodecount, true, true, false}, {"Merebel", "masternodeconnect", &masternodeconnect, true, true, false}, {"Merebel", "createmasternodebroadcast", &createmasternodebroadcast, true, true, false}, {"Merebel", "decodemasternodebroadcast", &decodemasternodebroadcast, true, true, false}, {"Merebel", "relaymasternodebroadcast", &relaymasternodebroadcast, true, true, false}, {"Merebel", "masternodecurrent", &masternodecurrent, true, true, false}, {"Merebel", "masternodedebug", &masternodedebug, true, true, false}, {"Merebel", "startmasternode", &startmasternode, true, true, false}, {"Merebel", "createmasternodekey", &createmasternodekey, true, true, false}, {"Merebel", "getmasternodeoutputs", &getmasternodeoutputs, true, true, false}, {"Merebel", "listmasternodeconf", &listmasternodeconf, true, true, false}, {"Merebel", "getmasternodestatus", &getmasternodestatus, true, true, false}, {"Merebel", "getmasternodewinners", &getmasternodewinners, true, true, false}, {"Merebel", "getmasternodescores", &getmasternodescores, true, true, false}, {"Merebel", "preparebudget", &preparebudget, true, true, false}, {"Merebel", "submitbudget", &submitbudget, true, true, false}, {"Merebel", "mnbudgetvote", &mnbudgetvote, true, true, false}, {"Merebel", "getbudgetvotes", &getbudgetvotes, true, true, false}, {"Merebel", "getnextsuperblock", &getnextsuperblock, true, true, false}, {"Merebel", "getbudgetprojection", &getbudgetprojection, true, true, false}, {"Merebel", "getbudgetinfo", &getbudgetinfo, true, true, false}, {"Merebel", "mnbudgetrawvote", &mnbudgetrawvote, true, true, false}, {"Merebel", "mnfinalbudget", &mnfinalbudget, true, true, false}, {"Merebel", "checkbudgets", &checkbudgets, true, true, false}, {"Merebel", "mnsync", &mnsync, true, true, false}, {"Merebel", "spork", &spork, true, true, false}, {"Merebel", "getpoolinfo", &getpoolinfo, true, true, false}, #ifdef ENABLE_WALLET /* Wallet */ {"wallet", "addmultisigaddress", &addmultisigaddress, true, false, true}, {"wallet", "autocombinerewards", &autocombinerewards, false, false, true}, {"wallet", "backupwallet", &backupwallet, true, false, true}, {"wallet", "enableautomintaddress", &enableautomintaddress, true, false, true}, {"wallet", "createautomintaddress", &createautomintaddress, true, false, true}, {"wallet", "dumpprivkey", &dumpprivkey, true, false, true}, {"wallet", "dumpwallet", &dumpwallet, true, false, true}, {"wallet", "bip38encrypt", &bip38encrypt, true, false, true}, {"wallet", "bip38decrypt", &bip38decrypt, true, false, true}, {"wallet", "encryptwallet", &encryptwallet, true, false, true}, {"wallet", "getaccountaddress", &getaccountaddress, true, false, true}, {"wallet", "getaccount", &getaccount, true, false, true}, {"wallet", "getaddressesbyaccount", &getaddressesbyaccount, true, false, true}, {"wallet", "getbalance", &getbalance, false, false, true}, {"wallet", "getnewaddress", &getnewaddress, true, false, true}, {"wallet", "getrawchangeaddress", &getrawchangeaddress, true, false, true}, {"wallet", "getreceivedbyaccount", &getreceivedbyaccount, false, false, true}, {"wallet", "getreceivedbyaddress", &getreceivedbyaddress, false, false, true}, {"wallet", "getstakingstatus", &getstakingstatus, false, false, true}, {"wallet", "getstakesplitthreshold", &getstakesplitthreshold, false, false, true}, {"wallet", "gettransaction", &gettransaction, false, false, true}, {"wallet", "getunconfirmedbalance", &getunconfirmedbalance, false, false, true}, {"wallet", "getwalletinfo", &getwalletinfo, false, false, true}, {"wallet", "importprivkey", &importprivkey, true, false, true}, {"wallet", "importwallet", &importwallet, true, false, true}, {"wallet", "importaddress", &importaddress, true, false, true}, {"wallet", "keypoolrefill", &keypoolrefill, true, false, true}, {"wallet", "listaccounts", &listaccounts, false, false, true}, {"wallet", "listaddressgroupings", &listaddressgroupings, false, false, true}, {"wallet", "listlockunspent", &listlockunspent, false, false, true}, {"wallet", "listreceivedbyaccount", &listreceivedbyaccount, false, false, true}, {"wallet", "listreceivedbyaddress", &listreceivedbyaddress, false, false, true}, {"wallet", "listsinceblock", &listsinceblock, false, false, true}, {"wallet", "listtransactions", &listtransactions, false, false, true}, {"wallet", "listunspent", &listunspent, false, false, true}, {"wallet", "lockunspent", &lockunspent, true, false, true}, {"wallet", "move", &movecmd, false, false, true}, {"wallet", "multisend", &multisend, false, false, true}, {"wallet", "sendfrom", &sendfrom, false, false, true}, {"wallet", "sendmany", &sendmany, false, false, true}, {"wallet", "sendtoaddress", &sendtoaddress, false, false, true}, {"wallet", "sendtoaddressix", &sendtoaddressix, false, false, true}, {"wallet", "setaccount", &setaccount, true, false, true}, {"wallet", "setstakesplitthreshold", &setstakesplitthreshold, false, false, true}, {"wallet", "settxfee", &settxfee, true, false, true}, {"wallet", "signmessage", &signmessage, true, false, true}, {"wallet", "walletlock", &walletlock, true, false, true}, {"wallet", "walletpassphrasechange", &walletpassphrasechange, true, false, true}, {"wallet", "walletpassphrase", &walletpassphrase, true, false, true}, {"zerocoin", "createrawzerocoinstake", &createrawzerocoinstake, false, false, true}, {"zerocoin", "createrawzerocoinpublicspend", &createrawzerocoinpublicspend, false, false, true}, {"zerocoin", "getzerocoinbalance", &getzerocoinbalance, false, false, true}, {"zerocoin", "listmintedzerocoins", &listmintedzerocoins, false, false, true}, {"zerocoin", "listspentzerocoins", &listspentzerocoins, false, false, true}, {"zerocoin", "listzerocoinamounts", &listzerocoinamounts, false, false, true}, {"zerocoin", "mintzerocoin", &mintzerocoin, false, false, true}, {"zerocoin", "spendzerocoin", &spendzerocoin, false, false, true}, {"zerocoin", "spendrawzerocoin", &spendrawzerocoin, true, false, false}, {"zerocoin", "spendzerocoinmints", &spendzerocoinmints, false, false, true}, {"zerocoin", "resetmintzerocoin", &resetmintzerocoin, false, false, true}, {"zerocoin", "resetspentzerocoin", &resetspentzerocoin, false, false, true}, {"zerocoin", "getarchivedzerocoin", &getarchivedzerocoin, false, false, true}, {"zerocoin", "importzerocoins", &importzerocoins, false, false, true}, {"zerocoin", "exportzerocoins", &exportzerocoins, false, false, true}, {"zerocoin", "reconsiderzerocoins", &reconsiderzerocoins, false, false, true}, {"zerocoin", "getspentzerocoinamount", &getspentzerocoinamount, false, false, false}, {"zerocoin", "getzmeriseed", &getzmeriseed, false, false, true}, {"zerocoin", "setzmeriseed", &setzmeriseed, false, false, true}, {"zerocoin", "generatemintlist", &generatemintlist, false, false, true}, {"zerocoin", "searchdzmeri", &searchdzmeri, false, false, true}, {"zerocoin", "dzmeristate", &dzmeristate, false, false, true}, {"zerocoin", "clearspendcache", &clearspendcache, false, false, true} #endif // ENABLE_WALLET }; CRPCTable::CRPCTable() { unsigned int vcidx; for (vcidx = 0; vcidx < (sizeof(vRPCCommands) / sizeof(vRPCCommands[0])); vcidx++) { const CRPCCommand* pcmd; pcmd = &vRPCCommands[vcidx]; mapCommands[pcmd->name] = pcmd; } } const CRPCCommand *CRPCTable::operator[](const std::string &name) const { std::map<std::string, const CRPCCommand*>::const_iterator it = mapCommands.find(name); if (it == mapCommands.end()) return NULL; return (*it).second; } bool StartRPC() { LogPrint("rpc", "Starting RPC\n"); fRPCRunning = true; g_rpcSignals.Started(); return true; } void InterruptRPC() { LogPrint("rpc", "Interrupting RPC\n"); // Interrupt e.g. running longpolls fRPCRunning = false; } void StopRPC() { LogPrint("rpc", "Stopping RPC\n"); deadlineTimers.clear(); g_rpcSignals.Stopped(); } bool IsRPCRunning() { return fRPCRunning; } void SetRPCWarmupStatus(const std::string& newStatus) { LOCK(cs_rpcWarmup); rpcWarmupStatus = newStatus; } void SetRPCWarmupFinished() { LOCK(cs_rpcWarmup); assert(fRPCInWarmup); fRPCInWarmup = false; } bool RPCIsInWarmup(std::string* outStatus) { LOCK(cs_rpcWarmup); if (outStatus) *outStatus = rpcWarmupStatus; return fRPCInWarmup; } void JSONRequest::parse(const UniValue& valRequest) { // Parse request if (!valRequest.isObject()) throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object"); const UniValue& request = valRequest.get_obj(); // Parse id now so errors from here on will have the id id = find_value(request, "id"); // Parse method UniValue valMethod = find_value(request, "method"); if (valMethod.isNull()) throw JSONRPCError(RPC_INVALID_REQUEST, "Missing method"); if (!valMethod.isStr()) throw JSONRPCError(RPC_INVALID_REQUEST, "Method must be a string"); strMethod = valMethod.get_str(); if (strMethod != "getblocktemplate") LogPrint("rpc", "ThreadRPCServer method=%s\n", SanitizeString(strMethod)); // Parse params UniValue valParams = find_value(request, "params"); if (valParams.isArray()) params = valParams.get_array(); else if (valParams.isNull()) params = UniValue(UniValue::VARR); else throw JSONRPCError(RPC_INVALID_REQUEST, "Params must be an array"); } static UniValue JSONRPCExecOne(const UniValue& req) { UniValue rpc_result(UniValue::VOBJ); JSONRequest jreq; try { jreq.parse(req); UniValue result = tableRPC.execute(jreq.strMethod, jreq.params); rpc_result = JSONRPCReplyObj(result, NullUniValue, jreq.id); } catch (const UniValue& objError) { rpc_result = JSONRPCReplyObj(NullUniValue, objError, jreq.id); } catch (std::exception& e) { rpc_result = JSONRPCReplyObj(NullUniValue, JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id); } return rpc_result; } std::string JSONRPCExecBatch(const UniValue& vReq) { UniValue ret(UniValue::VARR); for (unsigned int reqIdx = 0; reqIdx < vReq.size(); reqIdx++) ret.push_back(JSONRPCExecOne(vReq[reqIdx])); return ret.write() + "\n"; } UniValue CRPCTable::execute(const std::string &strMethod, const UniValue &params) const { // Find method const CRPCCommand* pcmd = tableRPC[strMethod]; if (!pcmd) throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found"); g_rpcSignals.PreCommand(*pcmd); try { // Execute return pcmd->actor(params, false); } catch (std::exception& e) { throw JSONRPCError(RPC_MISC_ERROR, e.what()); } g_rpcSignals.PostCommand(*pcmd); } std::vector<std::string> CRPCTable::listCommands() const { std::vector<std::string> commandList; typedef std::map<std::string, const CRPCCommand*> commandMap; std::transform( mapCommands.begin(), mapCommands.end(), std::back_inserter(commandList), boost::bind(&commandMap::value_type::first,_1) ); return commandList; } std::string HelpExampleCli(std::string methodname, std::string args) { return "> Merebel-cli " + methodname + " " + args + "\n"; } std::string HelpExampleRpc(std::string methodname, std::string args) { return "> curl --user myusername --data-binary '{\"jsonrpc\": \"1.0\", \"id\":\"curltest\", " "\"method\": \"" + methodname + "\", \"params\": [" + args + "] }' -H 'content-type: text/plain;' http://127.0.0.1:51473/\n"; } void RPCSetTimerInterfaceIfUnset(RPCTimerInterface *iface) { if (!timerInterface) timerInterface = iface; } void RPCSetTimerInterface(RPCTimerInterface *iface) { timerInterface = iface; } void RPCUnsetTimerInterface(RPCTimerInterface *iface) { if (timerInterface == iface) timerInterface = NULL; } void RPCRunLater(const std::string& name, boost::function<void(void)> func, int64_t nSeconds) { if (!timerInterface) throw JSONRPCError(RPC_INTERNAL_ERROR, "No timer handler registered for RPC"); deadlineTimers.erase(name); LogPrint("rpc", "queue run of timer %s in %i seconds (using %s)\n", name, nSeconds, timerInterface->Name()); deadlineTimers.insert(std::make_pair(name, boost::shared_ptr<RPCTimerBase>(timerInterface->NewTimer(func, nSeconds*1000)))); } const CRPCTable tableRPC;
[ "flouwshifter@gmail.com" ]
flouwshifter@gmail.com
2af87e07d8e394ced345d2b5ad1a3403135d9936
f6b7d6840e7aed48ec0d11fbdd8d2a548d1e233a
/NeilWarrack_SUPACOO_Assign3/system.cc
cdd5ee3043e7dfe6ea8188bb541e6bfb1dbbed67
[]
no_license
neilwarrack/c_tutorials
c035c5c42e6561007c40f686f53c87d466f7fea6
94e309e1dad55144da9a557ba9183b2ff64da59c
refs/heads/master
2021-09-01T20:05:40.988076
2017-12-28T14:18:32
2017-12-28T14:18:32
110,580,208
0
0
null
null
null
null
UTF-8
C++
false
false
2,963
cc
#include <vector> #include <string> #include <cmath> #include <iostream> #include "planets.h" #include "system.h" using namespace std ; System::System(const vector<Planet>& planets ){ m_system = planets ; m_planet1 = m_system[0] ; } vector<Planet> System::GetPlanets() { return m_system ; } void System::IndexSolarSystem(){ // index planets according to : // 1 = EARTH ; 2 = MOON ; 3 = SUN ; 4 = MERCURY ; 5 = VENUS ; 6 = MARS ; 7 = JUPITER ; 8 = SATURN ; 9 = URANUS ; 0 = NEPTUNE for (Planet& n : m_system ) { if (n.GetMass() == 5.9736e+24 ) {n.SetIndex(1) ;}// cout << "Earth indexed: " << n.GetIndex() ;} if (n.GetMass() == 7.3477e+22 ) {n.SetIndex(2) ;}// cout << "Moon indexed: " << n.GetIndex() ;} if (n.GetMass() == 1.9890e+30 ) {n.SetIndex(3) ;}// cout << "Sun indexed: " << n.GetIndex() ;} if (n.GetMass() == 3.3022e+23 ) {n.SetIndex(4) ;}// cout << "Mercury indexed: " << n.GetIndex() ;} if (n.GetMass() == 4.8685e+24 ) {n.SetIndex(5) ;}// cout << "Venus indexed: " << n.GetIndex() ;} if (n.GetMass() == 6.4185e+23 ) {n.SetIndex(6) ;}// cout << "Mars indexed: " << n.GetIndex() ;} if (n.GetMass() == 1.8986e+27 ) {n.SetIndex(7) ;}// cout << "Jupiter indexed: " << n.GetIndex() ;} if (n.GetMass() == 5.6846e+26 ) {n.SetIndex(8) ;}// cout << "Saturn indexed: " << n.GetIndex() ;} if (n.GetMass() == 8.6810e+25 ) {n.SetIndex(9) ;}// cout << "Uranus indexed: " << n.GetIndex() ;} if (n.GetMass() == 1.0243e+26 ) {n.SetIndex(0) ;}// cout << "Neptune indexed: " << n.GetIndex() ;} } } void System::EvolveSystem( double dt){ const static double days = 86400 ; double time = dt*days ; // time in seconds const static double G = 6.674e-11 ; // Gravitational constant double a = 0.0 ; // magnitudue of acceleration double a_x = 0.0 ; // acceleration in x direction double sum_a_x = 0.0 ; double a_y = 0.0 ; // acceleration in y direction double sum_a_y = 0.0 ; double rsqrd = 0.0 ; // distance double hypot = 0.0 ; // = sqrt(rsqrd) // Compute x and y accelleration of p due to all other bodies q. for (Planet& p : m_system ) { if ( sum_a_x != 0.0 ) sum_a_x = 0.0 ; // reset sum! if ( sum_a_y != 0.0 ) sum_a_y = 0.0 ; // reset sum! for (const Planet& q : m_system ){ if ( &p == &q ) continue ; // don't compute planets force 'with itself'! rsqrd = (p.GetX0() - q.GetX0() )*(p.GetX0() - q.GetX0() ) + (p.GetY0() - q.GetY0() )*(p.GetY0() - q.GetY0() ) ; hypot = sqrt(rsqrd) ; a = -G*q.GetMass()/rsqrd ; a_x = a*(p.GetX0() - q.GetX0() )/hypot ; a_y = a*(p.GetY0() - q.GetY0() )/hypot ; sum_a_x = sum_a_x + a_x ; sum_a_y = sum_a_y + a_y ; } p.SetXA0(sum_a_x); p.SetYA0(sum_a_y); } for ( Planet& s : m_system ){ s.EvolveX(time) ; s.EvolveY(time) ; } }
[ "neil.warrack@gmail.com" ]
neil.warrack@gmail.com
d5a8d73ed5d2f74624616f33747c6f71f85978b3
c67cbd22f9bc3c465fd763fdf87172f2c8ec77d4
/Desktop/Please Work/build/Android/Preview/app/src/main/include/Fuse.Animations.Easing.h
15a77c02e1f9747eb6ec9e650c5dfcc690c67ff0
[]
no_license
AzazelMoreno/Soteria-project
7c58896d6bf5a9ad919bde6ddc2a30f4a07fa0d4
04fdb71065941176867fb9007ecf38bbf851ad47
refs/heads/master
2020-03-11T16:33:22.153713
2018-04-19T19:47:55
2018-04-19T19:47:55
130,120,337
0
0
null
null
null
null
UTF-8
C++
false
false
4,959
h
// This file was generated based on C:/Users/rudy0/AppData/Local/Fusetools/Packages/Fuse.Common/1.8.1/Easing.uno. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Uno.Object.h> namespace g{namespace Fuse{namespace Animations{struct Easing;}}} namespace g{ namespace Fuse{ namespace Animations{ // public abstract class Easing :13 // { struct Easing_type : uType { void(*fp_Map)(::g::Fuse::Animations::Easing*, double*, double*); }; Easing_type* Easing_typeof(); void Easing__ctor__fn(Easing* __this); struct Easing : uObject { static uSStrong<Easing*> Linear_; static uSStrong<Easing*>& Linear() { return Easing_typeof()->Init(), Linear_; } static uSStrong<Easing*> QuadraticIn_; static uSStrong<Easing*>& QuadraticIn() { return Easing_typeof()->Init(), QuadraticIn_; } static uSStrong<Easing*> QuadraticOut_; static uSStrong<Easing*>& QuadraticOut() { return Easing_typeof()->Init(), QuadraticOut_; } static uSStrong<Easing*> QuadraticInOut_; static uSStrong<Easing*>& QuadraticInOut() { return Easing_typeof()->Init(), QuadraticInOut_; } static uSStrong<Easing*> CubicIn_; static uSStrong<Easing*>& CubicIn() { return Easing_typeof()->Init(), CubicIn_; } static uSStrong<Easing*> CubicOut_; static uSStrong<Easing*>& CubicOut() { return Easing_typeof()->Init(), CubicOut_; } static uSStrong<Easing*> CubicInOut_; static uSStrong<Easing*>& CubicInOut() { return Easing_typeof()->Init(), CubicInOut_; } static uSStrong<Easing*> QuarticIn_; static uSStrong<Easing*>& QuarticIn() { return Easing_typeof()->Init(), QuarticIn_; } static uSStrong<Easing*> QuarticOut_; static uSStrong<Easing*>& QuarticOut() { return Easing_typeof()->Init(), QuarticOut_; } static uSStrong<Easing*> QuarticInOut_; static uSStrong<Easing*>& QuarticInOut() { return Easing_typeof()->Init(), QuarticInOut_; } static uSStrong<Easing*> QuinticIn_; static uSStrong<Easing*>& QuinticIn() { return Easing_typeof()->Init(), QuinticIn_; } static uSStrong<Easing*> QuinticOut_; static uSStrong<Easing*>& QuinticOut() { return Easing_typeof()->Init(), QuinticOut_; } static uSStrong<Easing*> QuinticInOut_; static uSStrong<Easing*>& QuinticInOut() { return Easing_typeof()->Init(), QuinticInOut_; } static uSStrong<Easing*> SinusoidalIn_; static uSStrong<Easing*>& SinusoidalIn() { return Easing_typeof()->Init(), SinusoidalIn_; } static uSStrong<Easing*> SinusoidalOut_; static uSStrong<Easing*>& SinusoidalOut() { return Easing_typeof()->Init(), SinusoidalOut_; } static uSStrong<Easing*> SinusoidalInOut_; static uSStrong<Easing*>& SinusoidalInOut() { return Easing_typeof()->Init(), SinusoidalInOut_; } static uSStrong<Easing*> ExponentialIn_; static uSStrong<Easing*>& ExponentialIn() { return Easing_typeof()->Init(), ExponentialIn_; } static uSStrong<Easing*> ExponentialOut_; static uSStrong<Easing*>& ExponentialOut() { return Easing_typeof()->Init(), ExponentialOut_; } static uSStrong<Easing*> ExponentialInOut_; static uSStrong<Easing*>& ExponentialInOut() { return Easing_typeof()->Init(), ExponentialInOut_; } static uSStrong<Easing*> CircularIn_; static uSStrong<Easing*>& CircularIn() { return Easing_typeof()->Init(), CircularIn_; } static uSStrong<Easing*> CircularOut_; static uSStrong<Easing*>& CircularOut() { return Easing_typeof()->Init(), CircularOut_; } static uSStrong<Easing*> CircularInOut_; static uSStrong<Easing*>& CircularInOut() { return Easing_typeof()->Init(), CircularInOut_; } static uSStrong<Easing*> ElasticIn_; static uSStrong<Easing*>& ElasticIn() { return Easing_typeof()->Init(), ElasticIn_; } static uSStrong<Easing*> ElasticOut_; static uSStrong<Easing*>& ElasticOut() { return Easing_typeof()->Init(), ElasticOut_; } static uSStrong<Easing*> ElasticInOut_; static uSStrong<Easing*>& ElasticInOut() { return Easing_typeof()->Init(), ElasticInOut_; } static uSStrong<Easing*> BackIn_; static uSStrong<Easing*>& BackIn() { return Easing_typeof()->Init(), BackIn_; } static uSStrong<Easing*> BackOut_; static uSStrong<Easing*>& BackOut() { return Easing_typeof()->Init(), BackOut_; } static uSStrong<Easing*> BackInOut_; static uSStrong<Easing*>& BackInOut() { return Easing_typeof()->Init(), BackInOut_; } static uSStrong<Easing*> BounceIn_; static uSStrong<Easing*>& BounceIn() { return Easing_typeof()->Init(), BounceIn_; } static uSStrong<Easing*> BounceOut_; static uSStrong<Easing*>& BounceOut() { return Easing_typeof()->Init(), BounceOut_; } static uSStrong<Easing*> BounceInOut_; static uSStrong<Easing*>& BounceInOut() { return Easing_typeof()->Init(), BounceInOut_; } void ctor_(); double Map(double p) { double __retval; return (((Easing_type*)__type)->fp_Map)(this, &p, &__retval), __retval; } }; // } }}} // ::g::Fuse::Animations
[ "rudy0604594@gmail.com" ]
rudy0604594@gmail.com
8033764d59c73ba82bbbb30ac70226ddb171d20b
f68c1a09ade5d969f3973246747466e4a540ff74
/src/prod/src/ServiceModel/CodePackageDescription.cpp
81c55349b4d4681c2dcf7d09e4b4b00c1032c624
[ "MIT" ]
permissive
GitTorre/service-fabric
ab38752d4cc7c8f2ee03553372c0f3e05911ff67
88da19dc5ea8edfe1c9abebe25a5c5079995db63
refs/heads/master
2021-04-09T10:57:45.678751
2018-08-20T19:17:28
2018-08-20T19:17:28
125,401,516
0
0
MIT
2018-03-15T17:13:53
2018-03-15T17:13:52
null
UTF-8
C++
false
false
9,561
cpp
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #include "stdafx.h" using namespace std; using namespace Common; using namespace ServiceModel; CodePackageDescription::CodePackageDescription() : Name(), Version(), IsShared(false), SetupEntryPoint(), HasSetupEntryPoint(false), EntryPoint(), EnvironmentVariables() { } CodePackageDescription::CodePackageDescription(CodePackageDescription const & other) : Name(other.Name), Version(other.Version), IsShared(other.IsShared), SetupEntryPoint(other.SetupEntryPoint), HasSetupEntryPoint(other.HasSetupEntryPoint), EntryPoint(other.EntryPoint), EnvironmentVariables(other.EnvironmentVariables) { } CodePackageDescription::CodePackageDescription(CodePackageDescription && other) : Name(move(other.Name)), Version(move(other.Version)), IsShared(other.IsShared), SetupEntryPoint(move(other.SetupEntryPoint)), HasSetupEntryPoint(other.HasSetupEntryPoint), EntryPoint(move(other.EntryPoint)), EnvironmentVariables(move(other.EnvironmentVariables)) { } CodePackageDescription const & CodePackageDescription::operator = (CodePackageDescription const & other) { if (this != & other) { this->Name = other.Name; this->Version = other.Version; this->IsShared = other.IsShared; this->SetupEntryPoint = other.SetupEntryPoint; this->HasSetupEntryPoint = other.HasSetupEntryPoint; this->EntryPoint = other.EntryPoint; this->EnvironmentVariables = other.EnvironmentVariables; } return *this; } CodePackageDescription const & CodePackageDescription::operator = (CodePackageDescription && other) { if (this != & other) { this->Name = move(other.Name); this->Version = move(other.Version); this->IsShared = other.IsShared; this->SetupEntryPoint = move(other.SetupEntryPoint); this->HasSetupEntryPoint = other.HasSetupEntryPoint; this->EntryPoint = move(other.EntryPoint); this->EnvironmentVariables = move(other.EnvironmentVariables); } return *this; } bool CodePackageDescription::operator == (CodePackageDescription const & other) const { bool equals = true; equals = StringUtility::AreEqualCaseInsensitive(this->Name, other.Name); if (!equals) { return equals; } equals = StringUtility::AreEqualCaseInsensitive(this->Version, other.Version); if (!equals) { return equals; } equals = this->IsShared == other.IsShared; if (!equals) { return equals; } equals = this->HasSetupEntryPoint == other.HasSetupEntryPoint; if (!equals) { return equals; } equals = this->SetupEntryPoint == other.SetupEntryPoint; if (!equals) { return equals; } equals = this->EntryPoint == other.EntryPoint; if (!equals) { return equals; } equals = this->EnvironmentVariables == other.EnvironmentVariables; if (!equals) { return equals; } return equals; } bool CodePackageDescription::operator != (CodePackageDescription const & other) const { return !(*this == other); } void CodePackageDescription::WriteTo(TextWriter & w, FormatOptions const &) const { w.Write("CodePackageDescription { "); w.Write("Name = {0}, ", Name); w.Write("Version = {0}, ", Version); w.Write("IsShared = {0}, ", IsShared); w.Write("HasSetupEntryPoint = {0}, ", HasSetupEntryPoint); w.Write("SetupEntryPoint = {0}, ", SetupEntryPoint); w.Write("EntryPoint = {0}, ", EntryPoint); w.Write("}"); } void CodePackageDescription::ReadFromXml( XmlReaderUPtr const & xmlReader) { clear(); // ensure that we are on <CodePackage xmlReader->StartElement( *SchemaNames::Element_CodePackage, *SchemaNames::Namespace); // Attributes <CodePackage Name="" Version="" { this->Name = xmlReader->ReadAttributeValue(*SchemaNames::Attribute_Name); this->Version = xmlReader->ReadAttributeValue(*SchemaNames::Attribute_Version); if (xmlReader->HasAttribute(*SchemaNames::Attribute_IsShared)) { wstring attrValue = xmlReader->ReadAttributeValue(*SchemaNames::Attribute_IsShared); if (!StringUtility::TryFromWString<bool>( attrValue, this->IsShared)) { Parser::ThrowInvalidContent(xmlReader, L"true/false", attrValue); } } } if (xmlReader->IsEmptyElement()) { xmlReader->ReadElement(); } else { // <CodePackage ..> xmlReader->ReadStartElement(); // SetupEntryPoint { if (xmlReader->IsStartElement( *SchemaNames::Element_SetupEntryPoint, *SchemaNames::Namespace, false)) { xmlReader->ReadStartElement(); this->SetupEntryPoint.ReadFromXml(xmlReader); xmlReader->ReadEndElement(); this->HasSetupEntryPoint = true; } } // Main entrypoint { EntryPoint.ReadFromXml(xmlReader); } if (xmlReader->IsStartElement( *SchemaNames::Element_EnvironmentVariables, *SchemaNames::Namespace)) { EnvironmentVariables.ReadFromXml(xmlReader); } // </CodePackage> xmlReader->ReadEndElement(); } } ErrorCode CodePackageDescription::WriteToXml(XmlWriterUPtr const & xmlWriter) { //<CodePackage> ErrorCode er = xmlWriter->WriteStartElement(*SchemaNames::Element_CodePackage, L"", *SchemaNames::Namespace); if (!er.IsSuccess()) { return er; } er = xmlWriter->WriteAttribute(*SchemaNames::Attribute_Name, this->Name); if (!er.IsSuccess()) { return er; } er = xmlWriter->WriteAttribute(*SchemaNames::Attribute_Version, this->Version); if (!er.IsSuccess()) { return er; } er = xmlWriter->WriteBooleanAttribute(*SchemaNames::Attribute_IsShared, this->IsShared); if (!er.IsSuccess()) { return er; } if (this->HasSetupEntryPoint) { er = WriteSetupEntryPoint(xmlWriter); if (!er.IsSuccess()) { return er; } } er = WriteEntryPoint(xmlWriter); if (!er.IsSuccess()) { return er; } //</CodePackage> return xmlWriter->WriteEndElement(); } ErrorCode CodePackageDescription::WriteSetupEntryPoint(XmlWriterUPtr const & xmlWriter) { //<SetupEntryPoint> ErrorCode er = xmlWriter->WriteStartElement(*SchemaNames::Element_SetupEntryPoint, L"", *SchemaNames::Namespace); if (!er.IsSuccess()) { return er; } er = this->SetupEntryPoint.WriteToXml(xmlWriter); if (!er.IsSuccess()) { return er; } //</SetupEntryPoint> return xmlWriter->WriteEndElement(); } ErrorCode CodePackageDescription::WriteEntryPoint(XmlWriterUPtr const & xmlWriter) { //<EntryPoint> ErrorCode er = xmlWriter->WriteStartElement(*SchemaNames::Element_EntryPoint, L"", *SchemaNames::Namespace); if (!er.IsSuccess()) { return er; } er = this->EntryPoint.WriteToXml(xmlWriter); if (!er.IsSuccess()) { return er; } //</EntryPoint> return xmlWriter->WriteEndElement(); } ErrorCode CodePackageDescription::FromPublicApi(FABRIC_CODE_PACKAGE_DESCRIPTION const & description) { this->clear(); this->Name = description.Name; this->Version = description.Version; this->IsShared = (description.IsShared == TRUE ? true : false); if (description.SetupEntryPoint != NULL) { auto error = this->SetupEntryPoint.FromPublicApi(*(description.SetupEntryPoint)); if (!error.IsSuccess()) { return error; } this->HasSetupEntryPoint = true; } if (description.EntryPoint == NULL) { return ErrorCode(ErrorCodeValue::InvalidArgument); } auto error = EntryPoint.FromPublicApi(*(description.EntryPoint)); if (!error.IsSuccess()) { return error; } return ErrorCode(ErrorCodeValue::Success); } void CodePackageDescription::ToPublicApi( __in ScopedHeap & heap, __in std::wstring const& serviceManifestName, __in wstring const& serviceManifestVersion, __out FABRIC_CODE_PACKAGE_DESCRIPTION & publicDescription) const { publicDescription.Name = heap.AddString(this->Name); publicDescription.Version = heap.AddString(this->Version); publicDescription.ServiceManifestName = heap.AddString(serviceManifestName); publicDescription.ServiceManifestVersion = heap.AddString(serviceManifestVersion); publicDescription.IsShared = (this->IsShared ? true : false); if (this->HasSetupEntryPoint) { auto setupEntryPoint = heap.AddItem<FABRIC_EXEHOST_ENTRY_POINT_DESCRIPTION>(); this->SetupEntryPoint.ToPublicApi(heap, *setupEntryPoint); publicDescription.SetupEntryPoint = setupEntryPoint.GetRawPointer(); } else { publicDescription.SetupEntryPoint = NULL; } auto entryPoint = heap.AddItem<FABRIC_CODE_PACKAGE_ENTRY_POINT_DESCRIPTION>(); this->EntryPoint.ToPublicApi(heap, *entryPoint); publicDescription.EntryPoint = entryPoint.GetRawPointer(); } void CodePackageDescription::clear() { this->Name.clear(); this->Version.clear(); this->IsShared = false; this->SetupEntryPoint.clear(); this->HasSetupEntryPoint = false; this->EntryPoint.clear(); this->EnvironmentVariables.clear(); }
[ "noreply-sfteam@microsoft.com" ]
noreply-sfteam@microsoft.com
b6da779a6cd258bdddf33b3c65059ccaebbf225b
3b9b4049a8e7d38b49e07bb752780b2f1d792851
/src/native_client/toolchain/linux_x86/pnacl_newlib/x86_64-nacl/include/c++/v1/future
6fe6f8da5049f86df63f33d05165ba0a1e0efd84
[ "BSD-3-Clause", "Zlib", "Classpath-exception-2.0", "BSD-Source-Code", "LZMA-exception", "LicenseRef-scancode-unicode", "LGPL-3.0-only", "LGPL-2.0-or-later", "LicenseRef-scancode-philippe-de-muyter", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-intel-osl-1993", "HPND-sell-var...
permissive
webosce/chromium53
f8e745e91363586aee9620c609aacf15b3261540
9171447efcf0bb393d41d1dc877c7c13c46d8e38
refs/heads/webosce
2020-03-26T23:08:14.416858
2018-08-23T08:35:17
2018-09-20T14:25:18
145,513,343
0
2
Apache-2.0
2019-08-21T22:44:55
2018-08-21T05:52:31
null
UTF-8
C++
false
false
72,088
// -*- C++ -*- //===--------------------------- future -----------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef _LIBCPP_FUTURE #define _LIBCPP_FUTURE /* future synopsis namespace std { enum class future_errc { future_already_retrieved = 1, promise_already_satisfied, no_state, broken_promise }; enum class launch { async = 1, deferred = 2, any = async | deferred }; enum class future_status { ready, timeout, deferred }; template <> struct is_error_code_enum<future_errc> : public true_type { }; error_code make_error_code(future_errc e) noexcept; error_condition make_error_condition(future_errc e) noexcept; const error_category& future_category() noexcept; class future_error : public logic_error { public: future_error(error_code ec); // exposition only const error_code& code() const noexcept; const char* what() const noexcept; }; template <class R> class promise { public: promise(); template <class Allocator> promise(allocator_arg_t, const Allocator& a); promise(promise&& rhs) noexcept; promise(const promise& rhs) = delete; ~promise(); // assignment promise& operator=(promise&& rhs) noexcept; promise& operator=(const promise& rhs) = delete; void swap(promise& other) noexcept; // retrieving the result future<R> get_future(); // setting the result void set_value(const R& r); void set_value(R&& r); void set_exception(exception_ptr p); // setting the result with deferred notification void set_value_at_thread_exit(const R& r); void set_value_at_thread_exit(R&& r); void set_exception_at_thread_exit(exception_ptr p); }; template <class R> class promise<R&> { public: promise(); template <class Allocator> promise(allocator_arg_t, const Allocator& a); promise(promise&& rhs) noexcept; promise(const promise& rhs) = delete; ~promise(); // assignment promise& operator=(promise&& rhs) noexcept; promise& operator=(const promise& rhs) = delete; void swap(promise& other) noexcept; // retrieving the result future<R&> get_future(); // setting the result void set_value(R& r); void set_exception(exception_ptr p); // setting the result with deferred notification void set_value_at_thread_exit(R&); void set_exception_at_thread_exit(exception_ptr p); }; template <> class promise<void> { public: promise(); template <class Allocator> promise(allocator_arg_t, const Allocator& a); promise(promise&& rhs) noexcept; promise(const promise& rhs) = delete; ~promise(); // assignment promise& operator=(promise&& rhs) noexcept; promise& operator=(const promise& rhs) = delete; void swap(promise& other) noexcept; // retrieving the result future<void> get_future(); // setting the result void set_value(); void set_exception(exception_ptr p); // setting the result with deferred notification void set_value_at_thread_exit(); void set_exception_at_thread_exit(exception_ptr p); }; template <class R> void swap(promise<R>& x, promise<R>& y) noexcept; template <class R, class Alloc> struct uses_allocator<promise<R>, Alloc> : public true_type {}; template <class R> class future { public: future() noexcept; future(future&&) noexcept; future(const future& rhs) = delete; ~future(); future& operator=(const future& rhs) = delete; future& operator=(future&&) noexcept; shared_future<R> share(); // retrieving the value R get(); // functions to check state bool valid() const noexcept; void wait() const; template <class Rep, class Period> future_status wait_for(const chrono::duration<Rep, Period>& rel_time) const; template <class Clock, class Duration> future_status wait_until(const chrono::time_point<Clock, Duration>& abs_time) const; }; template <class R> class future<R&> { public: future() noexcept; future(future&&) noexcept; future(const future& rhs) = delete; ~future(); future& operator=(const future& rhs) = delete; future& operator=(future&&) noexcept; shared_future<R&> share(); // retrieving the value R& get(); // functions to check state bool valid() const noexcept; void wait() const; template <class Rep, class Period> future_status wait_for(const chrono::duration<Rep, Period>& rel_time) const; template <class Clock, class Duration> future_status wait_until(const chrono::time_point<Clock, Duration>& abs_time) const; }; template <> class future<void> { public: future() noexcept; future(future&&) noexcept; future(const future& rhs) = delete; ~future(); future& operator=(const future& rhs) = delete; future& operator=(future&&) noexcept; shared_future<void> share(); // retrieving the value void get(); // functions to check state bool valid() const noexcept; void wait() const; template <class Rep, class Period> future_status wait_for(const chrono::duration<Rep, Period>& rel_time) const; template <class Clock, class Duration> future_status wait_until(const chrono::time_point<Clock, Duration>& abs_time) const; }; template <class R> class shared_future { public: shared_future() noexcept; shared_future(const shared_future& rhs); shared_future(future<R>&&) noexcept; shared_future(shared_future&& rhs) noexcept; ~shared_future(); shared_future& operator=(const shared_future& rhs); shared_future& operator=(shared_future&& rhs) noexcept; // retrieving the value const R& get() const; // functions to check state bool valid() const noexcept; void wait() const; template <class Rep, class Period> future_status wait_for(const chrono::duration<Rep, Period>& rel_time) const; template <class Clock, class Duration> future_status wait_until(const chrono::time_point<Clock, Duration>& abs_time) const; }; template <class R> class shared_future<R&> { public: shared_future() noexcept; shared_future(const shared_future& rhs); shared_future(future<R&>&&) noexcept; shared_future(shared_future&& rhs) noexcept; ~shared_future(); shared_future& operator=(const shared_future& rhs); shared_future& operator=(shared_future&& rhs) noexcept; // retrieving the value R& get() const; // functions to check state bool valid() const noexcept; void wait() const; template <class Rep, class Period> future_status wait_for(const chrono::duration<Rep, Period>& rel_time) const; template <class Clock, class Duration> future_status wait_until(const chrono::time_point<Clock, Duration>& abs_time) const; }; template <> class shared_future<void> { public: shared_future() noexcept; shared_future(const shared_future& rhs); shared_future(future<void>&&) noexcept; shared_future(shared_future&& rhs) noexcept; ~shared_future(); shared_future& operator=(const shared_future& rhs); shared_future& operator=(shared_future&& rhs) noexcept; // retrieving the value void get() const; // functions to check state bool valid() const noexcept; void wait() const; template <class Rep, class Period> future_status wait_for(const chrono::duration<Rep, Period>& rel_time) const; template <class Clock, class Duration> future_status wait_until(const chrono::time_point<Clock, Duration>& abs_time) const; }; template <class F, class... Args> future<typename result_of<typename decay<F>::type(typename decay<Args>::type...)>::type> async(F&& f, Args&&... args); template <class F, class... Args> future<typename result_of<typename decay<F>::type(typename decay<Args>::type...)>::type> async(launch policy, F&& f, Args&&... args); template <class> class packaged_task; // undefined template <class R, class... ArgTypes> class packaged_task<R(ArgTypes...)> { public: typedef R result_type; // construction and destruction packaged_task() noexcept; template <class F> explicit packaged_task(F&& f); template <class F, class Allocator> explicit packaged_task(allocator_arg_t, const Allocator& a, F&& f); ~packaged_task(); // no copy packaged_task(const packaged_task&) = delete; packaged_task& operator=(const packaged_task&) = delete; // move support packaged_task(packaged_task&& other) noexcept; packaged_task& operator=(packaged_task&& other) noexcept; void swap(packaged_task& other) noexcept; bool valid() const noexcept; // result retrieval future<R> get_future(); // execution void operator()(ArgTypes... ); void make_ready_at_thread_exit(ArgTypes...); void reset(); }; template <class R> void swap(packaged_task<R(ArgTypes...)&, packaged_task<R(ArgTypes...)>&) noexcept; template <class R, class Alloc> struct uses_allocator<packaged_task<R>, Alloc>; } // std */ #include <__config> #include <system_error> #include <memory> #include <chrono> #include <exception> #include <mutex> #include <thread> #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) #pragma GCC system_header #endif #ifdef _LIBCPP_HAS_NO_THREADS #error <future> is not supported on this single threaded system #else // !_LIBCPP_HAS_NO_THREADS _LIBCPP_BEGIN_NAMESPACE_STD //enum class future_errc _LIBCPP_DECLARE_STRONG_ENUM(future_errc) { future_already_retrieved = 1, promise_already_satisfied, no_state, broken_promise }; _LIBCPP_DECLARE_STRONG_ENUM_EPILOG(future_errc) template <> struct _LIBCPP_TYPE_VIS_ONLY is_error_code_enum<future_errc> : public true_type {}; #ifdef _LIBCPP_HAS_NO_STRONG_ENUMS template <> struct _LIBCPP_TYPE_VIS_ONLY is_error_code_enum<future_errc::__lx> : public true_type { }; #endif //enum class launch _LIBCPP_DECLARE_STRONG_ENUM(launch) { async = 1, deferred = 2, any = async | deferred }; _LIBCPP_DECLARE_STRONG_ENUM_EPILOG(launch) #ifndef _LIBCPP_HAS_NO_STRONG_ENUMS #ifdef _LIBCXX_UNDERLYING_TYPE typedef underlying_type<launch>::type __launch_underlying_type; #else typedef int __launch_underlying_type; #endif inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR launch operator&(launch __x, launch __y) { return static_cast<launch>(static_cast<__launch_underlying_type>(__x) & static_cast<__launch_underlying_type>(__y)); } inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR launch operator|(launch __x, launch __y) { return static_cast<launch>(static_cast<__launch_underlying_type>(__x) | static_cast<__launch_underlying_type>(__y)); } inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR launch operator^(launch __x, launch __y) { return static_cast<launch>(static_cast<__launch_underlying_type>(__x) ^ static_cast<__launch_underlying_type>(__y)); } inline _LIBCPP_INLINE_VISIBILITY _LIBCPP_CONSTEXPR launch operator~(launch __x) { return static_cast<launch>(~static_cast<__launch_underlying_type>(__x) & 3); } inline _LIBCPP_INLINE_VISIBILITY launch& operator&=(launch& __x, launch __y) { __x = __x & __y; return __x; } inline _LIBCPP_INLINE_VISIBILITY launch& operator|=(launch& __x, launch __y) { __x = __x | __y; return __x; } inline _LIBCPP_INLINE_VISIBILITY launch& operator^=(launch& __x, launch __y) { __x = __x ^ __y; return __x; } #endif // !_LIBCPP_HAS_NO_STRONG_ENUMS //enum class future_status _LIBCPP_DECLARE_STRONG_ENUM(future_status) { ready, timeout, deferred }; _LIBCPP_DECLARE_STRONG_ENUM_EPILOG(future_status) _LIBCPP_FUNC_VIS const error_category& future_category() _NOEXCEPT; inline _LIBCPP_INLINE_VISIBILITY error_code make_error_code(future_errc __e) _NOEXCEPT { return error_code(static_cast<int>(__e), future_category()); } inline _LIBCPP_INLINE_VISIBILITY error_condition make_error_condition(future_errc __e) _NOEXCEPT { return error_condition(static_cast<int>(__e), future_category()); } class _LIBCPP_EXCEPTION_ABI future_error : public logic_error { error_code __ec_; public: future_error(error_code __ec); _LIBCPP_INLINE_VISIBILITY const error_code& code() const _NOEXCEPT {return __ec_;} virtual ~future_error() _NOEXCEPT; }; class _LIBCPP_TYPE_VIS __assoc_sub_state : public __shared_count { protected: exception_ptr __exception_; mutable mutex __mut_; mutable condition_variable __cv_; unsigned __state_; virtual void __on_zero_shared() _NOEXCEPT; void __sub_wait(unique_lock<mutex>& __lk); public: enum { __constructed = 1, __future_attached = 2, ready = 4, deferred = 8 }; _LIBCPP_INLINE_VISIBILITY __assoc_sub_state() : __state_(0) {} _LIBCPP_INLINE_VISIBILITY bool __has_value() const {return (__state_ & __constructed) || (__exception_ != nullptr);} _LIBCPP_INLINE_VISIBILITY void __set_future_attached() { lock_guard<mutex> __lk(__mut_); __state_ |= __future_attached; } _LIBCPP_INLINE_VISIBILITY bool __has_future_attached() const {return (__state_ & __future_attached) != 0;} _LIBCPP_INLINE_VISIBILITY void __set_deferred() {__state_ |= deferred;} void __make_ready(); _LIBCPP_INLINE_VISIBILITY bool __is_ready() const {return (__state_ & ready) != 0;} void set_value(); void set_value_at_thread_exit(); void set_exception(exception_ptr __p); void set_exception_at_thread_exit(exception_ptr __p); void copy(); void wait(); template <class _Rep, class _Period> future_status wait_for(const chrono::duration<_Rep, _Period>& __rel_time) const; template <class _Clock, class _Duration> future_status wait_until(const chrono::time_point<_Clock, _Duration>& __abs_time) const; virtual void __execute(); }; template <class _Clock, class _Duration> future_status __assoc_sub_state::wait_until(const chrono::time_point<_Clock, _Duration>& __abs_time) const { unique_lock<mutex> __lk(__mut_); if (__state_ & deferred) return future_status::deferred; while (!(__state_ & ready) && _Clock::now() < __abs_time) __cv_.wait_until(__lk, __abs_time); if (__state_ & ready) return future_status::ready; return future_status::timeout; } template <class _Rep, class _Period> inline _LIBCPP_INLINE_VISIBILITY future_status __assoc_sub_state::wait_for(const chrono::duration<_Rep, _Period>& __rel_time) const { return wait_until(chrono::steady_clock::now() + __rel_time); } template <class _Rp> class __assoc_state : public __assoc_sub_state { typedef __assoc_sub_state base; typedef typename aligned_storage<sizeof(_Rp), alignment_of<_Rp>::value>::type _Up; protected: _Up __value_; virtual void __on_zero_shared() _NOEXCEPT; public: template <class _Arg> #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES void set_value(_Arg&& __arg); #else void set_value(_Arg& __arg); #endif template <class _Arg> #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES void set_value_at_thread_exit(_Arg&& __arg); #else void set_value_at_thread_exit(_Arg& __arg); #endif _Rp move(); typename add_lvalue_reference<_Rp>::type copy(); }; template <class _Rp> void __assoc_state<_Rp>::__on_zero_shared() _NOEXCEPT { if (this->__state_ & base::__constructed) reinterpret_cast<_Rp*>(&__value_)->~_Rp(); delete this; } template <class _Rp> template <class _Arg> void #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES __assoc_state<_Rp>::set_value(_Arg&& __arg) #else __assoc_state<_Rp>::set_value(_Arg& __arg) #endif { unique_lock<mutex> __lk(this->__mut_); #ifndef _LIBCPP_NO_EXCEPTIONS if (this->__has_value()) throw future_error(make_error_code(future_errc::promise_already_satisfied)); #endif ::new(&__value_) _Rp(_VSTD::forward<_Arg>(__arg)); this->__state_ |= base::__constructed | base::ready; __lk.unlock(); __cv_.notify_all(); } template <class _Rp> template <class _Arg> void #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES __assoc_state<_Rp>::set_value_at_thread_exit(_Arg&& __arg) #else __assoc_state<_Rp>::set_value_at_thread_exit(_Arg& __arg) #endif { unique_lock<mutex> __lk(this->__mut_); #ifndef _LIBCPP_NO_EXCEPTIONS if (this->__has_value()) throw future_error(make_error_code(future_errc::promise_already_satisfied)); #endif ::new(&__value_) _Rp(_VSTD::forward<_Arg>(__arg)); this->__state_ |= base::__constructed; __thread_local_data()->__make_ready_at_thread_exit(this); __lk.unlock(); } template <class _Rp> _Rp __assoc_state<_Rp>::move() { unique_lock<mutex> __lk(this->__mut_); this->__sub_wait(__lk); if (this->__exception_ != nullptr) rethrow_exception(this->__exception_); return _VSTD::move(*reinterpret_cast<_Rp*>(&__value_)); } template <class _Rp> typename add_lvalue_reference<_Rp>::type __assoc_state<_Rp>::copy() { unique_lock<mutex> __lk(this->__mut_); this->__sub_wait(__lk); if (this->__exception_ != nullptr) rethrow_exception(this->__exception_); return *reinterpret_cast<_Rp*>(&__value_); } template <class _Rp> class __assoc_state<_Rp&> : public __assoc_sub_state { typedef __assoc_sub_state base; typedef _Rp* _Up; protected: _Up __value_; virtual void __on_zero_shared() _NOEXCEPT; public: void set_value(_Rp& __arg); void set_value_at_thread_exit(_Rp& __arg); _Rp& copy(); }; template <class _Rp> void __assoc_state<_Rp&>::__on_zero_shared() _NOEXCEPT { delete this; } template <class _Rp> void __assoc_state<_Rp&>::set_value(_Rp& __arg) { unique_lock<mutex> __lk(this->__mut_); #ifndef _LIBCPP_NO_EXCEPTIONS if (this->__has_value()) throw future_error(make_error_code(future_errc::promise_already_satisfied)); #endif __value_ = _VSTD::addressof(__arg); this->__state_ |= base::__constructed | base::ready; __lk.unlock(); __cv_.notify_all(); } template <class _Rp> void __assoc_state<_Rp&>::set_value_at_thread_exit(_Rp& __arg) { unique_lock<mutex> __lk(this->__mut_); #ifndef _LIBCPP_NO_EXCEPTIONS if (this->__has_value()) throw future_error(make_error_code(future_errc::promise_already_satisfied)); #endif __value_ = _VSTD::addressof(__arg); this->__state_ |= base::__constructed; __thread_local_data()->__make_ready_at_thread_exit(this); __lk.unlock(); } template <class _Rp> _Rp& __assoc_state<_Rp&>::copy() { unique_lock<mutex> __lk(this->__mut_); this->__sub_wait(__lk); if (this->__exception_ != nullptr) rethrow_exception(this->__exception_); return *__value_; } template <class _Rp, class _Alloc> class __assoc_state_alloc : public __assoc_state<_Rp> { typedef __assoc_state<_Rp> base; _Alloc __alloc_; virtual void __on_zero_shared() _NOEXCEPT; public: _LIBCPP_INLINE_VISIBILITY explicit __assoc_state_alloc(const _Alloc& __a) : __alloc_(__a) {} }; template <class _Rp, class _Alloc> void __assoc_state_alloc<_Rp, _Alloc>::__on_zero_shared() _NOEXCEPT { if (this->__state_ & base::__constructed) reinterpret_cast<_Rp*>(_VSTD::addressof(this->__value_))->~_Rp(); typedef typename __allocator_traits_rebind<_Alloc, __assoc_state_alloc>::type _A; typedef allocator_traits<_A> _ATraits; typedef pointer_traits<typename _ATraits::pointer> _PTraits; _A __a(__alloc_); this->~__assoc_state_alloc(); __a.deallocate(_PTraits::pointer_to(*this), 1); } template <class _Rp, class _Alloc> class __assoc_state_alloc<_Rp&, _Alloc> : public __assoc_state<_Rp&> { typedef __assoc_state<_Rp&> base; _Alloc __alloc_; virtual void __on_zero_shared() _NOEXCEPT; public: _LIBCPP_INLINE_VISIBILITY explicit __assoc_state_alloc(const _Alloc& __a) : __alloc_(__a) {} }; template <class _Rp, class _Alloc> void __assoc_state_alloc<_Rp&, _Alloc>::__on_zero_shared() _NOEXCEPT { typedef typename __allocator_traits_rebind<_Alloc, __assoc_state_alloc>::type _A; typedef allocator_traits<_A> _ATraits; typedef pointer_traits<typename _ATraits::pointer> _PTraits; _A __a(__alloc_); this->~__assoc_state_alloc(); __a.deallocate(_PTraits::pointer_to(*this), 1); } template <class _Alloc> class __assoc_sub_state_alloc : public __assoc_sub_state { typedef __assoc_sub_state base; _Alloc __alloc_; virtual void __on_zero_shared() _NOEXCEPT; public: _LIBCPP_INLINE_VISIBILITY explicit __assoc_sub_state_alloc(const _Alloc& __a) : __alloc_(__a) {} }; template <class _Alloc> void __assoc_sub_state_alloc<_Alloc>::__on_zero_shared() _NOEXCEPT { typedef typename __allocator_traits_rebind<_Alloc, __assoc_sub_state_alloc>::type _A; typedef allocator_traits<_A> _ATraits; typedef pointer_traits<typename _ATraits::pointer> _PTraits; _A __a(__alloc_); this->~__assoc_sub_state_alloc(); __a.deallocate(_PTraits::pointer_to(*this), 1); } template <class _Rp, class _Fp> class __deferred_assoc_state : public __assoc_state<_Rp> { typedef __assoc_state<_Rp> base; _Fp __func_; public: #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES explicit __deferred_assoc_state(_Fp&& __f); #endif virtual void __execute(); }; #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES template <class _Rp, class _Fp> inline _LIBCPP_INLINE_VISIBILITY __deferred_assoc_state<_Rp, _Fp>::__deferred_assoc_state(_Fp&& __f) : __func_(_VSTD::forward<_Fp>(__f)) { this->__set_deferred(); } #endif // _LIBCPP_HAS_NO_RVALUE_REFERENCES template <class _Rp, class _Fp> void __deferred_assoc_state<_Rp, _Fp>::__execute() { #ifndef _LIBCPP_NO_EXCEPTIONS try { #endif // _LIBCPP_NO_EXCEPTIONS this->set_value(__func_()); #ifndef _LIBCPP_NO_EXCEPTIONS } catch (...) { this->set_exception(current_exception()); } #endif // _LIBCPP_NO_EXCEPTIONS } template <class _Fp> class __deferred_assoc_state<void, _Fp> : public __assoc_sub_state { typedef __assoc_sub_state base; _Fp __func_; public: #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES explicit __deferred_assoc_state(_Fp&& __f); #endif virtual void __execute(); }; #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES template <class _Fp> inline _LIBCPP_INLINE_VISIBILITY __deferred_assoc_state<void, _Fp>::__deferred_assoc_state(_Fp&& __f) : __func_(_VSTD::forward<_Fp>(__f)) { this->__set_deferred(); } #endif // _LIBCPP_HAS_NO_RVALUE_REFERENCES template <class _Fp> void __deferred_assoc_state<void, _Fp>::__execute() { #ifndef _LIBCPP_NO_EXCEPTIONS try { #endif // _LIBCPP_NO_EXCEPTIONS __func_(); this->set_value(); #ifndef _LIBCPP_NO_EXCEPTIONS } catch (...) { this->set_exception(current_exception()); } #endif // _LIBCPP_NO_EXCEPTIONS } template <class _Rp, class _Fp> class __async_assoc_state : public __assoc_state<_Rp> { typedef __assoc_state<_Rp> base; _Fp __func_; virtual void __on_zero_shared() _NOEXCEPT; public: #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES explicit __async_assoc_state(_Fp&& __f); #endif virtual void __execute(); }; #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES template <class _Rp, class _Fp> inline _LIBCPP_INLINE_VISIBILITY __async_assoc_state<_Rp, _Fp>::__async_assoc_state(_Fp&& __f) : __func_(_VSTD::forward<_Fp>(__f)) { } #endif // _LIBCPP_HAS_NO_RVALUE_REFERENCES template <class _Rp, class _Fp> void __async_assoc_state<_Rp, _Fp>::__execute() { #ifndef _LIBCPP_NO_EXCEPTIONS try { #endif // _LIBCPP_NO_EXCEPTIONS this->set_value(__func_()); #ifndef _LIBCPP_NO_EXCEPTIONS } catch (...) { this->set_exception(current_exception()); } #endif // _LIBCPP_NO_EXCEPTIONS } template <class _Rp, class _Fp> void __async_assoc_state<_Rp, _Fp>::__on_zero_shared() _NOEXCEPT { this->wait(); base::__on_zero_shared(); } template <class _Fp> class __async_assoc_state<void, _Fp> : public __assoc_sub_state { typedef __assoc_sub_state base; _Fp __func_; virtual void __on_zero_shared() _NOEXCEPT; public: #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES explicit __async_assoc_state(_Fp&& __f); #endif virtual void __execute(); }; #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES template <class _Fp> inline _LIBCPP_INLINE_VISIBILITY __async_assoc_state<void, _Fp>::__async_assoc_state(_Fp&& __f) : __func_(_VSTD::forward<_Fp>(__f)) { } #endif // _LIBCPP_HAS_NO_RVALUE_REFERENCES template <class _Fp> void __async_assoc_state<void, _Fp>::__execute() { #ifndef _LIBCPP_NO_EXCEPTIONS try { #endif // _LIBCPP_NO_EXCEPTIONS __func_(); this->set_value(); #ifndef _LIBCPP_NO_EXCEPTIONS } catch (...) { this->set_exception(current_exception()); } #endif // _LIBCPP_NO_EXCEPTIONS } template <class _Fp> void __async_assoc_state<void, _Fp>::__on_zero_shared() _NOEXCEPT { this->wait(); base::__on_zero_shared(); } template <class _Rp> class _LIBCPP_TYPE_VIS_ONLY promise; template <class _Rp> class _LIBCPP_TYPE_VIS_ONLY shared_future; // future template <class _Rp> class _LIBCPP_TYPE_VIS_ONLY future; template <class _Rp, class _Fp> future<_Rp> #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES __make_deferred_assoc_state(_Fp&& __f); #else __make_deferred_assoc_state(_Fp __f); #endif template <class _Rp, class _Fp> future<_Rp> #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES __make_async_assoc_state(_Fp&& __f); #else __make_async_assoc_state(_Fp __f); #endif template <class _Rp> class _LIBCPP_TYPE_VIS_ONLY future { __assoc_state<_Rp>* __state_; explicit future(__assoc_state<_Rp>* __state); template <class> friend class promise; template <class> friend class shared_future; #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES template <class _R1, class _Fp> friend future<_R1> __make_deferred_assoc_state(_Fp&& __f); template <class _R1, class _Fp> friend future<_R1> __make_async_assoc_state(_Fp&& __f); #else template <class _R1, class _Fp> friend future<_R1> __make_deferred_assoc_state(_Fp __f); template <class _R1, class _Fp> friend future<_R1> __make_async_assoc_state(_Fp __f); #endif public: _LIBCPP_INLINE_VISIBILITY future() _NOEXCEPT : __state_(nullptr) {} #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES _LIBCPP_INLINE_VISIBILITY future(future&& __rhs) _NOEXCEPT : __state_(__rhs.__state_) {__rhs.__state_ = nullptr;} future(const future&) = delete; future& operator=(const future&) = delete; _LIBCPP_INLINE_VISIBILITY future& operator=(future&& __rhs) _NOEXCEPT { future(std::move(__rhs)).swap(*this); return *this; } #else // _LIBCPP_HAS_NO_RVALUE_REFERENCES private: future(const future&); future& operator=(const future&); public: #endif // _LIBCPP_HAS_NO_RVALUE_REFERENCES ~future(); shared_future<_Rp> share(); // retrieving the value _Rp get(); _LIBCPP_INLINE_VISIBILITY void swap(future& __rhs) _NOEXCEPT {_VSTD::swap(__state_, __rhs.__state_);} // functions to check state _LIBCPP_INLINE_VISIBILITY bool valid() const _NOEXCEPT {return __state_ != nullptr;} _LIBCPP_INLINE_VISIBILITY void wait() const {__state_->wait();} template <class _Rep, class _Period> _LIBCPP_INLINE_VISIBILITY future_status wait_for(const chrono::duration<_Rep, _Period>& __rel_time) const {return __state_->wait_for(__rel_time);} template <class _Clock, class _Duration> _LIBCPP_INLINE_VISIBILITY future_status wait_until(const chrono::time_point<_Clock, _Duration>& __abs_time) const {return __state_->wait_until(__abs_time);} }; template <class _Rp> future<_Rp>::future(__assoc_state<_Rp>* __state) : __state_(__state) { #ifndef _LIBCPP_NO_EXCEPTIONS if (__state_->__has_future_attached()) throw future_error(make_error_code(future_errc::future_already_retrieved)); #endif __state_->__add_shared(); __state_->__set_future_attached(); } struct __release_shared_count { void operator()(__shared_count* p) {p->__release_shared();} }; template <class _Rp> future<_Rp>::~future() { if (__state_) __state_->__release_shared(); } template <class _Rp> _Rp future<_Rp>::get() { unique_ptr<__shared_count, __release_shared_count> __(__state_); __assoc_state<_Rp>* __s = __state_; __state_ = nullptr; return __s->move(); } template <class _Rp> class _LIBCPP_TYPE_VIS_ONLY future<_Rp&> { __assoc_state<_Rp&>* __state_; explicit future(__assoc_state<_Rp&>* __state); template <class> friend class promise; template <class> friend class shared_future; #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES template <class _R1, class _Fp> friend future<_R1> __make_deferred_assoc_state(_Fp&& __f); template <class _R1, class _Fp> friend future<_R1> __make_async_assoc_state(_Fp&& __f); #else template <class _R1, class _Fp> friend future<_R1> __make_deferred_assoc_state(_Fp __f); template <class _R1, class _Fp> friend future<_R1> __make_async_assoc_state(_Fp __f); #endif public: _LIBCPP_INLINE_VISIBILITY future() _NOEXCEPT : __state_(nullptr) {} #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES _LIBCPP_INLINE_VISIBILITY future(future&& __rhs) _NOEXCEPT : __state_(__rhs.__state_) {__rhs.__state_ = nullptr;} future(const future&) = delete; future& operator=(const future&) = delete; _LIBCPP_INLINE_VISIBILITY future& operator=(future&& __rhs) _NOEXCEPT { future(std::move(__rhs)).swap(*this); return *this; } #else // _LIBCPP_HAS_NO_RVALUE_REFERENCES private: future(const future&); future& operator=(const future&); public: #endif // _LIBCPP_HAS_NO_RVALUE_REFERENCES ~future(); shared_future<_Rp&> share(); // retrieving the value _Rp& get(); _LIBCPP_INLINE_VISIBILITY void swap(future& __rhs) _NOEXCEPT {_VSTD::swap(__state_, __rhs.__state_);} // functions to check state _LIBCPP_INLINE_VISIBILITY bool valid() const _NOEXCEPT {return __state_ != nullptr;} _LIBCPP_INLINE_VISIBILITY void wait() const {__state_->wait();} template <class _Rep, class _Period> _LIBCPP_INLINE_VISIBILITY future_status wait_for(const chrono::duration<_Rep, _Period>& __rel_time) const {return __state_->wait_for(__rel_time);} template <class _Clock, class _Duration> _LIBCPP_INLINE_VISIBILITY future_status wait_until(const chrono::time_point<_Clock, _Duration>& __abs_time) const {return __state_->wait_until(__abs_time);} }; template <class _Rp> future<_Rp&>::future(__assoc_state<_Rp&>* __state) : __state_(__state) { #ifndef _LIBCPP_NO_EXCEPTIONS if (__state_->__has_future_attached()) throw future_error(make_error_code(future_errc::future_already_retrieved)); #endif __state_->__add_shared(); __state_->__set_future_attached(); } template <class _Rp> future<_Rp&>::~future() { if (__state_) __state_->__release_shared(); } template <class _Rp> _Rp& future<_Rp&>::get() { unique_ptr<__shared_count, __release_shared_count> __(__state_); __assoc_state<_Rp&>* __s = __state_; __state_ = nullptr; return __s->copy(); } template <> class _LIBCPP_TYPE_VIS future<void> { __assoc_sub_state* __state_; explicit future(__assoc_sub_state* __state); template <class> friend class promise; template <class> friend class shared_future; #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES template <class _R1, class _Fp> friend future<_R1> __make_deferred_assoc_state(_Fp&& __f); template <class _R1, class _Fp> friend future<_R1> __make_async_assoc_state(_Fp&& __f); #else template <class _R1, class _Fp> friend future<_R1> __make_deferred_assoc_state(_Fp __f); template <class _R1, class _Fp> friend future<_R1> __make_async_assoc_state(_Fp __f); #endif public: _LIBCPP_INLINE_VISIBILITY future() _NOEXCEPT : __state_(nullptr) {} #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES _LIBCPP_INLINE_VISIBILITY future(future&& __rhs) _NOEXCEPT : __state_(__rhs.__state_) {__rhs.__state_ = nullptr;} future(const future&) = delete; future& operator=(const future&) = delete; _LIBCPP_INLINE_VISIBILITY future& operator=(future&& __rhs) _NOEXCEPT { future(std::move(__rhs)).swap(*this); return *this; } #else // _LIBCPP_HAS_NO_RVALUE_REFERENCES private: future(const future&); future& operator=(const future&); public: #endif // _LIBCPP_HAS_NO_RVALUE_REFERENCES ~future(); shared_future<void> share(); // retrieving the value void get(); _LIBCPP_INLINE_VISIBILITY void swap(future& __rhs) _NOEXCEPT {_VSTD::swap(__state_, __rhs.__state_);} // functions to check state _LIBCPP_INLINE_VISIBILITY bool valid() const _NOEXCEPT {return __state_ != nullptr;} _LIBCPP_INLINE_VISIBILITY void wait() const {__state_->wait();} template <class _Rep, class _Period> _LIBCPP_INLINE_VISIBILITY future_status wait_for(const chrono::duration<_Rep, _Period>& __rel_time) const {return __state_->wait_for(__rel_time);} template <class _Clock, class _Duration> _LIBCPP_INLINE_VISIBILITY future_status wait_until(const chrono::time_point<_Clock, _Duration>& __abs_time) const {return __state_->wait_until(__abs_time);} }; template <class _Rp> inline _LIBCPP_INLINE_VISIBILITY void swap(future<_Rp>& __x, future<_Rp>& __y) _NOEXCEPT { __x.swap(__y); } // promise<R> template <class _Callable> class packaged_task; template <class _Rp> class _LIBCPP_TYPE_VIS_ONLY promise { __assoc_state<_Rp>* __state_; _LIBCPP_INLINE_VISIBILITY explicit promise(nullptr_t) _NOEXCEPT : __state_(nullptr) {} template <class> friend class packaged_task; public: promise(); template <class _Alloc> promise(allocator_arg_t, const _Alloc& __a); #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES _LIBCPP_INLINE_VISIBILITY promise(promise&& __rhs) _NOEXCEPT : __state_(__rhs.__state_) {__rhs.__state_ = nullptr;} promise(const promise& __rhs) = delete; #else // _LIBCPP_HAS_NO_RVALUE_REFERENCES private: promise(const promise& __rhs); public: #endif // _LIBCPP_HAS_NO_RVALUE_REFERENCES ~promise(); // assignment #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES _LIBCPP_INLINE_VISIBILITY promise& operator=(promise&& __rhs) _NOEXCEPT { promise(std::move(__rhs)).swap(*this); return *this; } promise& operator=(const promise& __rhs) = delete; #else // _LIBCPP_HAS_NO_RVALUE_REFERENCES private: promise& operator=(const promise& __rhs); public: #endif // _LIBCPP_HAS_NO_RVALUE_REFERENCES _LIBCPP_INLINE_VISIBILITY void swap(promise& __rhs) _NOEXCEPT {_VSTD::swap(__state_, __rhs.__state_);} // retrieving the result future<_Rp> get_future(); // setting the result void set_value(const _Rp& __r); #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES void set_value(_Rp&& __r); #endif void set_exception(exception_ptr __p); // setting the result with deferred notification void set_value_at_thread_exit(const _Rp& __r); #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES void set_value_at_thread_exit(_Rp&& __r); #endif void set_exception_at_thread_exit(exception_ptr __p); }; template <class _Rp> promise<_Rp>::promise() : __state_(new __assoc_state<_Rp>) { } template <class _Rp> template <class _Alloc> promise<_Rp>::promise(allocator_arg_t, const _Alloc& __a0) { typedef __assoc_state_alloc<_Rp, _Alloc> _State; typedef typename __allocator_traits_rebind<_Alloc, _State>::type _A2; typedef __allocator_destructor<_A2> _D2; _A2 __a(__a0); unique_ptr<_State, _D2> __hold(__a.allocate(1), _D2(__a, 1)); ::new(static_cast<void*>(_VSTD::addressof(*__hold.get()))) _State(__a0); __state_ = _VSTD::addressof(*__hold.release()); } template <class _Rp> promise<_Rp>::~promise() { if (__state_) { if (!__state_->__has_value() && __state_->use_count() > 1) __state_->set_exception(make_exception_ptr( future_error(make_error_code(future_errc::broken_promise)) )); __state_->__release_shared(); } } template <class _Rp> future<_Rp> promise<_Rp>::get_future() { #ifndef _LIBCPP_NO_EXCEPTIONS if (__state_ == nullptr) throw future_error(make_error_code(future_errc::no_state)); #endif return future<_Rp>(__state_); } template <class _Rp> void promise<_Rp>::set_value(const _Rp& __r) { #ifndef _LIBCPP_NO_EXCEPTIONS if (__state_ == nullptr) throw future_error(make_error_code(future_errc::no_state)); #endif __state_->set_value(__r); } #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES template <class _Rp> void promise<_Rp>::set_value(_Rp&& __r) { #ifndef _LIBCPP_NO_EXCEPTIONS if (__state_ == nullptr) throw future_error(make_error_code(future_errc::no_state)); #endif __state_->set_value(_VSTD::move(__r)); } #endif // _LIBCPP_HAS_NO_RVALUE_REFERENCES template <class _Rp> void promise<_Rp>::set_exception(exception_ptr __p) { #ifndef _LIBCPP_NO_EXCEPTIONS if (__state_ == nullptr) throw future_error(make_error_code(future_errc::no_state)); #endif __state_->set_exception(__p); } template <class _Rp> void promise<_Rp>::set_value_at_thread_exit(const _Rp& __r) { #ifndef _LIBCPP_NO_EXCEPTIONS if (__state_ == nullptr) throw future_error(make_error_code(future_errc::no_state)); #endif __state_->set_value_at_thread_exit(__r); } #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES template <class _Rp> void promise<_Rp>::set_value_at_thread_exit(_Rp&& __r) { #ifndef _LIBCPP_NO_EXCEPTIONS if (__state_ == nullptr) throw future_error(make_error_code(future_errc::no_state)); #endif __state_->set_value_at_thread_exit(_VSTD::move(__r)); } #endif // _LIBCPP_HAS_NO_RVALUE_REFERENCES template <class _Rp> void promise<_Rp>::set_exception_at_thread_exit(exception_ptr __p) { #ifndef _LIBCPP_NO_EXCEPTIONS if (__state_ == nullptr) throw future_error(make_error_code(future_errc::no_state)); #endif __state_->set_exception_at_thread_exit(__p); } // promise<R&> template <class _Rp> class _LIBCPP_TYPE_VIS_ONLY promise<_Rp&> { __assoc_state<_Rp&>* __state_; _LIBCPP_INLINE_VISIBILITY explicit promise(nullptr_t) _NOEXCEPT : __state_(nullptr) {} template <class> friend class packaged_task; public: promise(); template <class _Allocator> promise(allocator_arg_t, const _Allocator& __a); #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES _LIBCPP_INLINE_VISIBILITY promise(promise&& __rhs) _NOEXCEPT : __state_(__rhs.__state_) {__rhs.__state_ = nullptr;} promise(const promise& __rhs) = delete; #else // _LIBCPP_HAS_NO_RVALUE_REFERENCES private: promise(const promise& __rhs); public: #endif // _LIBCPP_HAS_NO_RVALUE_REFERENCES ~promise(); // assignment #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES _LIBCPP_INLINE_VISIBILITY promise& operator=(promise&& __rhs) _NOEXCEPT { promise(std::move(__rhs)).swap(*this); return *this; } promise& operator=(const promise& __rhs) = delete; #else // _LIBCPP_HAS_NO_RVALUE_REFERENCES private: promise& operator=(const promise& __rhs); public: #endif // _LIBCPP_HAS_NO_RVALUE_REFERENCES _LIBCPP_INLINE_VISIBILITY void swap(promise& __rhs) _NOEXCEPT {_VSTD::swap(__state_, __rhs.__state_);} // retrieving the result future<_Rp&> get_future(); // setting the result void set_value(_Rp& __r); void set_exception(exception_ptr __p); // setting the result with deferred notification void set_value_at_thread_exit(_Rp&); void set_exception_at_thread_exit(exception_ptr __p); }; template <class _Rp> promise<_Rp&>::promise() : __state_(new __assoc_state<_Rp&>) { } template <class _Rp> template <class _Alloc> promise<_Rp&>::promise(allocator_arg_t, const _Alloc& __a0) { typedef __assoc_state_alloc<_Rp&, _Alloc> _State; typedef typename __allocator_traits_rebind<_Alloc, _State>::type _A2; typedef __allocator_destructor<_A2> _D2; _A2 __a(__a0); unique_ptr<_State, _D2> __hold(__a.allocate(1), _D2(__a, 1)); ::new(static_cast<void*>(_VSTD::addressof(*__hold.get()))) _State(__a0); __state_ = _VSTD::addressof(*__hold.release()); } template <class _Rp> promise<_Rp&>::~promise() { if (__state_) { if (!__state_->__has_value() && __state_->use_count() > 1) __state_->set_exception(make_exception_ptr( future_error(make_error_code(future_errc::broken_promise)) )); __state_->__release_shared(); } } template <class _Rp> future<_Rp&> promise<_Rp&>::get_future() { #ifndef _LIBCPP_NO_EXCEPTIONS if (__state_ == nullptr) throw future_error(make_error_code(future_errc::no_state)); #endif return future<_Rp&>(__state_); } template <class _Rp> void promise<_Rp&>::set_value(_Rp& __r) { #ifndef _LIBCPP_NO_EXCEPTIONS if (__state_ == nullptr) throw future_error(make_error_code(future_errc::no_state)); #endif __state_->set_value(__r); } template <class _Rp> void promise<_Rp&>::set_exception(exception_ptr __p) { #ifndef _LIBCPP_NO_EXCEPTIONS if (__state_ == nullptr) throw future_error(make_error_code(future_errc::no_state)); #endif __state_->set_exception(__p); } template <class _Rp> void promise<_Rp&>::set_value_at_thread_exit(_Rp& __r) { #ifndef _LIBCPP_NO_EXCEPTIONS if (__state_ == nullptr) throw future_error(make_error_code(future_errc::no_state)); #endif __state_->set_value_at_thread_exit(__r); } template <class _Rp> void promise<_Rp&>::set_exception_at_thread_exit(exception_ptr __p) { #ifndef _LIBCPP_NO_EXCEPTIONS if (__state_ == nullptr) throw future_error(make_error_code(future_errc::no_state)); #endif __state_->set_exception_at_thread_exit(__p); } // promise<void> template <> class _LIBCPP_TYPE_VIS promise<void> { __assoc_sub_state* __state_; _LIBCPP_INLINE_VISIBILITY explicit promise(nullptr_t) _NOEXCEPT : __state_(nullptr) {} template <class> friend class packaged_task; public: promise(); template <class _Allocator> promise(allocator_arg_t, const _Allocator& __a); #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES _LIBCPP_INLINE_VISIBILITY promise(promise&& __rhs) _NOEXCEPT : __state_(__rhs.__state_) {__rhs.__state_ = nullptr;} promise(const promise& __rhs) = delete; #else // _LIBCPP_HAS_NO_RVALUE_REFERENCES private: promise(const promise& __rhs); public: #endif // _LIBCPP_HAS_NO_RVALUE_REFERENCES ~promise(); // assignment #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES _LIBCPP_INLINE_VISIBILITY promise& operator=(promise&& __rhs) _NOEXCEPT { promise(std::move(__rhs)).swap(*this); return *this; } promise& operator=(const promise& __rhs) = delete; #else // _LIBCPP_HAS_NO_RVALUE_REFERENCES private: promise& operator=(const promise& __rhs); public: #endif // _LIBCPP_HAS_NO_RVALUE_REFERENCES _LIBCPP_INLINE_VISIBILITY void swap(promise& __rhs) _NOEXCEPT {_VSTD::swap(__state_, __rhs.__state_);} // retrieving the result future<void> get_future(); // setting the result void set_value(); void set_exception(exception_ptr __p); // setting the result with deferred notification void set_value_at_thread_exit(); void set_exception_at_thread_exit(exception_ptr __p); }; template <class _Alloc> promise<void>::promise(allocator_arg_t, const _Alloc& __a0) { typedef __assoc_sub_state_alloc<_Alloc> _State; typedef typename __allocator_traits_rebind<_Alloc, _State>::type _A2; typedef __allocator_destructor<_A2> _D2; _A2 __a(__a0); unique_ptr<_State, _D2> __hold(__a.allocate(1), _D2(__a, 1)); ::new(static_cast<void*>(_VSTD::addressof(*__hold.get()))) _State(__a0); __state_ = _VSTD::addressof(*__hold.release()); } template <class _Rp> inline _LIBCPP_INLINE_VISIBILITY void swap(promise<_Rp>& __x, promise<_Rp>& __y) _NOEXCEPT { __x.swap(__y); } template <class _Rp, class _Alloc> struct _LIBCPP_TYPE_VIS_ONLY uses_allocator<promise<_Rp>, _Alloc> : public true_type {}; #ifndef _LIBCPP_HAS_NO_VARIADICS // packaged_task template<class _Fp> class __packaged_task_base; template<class _Rp, class ..._ArgTypes> class __packaged_task_base<_Rp(_ArgTypes...)> { __packaged_task_base(const __packaged_task_base&); __packaged_task_base& operator=(const __packaged_task_base&); public: _LIBCPP_INLINE_VISIBILITY __packaged_task_base() {} _LIBCPP_INLINE_VISIBILITY virtual ~__packaged_task_base() {} virtual void __move_to(__packaged_task_base*) _NOEXCEPT = 0; virtual void destroy() = 0; virtual void destroy_deallocate() = 0; virtual _Rp operator()(_ArgTypes&& ...) = 0; }; template<class _FD, class _Alloc, class _FB> class __packaged_task_func; template<class _Fp, class _Alloc, class _Rp, class ..._ArgTypes> class __packaged_task_func<_Fp, _Alloc, _Rp(_ArgTypes...)> : public __packaged_task_base<_Rp(_ArgTypes...)> { __compressed_pair<_Fp, _Alloc> __f_; public: _LIBCPP_INLINE_VISIBILITY explicit __packaged_task_func(const _Fp& __f) : __f_(__f) {} _LIBCPP_INLINE_VISIBILITY explicit __packaged_task_func(_Fp&& __f) : __f_(_VSTD::move(__f)) {} _LIBCPP_INLINE_VISIBILITY __packaged_task_func(const _Fp& __f, const _Alloc& __a) : __f_(__f, __a) {} _LIBCPP_INLINE_VISIBILITY __packaged_task_func(_Fp&& __f, const _Alloc& __a) : __f_(_VSTD::move(__f), __a) {} virtual void __move_to(__packaged_task_base<_Rp(_ArgTypes...)>*) _NOEXCEPT; virtual void destroy(); virtual void destroy_deallocate(); virtual _Rp operator()(_ArgTypes&& ... __args); }; template<class _Fp, class _Alloc, class _Rp, class ..._ArgTypes> void __packaged_task_func<_Fp, _Alloc, _Rp(_ArgTypes...)>::__move_to( __packaged_task_base<_Rp(_ArgTypes...)>* __p) _NOEXCEPT { ::new (__p) __packaged_task_func(_VSTD::move(__f_.first()), _VSTD::move(__f_.second())); } template<class _Fp, class _Alloc, class _Rp, class ..._ArgTypes> void __packaged_task_func<_Fp, _Alloc, _Rp(_ArgTypes...)>::destroy() { __f_.~__compressed_pair<_Fp, _Alloc>(); } template<class _Fp, class _Alloc, class _Rp, class ..._ArgTypes> void __packaged_task_func<_Fp, _Alloc, _Rp(_ArgTypes...)>::destroy_deallocate() { typedef typename __allocator_traits_rebind<_Alloc, __packaged_task_func>::type _Ap; typedef allocator_traits<_Ap> _ATraits; typedef pointer_traits<typename _ATraits::pointer> _PTraits; _Ap __a(__f_.second()); __f_.~__compressed_pair<_Fp, _Alloc>(); __a.deallocate(_PTraits::pointer_to(*this), 1); } template<class _Fp, class _Alloc, class _Rp, class ..._ArgTypes> _Rp __packaged_task_func<_Fp, _Alloc, _Rp(_ArgTypes...)>::operator()(_ArgTypes&& ... __arg) { return __invoke(__f_.first(), _VSTD::forward<_ArgTypes>(__arg)...); } template <class _Callable> class __packaged_task_function; template<class _Rp, class ..._ArgTypes> class __packaged_task_function<_Rp(_ArgTypes...)> { typedef __packaged_task_base<_Rp(_ArgTypes...)> __base; typename aligned_storage<3*sizeof(void*)>::type __buf_; __base* __f_; public: typedef _Rp result_type; // construct/copy/destroy: _LIBCPP_INLINE_VISIBILITY __packaged_task_function() _NOEXCEPT : __f_(nullptr) {} template<class _Fp> __packaged_task_function(_Fp&& __f); template<class _Fp, class _Alloc> __packaged_task_function(allocator_arg_t, const _Alloc& __a, _Fp&& __f); __packaged_task_function(__packaged_task_function&&) _NOEXCEPT; __packaged_task_function& operator=(__packaged_task_function&&) _NOEXCEPT; __packaged_task_function(const __packaged_task_function&) = delete; __packaged_task_function& operator=(const __packaged_task_function&) = delete; ~__packaged_task_function(); void swap(__packaged_task_function&) _NOEXCEPT; _Rp operator()(_ArgTypes...) const; }; template<class _Rp, class ..._ArgTypes> __packaged_task_function<_Rp(_ArgTypes...)>::__packaged_task_function(__packaged_task_function&& __f) _NOEXCEPT { if (__f.__f_ == nullptr) __f_ = nullptr; else if (__f.__f_ == (__base*)&__f.__buf_) { __f_ = (__base*)&__buf_; __f.__f_->__move_to(__f_); } else { __f_ = __f.__f_; __f.__f_ = nullptr; } } template<class _Rp, class ..._ArgTypes> template <class _Fp> __packaged_task_function<_Rp(_ArgTypes...)>::__packaged_task_function(_Fp&& __f) : __f_(nullptr) { typedef typename remove_reference<typename decay<_Fp>::type>::type _FR; typedef __packaged_task_func<_FR, allocator<_FR>, _Rp(_ArgTypes...)> _FF; if (sizeof(_FF) <= sizeof(__buf_)) { __f_ = (__base*)&__buf_; ::new (__f_) _FF(_VSTD::forward<_Fp>(__f)); } else { typedef allocator<_FF> _Ap; _Ap __a; typedef __allocator_destructor<_Ap> _Dp; unique_ptr<__base, _Dp> __hold(__a.allocate(1), _Dp(__a, 1)); ::new (__hold.get()) _FF(_VSTD::forward<_Fp>(__f), allocator<_FR>(__a)); __f_ = __hold.release(); } } template<class _Rp, class ..._ArgTypes> template <class _Fp, class _Alloc> __packaged_task_function<_Rp(_ArgTypes...)>::__packaged_task_function( allocator_arg_t, const _Alloc& __a0, _Fp&& __f) : __f_(nullptr) { typedef typename remove_reference<typename decay<_Fp>::type>::type _FR; typedef __packaged_task_func<_FR, _Alloc, _Rp(_ArgTypes...)> _FF; if (sizeof(_FF) <= sizeof(__buf_)) { __f_ = (__base*)&__buf_; ::new (__f_) _FF(_VSTD::forward<_Fp>(__f)); } else { typedef typename __allocator_traits_rebind<_Alloc, _FF>::type _Ap; _Ap __a(__a0); typedef __allocator_destructor<_Ap> _Dp; unique_ptr<__base, _Dp> __hold(__a.allocate(1), _Dp(__a, 1)); ::new (static_cast<void*>(_VSTD::addressof(*__hold.get()))) _FF(_VSTD::forward<_Fp>(__f), _Alloc(__a)); __f_ = _VSTD::addressof(*__hold.release()); } } template<class _Rp, class ..._ArgTypes> __packaged_task_function<_Rp(_ArgTypes...)>& __packaged_task_function<_Rp(_ArgTypes...)>::operator=(__packaged_task_function&& __f) _NOEXCEPT { if (__f_ == (__base*)&__buf_) __f_->destroy(); else if (__f_) __f_->destroy_deallocate(); __f_ = nullptr; if (__f.__f_ == nullptr) __f_ = nullptr; else if (__f.__f_ == (__base*)&__f.__buf_) { __f_ = (__base*)&__buf_; __f.__f_->__move_to(__f_); } else { __f_ = __f.__f_; __f.__f_ = nullptr; } return *this; } template<class _Rp, class ..._ArgTypes> __packaged_task_function<_Rp(_ArgTypes...)>::~__packaged_task_function() { if (__f_ == (__base*)&__buf_) __f_->destroy(); else if (__f_) __f_->destroy_deallocate(); } template<class _Rp, class ..._ArgTypes> void __packaged_task_function<_Rp(_ArgTypes...)>::swap(__packaged_task_function& __f) _NOEXCEPT { if (__f_ == (__base*)&__buf_ && __f.__f_ == (__base*)&__f.__buf_) { typename aligned_storage<sizeof(__buf_)>::type __tempbuf; __base* __t = (__base*)&__tempbuf; __f_->__move_to(__t); __f_->destroy(); __f_ = nullptr; __f.__f_->__move_to((__base*)&__buf_); __f.__f_->destroy(); __f.__f_ = nullptr; __f_ = (__base*)&__buf_; __t->__move_to((__base*)&__f.__buf_); __t->destroy(); __f.__f_ = (__base*)&__f.__buf_; } else if (__f_ == (__base*)&__buf_) { __f_->__move_to((__base*)&__f.__buf_); __f_->destroy(); __f_ = __f.__f_; __f.__f_ = (__base*)&__f.__buf_; } else if (__f.__f_ == (__base*)&__f.__buf_) { __f.__f_->__move_to((__base*)&__buf_); __f.__f_->destroy(); __f.__f_ = __f_; __f_ = (__base*)&__buf_; } else _VSTD::swap(__f_, __f.__f_); } template<class _Rp, class ..._ArgTypes> inline _LIBCPP_INLINE_VISIBILITY _Rp __packaged_task_function<_Rp(_ArgTypes...)>::operator()(_ArgTypes... __arg) const { return (*__f_)(_VSTD::forward<_ArgTypes>(__arg)...); } template<class _Rp, class ..._ArgTypes> class _LIBCPP_TYPE_VIS_ONLY packaged_task<_Rp(_ArgTypes...)> { public: typedef _Rp result_type; private: __packaged_task_function<result_type(_ArgTypes...)> __f_; promise<result_type> __p_; public: // construction and destruction _LIBCPP_INLINE_VISIBILITY packaged_task() _NOEXCEPT : __p_(nullptr) {} template <class _Fp, class = typename enable_if < !is_same< typename decay<_Fp>::type, packaged_task >::value >::type > _LIBCPP_INLINE_VISIBILITY explicit packaged_task(_Fp&& __f) : __f_(_VSTD::forward<_Fp>(__f)) {} template <class _Fp, class _Allocator, class = typename enable_if < !is_same< typename decay<_Fp>::type, packaged_task >::value >::type > _LIBCPP_INLINE_VISIBILITY explicit packaged_task(allocator_arg_t, const _Allocator& __a, _Fp&& __f) : __f_(allocator_arg, __a, _VSTD::forward<_Fp>(__f)), __p_(allocator_arg, __a) {} // ~packaged_task() = default; // no copy packaged_task(const packaged_task&) = delete; packaged_task& operator=(const packaged_task&) = delete; // move support _LIBCPP_INLINE_VISIBILITY packaged_task(packaged_task&& __other) _NOEXCEPT : __f_(_VSTD::move(__other.__f_)), __p_(_VSTD::move(__other.__p_)) {} _LIBCPP_INLINE_VISIBILITY packaged_task& operator=(packaged_task&& __other) _NOEXCEPT { __f_ = _VSTD::move(__other.__f_); __p_ = _VSTD::move(__other.__p_); return *this; } _LIBCPP_INLINE_VISIBILITY void swap(packaged_task& __other) _NOEXCEPT { __f_.swap(__other.__f_); __p_.swap(__other.__p_); } _LIBCPP_INLINE_VISIBILITY bool valid() const _NOEXCEPT {return __p_.__state_ != nullptr;} // result retrieval _LIBCPP_INLINE_VISIBILITY future<result_type> get_future() {return __p_.get_future();} // execution void operator()(_ArgTypes... __args); void make_ready_at_thread_exit(_ArgTypes... __args); void reset(); }; template<class _Rp, class ..._ArgTypes> void packaged_task<_Rp(_ArgTypes...)>::operator()(_ArgTypes... __args) { #ifndef _LIBCPP_NO_EXCEPTIONS if (__p_.__state_ == nullptr) throw future_error(make_error_code(future_errc::no_state)); if (__p_.__state_->__has_value()) throw future_error(make_error_code(future_errc::promise_already_satisfied)); try { #endif // _LIBCPP_NO_EXCEPTIONS __p_.set_value(__f_(_VSTD::forward<_ArgTypes>(__args)...)); #ifndef _LIBCPP_NO_EXCEPTIONS } catch (...) { __p_.set_exception(current_exception()); } #endif // _LIBCPP_NO_EXCEPTIONS } template<class _Rp, class ..._ArgTypes> void packaged_task<_Rp(_ArgTypes...)>::make_ready_at_thread_exit(_ArgTypes... __args) { #ifndef _LIBCPP_NO_EXCEPTIONS if (__p_.__state_ == nullptr) throw future_error(make_error_code(future_errc::no_state)); if (__p_.__state_->__has_value()) throw future_error(make_error_code(future_errc::promise_already_satisfied)); try { #endif // _LIBCPP_NO_EXCEPTIONS __p_.set_value_at_thread_exit(__f_(_VSTD::forward<_ArgTypes>(__args)...)); #ifndef _LIBCPP_NO_EXCEPTIONS } catch (...) { __p_.set_exception_at_thread_exit(current_exception()); } #endif // _LIBCPP_NO_EXCEPTIONS } template<class _Rp, class ..._ArgTypes> void packaged_task<_Rp(_ArgTypes...)>::reset() { #ifndef _LIBCPP_NO_EXCEPTIONS if (!valid()) throw future_error(make_error_code(future_errc::no_state)); #endif // _LIBCPP_NO_EXCEPTIONS __p_ = promise<result_type>(); } template<class ..._ArgTypes> class _LIBCPP_TYPE_VIS_ONLY packaged_task<void(_ArgTypes...)> { public: typedef void result_type; private: __packaged_task_function<result_type(_ArgTypes...)> __f_; promise<result_type> __p_; public: // construction and destruction _LIBCPP_INLINE_VISIBILITY packaged_task() _NOEXCEPT : __p_(nullptr) {} template <class _Fp, class = typename enable_if < !is_same< typename decay<_Fp>::type, packaged_task >::value >::type > _LIBCPP_INLINE_VISIBILITY explicit packaged_task(_Fp&& __f) : __f_(_VSTD::forward<_Fp>(__f)) {} template <class _Fp, class _Allocator, class = typename enable_if < !is_same< typename decay<_Fp>::type, packaged_task >::value >::type > _LIBCPP_INLINE_VISIBILITY explicit packaged_task(allocator_arg_t, const _Allocator& __a, _Fp&& __f) : __f_(allocator_arg, __a, _VSTD::forward<_Fp>(__f)), __p_(allocator_arg, __a) {} // ~packaged_task() = default; // no copy packaged_task(const packaged_task&) = delete; packaged_task& operator=(const packaged_task&) = delete; // move support _LIBCPP_INLINE_VISIBILITY packaged_task(packaged_task&& __other) _NOEXCEPT : __f_(_VSTD::move(__other.__f_)), __p_(_VSTD::move(__other.__p_)) {} _LIBCPP_INLINE_VISIBILITY packaged_task& operator=(packaged_task&& __other) _NOEXCEPT { __f_ = _VSTD::move(__other.__f_); __p_ = _VSTD::move(__other.__p_); return *this; } _LIBCPP_INLINE_VISIBILITY void swap(packaged_task& __other) _NOEXCEPT { __f_.swap(__other.__f_); __p_.swap(__other.__p_); } _LIBCPP_INLINE_VISIBILITY bool valid() const _NOEXCEPT {return __p_.__state_ != nullptr;} // result retrieval _LIBCPP_INLINE_VISIBILITY future<result_type> get_future() {return __p_.get_future();} // execution void operator()(_ArgTypes... __args); void make_ready_at_thread_exit(_ArgTypes... __args); void reset(); }; template<class ..._ArgTypes> void packaged_task<void(_ArgTypes...)>::operator()(_ArgTypes... __args) { #ifndef _LIBCPP_NO_EXCEPTIONS if (__p_.__state_ == nullptr) throw future_error(make_error_code(future_errc::no_state)); if (__p_.__state_->__has_value()) throw future_error(make_error_code(future_errc::promise_already_satisfied)); try { #endif // _LIBCPP_NO_EXCEPTIONS __f_(_VSTD::forward<_ArgTypes>(__args)...); __p_.set_value(); #ifndef _LIBCPP_NO_EXCEPTIONS } catch (...) { __p_.set_exception(current_exception()); } #endif // _LIBCPP_NO_EXCEPTIONS } template<class ..._ArgTypes> void packaged_task<void(_ArgTypes...)>::make_ready_at_thread_exit(_ArgTypes... __args) { #ifndef _LIBCPP_NO_EXCEPTIONS if (__p_.__state_ == nullptr) throw future_error(make_error_code(future_errc::no_state)); if (__p_.__state_->__has_value()) throw future_error(make_error_code(future_errc::promise_already_satisfied)); try { #endif // _LIBCPP_NO_EXCEPTIONS __f_(_VSTD::forward<_ArgTypes>(__args)...); __p_.set_value_at_thread_exit(); #ifndef _LIBCPP_NO_EXCEPTIONS } catch (...) { __p_.set_exception_at_thread_exit(current_exception()); } #endif // _LIBCPP_NO_EXCEPTIONS } template<class ..._ArgTypes> void packaged_task<void(_ArgTypes...)>::reset() { #ifndef _LIBCPP_NO_EXCEPTIONS if (!valid()) throw future_error(make_error_code(future_errc::no_state)); #endif // _LIBCPP_NO_EXCEPTIONS __p_ = promise<result_type>(); } template <class _Callable> inline _LIBCPP_INLINE_VISIBILITY void swap(packaged_task<_Callable>& __x, packaged_task<_Callable>& __y) _NOEXCEPT { __x.swap(__y); } template <class _Callable, class _Alloc> struct _LIBCPP_TYPE_VIS_ONLY uses_allocator<packaged_task<_Callable>, _Alloc> : public true_type {}; template <class _Rp, class _Fp> future<_Rp> #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES __make_deferred_assoc_state(_Fp&& __f) #else __make_deferred_assoc_state(_Fp __f) #endif { unique_ptr<__deferred_assoc_state<_Rp, _Fp>, __release_shared_count> __h(new __deferred_assoc_state<_Rp, _Fp>(_VSTD::forward<_Fp>(__f))); return future<_Rp>(__h.get()); } template <class _Rp, class _Fp> future<_Rp> #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES __make_async_assoc_state(_Fp&& __f) #else __make_async_assoc_state(_Fp __f) #endif { unique_ptr<__async_assoc_state<_Rp, _Fp>, __release_shared_count> __h(new __async_assoc_state<_Rp, _Fp>(_VSTD::forward<_Fp>(__f))); _VSTD::thread(&__async_assoc_state<_Rp, _Fp>::__execute, __h.get()).detach(); return future<_Rp>(__h.get()); } template <class _Fp, class... _Args> class __async_func { tuple<_Fp, _Args...> __f_; public: typedef typename __invoke_of<_Fp, _Args...>::type _Rp; _LIBCPP_INLINE_VISIBILITY explicit __async_func(_Fp&& __f, _Args&&... __args) : __f_(_VSTD::move(__f), _VSTD::move(__args)...) {} _LIBCPP_INLINE_VISIBILITY __async_func(__async_func&& __f) : __f_(_VSTD::move(__f.__f_)) {} _Rp operator()() { typedef typename __make_tuple_indices<1+sizeof...(_Args), 1>::type _Index; return __execute(_Index()); } private: template <size_t ..._Indices> _Rp __execute(__tuple_indices<_Indices...>) { return __invoke(_VSTD::move(_VSTD::get<0>(__f_)), _VSTD::move(_VSTD::get<_Indices>(__f_))...); } }; inline _LIBCPP_INLINE_VISIBILITY bool __does_policy_contain(launch __policy, launch __value ) { return (int(__policy) & int(__value)) != 0; } template <class _Fp, class... _Args> future<typename __invoke_of<typename decay<_Fp>::type, typename decay<_Args>::type...>::type> async(launch __policy, _Fp&& __f, _Args&&... __args) { typedef __async_func<typename decay<_Fp>::type, typename decay<_Args>::type...> _BF; typedef typename _BF::_Rp _Rp; #ifndef _LIBCPP_NO_EXCEPTIONS try { #endif if (__does_policy_contain(__policy, launch::async)) return _VSTD::__make_async_assoc_state<_Rp>(_BF(__decay_copy(_VSTD::forward<_Fp>(__f)), __decay_copy(_VSTD::forward<_Args>(__args))...)); #ifndef _LIBCPP_NO_EXCEPTIONS } catch ( ... ) { if (__policy == launch::async) throw ; } #endif if (__does_policy_contain(__policy, launch::deferred)) return _VSTD::__make_deferred_assoc_state<_Rp>(_BF(__decay_copy(_VSTD::forward<_Fp>(__f)), __decay_copy(_VSTD::forward<_Args>(__args))...)); return future<_Rp>{}; } template <class _Fp, class... _Args> inline _LIBCPP_INLINE_VISIBILITY future<typename __invoke_of<typename decay<_Fp>::type, typename decay<_Args>::type...>::type> async(_Fp&& __f, _Args&&... __args) { return _VSTD::async(launch::any, _VSTD::forward<_Fp>(__f), _VSTD::forward<_Args>(__args)...); } #endif // _LIBCPP_HAS_NO_VARIADICS // shared_future template <class _Rp> class _LIBCPP_TYPE_VIS_ONLY shared_future { __assoc_state<_Rp>* __state_; public: _LIBCPP_INLINE_VISIBILITY shared_future() _NOEXCEPT : __state_(nullptr) {} _LIBCPP_INLINE_VISIBILITY shared_future(const shared_future& __rhs) : __state_(__rhs.__state_) {if (__state_) __state_->__add_shared();} #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES _LIBCPP_INLINE_VISIBILITY shared_future(future<_Rp>&& __f) _NOEXCEPT : __state_(__f.__state_) {__f.__state_ = nullptr;} _LIBCPP_INLINE_VISIBILITY shared_future(shared_future&& __rhs) _NOEXCEPT : __state_(__rhs.__state_) {__rhs.__state_ = nullptr;} #endif // _LIBCPP_HAS_NO_RVALUE_REFERENCES ~shared_future(); shared_future& operator=(const shared_future& __rhs); #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES _LIBCPP_INLINE_VISIBILITY shared_future& operator=(shared_future&& __rhs) _NOEXCEPT { shared_future(std::move(__rhs)).swap(*this); return *this; } #endif // _LIBCPP_HAS_NO_RVALUE_REFERENCES // retrieving the value _LIBCPP_INLINE_VISIBILITY const _Rp& get() const {return __state_->copy();} _LIBCPP_INLINE_VISIBILITY void swap(shared_future& __rhs) _NOEXCEPT {_VSTD::swap(__state_, __rhs.__state_);} // functions to check state _LIBCPP_INLINE_VISIBILITY bool valid() const _NOEXCEPT {return __state_ != nullptr;} _LIBCPP_INLINE_VISIBILITY void wait() const {__state_->wait();} template <class _Rep, class _Period> _LIBCPP_INLINE_VISIBILITY future_status wait_for(const chrono::duration<_Rep, _Period>& __rel_time) const {return __state_->wait_for(__rel_time);} template <class _Clock, class _Duration> _LIBCPP_INLINE_VISIBILITY future_status wait_until(const chrono::time_point<_Clock, _Duration>& __abs_time) const {return __state_->wait_until(__abs_time);} }; template <class _Rp> shared_future<_Rp>::~shared_future() { if (__state_) __state_->__release_shared(); } template <class _Rp> shared_future<_Rp>& shared_future<_Rp>::operator=(const shared_future& __rhs) { if (__rhs.__state_) __rhs.__state_->__add_shared(); if (__state_) __state_->__release_shared(); __state_ = __rhs.__state_; return *this; } template <class _Rp> class _LIBCPP_TYPE_VIS_ONLY shared_future<_Rp&> { __assoc_state<_Rp&>* __state_; public: _LIBCPP_INLINE_VISIBILITY shared_future() _NOEXCEPT : __state_(nullptr) {} _LIBCPP_INLINE_VISIBILITY shared_future(const shared_future& __rhs) : __state_(__rhs.__state_) {if (__state_) __state_->__add_shared();} #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES _LIBCPP_INLINE_VISIBILITY shared_future(future<_Rp&>&& __f) _NOEXCEPT : __state_(__f.__state_) {__f.__state_ = nullptr;} _LIBCPP_INLINE_VISIBILITY shared_future(shared_future&& __rhs) _NOEXCEPT : __state_(__rhs.__state_) {__rhs.__state_ = nullptr;} #endif // _LIBCPP_HAS_NO_RVALUE_REFERENCES ~shared_future(); shared_future& operator=(const shared_future& __rhs); #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES _LIBCPP_INLINE_VISIBILITY shared_future& operator=(shared_future&& __rhs) _NOEXCEPT { shared_future(std::move(__rhs)).swap(*this); return *this; } #endif // _LIBCPP_HAS_NO_RVALUE_REFERENCES // retrieving the value _LIBCPP_INLINE_VISIBILITY _Rp& get() const {return __state_->copy();} _LIBCPP_INLINE_VISIBILITY void swap(shared_future& __rhs) _NOEXCEPT {_VSTD::swap(__state_, __rhs.__state_);} // functions to check state _LIBCPP_INLINE_VISIBILITY bool valid() const _NOEXCEPT {return __state_ != nullptr;} _LIBCPP_INLINE_VISIBILITY void wait() const {__state_->wait();} template <class _Rep, class _Period> _LIBCPP_INLINE_VISIBILITY future_status wait_for(const chrono::duration<_Rep, _Period>& __rel_time) const {return __state_->wait_for(__rel_time);} template <class _Clock, class _Duration> _LIBCPP_INLINE_VISIBILITY future_status wait_until(const chrono::time_point<_Clock, _Duration>& __abs_time) const {return __state_->wait_until(__abs_time);} }; template <class _Rp> shared_future<_Rp&>::~shared_future() { if (__state_) __state_->__release_shared(); } template <class _Rp> shared_future<_Rp&>& shared_future<_Rp&>::operator=(const shared_future& __rhs) { if (__rhs.__state_) __rhs.__state_->__add_shared(); if (__state_) __state_->__release_shared(); __state_ = __rhs.__state_; return *this; } template <> class _LIBCPP_TYPE_VIS shared_future<void> { __assoc_sub_state* __state_; public: _LIBCPP_INLINE_VISIBILITY shared_future() _NOEXCEPT : __state_(nullptr) {} _LIBCPP_INLINE_VISIBILITY shared_future(const shared_future& __rhs) : __state_(__rhs.__state_) {if (__state_) __state_->__add_shared();} #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES _LIBCPP_INLINE_VISIBILITY shared_future(future<void>&& __f) _NOEXCEPT : __state_(__f.__state_) {__f.__state_ = nullptr;} _LIBCPP_INLINE_VISIBILITY shared_future(shared_future&& __rhs) _NOEXCEPT : __state_(__rhs.__state_) {__rhs.__state_ = nullptr;} #endif // _LIBCPP_HAS_NO_RVALUE_REFERENCES ~shared_future(); shared_future& operator=(const shared_future& __rhs); #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES _LIBCPP_INLINE_VISIBILITY shared_future& operator=(shared_future&& __rhs) _NOEXCEPT { shared_future(std::move(__rhs)).swap(*this); return *this; } #endif // _LIBCPP_HAS_NO_RVALUE_REFERENCES // retrieving the value _LIBCPP_INLINE_VISIBILITY void get() const {__state_->copy();} _LIBCPP_INLINE_VISIBILITY void swap(shared_future& __rhs) _NOEXCEPT {_VSTD::swap(__state_, __rhs.__state_);} // functions to check state _LIBCPP_INLINE_VISIBILITY bool valid() const _NOEXCEPT {return __state_ != nullptr;} _LIBCPP_INLINE_VISIBILITY void wait() const {__state_->wait();} template <class _Rep, class _Period> _LIBCPP_INLINE_VISIBILITY future_status wait_for(const chrono::duration<_Rep, _Period>& __rel_time) const {return __state_->wait_for(__rel_time);} template <class _Clock, class _Duration> _LIBCPP_INLINE_VISIBILITY future_status wait_until(const chrono::time_point<_Clock, _Duration>& __abs_time) const {return __state_->wait_until(__abs_time);} }; template <class _Rp> inline _LIBCPP_INLINE_VISIBILITY void swap(shared_future<_Rp>& __x, shared_future<_Rp>& __y) _NOEXCEPT { __x.swap(__y); } template <class _Rp> inline _LIBCPP_INLINE_VISIBILITY shared_future<_Rp> future<_Rp>::share() { return shared_future<_Rp>(_VSTD::move(*this)); } template <class _Rp> inline _LIBCPP_INLINE_VISIBILITY shared_future<_Rp&> future<_Rp&>::share() { return shared_future<_Rp&>(_VSTD::move(*this)); } #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES inline _LIBCPP_INLINE_VISIBILITY shared_future<void> future<void>::share() { return shared_future<void>(_VSTD::move(*this)); } #endif // _LIBCPP_HAS_NO_RVALUE_REFERENCES _LIBCPP_END_NAMESPACE_STD #endif // !_LIBCPP_HAS_NO_THREADS #endif // _LIBCPP_FUTURE
[ "changhyeok.bae@lge.com" ]
changhyeok.bae@lge.com
66e8e05db4a36ca2a2cd99aea1a2c6f50dc009f2
f048ac073eb2bef649a7eddfc69412a3b34e82ca
/Graphs/countPaths.cpp
8ca07ea2f228dc0b8fcdcea8c326e0e4eb0ea8c1
[]
no_license
tiwason/practice
85189ce6ab2b6d2a233a54a66d8bc89211c9dde4
e312cc39024a3d87fc2c8982aa83a2e0b38d9d21
refs/heads/master
2023-04-26T23:16:25.065399
2021-05-23T08:36:06
2021-05-23T08:36:06
315,837,804
0
0
null
null
null
null
UTF-8
C++
false
false
1,806
cpp
#include <iostream> #include <vector> #include <algorithm> using namespace std; struct Graph { int v; vector<int>* adjList; }; Graph* createGraph(int V) { Graph* graph = new Graph(); graph->v = V; graph->adjList = new vector<int>[V]; return graph; } void addEdge(Graph* graph, int u, int v) //edge u to v { if(graph == NULL) return; graph->adjList[u].push_back(v); } void printGraph(Graph* graph) { if(graph == NULL) return; for (int i=0; i<graph->v; i++) { cout << "Adjacency list of vertex "<<i << " : "; for (auto e: graph->adjList[i]) cout << e <<" ,"; cout <<endl; } } //checks if there is an edge between u and v bool searchEdge(Graph* graph , int u, int v) { if (graph) { vector<int>::iterator it = find(graph->adjList[u].begin() , graph->adjList[u].end(), v); return (it != graph->adjList[u].end()); } return false; } void printPath(vector<int> path) { for(auto v: path) cout << v << " -> "; } void dfs(Graph *g, int src, int dest, vector<int> path) { if(g == NULL) return; path.push_back(src); for(auto e: g->adjList[src]) { if (e == dest) { printPath(path); cout << e; cout << endl; } else dfs(g, e, dest, path); } } void countPaths(Graph* g, int src, int dest) { dfs(g, src, dest, {}); } int main() { Graph* graph = createGraph(5); addEdge(graph, 0, 1); addEdge(graph, 0, 2); addEdge(graph, 0, 4); addEdge(graph, 1, 3); addEdge(graph, 1, 4); addEdge(graph, 2, 4); addEdge(graph, 3, 2); countPaths(graph, 0, 4); return 0; }
[ "sonam5488@gmail.com" ]
sonam5488@gmail.com
a369b180e9caac79759369d7741127d65996ef25
a8de7a6074dce723c6d76dae10202fd3a490d9e5
/base/error_handler.h
4bb3bda63de80888cc090dd9fdd5f3e0193b0f71
[]
no_license
gykeve/owl
3aa635d8d969007327f8953eef520ee6080fc1b6
7c87f341c22fafae00d626c99572ee4c66228ad9
refs/heads/master
2020-12-13T03:38:33.398585
2019-12-05T11:32:23
2019-12-05T11:32:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
312
h
/** * @brief error handler * * **/ #ifndef OWL_BASE_ERRORHANDLING #define OWL_BASE_ERRORHANDLING #include <iostream> #include <string> using namespace std; namespace owl { namespace base { //TODO: void error_handler(string name) { cout << name << endl; //TODO: } } } #endif
[ "1816703663@qq.com" ]
1816703663@qq.com
838c5c0918a83e65553e72a8551a11cc8e3281f0
0fc6e94129f170153568f1e54dd301dbd984c75d
/topic learning/samsung problem set/fisherman.cpp
7e08cad4838f94fc05fc3f9c61ac87d533516f08
[]
no_license
shakkhor/Preparation
da557151e3b0a30b4c91aaf5e2a4a2aece0e9c98
685f6cbc4a38bb0f5ecf0c7ed35b738a5d724401
refs/heads/master
2020-04-21T07:27:41.491259
2019-07-19T14:37:03
2019-07-19T14:37:08
169,393,334
0
0
null
null
null
null
UTF-8
C++
false
false
3,490
cpp
#include<iostream> using namespace std; int point[100], n; int left_calculation(int p , int x) { int dist = 0; for(int i = 1; i<=x; i++) { int l =0, r = 0, flag =1; for(int j = p ; j>= 1; j--) { if(point[j]==0) { l++; flag = 0; break; } l++; } if(flag) { l = 1000; } flag = 1; for(int j = p; j<=n; j++ ) { if(point[j]==0) { r++; flag = 0; break; } r++; } if(flag) { r = 1000; } if(l<=r) { dist+= r; point[p-l+1]=1; } else { dist+=r; point[p+r-1]=1; } } return dist; } int right_calculation(int p, int x) { int dist = 0; for(int i =1; i<=x; i++) { int l =0, r = 0, flag =1; for(int j = p; j>=1; j--) { if(point[j]==0) { l++; flag = 0; break; } l++; } if(flag) { l = 1000; } flag = 1; for(int j = p ;j<=n; j++) { if(point[j]==0) { r++; flag = 0; break; } r++; } if(flag) { r = 1000; } if(l<r) { dist+=1; point[p-l+1]=1; } else { dist+=r; point[p+r-1]=1; } } return dist; } int main() { int t; cin>> t; for(int test = 1; test<=t; test++) { cin>>n ; int ans = 1000; int gate[10][10]; for(int i =1; i<=3; i++) { int p,m; cin>>p>>m; gate[i][1]= p; gate[i][2]= m; } for(int i =1; i<=3; i++) { for(int j =1; j<=3; j++) { if(i==j) continue; for(int k =1; k<=3; k++) { if(i==k || j==k) continue; int dist = 0; for(int x = 1; x<=n; x++) { point[x]=0; } dist += left_calculation(gate[i][1], gate[i][2]); dist += left_calculation(gate[j][1], gate[j][2]); dist += left_calculation(gate[k][1], gate[k][2]); if(ans > dist) ans = dist; dist = 0; for(int x =1; x<=n; x++) { point[x]=0; } dist += right_calculation(gate[i][1], gate[i][2]); dist += right_calculation(gate[j][1], gate[j][2]); dist += right_calculation(gate[k][1], gate[k][2]); if(ans > dist) ans =dist; } } } //printf("#%d %d", test, ans); cout<<"#"<<test<<": "<<ans<<endl; } return 0; }
[ "abdullahshakkhor@gmail.com" ]
abdullahshakkhor@gmail.com
7605e6555c12f7c07e7775eb9d0829fbd02d1847
b7994619e48c411f199def05c0c7cb7ac657d3c4
/chronochat/ChronoChat/chat-message.cpp
21707d2db5d0fade6633b9737b8cd0a40c08ef4e
[]
no_license
sijiahi/ndn_app_old
a9fc0fa7402098a8d7e38b04fc1482721efe009f
73f85cd88c469ec05166c7729fca0f5d72976c7b
refs/heads/master
2023-01-24T22:31:47.250074
2020-12-14T07:21:49
2020-12-14T07:21:49
314,401,555
2
0
null
null
null
null
UTF-8
C++
false
false
4,635
cpp
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil -*- */ /* * Copyright (c) 2013, Regents of the University of California * * BSD license, See the LICENSE file for more information * * Author: Qiuhan Ding <qiuhanding@cs.ucla.edu> */ #include "chat-message.hpp" namespace chronochat { BOOST_CONCEPT_ASSERT((ndn::WireEncodable<ChatMessage>)); BOOST_CONCEPT_ASSERT((ndn::WireDecodable<ChatMessage>)); ChatMessage::ChatMessage() { } ChatMessage::ChatMessage(const Block& chatMsgWire) { this->wireDecode(chatMsgWire); } template<bool T> size_t ChatMessage::wireEncode(ndn::EncodingImpl<T>& encoder) const { // ChatMessage := CHAT-MESSAGE-TYPE TLV-LENGTH // Nick // ChatroomName // ChatMessageType // ChatData // Timestamp // // Nick := NICK-NAME-TYPE TLV-LENGTH // String // // ChatroomName := CHATROOM-NAME-TYPE TLV-LENGTH // String // // ChatMessageType := CHAT-MESSAGE-TYPE TLV-LENGTH // nonNegativeInteger // // ChatData := CHAT-DATA-TYPE TLV-LENGTH // String // // Timestamp := TIMESTAMP-TYPE TLV-LENGTH // VarNumber // size_t totalLength = 0; // Timestamp totalLength += prependNonNegativeIntegerBlock(encoder, tlv::Timestamp, m_timestamp); // ChatData if (m_msgType == CHAT) { const uint8_t* dataWire = reinterpret_cast<const uint8_t*>(m_data.c_str()); totalLength += encoder.prependByteArrayBlock(tlv::ChatData, dataWire, m_data.length()); } // ChatMessageType totalLength += prependNonNegativeIntegerBlock(encoder, tlv::ChatMessageType, m_msgType); // ChatroomName const uint8_t* chatroomWire = reinterpret_cast<const uint8_t*>(m_chatroomName.c_str()); totalLength += encoder.prependByteArrayBlock(tlv::ChatroomName, chatroomWire, m_chatroomName.length()); // Nick const uint8_t* nickWire = reinterpret_cast<const uint8_t*>(m_nick.c_str()); totalLength += encoder.prependByteArrayBlock(tlv::Nick, nickWire, m_nick.length()); // Chat Message totalLength += encoder.prependVarNumber(totalLength); totalLength += encoder.prependVarNumber(tlv::ChatMessage); return totalLength; } const Block& ChatMessage::wireEncode() const { ndn::EncodingEstimator estimator; size_t estimatedSize = wireEncode(estimator); ndn::EncodingBuffer buffer(estimatedSize, 0); wireEncode(buffer); m_wire = buffer.block(); m_wire.parse(); return m_wire; } void ChatMessage::wireDecode(const Block& chatMsgWire) { m_wire = chatMsgWire; m_wire.parse(); if (m_wire.type() != tlv::ChatMessage) throw Error("Unexpected TLV number when decoding chat message packet"); Block::element_const_iterator i = m_wire.elements_begin(); if (i == m_wire.elements_end() || i->type() != tlv::Nick) throw Error("Expect Nick but get ..."); m_nick = std::string(reinterpret_cast<const char* >(i->value()), i->value_size());; i++; if (i == m_wire.elements_end() || i->type() != tlv::ChatroomName) throw Error("Expect Chatroom Name but get ..."); m_chatroomName = std::string(reinterpret_cast<const char* >(i->value()), i->value_size());; i++; if (i == m_wire.elements_end() || i->type() != tlv::ChatMessageType) throw Error("Expect Chat Message Type but get ..."); m_msgType = static_cast<ChatMessageType>(readNonNegativeInteger(*i)); i++; if (m_msgType != CHAT) m_data = ""; else { if (i == m_wire.elements_end() || i->type() != tlv::ChatData) throw Error("Expect Chat Data but get ..."); m_data = std::string(reinterpret_cast<const char* >(i->value()), i->value_size());; i++; } if (i == m_wire.elements_end() || i->type() != tlv::Timestamp) throw Error("Expect Timestamp but get ..."); m_timestamp = static_cast<time_t>(readNonNegativeInteger(*i)); i++; if (i != m_wire.elements_end()) { throw Error("Unexpected element"); } } void ChatMessage::setNick(const std::string& nick) { m_wire.reset(); m_nick = nick; } void ChatMessage::setChatroomName(const std::string& chatroomName) { m_wire.reset(); m_chatroomName = chatroomName; } void ChatMessage::setMsgType(const ChatMessageType msgType) { m_wire.reset(); m_msgType = msgType; } void ChatMessage::setData(const std::string& data) { m_wire.reset(); m_data = data; } void ChatMessage::setTimestamp(const time_t timestamp) { m_wire.reset(); m_timestamp = timestamp; } }// namespace chronochat
[ "sijia.zhang@buaa.edu.cn" ]
sijia.zhang@buaa.edu.cn
0e9f3e49d399d193d36882da17ae62a1d93661be
984c70b313933f25a1c2c478fc58bf335b2c72b7
/ex04_recursive_bruteforce/main.cpp
af5fe524ac088947ab153836bd6f2a4e16512cdf
[]
no_license
moredrowsy/data_structures_i
2aa487985964d569aa8e98ea858fd37f25be240b
d0dde46362b6eebfb4897f52f6aedf12c76f3052
refs/heads/main
2021-06-07T11:47:20.321604
2020-11-26T01:39:45
2020-11-26T01:39:45
147,608,176
1
0
null
null
null
null
UTF-8
C++
false
false
1,220
cpp
/******************************************************************************* * AUTHOR : Thuan Tang * ID : 00991588 * CLASS : CS008 * EXERCISE 04 : Recursive Brute Force * DESCRIPTION : Simple exercise to demonstrate brute force combination ******************************************************************************/ #include <iostream> // output stream #include <string> // string void brute_force(std::string &list, std::string str, int level, int &count) { if(level > 0) { for(std::size_t i = 0; i < list.size(); ++i) { brute_force(list, str + list[i], level - 1, count); } } else { std::cout << str << '\n'; ++count; } } int main() { int count = 0; // hold the number of combinations std::string list; // list for characters to rearrange // add numerals to list for(char c = '0'; c <= '9'; ++c) list += c; // add upper case alphabet for(char c = 'A'; c <= 'Z'; ++c) list += c; // add lower case alphabet for(char c = 'a'; c <= 'z'; ++c) list += c; brute_force(list, std::string(), 4, count); std::cout << "Permutations: " << count << std::endl; return 0; }
[ "thuantang@gmail.com" ]
thuantang@gmail.com
67e72be40ef3e5ace5aba73f53f3963cce78abd7
7e17d9516c8c68a3adfd8e3aa4057c52734dbd07
/pbscpp_task_forLect7/main.cpp
9a9a288b767b1b763094292162be463f575ac7d5
[]
no_license
mlshf/PBSC
d0f1f5b8f2591c7056dabb5be6883df45215b626
9cd0888308ccbc6fef9e11c060a2725f05ffe759
refs/heads/master
2020-03-30T21:34:27.926889
2018-12-25T05:10:49
2018-12-25T05:10:49
150,642,558
0
0
null
null
null
null
UTF-8
C++
false
false
1,363
cpp
#include <iostream> #include <memory> class A { public: // ... static void* operator new(size_t size) { std::cout << "operator new!" << std::endl; return ::operator new(size); } static void operator delete(void* p, size_t size) { std::cout << "operator delete!" << std::endl; return ::operator delete(p); } }; template < class T > struct TAllocator_forClass_A { typedef T value_type; TAllocator_forClass_A() = default; template< class U > TAllocator_forClass_A( const TAllocator_forClass_A< U >& ) {}; T* allocate( std::size_t size ) { if( size > std::size_t( -1 ) / sizeof( value_type ) ) throw std::bad_alloc(); if( auto p = static_cast< value_type* >( A::operator new( size * sizeof( value_type ) ) ) ) return p; throw std::bad_alloc(); } void deallocate(value_type* p, std::size_t size) { A::operator delete( p, size * sizeof(value_type) ); } }; template <class T, class U> bool operator==(const TAllocator_forClass_A<T>&, const TAllocator_forClass_A<U>&) { return true; } template <class T, class U> bool operator!=(const TAllocator_forClass_A<T>&, const TAllocator_forClass_A<U>&) { return false; } int main() { auto my_allocator = TAllocator_forClass_A<A>(); auto sp = std::allocate_shared<A>(my_allocator); }
[ "nikita.s.malyshev@gmail.com" ]
nikita.s.malyshev@gmail.com
90a2b77b9671b9ac5181b9845d0644c15f4c2f50
6751d19567116ff264633fbf3e7e42b7723cf355
/engine3d/mesh.hpp
93e6b2d15036dca0f28a99c6c1838d0236030b03
[]
no_license
meowyih/simple-3d-engine
dec3e838f615f53b38dc6d37e1445773d4882991
c3db3909c8ba9395c234aa2349cc25e06f4b70d5
refs/heads/master
2020-03-25T01:22:55.012508
2018-09-19T05:13:10
2018-09-19T05:13:10
143,234,549
1
0
null
null
null
null
UTF-8
C++
false
false
2,082
hpp
#ifndef OCTILLION_ENGINE3D_MESH_HEADER #define OCTILLION_ENGINE3D_MESH_HEADER #include <iostream> #include <vector> #include <string> #include "../jsonw/jsonw.hpp" #include "face.hpp" class Mesh { public: Mesh() {} void init(std::string jsonfile) { // reset data valid_ = false; faces_.clear(); // open file std::ifstream fin(jsonfile); if (!fin.good()) return; // read file into json octillion::JsonW json(fin); if (json.valid() == false) return; // get vertices array octillion::JsonW* vertices = json.get("vertices"); if (vertices->size() == 0 || vertices->size() % 9 != 0) return; // get normals array octillion::JsonW* normals = json.get("normals"); if (normals->size() != vertices->size() ) return; // feed data into faces_ faces_.reserve(vertices->size() / 3); for (size_t idx = 0; idx < vertices->size(); idx = idx + 9) { faces_.push_back( Face( PointF( vertices->get(idx)->frac(), vertices->get(idx + 1)->frac(), vertices->get(idx + 2)->frac() ), VectorF( normals->get(idx)->frac(), normals->get(idx + 1)->frac(), normals->get(idx + 2)->frac()), PointF( vertices->get(idx + 3)->frac(), vertices->get(idx + 4)->frac(), vertices->get(idx + 5)->frac()), VectorF( normals->get(idx + 3)->frac(), normals->get(idx + 4)->frac(), normals->get(idx + 5)->frac()), PointF( vertices->get(idx + 6)->frac(), vertices->get(idx + 7)->frac(), vertices->get(idx + 8)->frac()), VectorF( normals->get(idx + 6)->frac(), normals->get(idx + 7)->frac(), normals->get(idx + 8)->frac()) ) ); } valid_ = true; } public: bool valid_ = false; std::vector<Face> faces_; }; #endif
[ "yhorng75@gmail.com" ]
yhorng75@gmail.com
43526dc2619c2cbf662111335f75ab3bc7f9941a
dbafd6748b55bdc5d35e6b7666b4ad049d82e758
/player/NymphCastPlayer/mainwindow.h
c479d052ff0dc26521a570fcc26607eb1f10417e
[ "BSD-3-Clause" ]
permissive
joe-nano/NymphCast
401c4fcb756524aa65f781339180ecfd8a40ca6d
5592d3d8327df53ac2f8f29ef5ac0f65cc0428af
refs/heads/master
2022-04-17T21:11:34.500481
2020-04-11T14:38:31
2020-04-11T14:38:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,309
h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include "nymphcast_client.h" namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = nullptr); ~MainWindow(); private slots: void openFile(); void connectServer(); void connectServerIP(std::string ip); void disconnectServer(); void about(); void quit(); void castFile(); void castUrl(); void addFile(); void removeFile(); void findServer(); void play(); void stop(); void pause(); void forward(); void rewind(); void seek(); void mute(); void adjustVolume(int value); void setPlaying(uint32_t handle, NymphPlaybackStatus status); void remoteListRefresh(); void remoteConnectSelected(); void remoteDisconnectSelected(); void appsListRefresh(); void sendCommand(); signals: void playbackStatusChange(uint32_t handle, NymphPlaybackStatus status); private: Ui::MainWindow *ui; bool connected = false; bool muted = false; bool playingTrack = false; uint32_t serverHandle; NymphCastClient client; void statusUpdateCallback(uint32_t handle, NymphPlaybackStatus status); }; #endif // MAINWINDOW_H
[ "maya@nyanko.ws" ]
maya@nyanko.ws
6a22ccad3599ad9e0ce95f6d065f6515fb380da3
349886cf3a8664c79511fffb4a182bd4019093e1
/ListasDobles/ListasDobles/ListasDobles.cpp
50b531e1acbc86a0030181f667ffaca117316381
[]
no_license
bmigue/Listas-Dobles
a7fc8a5de433ee5de230ed1bb34fa4741dc138ac
03bf29e5949d128732d2eb670c1e895b06c29172
refs/heads/main
2023-01-18T23:35:02.550097
2020-11-12T22:07:17
2020-11-12T22:07:17
312,407,153
0
0
null
null
null
null
UTF-8
C++
false
false
4,042
cpp
// ListasDobles.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include <iostream> #include "listaDobleLineal.h" #include "listaDobleCircular.h" using namespace std; int main() { int opcion; listaDobleCircular* lista = new listaDobleCircular(); lista->agregarInicio(2); lista->agregarInicio(4); lista->agregarInicio(2); lista->agregarInicio(15); lista->agregarInicio(10); lista->desplegar(); cout << "--------------------------------------------" << endl; lista->desplegarMultiplos(2); listaDobleCircular* listaClon = lista->listaInvertida(); cout << "--------------------------------------------" << endl; listaClon->desplegar(); /*do { cout << "Digite la opcion a utilizar para la lista creada: " << endl; cout << "1- Desplegar lista" << endl; cout << "2- Agregar un nodo al inicio" << endl; cout << "3- Agregar un antes de " << endl; cout << "4- Agregar despues de " << endl; cout << "5- Agregar al final " << endl; cout << "6- Valor del indice " << endl; cout << "7- Agregar por indice" << endl; cout << "8- Nodo por valor" << endl; cout << "9- Nodo anterior a un valor" << endl; cout << "10- Nodo final" << endl; cout << "11- Nodo por indice" << endl; cout << "12- Eliminar por indice" << endl; cout << "13- Eliminar por valor" << endl; int valor; int valor2; cin >> opcion; switch (opcion) { case 1: cout << "--------------------------------------------" << endl; lista->desplegar(); cout << "--------------------------------------------" << endl; break; case 2: cout << "Digite el valor:" << endl; cin >> valor; lista->agregarInicio(valor); break; case 3: cout << "Digite el valor de referencia" << endl; cin >> valor2; cout << "Digite el valor a agregar" << endl; cin >> valor; lista->agregarAntesDe(valor, valor2); break; case 4: cout << "Digite el valor de referencia" << endl; cin >> valor2; cout << "Digite el valor a agregar" << endl; cin >> valor; lista->agregarDespuesDe(valor, valor2); break; case 5: cout << "Digite el valor:" << endl; cin >> valor; lista->agregarFinal(valor); break; case 6: cout << "Digite el indice:" << endl; cin >> valor; cout << lista->valorIndice(valor) << endl; break; case 7: cout << "Digite el indice:" << endl; cin >> valor; cout << "Digite el valor a agregar" << endl; cin >> valor2; lista->agregarIndice(valor2, valor); break; case 8: cout << "Digite el valor:" << endl; cin >> valor; cout << lista->dirNodo(valor) << endl; break; case 9: cout << "Digite el valor:" << endl; cin >> valor; cout << lista->dirAnterior(valor) << endl; break; case 10: cout << lista->dirUltimo() << endl; break; case 11: cout << "Digite el indice:" << endl; cin >> valor; cout << lista->dirNodoIndice(valor) << endl; break; case 12: cout << "Digite el indice:" << endl; cin >> valor; lista->eliminarIndice(valor); break; case 13: cout << "Digite el valor:" << endl; cin >> valor; lista->eliminar(valor); break; case 14: break; default: cout << "Valor incorrecto" << endl; break; } } while(opcion != 14);*/ }
[ "mgutierrezb@ucenfotec.ac.cr" ]
mgutierrezb@ucenfotec.ac.cr
6fcebdd407979af076607c339b0046b3a1489a4c
c8b082e71d496c1f06877f5b940facf54d85cbfa
/src/file_stream.h
baac810661732c6a4d24bffa33b3241d60a3561a
[ "NCSA", "LLVM-exception", "Apache-2.0" ]
permissive
azharudd/apple-llvm-infrastructure-tools
c28a44b94052bb37962c8f5cc30de6be48407caf
7c64a2369abf016efa2fd36ab56862f71978ed4f
refs/heads/master
2021-07-16T08:49:34.068902
2020-05-08T18:40:56
2020-05-08T18:40:56
236,829,430
0
0
Apache-2.0
2020-01-28T20:03:59
2020-01-28T20:03:58
null
UTF-8
C++
false
false
3,066
h
// file_stream.h #pragma once #include "mmapped_file.h" #include <cstdio> #include <cstring> namespace { class file_stream { FILE *stream = nullptr; mmapped_file mmapped; size_t num_bytes_on_open = -1; bool is_stream = false; bool is_initialized = false; long position = 0; public: file_stream() = default; int init(int fd, bool is_read_only) { return is_read_only ? init_mmap(fd) : init_stream(fd); } int init_stream(int fd); int init_mmap(int fd); size_t get_num_bytes_on_open() const { return num_bytes_on_open; } int seek_end(); long tell(); int seek(long pos); int read(unsigned char *bytes, int count); int seek_and_read(long pos, unsigned char *bytes, int count); int write(const unsigned char *bytes, int count); int close(); ~file_stream() { close(); } }; } // end namespace int file_stream::init_stream(int fd) { assert(fd != -1); assert(!is_initialized); if (!(stream = fdopen(fd, "w+b")) || fseek(stream, 0, SEEK_END) || (num_bytes_on_open = ftell(stream)) == -1u || fseek(stream, 0, SEEK_SET)) { ::close(fd); return 1; } is_initialized = true; is_stream = true; return 0; } int file_stream::init_mmap(int fd) { assert(!is_initialized); is_initialized = true; is_stream = false; mmapped.init(fd); num_bytes_on_open = mmapped.num_bytes; return 0; } int file_stream::seek_end() { assert(is_initialized); if (is_stream) return fseek(stream, 0, SEEK_END); position = num_bytes_on_open; return 0; } long file_stream::tell() { assert(is_initialized); if (is_stream) return ftell(stream); return position; } int file_stream::seek_and_read(long pos, unsigned char *bytes, int count) { assert(is_initialized); // TODO: add a testcase for reading after writing in the same stream. if (is_stream) return seek(pos) ? 0 : read(bytes, count); // Check that the position is valid first. if (pos >= (long)num_bytes_on_open) return 0; if (pos > (long)num_bytes_on_open || seek(pos)) return 0; if (count + pos > (long)num_bytes_on_open) count = num_bytes_on_open - pos; if (!count) return 0; return read(bytes, count); } int file_stream::seek(long pos) { assert(is_initialized); if (is_stream) return fseek(stream, pos, SEEK_SET); if (pos > (long)num_bytes_on_open) return 1; position = pos; return 0; } int file_stream::read(unsigned char *bytes, int count) { assert(is_initialized); if (is_stream) return fread(bytes, 1, count, stream); if (position + count > (long)num_bytes_on_open) count = num_bytes_on_open - position; if (count > 0) std::memcpy(bytes, mmapped.bytes + position, count); position += count; return count; } int file_stream::write(const unsigned char *bytes, int count) { assert(is_initialized); assert(is_stream); return fwrite(bytes, 1, count, stream); } int file_stream::close() { if (!is_initialized) return 0; is_initialized = false; num_bytes_on_open = -1; if (is_stream) return fclose(stream); return mmapped.close(); }
[ "dexonsmith@apple.com" ]
dexonsmith@apple.com
3c480678a76080c5eef31ee8099d885c1da4cdcf
948f4e13af6b3014582909cc6d762606f2a43365
/testcases/juliet_test_suite/testcases/CWE191_Integer_Underflow/s02/CWE191_Integer_Underflow__int_connect_socket_sub_82a.cpp
9290dece773d5fd3033a7bf03690554b624be0e3
[]
no_license
junxzm1990/ASAN--
0056a341b8537142e10373c8417f27d7825ad89b
ca96e46422407a55bed4aa551a6ad28ec1eeef4e
refs/heads/master
2022-08-02T15:38:56.286555
2022-06-16T22:19:54
2022-06-16T22:19:54
408,238,453
74
13
null
2022-06-16T22:19:55
2021-09-19T21:14:59
null
UTF-8
C++
false
false
7,074
cpp
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE191_Integer_Underflow__int_connect_socket_sub_82a.cpp Label Definition File: CWE191_Integer_Underflow__int.label.xml Template File: sources-sinks-82a.tmpl.cpp */ /* * @description * CWE: 191 Integer Underflow * BadSource: connect_socket Read data using a connect socket (client side) * GoodSource: Set data to a small, non-zero number (negative two) * Sinks: sub * GoodSink: Ensure there will not be an underflow before subtracting 1 from data * BadSink : Subtract 1 from data, which can cause an Underflow * Flow Variant: 82 Data flow: data passed in a parameter to an virtual method called via a pointer * * */ #include "std_testcase.h" #include "CWE191_Integer_Underflow__int_connect_socket_sub_82.h" #ifdef _WIN32 #include <winsock2.h> #include <windows.h> #include <direct.h> #pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */ #define CLOSE_SOCKET closesocket #else /* NOT _WIN32 */ #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #define INVALID_SOCKET -1 #define SOCKET_ERROR -1 #define CLOSE_SOCKET close #define SOCKET int #endif #define TCP_PORT 27015 #define IP_ADDRESS "127.0.0.1" #define CHAR_ARRAY_SIZE (3 * sizeof(data) + 2) namespace CWE191_Integer_Underflow__int_connect_socket_sub_82 { #ifndef OMITBAD void bad() { int data; /* Initialize data */ data = 0; { #ifdef _WIN32 WSADATA wsaData; int wsaDataInit = 0; #endif int recvResult; struct sockaddr_in service; SOCKET connectSocket = INVALID_SOCKET; char inputBuffer[CHAR_ARRAY_SIZE]; do { #ifdef _WIN32 if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR) { break; } wsaDataInit = 1; #endif /* POTENTIAL FLAW: Read data using a connect socket */ connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (connectSocket == INVALID_SOCKET) { break; } memset(&service, 0, sizeof(service)); service.sin_family = AF_INET; service.sin_addr.s_addr = inet_addr(IP_ADDRESS); service.sin_port = htons(TCP_PORT); if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR) { break; } /* Abort on error or the connection was closed, make sure to recv one * less char than is in the recv_buf in order to append a terminator */ recvResult = recv(connectSocket, inputBuffer, CHAR_ARRAY_SIZE - 1, 0); if (recvResult == SOCKET_ERROR || recvResult == 0) { break; } /* NUL-terminate the string */ inputBuffer[recvResult] = '\0'; /* Convert to int */ data = atoi(inputBuffer); } while (0); if (connectSocket != INVALID_SOCKET) { CLOSE_SOCKET(connectSocket); } #ifdef _WIN32 if (wsaDataInit) { WSACleanup(); } #endif } CWE191_Integer_Underflow__int_connect_socket_sub_82_base* baseObject = new CWE191_Integer_Underflow__int_connect_socket_sub_82_bad; baseObject->action(data); delete baseObject; } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ static void goodG2B() { int data; /* Initialize data */ data = 0; /* FIX: Use a small, non-zero value that will not cause an integer underflow in the sinks */ data = -2; CWE191_Integer_Underflow__int_connect_socket_sub_82_base* baseObject = new CWE191_Integer_Underflow__int_connect_socket_sub_82_goodG2B; baseObject->action(data); delete baseObject; } /* goodB2G uses the BadSource with the GoodSink */ static void goodB2G() { int data; /* Initialize data */ data = 0; { #ifdef _WIN32 WSADATA wsaData; int wsaDataInit = 0; #endif int recvResult; struct sockaddr_in service; SOCKET connectSocket = INVALID_SOCKET; char inputBuffer[CHAR_ARRAY_SIZE]; do { #ifdef _WIN32 if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR) { break; } wsaDataInit = 1; #endif /* POTENTIAL FLAW: Read data using a connect socket */ connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (connectSocket == INVALID_SOCKET) { break; } memset(&service, 0, sizeof(service)); service.sin_family = AF_INET; service.sin_addr.s_addr = inet_addr(IP_ADDRESS); service.sin_port = htons(TCP_PORT); if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR) { break; } /* Abort on error or the connection was closed, make sure to recv one * less char than is in the recv_buf in order to append a terminator */ recvResult = recv(connectSocket, inputBuffer, CHAR_ARRAY_SIZE - 1, 0); if (recvResult == SOCKET_ERROR || recvResult == 0) { break; } /* NUL-terminate the string */ inputBuffer[recvResult] = '\0'; /* Convert to int */ data = atoi(inputBuffer); } while (0); if (connectSocket != INVALID_SOCKET) { CLOSE_SOCKET(connectSocket); } #ifdef _WIN32 if (wsaDataInit) { WSACleanup(); } #endif } CWE191_Integer_Underflow__int_connect_socket_sub_82_base* baseObject = new CWE191_Integer_Underflow__int_connect_socket_sub_82_goodB2G; baseObject->action(data); delete baseObject; } void good() { goodG2B(); goodB2G(); } #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 CWE191_Integer_Underflow__int_connect_socket_sub_82; /* 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
[ "yzhang0701@gmail.com" ]
yzhang0701@gmail.com
ee01b15d06193c26a6cf5e06d17717b9ebce1647
ffa2014a838b6c34ca6a79c975c280d17616b3d2
/Graphs/dag shortest path.cpp
c9ce4873be64f1f39f24ac16a91f0fb7f17be7a0
[]
no_license
TarunSinghania/Prewritten-code
ada2b9d71b3bd452b5b0583e38c6c1d656529a18
fcb3b951fdf82fa88abeeb7133564515232bfff0
refs/heads/master
2020-12-31T08:46:57.394606
2020-12-26T17:47:52
2020-12-26T17:47:52
238,958,293
2
0
null
null
null
null
UTF-8
C++
false
false
3,438
cpp
#include<bits/stdc++.h> using namespace std; #define ll long long #define ull unsigned long long #define fr(i,a,b) for(int i =a ; i < b; i++) #define FR(i,a,b) for(int i =a ; i > b; i--) #define frj(j,a,b) for(int j =a ; j < b; j++) #define FRE(i,a,b) for(int i =a ; i >= b; i--) #define fre(i,a,b) for(int i =a ; i <= b; i++) #define fra(s) for(auto it = s.begin(); it != s.end() ; ++it) #define mkp make_pair #define pb push_back #define pii pair<int,int> #define speed ios::sync_with_stdio(false), cin.tie(0) , cout.tie(0) //#define c(a,b) cout<<a<<"--"<<b<<endl; #define frv(i,a,v) for(int i = a ; i < v.size() ; ++i) #define cp(a,i) cout<<a[i].first<<" "<<a[i].second<<endl; #define pp(a) cout<<a.first<<" "<<a.second<<endl; //sum array #define sa(n) int a[n]; int s[n];cin>>a[0];s[0]=a[0];fr(i,1,n) {cin>>a[i];s[i]=s[i-1]+a[i];} #define sa1(n) int a[n+1]; long long s[n+1]; a[0]=0; s[0]=0;cin>>a[1];s[1]=a[1];fr(i,2,n+1) {cin>>a[i];\ s[i]=s[i-1]+a[i];} #define pr(a,n) fr(i,0,n){cout<<a[i]<<" ";}cout<<endl; #define prv(v) for(auto it = v.begin() ; it!= v.end() ;++it){cout<<*it<<" ";}cout<<endl; #define prs(s) for(auto x : s){cout<<x<<" ";}cout<<endl; #define all(x) x.begin(), x.end() #define prm(m,r,c) fr(i,0,r){frj(j,0,c){cout<<m[i][j]<<" "; }cout<<endl;} #define fillm(m,r,c,k) fr(i,0,r)frj(j,0,c)m[i][j]=k; constexpr auto PI = 3.14159265358979323846L; constexpr auto eps = 1e-6; constexpr auto mod = 1000000007; #define MOD 1000000007 #define maxv 100005 #define MAXN 100001 template<class T> ostream& operator<<(ostream& out, vector<T> vec) { out<<"("; for (auto& v: vec) out<<v<<", "; return out<<")"; } template<class T> ostream& operator<<(ostream& out, set<T> vec) { out<<"("; for (auto& v: vec) out<<v<<", "; return out<<")"; } const int INF= 1e9 +5; vector<int> topsort(int v,vector<pair<int, int> > adj[]) { int in[v+1]={0}; fr(i,1,v+1){ for(auto x : adj[i]) { in[x.first]++; } } vector<int> ans; queue<int> q ; fr(i,1,v+1) if(in[i]==0) q.push(i); while(!q.empty()) { int k= q.front(); q.pop(); ans.pb(k); for(auto x : adj[k]) if(--in[x.first]==0) q.push(x.first); } if(int(ans.size()) != v) exit(2);//error not a dag return ans; } int main(){ speed; int v,e; cin>>v>>e; vector<pair<int,int> > adj[v+1]; int x,y,w; fr(i,0,e) { //path from x to y with weight w; cin>>x>>y>>w; adj[x].pb(mkp(y,w)); } vector<int> tp = topsort(v,adj); int dist[v+1]={INF}; fr(i,0,v+1) dist[i]={INF};//use -INF for longest paths and change comparison //do not use INT_max will give overflow //supply starting index int start = 2; dist[start] = 0; for(auto x : tp) { for(auto y : adj[x]) if(dist[y.first] > dist[x] + y.second)//use < for longest path and change -INF dist[y.first] = dist[x] + y.second; } pr(dist,v+1); return 0; }
[ "tarunsinghania1997@gmail.com" ]
tarunsinghania1997@gmail.com
70b41bab7476c152318e7e7cfbb9a1d99c4942af
e1a74ca86763a107114199e255f87ad9de5c7ab0
/Android/app/src/main/cpp/Anime4KCPPWrapper.cpp
7212fc00e20be477e5199da92523e4eb9fa35c33
[ "MIT" ]
permissive
dqhcjlu06/Anime4KCPP
3e649a2e67e551cd4a3f30966df93b9f86a6654a
250a95eb7ebd1a1203916a9f478d2b97913926a8
refs/heads/master
2022-11-23T08:51:02.262271
2020-07-25T16:04:26
2020-07-25T16:04:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,582
cpp
#include <jni.h> #include <string> #include "Anime4KCPP.h" #ifdef DEBUG #include <android/log.h> #define TAG "Anime4K-jni-test" #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,TAG ,__VA_ARGS__) #endif extern "C" { JNIEXPORT jlong JNICALL Java_github_tianzerl_anime4kcpp_wrapper_Anime4KCPU_createAnime4KCPU( JNIEnv *env, jobject /* this */) { return (jlong)(new Anime4KCPP::Anime4KCPU()); } JNIEXPORT jlong JNICALL Java_github_tianzerl_anime4kcpp_wrapper_Anime4KCPU_createAnime4KCPUByArgs( JNIEnv *env, jobject /* this */, jint passes, jint pushColorCount, jdouble strengthColor, jdouble strengthGradient, jdouble zoomFactor, jboolean fastMode, jboolean videoMode, jboolean preprocessing, jboolean postprocessing, jbyte preFilters, jbyte postFilters) { return (jlong)(new Anime4KCPP::Anime4KCPU( Anime4KCPP::Parameters( passes, pushColorCount, strengthColor, strengthGradient, zoomFactor, fastMode, videoMode, preprocessing, postprocessing, preFilters, postFilters )) ); } JNIEXPORT jlong JNICALL Java_github_tianzerl_anime4kcpp_wrapper_Anime4KGPU_createAnime4KGPU( JNIEnv *env, jobject /* this */) { return (jlong)(new Anime4KCPP::Anime4KGPU()); } JNIEXPORT jlong JNICALL Java_github_tianzerl_anime4kcpp_wrapper_Anime4KGPU_createAnime4KGPUByArgs( JNIEnv *env, jobject /* this */, jint passes, jint pushColorCount, jdouble strengthColor, jdouble strengthGradient, jdouble zoomFactor, jboolean fastMode, jboolean videoMode, jboolean preprocessing, jboolean postprocessing, jbyte preFilters, jbyte postFilters) { return (jlong)(new Anime4KCPP::Anime4KGPU( Anime4KCPP::Parameters( passes, pushColorCount, strengthColor, strengthGradient, zoomFactor, fastMode, videoMode, preprocessing, postprocessing, preFilters, postFilters )) ); } JNIEXPORT jlong JNICALL Java_github_tianzerl_anime4kcpp_wrapper_Anime4KCPUCNN_createAnime4KCPUCNN( JNIEnv *env, jobject /* this */) { return (jlong)(new Anime4KCPP::Anime4KCPUCNN()); } JNIEXPORT jlong JNICALL Java_github_tianzerl_anime4kcpp_wrapper_Anime4KCPUCNN_createAnime4KCPUCNNByArgs( JNIEnv *env, jobject /* this */, jint passes, jint pushColorCount, jdouble strengthColor, jdouble strengthGradient, jdouble zoomFactor, jboolean fastMode, jboolean videoMode, jboolean preprocessing, jboolean postprocessing, jbyte preFilters, jbyte postFilters, jboolean HDN) { return (jlong)(new Anime4KCPP::Anime4KCPUCNN( Anime4KCPP::Parameters( passes, pushColorCount, strengthColor, strengthGradient, zoomFactor, fastMode, videoMode, preprocessing, postprocessing, preFilters, postFilters, std::thread::hardware_concurrency(), HDN )) ); } JNIEXPORT jlong JNICALL Java_github_tianzerl_anime4kcpp_wrapper_Anime4KGPUCNN_createAnime4KGPUCNN( JNIEnv *env, jobject /* this */) { return (jlong)(new Anime4KCPP::Anime4KGPUCNN()); } JNIEXPORT jlong JNICALL Java_github_tianzerl_anime4kcpp_wrapper_Anime4KGPUCNN_createAnime4KGPUCNNByArgs( JNIEnv *env, jobject /* this */, jint passes, jint pushColorCount, jdouble strengthColor, jdouble strengthGradient, jdouble zoomFactor, jboolean fastMode, jboolean videoMode, jboolean preprocessing, jboolean postprocessing, jbyte preFilters, jbyte postFilters, jboolean HDN) { return (jlong)(new Anime4KCPP::Anime4KGPUCNN( Anime4KCPP::Parameters( passes, pushColorCount, strengthColor, strengthGradient, zoomFactor, fastMode, videoMode, preprocessing, postprocessing, preFilters, postFilters, std::thread::hardware_concurrency(), HDN )) ); } JNIEXPORT void JNICALL Java_github_tianzerl_anime4kcpp_wrapper_Anime4K_setArgumentsAnime4K( JNIEnv *env, jobject /* this */, jlong ptrAnime4K, jint passes, jint pushColorCount, jdouble strengthColor, jdouble strengthGradient, jdouble zoomFactor, jboolean fastMode, jboolean videoMode, jboolean preprocessing, jboolean postprocessing, jbyte preFilters, jbyte postFilters) { ((Anime4KCPP::Anime4K *)(ptrAnime4K))->setArguments( Anime4KCPP::Parameters( passes, pushColorCount, strengthColor, strengthGradient, zoomFactor, fastMode, videoMode, preprocessing, postprocessing, preFilters, postFilters ) ); } JNIEXPORT void JNICALL Java_github_tianzerl_anime4kcpp_wrapper_Anime4K_releaseAnime4K( JNIEnv *env, jobject /* this */, jlong ptrAnime4K) { delete ((Anime4KCPP::Anime4K*)(ptrAnime4K)); } JNIEXPORT void JNICALL Java_github_tianzerl_anime4kcpp_wrapper_Anime4K_loadImageAnime4K( JNIEnv *env, jobject /* this */, jlong ptrAnime4K, jstring src) { try { ((Anime4KCPP::Anime4K*)(ptrAnime4K))->loadImage(std::string(env->GetStringUTFChars(src, JNI_FALSE))); } catch (const char* err) { env->ThrowNew(env->FindClass("java/lang/Exception"), err); } } JNIEXPORT void JNICALL Java_github_tianzerl_anime4kcpp_wrapper_Anime4K_processAnime4K( JNIEnv *env, jobject /* this */, jlong ptrAnime4K) { ((Anime4KCPP::Anime4K*)(ptrAnime4K))->process(); } JNIEXPORT void JNICALL Java_github_tianzerl_anime4kcpp_wrapper_Anime4K_processWithProgressAnime4K( JNIEnv *env, jobject thiz /* this */, jlong ptrAnime4K) { jclass classID = env->GetObjectClass(thiz); jmethodID callback = env->GetMethodID(classID,"progressCallback", "(DD)V"); std::chrono::steady_clock::time_point s = std::chrono::steady_clock::now(); ((Anime4KCPP::Anime4K*)(ptrAnime4K))->processWithProgress( [&env, &thiz, &callback, &s](double v) { std::chrono::steady_clock::time_point e = std::chrono::steady_clock::now(); env->CallVoidMethod(thiz, callback, v, std::chrono::duration_cast<std::chrono::milliseconds>(e - s).count() / 1000.0); }); } JNIEXPORT void JNICALL Java_github_tianzerl_anime4kcpp_wrapper_Anime4K_saveImageAnime4K( JNIEnv *env, jobject /* this */, jlong ptrAnime4K, jstring dst) { ((Anime4KCPP::Anime4K*)(ptrAnime4K))->saveImage(std::string(env->GetStringUTFChars(dst, JNI_FALSE))); } JNIEXPORT void JNICALL Java_github_tianzerl_anime4kcpp_wrapper_Anime4K_setVideoModeAnime4K( JNIEnv *env, jobject /* this */, jlong ptrAnime4K, jboolean flag) { ((Anime4KCPP::Anime4K*)(ptrAnime4K))->setVideoMode(flag); } JNIEXPORT void JNICALL Java_github_tianzerl_anime4kcpp_wrapper_Anime4K_loadVideoAnime4K( JNIEnv *env, jobject /* this */, jlong ptrAnime4K, jstring src) { try { ((Anime4KCPP::Anime4K*)(ptrAnime4K))->loadVideo(std::string(env->GetStringUTFChars(src, JNI_FALSE))); } catch (const char* err) { env->ThrowNew(env->FindClass("java/lang/Exception"), err); } } JNIEXPORT void JNICALL Java_github_tianzerl_anime4kcpp_wrapper_Anime4K_setVideoSaveInfoAnime4K( JNIEnv *env, jobject /* this */, jlong ptrAnime4K, jstring dst) { try { ((Anime4KCPP::Anime4K*)(ptrAnime4K))->setVideoSaveInfo(std::string(env->GetStringUTFChars(dst, JNI_FALSE))); } catch (const char* err) { env->ThrowNew(env->FindClass("java/lang/Exception"), err); } } JNIEXPORT void JNICALL Java_github_tianzerl_anime4kcpp_wrapper_Anime4K_saveVideoAnime4K( JNIEnv *env, jobject /* this */, jlong ptrAnime4K) { ((Anime4KCPP::Anime4K*)(ptrAnime4K))->saveVideo(); } JNIEXPORT jboolean JNICALL Java_github_tianzerl_anime4kcpp_wrapper_Anime4KGPU_checkGPUSupportAnime4KGPU( JNIEnv *env, jclass clazz) { return (jboolean)(Anime4KCPP::Anime4KGPU::checkGPUSupport(0, 0).first); } JNIEXPORT void JNICALL Java_github_tianzerl_anime4kcpp_wrapper_Anime4KGPU_initGPUAnime4KGPU( JNIEnv *env, jclass clazz) { Anime4KCPP::Anime4KGPU::initGPU(); } JNIEXPORT void JNICALL Java_github_tianzerl_anime4kcpp_wrapper_Anime4KGPUCNN_initGPUAnime4KGPUCNN( JNIEnv *env, jclass clazz) { Anime4KCPP::Anime4KGPUCNN::initGPU(); } JNIEXPORT void JNICALL Java_github_tianzerl_anime4kcpp_wrapper_Anime4KGPU_releaseGPUAnime4KGPU( JNIEnv *env, jclass clazz) { Anime4KCPP::Anime4KGPU::releaseGPU(); } JNIEXPORT void JNICALL Java_github_tianzerl_anime4kcpp_wrapper_Anime4KGPUCNN_releaseGPUAnime4KGPUCNN( JNIEnv *env, jclass clazz) { Anime4KCPP::Anime4KGPUCNN::releaseGPU(); } JNIEXPORT jboolean JNICALL Java_github_tianzerl_anime4kcpp_wrapper_Anime4KGPU_isInitializedGPUAnime4KGPU( JNIEnv *env, jclass clazz) { return (jboolean)(Anime4KCPP::Anime4KGPU::isInitializedGPU()); } JNIEXPORT jboolean JNICALL Java_github_tianzerl_anime4kcpp_wrapper_Anime4KGPUCNN_isInitializedGPUAnime4KGPUCNN( JNIEnv *env, jclass clazz) { return (jboolean)(Anime4KCPP::Anime4KGPUCNN::isInitializedGPU()); } JNIEXPORT jstring JNICALL Java_github_tianzerl_anime4kcpp_wrapper_Anime4K_getCoreVersionAnime4K( JNIEnv *env, jclass clazz) { return env->NewStringUTF(ANIME4KCPP_CORE_VERSION); } }
[ "TianLin2112@outlook.com" ]
TianLin2112@outlook.com
9a700cc8416e0c81a7abe76b22fccc7f4a08180c
956c6420a7921b10802e78f394b7254a5408d49e
/src/nsPyramidProject/Stair.h
123bb83e5e08c6b0b3018e1c70a9121524af6f1a
[]
no_license
PierreAntoineGuillaume/PyramidProject
b9b8808de45bf832de8e5f34290811735f14faea
2b1e63ae91fa244d3e2ce398d9630422db54b3f5
refs/heads/master
2021-11-09T18:29:13.218238
2015-10-14T19:48:53
2015-10-14T19:48:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
333
h
// // Created by Pierre-Antoine on 17/07/2015. // #ifndef PYRAMIDPROJECT_STAIR_H #define PYRAMIDPROJECT_STAIR_H #include "../Utility/typedef.hpp" namespace nsPyramidProject { class Stair { private: byte_t floor; public: byte_t getFloor () const noexcept; }; } #endif //PYRAMIDPROJECT_STAIR_H
[ "pierreantoine.guillaume+github@gmail.com" ]
pierreantoine.guillaume+github@gmail.com
34463a0ef92e1cb4873b73177d96f6231171eb20
04b1803adb6653ecb7cb827c4f4aa616afacf629
/services/proxy_resolver/host_resolver_mojo.cc
d1a89b85cb153567f598c2f0df677d95d501b962
[ "BSD-3-Clause" ]
permissive
Samsung/Castanets
240d9338e097b75b3f669604315b06f7cf129d64
4896f732fc747dfdcfcbac3d442f2d2d42df264a
refs/heads/castanets_76_dev
2023-08-31T09:01:04.744346
2021-07-30T04:56:25
2021-08-11T05:45:21
125,484,161
58
49
BSD-3-Clause
2022-10-16T19:31:26
2018-03-16T08:07:37
null
UTF-8
C++
false
false
5,296
cc
// Copyright 2015 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 "services/proxy_resolver/host_resolver_mojo.h" #include <memory> #include <utility> #include <vector> #include "base/bind.h" #include "base/callback_helpers.h" #include "base/time/time.h" #include "mojo/public/cpp/bindings/binding.h" #include "net/base/address_family.h" #include "net/base/address_list.h" #include "net/base/completion_once_callback.h" #include "net/base/ip_address.h" #include "net/base/net_errors.h" namespace proxy_resolver { namespace { // Default TTL for successful host resolutions. constexpr auto kCacheEntryTTL = base::TimeDelta::FromSeconds(5); // Default TTL for unsuccessful host resolutions. constexpr auto kNegativeCacheEntryTTL = base::TimeDelta(); net::HostCache::Key CacheKeyForRequest( const std::string& hostname, net::ProxyResolveDnsOperation operation) { net::AddressFamily address_family = net::ADDRESS_FAMILY_UNSPECIFIED; if (operation == net::ProxyResolveDnsOperation::MY_IP_ADDRESS || operation == net::ProxyResolveDnsOperation::DNS_RESOLVE) { address_family = net::ADDRESS_FAMILY_IPV4; } return net::HostCache::Key(hostname, address_family, 0 /* host_resolver_flags */); } } // namespace class HostResolverMojo::RequestImpl : public ProxyHostResolver::Request, public mojom::HostResolverRequestClient { public: RequestImpl(const std::string& hostname, net::ProxyResolveDnsOperation operation, base::WeakPtr<net::HostCache> host_cache, Impl* impl) : hostname_(hostname), operation_(operation), binding_(this), host_cache_(std::move(host_cache)), impl_(impl) {} ~RequestImpl() override = default; // ProxyHostResolver::Request override int Start(net::CompletionOnceCallback callback) override { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); DVLOG(1) << "Resolve " << hostname_; int cached_result = ResolveFromCacheInternal(); if (cached_result != net::ERR_DNS_CACHE_MISS) { DVLOG(1) << "Resolved " << hostname_ << " from cache"; return cached_result; } callback_ = std::move(callback); mojom::HostResolverRequestClientPtr handle; binding_.Bind(mojo::MakeRequest(&handle)); binding_.set_connection_error_handler(base::BindOnce( &RequestImpl::OnConnectionError, base::Unretained(this))); impl_->ResolveDns(hostname_, operation_, std::move(handle)); return net::ERR_IO_PENDING; } const std::vector<net::IPAddress>& GetResults() const override { return results_; } // mojom::HostResolverRequestClient override void ReportResult(int32_t error, const std::vector<net::IPAddress>& result) override { DCHECK_CALLED_ON_VALID_THREAD(thread_checker_); if (error == net::OK) results_ = result; if (host_cache_) { base::TimeDelta ttl = error == net::OK ? kCacheEntryTTL : kNegativeCacheEntryTTL; net::HostCache::Entry entry( error, net::AddressList::CreateFromIPAddressList(result, ""), net::HostCache::Entry::SOURCE_UNKNOWN, ttl); host_cache_->Set(CacheKeyForRequest(hostname_, operation_), entry, base::TimeTicks::Now(), ttl); } if (binding_.is_bound()) binding_.Close(); std::move(callback_).Run(error); } private: int ResolveFromCacheInternal() { DCHECK(host_cache_); net::HostCache::Key key = CacheKeyForRequest(hostname_, operation_); const std::pair<const net::HostCache::Key, net::HostCache::Entry>* cache_result = host_cache_->Lookup(key, base::TimeTicks::Now()); if (!cache_result) return net::ERR_DNS_CACHE_MISS; results_ = AddressListToAddresses(cache_result->second.addresses().value()); return cache_result->second.error(); } void OnConnectionError() { ReportResult(net::ERR_FAILED, {} /* result */); } static std::vector<net::IPAddress> AddressListToAddresses( net::AddressList address_list) { std::vector<net::IPAddress> result; for (net::IPEndPoint endpoint : address_list.endpoints()) { result.push_back(endpoint.address()); } return result; } const std::string hostname_; const net::ProxyResolveDnsOperation operation_; mojo::Binding<mojom::HostResolverRequestClient> binding_; net::CompletionOnceCallback callback_; base::WeakPtr<net::HostCache> host_cache_; Impl* const impl_; std::vector<net::IPAddress> results_; THREAD_CHECKER(thread_checker_); }; HostResolverMojo::HostResolverMojo(Impl* impl) : impl_(impl), host_cache_(net::HostCache::CreateDefaultCache()), host_cache_weak_factory_(host_cache_.get()) {} HostResolverMojo::~HostResolverMojo() = default; std::unique_ptr<net::ProxyHostResolver::Request> HostResolverMojo::CreateRequest(const std::string& hostname, net::ProxyResolveDnsOperation operation) { DCHECK(thread_checker_.CalledOnValidThread()); return std::make_unique<RequestImpl>( hostname, operation, host_cache_weak_factory_.GetWeakPtr(), impl_); } } // namespace proxy_resolver
[ "sunny.nam@samsung.com" ]
sunny.nam@samsung.com
637c43a4c5e639c65a35ef57b58e05bc9a6eeebd
fab7008217edf2db4a3399b5f0204e85d8d3b1da
/solution1/.autopilot/db/Softmax.pp.0.cpp.ap-line.cpp
4c3cc77e97fc61ba21c588e6ca5368637ad96d02
[]
no_license
mlzxy/VCNN
22191854a964e45f494fe4246d76b1fe47a2b96b
e30d47d6beb8a02677c89c8766ee03a2c820ef56
refs/heads/master
2021-06-02T22:07:10.934306
2016-09-03T03:37:40
2016-09-03T03:37:40
58,327,478
0
1
null
null
null
null
UTF-8
C++
false
false
108,927
cpp
#pragma line 1 "VCNN/src/lib/layers/Softmax.cpp" #pragma line 1 "VCNN/src/lib/layers/Softmax.cpp" 1 #pragma line 1 "<built-in>" 1 #pragma line 1 "<built-in>" 3 #pragma line 155 "<built-in>" 3 #pragma line 1 "<command line>" 1 #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma line 1 "/opt/Xilinx/Vivado_HLS/2016.1/common/technology/autopilot/etc/autopilot_ssdm_op.h" 1 /* autopilot_ssdm_op.h*/ /* #- (c) Copyright 2011-2016 Xilinx, Inc. All rights reserved. #- #- This file contains confidential and proprietary information #- of Xilinx, Inc. and is protected under U.S. and #- international copyright and other intellectual property #- laws. #- #- DISCLAIMER #- This disclaimer is not a license and does not grant any #- rights to the materials distributed herewith. Except as #- otherwise provided in a valid license issued to you by #- Xilinx, and to the maximum extent permitted by applicable #- law: (1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND #- WITH ALL FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES #- AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING #- BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON- #- INFRINGEMENT, OR FITNESS FOR ANY PARTICULAR PURPOSE; and #- (2) Xilinx shall not be liable (whether in contract or tort, #- including negligence, or under any other theory of #- liability) for any loss or damage of any kind or nature #- related to, arising under or in connection with these #- materials, including for any direct, or any indirect, #- special, incidental, or consequential loss or damage #- (including loss of data, profits, goodwill, or any type of #- loss or damage suffered as a result of any action brought #- by a third party) even if such damage or loss was #- reasonably foreseeable or Xilinx had been advised of the #- possibility of the same. #- #- CRITICAL APPLICATIONS #- Xilinx products are not designed or intended to be fail- #- safe, or for use in any application requiring fail-safe #- performance, such as life-support or safety devices or #- systems, Class III medical devices, nuclear facilities, #- applications related to the deployment of airbags, or any #- other applications that could lead to death, personal #- injury, or severe property or environmental damage #- (individually and collectively, "Critical #- Applications"). Customer assumes the sole risk and #- liability of any use of Xilinx products in Critical #- Applications, subject only to applicable laws and #- regulations governing limitations on product liability. #- #- THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS #- PART OF THIS FILE AT ALL TIMES. #- ************************************************************************ #pragma empty_line * * $Id$ */ #pragma line 145 "/opt/Xilinx/Vivado_HLS/2016.1/common/technology/autopilot/etc/autopilot_ssdm_op.h" /*#define AP_SPEC_ATTR __attribute__ ((pure))*/ #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line extern "C" { #pragma empty_line /****** SSDM Intrinsics: OPERATIONS ***/ // Interface operations #pragma empty_line //typedef unsigned int __attribute__ ((bitwidth(1))) _uint1_; typedef bool _uint1_; #pragma empty_line void _ssdm_op_IfRead(...) __attribute__ ((nothrow)); void _ssdm_op_IfWrite(...) __attribute__ ((nothrow)); _uint1_ _ssdm_op_IfNbRead(...) __attribute__ ((nothrow)); _uint1_ _ssdm_op_IfNbWrite(...) __attribute__ ((nothrow)); _uint1_ _ssdm_op_IfCanRead(...) __attribute__ ((nothrow)); _uint1_ _ssdm_op_IfCanWrite(...) __attribute__ ((nothrow)); #pragma empty_line // Stream Intrinsics void _ssdm_StreamRead(...) __attribute__ ((nothrow)); void _ssdm_StreamWrite(...) __attribute__ ((nothrow)); _uint1_ _ssdm_StreamNbRead(...) __attribute__ ((nothrow)); _uint1_ _ssdm_StreamNbWrite(...) __attribute__ ((nothrow)); _uint1_ _ssdm_StreamCanRead(...) __attribute__ ((nothrow)); _uint1_ _ssdm_StreamCanWrite(...) __attribute__ ((nothrow)); unsigned _ssdm_StreamSize(...) __attribute__ ((nothrow)); #pragma empty_line // Misc void _ssdm_op_MemShiftRead(...) __attribute__ ((nothrow)); #pragma empty_line void _ssdm_op_Wait(...) __attribute__ ((nothrow)); void _ssdm_op_Poll(...) __attribute__ ((nothrow)); #pragma empty_line void _ssdm_op_Return(...) __attribute__ ((nothrow)); #pragma empty_line /* SSDM Intrinsics: SPECIFICATIONS */ void _ssdm_op_SpecSynModule(...) __attribute__ ((nothrow)); void _ssdm_op_SpecTopModule(...) __attribute__ ((nothrow)); void _ssdm_op_SpecProcessDecl(...) __attribute__ ((nothrow)); void _ssdm_op_SpecProcessDef(...) __attribute__ ((nothrow)); void _ssdm_op_SpecPort(...) __attribute__ ((nothrow)); void _ssdm_op_SpecConnection(...) __attribute__ ((nothrow)); void _ssdm_op_SpecChannel(...) __attribute__ ((nothrow)); void _ssdm_op_SpecSensitive(...) __attribute__ ((nothrow)); void _ssdm_op_SpecModuleInst(...) __attribute__ ((nothrow)); void _ssdm_op_SpecPortMap(...) __attribute__ ((nothrow)); #pragma empty_line void _ssdm_op_SpecReset(...) __attribute__ ((nothrow)); #pragma empty_line void _ssdm_op_SpecPlatform(...) __attribute__ ((nothrow)); void _ssdm_op_SpecClockDomain(...) __attribute__ ((nothrow)); void _ssdm_op_SpecPowerDomain(...) __attribute__ ((nothrow)); #pragma empty_line int _ssdm_op_SpecRegionBegin(...) __attribute__ ((nothrow)); int _ssdm_op_SpecRegionEnd(...) __attribute__ ((nothrow)); #pragma empty_line void _ssdm_op_SpecLoopName(...) __attribute__ ((nothrow)); #pragma empty_line void _ssdm_op_SpecLoopTripCount(...) __attribute__ ((nothrow)); #pragma empty_line int _ssdm_op_SpecStateBegin(...) __attribute__ ((nothrow)); int _ssdm_op_SpecStateEnd(...) __attribute__ ((nothrow)); #pragma empty_line void _ssdm_op_SpecInterface(...) __attribute__ ((nothrow)); #pragma empty_line void _ssdm_op_SpecPipeline(...) __attribute__ ((nothrow)); void _ssdm_op_SpecDataflowPipeline(...) __attribute__ ((nothrow)); #pragma empty_line #pragma empty_line void _ssdm_op_SpecLatency(...) __attribute__ ((nothrow)); void _ssdm_op_SpecParallel(...) __attribute__ ((nothrow)); void _ssdm_op_SpecProtocol(...) __attribute__ ((nothrow)); void _ssdm_op_SpecOccurrence(...) __attribute__ ((nothrow)); #pragma empty_line void _ssdm_op_SpecResource(...) __attribute__ ((nothrow)); void _ssdm_op_SpecResourceLimit(...) __attribute__ ((nothrow)); void _ssdm_op_SpecCHCore(...) __attribute__ ((nothrow)); void _ssdm_op_SpecFUCore(...) __attribute__ ((nothrow)); void _ssdm_op_SpecIFCore(...) __attribute__ ((nothrow)); void _ssdm_op_SpecIPCore(...) __attribute__ ((nothrow)); void _ssdm_op_SpecKeepValue(...) __attribute__ ((nothrow)); void _ssdm_op_SpecMemCore(...) __attribute__ ((nothrow)); #pragma empty_line void _ssdm_op_SpecExt(...) __attribute__ ((nothrow)); /*void* _ssdm_op_SpecProcess(...) SSDM_SPEC_ATTR; void* _ssdm_op_SpecEdge(...) SSDM_SPEC_ATTR; */ #pragma empty_line /* Presynthesis directive functions */ void _ssdm_SpecArrayDimSize(...) __attribute__ ((nothrow)); #pragma empty_line void _ssdm_RegionBegin(...) __attribute__ ((nothrow)); void _ssdm_RegionEnd(...) __attribute__ ((nothrow)); #pragma empty_line void _ssdm_Unroll(...) __attribute__ ((nothrow)); void _ssdm_UnrollRegion(...) __attribute__ ((nothrow)); #pragma empty_line void _ssdm_InlineAll(...) __attribute__ ((nothrow)); void _ssdm_InlineLoop(...) __attribute__ ((nothrow)); void _ssdm_Inline(...) __attribute__ ((nothrow)); void _ssdm_InlineSelf(...) __attribute__ ((nothrow)); void _ssdm_InlineRegion(...) __attribute__ ((nothrow)); #pragma empty_line void _ssdm_SpecArrayMap(...) __attribute__ ((nothrow)); void _ssdm_SpecArrayPartition(...) __attribute__ ((nothrow)); void _ssdm_SpecArrayReshape(...) __attribute__ ((nothrow)); #pragma empty_line void _ssdm_SpecStream(...) __attribute__ ((nothrow)); #pragma empty_line void _ssdm_SpecExpr(...) __attribute__ ((nothrow)); void _ssdm_SpecExprBalance(...) __attribute__ ((nothrow)); #pragma empty_line void _ssdm_SpecDependence(...) __attribute__ ((nothrow)); #pragma empty_line void _ssdm_SpecLoopMerge(...) __attribute__ ((nothrow)); void _ssdm_SpecLoopFlatten(...) __attribute__ ((nothrow)); void _ssdm_SpecLoopRewind(...) __attribute__ ((nothrow)); #pragma empty_line void _ssdm_SpecFuncInstantiation(...) __attribute__ ((nothrow)); void _ssdm_SpecFuncBuffer(...) __attribute__ ((nothrow)); void _ssdm_SpecFuncExtract(...) __attribute__ ((nothrow)); void _ssdm_SpecConstant(...) __attribute__ ((nothrow)); #pragma empty_line void _ssdm_DataPack(...) __attribute__ ((nothrow)); void _ssdm_SpecDataPack(...) __attribute__ ((nothrow)); #pragma empty_line void _ssdm_op_SpecBitsMap(...) __attribute__ ((nothrow)); void _ssdm_op_SpecLicense(...) __attribute__ ((nothrow)); #pragma empty_line void __xilinx_ip_top(...) __attribute__ ((nothrow)); #pragma empty_line #pragma empty_line } #pragma line 407 "/opt/Xilinx/Vivado_HLS/2016.1/common/technology/autopilot/etc/autopilot_ssdm_op.h" /*#define _ssdm_op_WaitUntil(X) while (!(X)) _ssdm_op_Wait(1); #define _ssdm_op_Delayed(X) X */ #pragma line 421 "/opt/Xilinx/Vivado_HLS/2016.1/common/technology/autopilot/etc/autopilot_ssdm_op.h" // XSIP watermark, do not delete 67d7842dbbe25473c3c32b93c0da8047785f30d78e8a024de1b57352245f9689 #pragma line 6 "<command line>" 2 #pragma line 1 "<built-in>" 2 #pragma line 1 "VCNN/src/lib/layers/Softmax.cpp" 2 #pragma line 1 "VCNN/src/lib/layers/layers.h" 1 #pragma empty_line #pragma empty_line #pragma empty_line #pragma line 1 "VCNN/src/lib/layers/../../custom/caffe_model_layer.h" 1 #pragma empty_line #pragma empty_line static int const nLayers = 9; static float const dataScale= 0.00390625; static int const nOutput = 10; typedef enum {CONVOLUTION,POOLING_AVG,POOLING_MAX,RELU,INNERPRODUCT,SOFTMAX,RETURN_CALLBACK} LayerType; #pragma empty_line typedef struct { int id; LayerType type; /* # Meta Data All meta data for every type of layer are put here, for easy initialization. HLS C don't allow dynamic memory operation. Hopefully the complier will optimize the unused variable for us.(It should be able to.) */ /* for convolutional layer the conv layer here won't take care about padding, since we gonna use pixel streaming, FPGA is best for streaming processing, fast and efficient*/ #pragma empty_line int conv_filter_channels; int conv_filter_size; int conv_filter_num; int conv_stride; int conv_pad; #pragma empty_line /*for pooling layer*/ int pl_kernel_size; int pl_stride; #pragma empty_line /*for inner product layer*/ int ip_channel_num; int ip_output_num; #pragma empty_line #pragma empty_line int input_channel_num; int input_feature_map_height; int input_feature_map_width; #pragma empty_line float* input_data; } Layer; #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line typedef struct { #pragma empty_line int id; //for convolutional layer float *conv_filter_weight; // 32->3->5x5 float *conv_bias; //1x32 #pragma empty_line /*for inner product layer*/ float *ip_weight; float *ip_bias; #pragma empty_line } LayerWeight; #pragma empty_line #pragma empty_line static int const nChannels = 1; static int const imgWidth = 28; static int const imgHeight = 28; static int const nLayerTypes = 7; extern float mean_image[1][28][28]; #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line extern LayerWeight layers_weight[9]; extern Layer layers[10]; #pragma line 5 "VCNN/src/lib/layers/layers.h" 2 #pragma empty_line using namespace std; #pragma empty_line #pragma empty_line #pragma empty_line typedef void (*Layer_f) (Layer current, LayerWeight cw, Layer next); #pragma empty_line //you must take layer weight as input parameter, because they //may in the external memory void Convolution(Layer current, LayerWeight cw, Layer next); void PoolingAvg(Layer current, LayerWeight cw, Layer next); void PoolingMax(Layer current, LayerWeight cw, Layer next); void Relu(Layer current, LayerWeight cw, Layer next); void InnerProduct(Layer current, LayerWeight cw, Layer next); void Softmax(Layer current, LayerWeight cw, Layer next); void ReturnCallback(Layer current, LayerWeight cw, Layer next); #pragma empty_line //you don't need mean image here, just substract them in the main // function static Layer_f layer_dict[nLayerTypes] = { Convolution, PoolingAvg, PoolingMax, Relu, InnerProduct, Softmax, ReturnCallback }; #pragma line 2 "VCNN/src/lib/layers/Softmax.cpp" 2 #pragma line 1 "VCNN/src/lib/layers/../util.h" 1 //#ifdef VCNN_UTIL_H //#define VCNN_UTIL_H #pragma line 12 "VCNN/src/lib/layers/../util.h" //#endif #pragma line 3 "VCNN/src/lib/layers/Softmax.cpp" 2 #pragma line 1 "/usr/include/math.h" 1 3 4 /* Declarations for math functions. Copyright (C) 1991-2016 Free Software Foundation, Inc. This file is part of the GNU C Library. #pragma empty_line The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. #pragma empty_line The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. #pragma empty_line You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ #pragma empty_line /* * ISO C99 Standard: 7.12 Mathematics <math.h> */ #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma line 1 "/usr/include/features.h" 1 3 4 /* Copyright (C) 1991-2016 Free Software Foundation, Inc. This file is part of the GNU C Library. #pragma empty_line The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. #pragma empty_line The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. #pragma empty_line You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* These are defined by the user (or the compiler) to specify the desired environment: #pragma empty_line __STRICT_ANSI__ ISO Standard C. _ISOC99_SOURCE Extensions to ISO C89 from ISO C99. _ISOC11_SOURCE Extensions to ISO C99 from ISO C11. _POSIX_SOURCE IEEE Std 1003.1. _POSIX_C_SOURCE If ==1, like _POSIX_SOURCE; if >=2 add IEEE Std 1003.2; if >=199309L, add IEEE Std 1003.1b-1993; if >=199506L, add IEEE Std 1003.1c-1995; if >=200112L, all of IEEE 1003.1-2004 if >=200809L, all of IEEE 1003.1-2008 _XOPEN_SOURCE Includes POSIX and XPG things. Set to 500 if Single Unix conformance is wanted, to 600 for the sixth revision, to 700 for the seventh revision. _XOPEN_SOURCE_EXTENDED XPG things and X/Open Unix extensions. _LARGEFILE_SOURCE Some more functions for correct standard I/O. _LARGEFILE64_SOURCE Additional functionality from LFS for large files. _FILE_OFFSET_BITS=N Select default filesystem interface. _ATFILE_SOURCE Additional *at interfaces. _GNU_SOURCE All of the above, plus GNU extensions. _DEFAULT_SOURCE The default set of features (taking precedence over __STRICT_ANSI__). _REENTRANT Select additionally reentrant object. _THREAD_SAFE Same as _REENTRANT, often used by other systems. _FORTIFY_SOURCE If set to numeric value > 0 additional security measures are defined, according to level. #pragma empty_line The `-ansi' switch to the GNU C compiler, and standards conformance options such as `-std=c99', define __STRICT_ANSI__. If none of these are defined, or if _DEFAULT_SOURCE is defined, the default is to have _POSIX_SOURCE set to one and _POSIX_C_SOURCE set to 200809L, as well as enabling miscellaneous functions from BSD and SVID. If more than one of these are defined, they accumulate. For example __STRICT_ANSI__, _POSIX_SOURCE and _POSIX_C_SOURCE together give you ISO C, 1003.1, and 1003.2, but nothing else. #pragma empty_line These are defined by this file and are used by the header files to decide what to declare or define: #pragma empty_line __USE_ISOC11 Define ISO C11 things. __USE_ISOC99 Define ISO C99 things. __USE_ISOC95 Define ISO C90 AMD1 (C95) things. __USE_POSIX Define IEEE Std 1003.1 things. __USE_POSIX2 Define IEEE Std 1003.2 things. __USE_POSIX199309 Define IEEE Std 1003.1, and .1b things. __USE_POSIX199506 Define IEEE Std 1003.1, .1b, .1c and .1i things. __USE_XOPEN Define XPG things. __USE_XOPEN_EXTENDED Define X/Open Unix things. __USE_UNIX98 Define Single Unix V2 things. __USE_XOPEN2K Define XPG6 things. __USE_XOPEN2KXSI Define XPG6 XSI things. __USE_XOPEN2K8 Define XPG7 things. __USE_XOPEN2K8XSI Define XPG7 XSI things. __USE_LARGEFILE Define correct standard I/O things. __USE_LARGEFILE64 Define LFS things with separate names. __USE_FILE_OFFSET64 Define 64bit interface as default. __USE_MISC Define things from 4.3BSD or System V Unix. __USE_ATFILE Define *at interfaces and AT_* constants for them. __USE_GNU Define GNU extensions. __USE_REENTRANT Define reentrant/thread-safe *_r functions. __USE_FORTIFY_LEVEL Additional security measures used, according to level. #pragma empty_line The macros `__GNU_LIBRARY__', `__GLIBC__', and `__GLIBC_MINOR__' are defined by this file unconditionally. `__GNU_LIBRARY__' is provided only for compatibility. All new code should use the other symbols to test for features. #pragma empty_line All macros listed above as possibly being defined by this file are explicitly undefined if they are not explicitly defined. Feature-test macros that are not defined by the user or compiler but are implied by the other feature-test macros defined (or by the lack of any definitions) are defined by the file. */ #pragma empty_line #pragma empty_line /* Undefine everything, so we get a clean slate. */ #pragma line 122 "/usr/include/features.h" 3 4 /* Suppress kernel-name space pollution unless user expressedly asks for it. */ #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Convenience macros to test the versions of glibc and gcc. Use them like this: #if __GNUC_PREREQ (2,8) ... code requiring gcc 2.8 or later ... #endif Note - they won't work for gcc1 or glibc1, since the _MINOR macros were not defined then. */ #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* _BSD_SOURCE and _SVID_SOURCE are deprecated aliases for _DEFAULT_SOURCE. If _DEFAULT_SOURCE is present we do not issue a warning; the expectation is that the source is being transitioned to use the new macro. */ #pragma line 156 "/usr/include/features.h" 3 4 /* If _GNU_SOURCE was defined by the user, turn on all the other features. */ #pragma line 180 "/usr/include/features.h" 3 4 /* If nothing (other than _GNU_SOURCE and _DEFAULT_SOURCE) is defined, define _DEFAULT_SOURCE. */ #pragma line 191 "/usr/include/features.h" 3 4 /* This is to enable the ISO C11 extension. */ #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* This is to enable the ISO C99 extension. */ #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* This is to enable the ISO C90 Amendment 1:1995 extension. */ #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* This is to enable compatibility for ISO C++11. #pragma empty_line So far g++ does not provide a macro. Check the temporary macro for now, too. */ #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* If none of the ANSI/POSIX macros are defined, or if _DEFAULT_SOURCE is defined, use POSIX.1-2008 (or another version depending on _XOPEN_SOURCE). */ #pragma line 343 "/usr/include/features.h" 3 4 /* Get definitions of __STDC_* predefined macros, if the compiler has not preincluded this header automatically. */ #pragma empty_line #pragma line 1 "/usr/include/stdc-predef.h" 1 3 4 /* Copyright (C) 1991-2016 Free Software Foundation, Inc. This file is part of the GNU C Library. #pragma empty_line The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. #pragma empty_line The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. #pragma empty_line You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* This header is separate from features.h so that the compiler can include it implicitly at the start of every compilation. It must not itself include <features.h> or any other header that includes <features.h> because the implicit include comes before any feature test macros that may be defined in a source file before it first explicitly includes a system header. GCC knows the name of this header in order to preinclude it. */ #pragma empty_line /* glibc's intent is to support the IEC 559 math functionality, real and complex. If the GCC (4.9 and later) predefined macros specifying compiler intent are available, use them to determine whether the overall intent is to support these features; otherwise, presume an older compiler has intent to support these features and define these macros by default. */ #pragma line 52 "/usr/include/stdc-predef.h" 3 4 /* wchar_t uses Unicode 8.0.0. Version 8.0 of the Unicode Standard is synchronized with ISO/IEC 10646:2014, plus Amendment 1 (published 2015-05-15). */ #pragma empty_line #pragma empty_line /* We do not support C11 <threads.h>. */ #pragma line 346 "/usr/include/features.h" 2 3 4 #pragma empty_line /* This macro indicates that the installed library is the GNU C Library. For historic reasons the value now is 6 and this will stay from now on. The use of this variable is deprecated. Use __GLIBC__ and __GLIBC_MINOR__ now (see below) when you want to test for a specific GNU C library version and use the values in <gnu/lib-names.h> to get the sonames of the shared libraries. */ #pragma empty_line #pragma empty_line #pragma empty_line /* Major and minor version number of the GNU C library package. Use these macros to test for features in specific releases. */ #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* This is here only because every header file already includes this one. */ #pragma empty_line #pragma empty_line #pragma empty_line #pragma line 1 "/usr/include/x86_64-linux-gnu/sys/cdefs.h" 1 3 4 /* Copyright (C) 1992-2016 Free Software Foundation, Inc. This file is part of the GNU C Library. #pragma empty_line The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. #pragma empty_line The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. #pragma empty_line You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* We are almost always included from features.h. */ #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* The GNU libc does not support any K&R compilers or the traditional mode of ISO C compilers anymore. Check for some of the combinations not anymore supported. */ #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Some user header file might have defined this before. */ #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* All functions, except those with callbacks or those that synchronize memory, are leaf functions. */ #pragma line 49 "/usr/include/x86_64-linux-gnu/sys/cdefs.h" 3 4 /* GCC can always grok prototypes. For C++ programs we add throw() to help it optimize the function calls. But this works only with gcc 2.8.x and egcs. For gcc 3.2 and up we even mark C functions as non-throwing using a function attribute since programs can use the -fexceptions options for C code as well. */ #pragma line 80 "/usr/include/x86_64-linux-gnu/sys/cdefs.h" 3 4 /* These two macros are not used in glibc anymore. They are kept here only because some other projects expect the macros to be defined. */ #pragma empty_line #pragma empty_line #pragma empty_line /* For these things, GCC behaves the ANSI way normally, and the non-ANSI way under -traditional. */ #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* This is not a typedef so `const __ptr_t' does the right thing. */ #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* C++ needs to know that types and declarations are C, not C++. */ #pragma line 106 "/usr/include/x86_64-linux-gnu/sys/cdefs.h" 3 4 /* The standard library needs the functions from the ISO C90 standard in the std namespace. At the same time we want to be safe for future changes and we include the ISO C99 code in the non-standard namespace __c99. The C++ wrapper header take case of adding the definitions to the global namespace. */ #pragma line 119 "/usr/include/x86_64-linux-gnu/sys/cdefs.h" 3 4 /* For compatibility we do not add the declarations into any namespace. They will end up in the global namespace which is what old code expects. */ #pragma line 131 "/usr/include/x86_64-linux-gnu/sys/cdefs.h" 3 4 /* Fortify support. */ #pragma line 147 "/usr/include/x86_64-linux-gnu/sys/cdefs.h" 3 4 /* Support for flexible arrays. */ #pragma empty_line /* GCC 2.97 supports C99 flexible array members. */ #pragma line 165 "/usr/include/x86_64-linux-gnu/sys/cdefs.h" 3 4 /* __asm__ ("xyz") is used throughout the headers to rename functions at the assembly language level. This is wrapped by the __REDIRECT macro, in order to support compilers that can do this some other way. When compilers don't support asm-names at all, we have to do preprocessor tricks instead (which don't have exactly the right semantics, but it's the best we can do). #pragma empty_line Example: int __REDIRECT(setpgrp, (__pid_t pid, __pid_t pgrp), setpgid); */ #pragma line 192 "/usr/include/x86_64-linux-gnu/sys/cdefs.h" 3 4 /* #elif __SOME_OTHER_COMPILER__ #pragma empty_line # define __REDIRECT(name, proto, alias) name proto; \ _Pragma("let " #name " = " #alias) */ #pragma empty_line #pragma empty_line /* GCC has various useful declarations that can be made with the `__attribute__' syntax. All of the ways we use this do fine if they are omitted for compilers that don't understand it. */ #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* At some point during the gcc 2.96 development the `malloc' attribute for functions was introduced. We don't want to use it unconditionally (although this would be possible) since it generates warnings. */ #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Tell the compiler which arguments to an allocation function indicate the size of the allocation. */ #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* At some point during the gcc 2.96 development the `pure' attribute for functions was introduced. We don't want to use it unconditionally (although this would be possible) since it generates warnings. */ #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* This declaration tells the compiler that the value is constant. */ #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* At some point during the gcc 3.1 development the `used' attribute for functions was introduced. We don't want to use it unconditionally (although this would be possible) since it generates warnings. */ #pragma line 252 "/usr/include/x86_64-linux-gnu/sys/cdefs.h" 3 4 /* gcc allows marking deprecated functions. */ #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* At some point during the gcc 2.8 development the `format_arg' attribute for functions was introduced. We don't want to use it unconditionally (although this would be possible) since it generates warnings. If several `format_arg' attributes are given for the same function, in gcc-3.0 and older, all but the last one are ignored. In newer gccs, all designated arguments are considered. */ #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* At some point during the gcc 2.97 development the `strfmon' format attribute for functions was introduced. We don't want to use it unconditionally (although this would be possible) since it generates warnings. */ #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* The nonull function attribute allows to mark pointer parameters which must not be NULL. */ #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* If fortification mode, we warn about unused results of certain function calls which can lead to problems. */ #pragma line 305 "/usr/include/x86_64-linux-gnu/sys/cdefs.h" 3 4 /* Forces a function to be always inlined. */ #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Associate error messages with the source location of the call site rather than with the source location inside the function. */ #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* GCC 4.3 and above with -std=c99 or -std=gnu99 implements ISO C99 inline semantics, unless -fgnu89-inline is used. Using __GNUC_STDC_INLINE__ or __GNUC_GNU_INLINE is not a good enough check for gcc because gcc versions older than 4.3 may define these macros and still not guarantee GNU inlining semantics. #pragma empty_line clang++ identifies itself as gcc-4.2, but has support for GNU inlining semantics, that can be checked fot by using the __GNUC_STDC_INLINE_ and __GNUC_GNU_INLINE__ macro definitions. */ #pragma line 346 "/usr/include/x86_64-linux-gnu/sys/cdefs.h" 3 4 /* GCC 4.3 and above allow passing all anonymous arguments of an __extern_always_inline function to some other vararg function. */ #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* It is possible to compile containing GCC extensions even if GCC is run in pedantic mode if the uses are carefully marked using the `__extension__' keyword. But this is not generally available before version 2.8. */ #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* __restrict is known in EGCS 1.2 and above. */ #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* ISO C99 also allows to declare arrays as non-overlapping. The syntax is array_name[restrict] GCC 3.1 supports this. */ #pragma line 410 "/usr/include/x86_64-linux-gnu/sys/cdefs.h" 3 4 #pragma line 1 "/usr/include/x86_64-linux-gnu/bits/wordsize.h" 1 3 4 /* Determine the wordsize from the preprocessor defines. */ #pragma line 11 "/usr/include/x86_64-linux-gnu/bits/wordsize.h" 3 4 /* Both x86-64 and x32 use the 64-bit system call interface. */ #pragma line 411 "/usr/include/x86_64-linux-gnu/sys/cdefs.h" 2 3 4 #pragma line 368 "/usr/include/features.h" 2 3 4 #pragma empty_line #pragma empty_line /* If we don't have __REDIRECT, prototypes will be missing if __USE_FILE_OFFSET64 but not __USE_LARGEFILE[64]. */ #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Decide whether we can define 'extern inline' functions in headers. */ #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* This is here only because every header file already includes this one. Get the definitions of all the appropriate `__stub_FUNCTION' symbols. <gnu/stubs.h> contains `#define __stub_FUNCTION' when FUNCTION is a stub that will always return failure (and set errno to ENOSYS). */ #pragma empty_line #pragma line 1 "/usr/include/x86_64-linux-gnu/gnu/stubs.h" 1 3 4 /* This file is automatically generated. This file selects the right generated file of `__stub_FUNCTION' macros based on the architecture being compiled for. */ #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma line 1 "/usr/include/x86_64-linux-gnu/gnu/stubs-64.h" 1 3 4 /* This file is automatically generated. It defines a symbol `__stub_FUNCTION' for each function in the C library which is a stub, meaning it will fail every time called, usually setting errno to ENOSYS. */ #pragma line 11 "/usr/include/x86_64-linux-gnu/gnu/stubs.h" 2 3 4 #pragma line 392 "/usr/include/features.h" 2 3 4 #pragma line 27 "/usr/include/math.h" 2 3 4 #pragma empty_line extern "C" { #pragma empty_line /* Get machine-dependent vector math functions declarations. */ #pragma empty_line #pragma line 1 "/usr/include/x86_64-linux-gnu/bits/math-vector.h" 1 3 4 /* Platform-specific SIMD declarations of math functions. Copyright (C) 2014-2016 Free Software Foundation, Inc. This file is part of the GNU C Library. #pragma empty_line The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. #pragma empty_line The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. #pragma empty_line You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Get default empty definitions for simd declarations. */ #pragma empty_line #pragma line 1 "/usr/include/x86_64-linux-gnu/bits/libm-simd-decl-stubs.h" 1 3 4 /* Empty definitions required for __MATHCALL_VEC unfolding in mathcalls.h. Copyright (C) 2014-2016 Free Software Foundation, Inc. This file is part of the GNU C Library. #pragma empty_line The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. #pragma empty_line The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. #pragma empty_line You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Needed definitions could be generated with: for func in $(grep __MATHCALL_VEC math/bits/mathcalls.h |\ sed -r "s|__MATHCALL_VEC.?\(||; s|,.*||"); do echo "#define __DECL_SIMD_${func}"; echo "#define __DECL_SIMD_${func}f"; echo "#define __DECL_SIMD_${func}l"; done */ #pragma line 26 "/usr/include/x86_64-linux-gnu/bits/math-vector.h" 2 3 4 #pragma line 32 "/usr/include/math.h" 2 3 4 #pragma empty_line /* Get machine-dependent HUGE_VAL value (returned on overflow). On all IEEE754 machines, this is +Infinity. */ #pragma empty_line #pragma line 1 "/usr/include/x86_64-linux-gnu/bits/huge_val.h" 1 3 4 /* `HUGE_VAL' constant for IEEE 754 machines (where it is infinity). Used by <stdlib.h> and <math.h> functions for overflow. Copyright (C) 1992-2016 Free Software Foundation, Inc. This file is part of the GNU C Library. #pragma empty_line The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. #pragma empty_line The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. #pragma empty_line You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* IEEE positive infinity (-HUGE_VAL is negative infinity). */ #pragma line 36 "/usr/include/math.h" 2 3 4 #pragma empty_line #pragma line 1 "/usr/include/x86_64-linux-gnu/bits/huge_valf.h" 1 3 4 /* `HUGE_VALF' constant for IEEE 754 machines (where it is infinity). Used by <stdlib.h> and <math.h> functions for overflow. Copyright (C) 1992-2016 Free Software Foundation, Inc. This file is part of the GNU C Library. #pragma empty_line The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. #pragma empty_line The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. #pragma empty_line You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* IEEE positive infinity (-HUGE_VAL is negative infinity). */ #pragma line 38 "/usr/include/math.h" 2 3 4 #pragma line 1 "/usr/include/x86_64-linux-gnu/bits/huge_vall.h" 1 3 4 /* `HUGE_VALL' constant for ix86 (where it is infinity). Used by <stdlib.h> and <math.h> functions for overflow. Copyright (C) 1992-2016 Free Software Foundation, Inc. This file is part of the GNU C Library. #pragma empty_line The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. #pragma empty_line The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. #pragma empty_line You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ #pragma line 39 "/usr/include/math.h" 2 3 4 #pragma empty_line /* Get machine-dependent INFINITY value. */ #pragma empty_line #pragma line 1 "/usr/include/x86_64-linux-gnu/bits/inf.h" 1 3 4 /* `INFINITY' constant for IEEE 754 machines. Copyright (C) 2004-2016 Free Software Foundation, Inc. This file is part of the GNU C Library. #pragma empty_line The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. #pragma empty_line The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. #pragma empty_line You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* IEEE positive infinity. */ #pragma line 42 "/usr/include/math.h" 2 3 4 #pragma empty_line /* Get machine-dependent NAN value (returned for some domain errors). */ #pragma empty_line #pragma line 1 "/usr/include/x86_64-linux-gnu/bits/nan.h" 1 3 4 /* `NAN' constant for IEEE 754 machines. Copyright (C) 1992-2016 Free Software Foundation, Inc. This file is part of the GNU C Library. #pragma empty_line The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. #pragma empty_line The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. #pragma empty_line You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* IEEE Not A Number. */ #pragma line 45 "/usr/include/math.h" 2 3 4 #pragma empty_line #pragma empty_line /* Get general and ISO C99 specific information. */ #pragma empty_line #pragma line 1 "/usr/include/x86_64-linux-gnu/bits/mathdef.h" 1 3 4 /* Copyright (C) 2001-2016 Free Software Foundation, Inc. This file is part of the GNU C Library. #pragma empty_line The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. #pragma empty_line The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. #pragma empty_line You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ #pragma line 26 "/usr/include/x86_64-linux-gnu/bits/mathdef.h" 3 4 /* The x86-64 architecture computes values with the precission of the used type. Similarly for -m32 -mfpmath=sse. */ typedef float float_t; /* `float' expressions are evaluated as `float'. */ typedef double double_t; /* `double' expressions are evaluated as `double'. */ #pragma line 41 "/usr/include/x86_64-linux-gnu/bits/mathdef.h" 3 4 /* The values returned by `ilogb' for 0 and NaN respectively. */ #pragma empty_line #pragma empty_line #pragma empty_line /* The GCC 4.6 compiler will define __FP_FAST_FMA{,F,L} if the fma{,f,l} builtins are supported. */ #pragma line 49 "/usr/include/math.h" 2 3 4 #pragma empty_line /* The file <bits/mathcalls.h> contains the prototypes for all the actual math functions. These macros are used for those prototypes, so we can easily declare each function as both `name' and `__name', and can declare the float versions `namef' and `__namef'. */ #pragma line 83 "/usr/include/math.h" 3 4 #pragma line 1 "/usr/include/x86_64-linux-gnu/bits/mathcalls.h" 1 3 4 /* Prototype declarations for math functions; helper file for <math.h>. Copyright (C) 1996-2016 Free Software Foundation, Inc. This file is part of the GNU C Library. #pragma empty_line The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. #pragma empty_line The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. #pragma empty_line You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ #pragma empty_line /* NOTE: Because of the special way this file is used by <math.h>, this file must NOT be protected from multiple inclusion as header files usually are. #pragma empty_line This file provides prototype declarations for the math functions. Most functions are declared using the macro: #pragma empty_line __MATHCALL (NAME,[_r], (ARGS...)); #pragma empty_line This means there is a function `NAME' returning `double' and a function `NAMEf' returning `float'. Each place `_Mdouble_' appears in the prototype, that is actually `double' in the prototype for `NAME' and `float' in the prototype for `NAMEf'. Reentrant variant functions are called `NAME_r' and `NAMEf_r'. #pragma empty_line Functions returning other types like `int' are declared using the macro: #pragma empty_line __MATHDECL (TYPE, NAME,[_r], (ARGS...)); #pragma empty_line This is just like __MATHCALL but for a function returning `TYPE' instead of `_Mdouble_'. In all of these cases, there is still both a `NAME' and a `NAMEf' that takes `float' arguments. #pragma empty_line Note that there must be no whitespace before the argument passed for NAME, to make token pasting work with -traditional. */ #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Trigonometric functions. */ #pragma empty_line #pragma empty_line /* Arc cosine of X. */ extern double acos (double __x) throw (); extern double __acos (double __x) throw (); /* Arc sine of X. */ extern double asin (double __x) throw (); extern double __asin (double __x) throw (); /* Arc tangent of X. */ extern double atan (double __x) throw (); extern double __atan (double __x) throw (); /* Arc tangent of Y/X. */ extern double atan2 (double __y, double __x) throw (); extern double __atan2 (double __y, double __x) throw (); #pragma empty_line /* Cosine of X. */ extern double cos (double __x) throw (); extern double __cos (double __x) throw (); /* Sine of X. */ extern double sin (double __x) throw (); extern double __sin (double __x) throw (); /* Tangent of X. */ extern double tan (double __x) throw (); extern double __tan (double __x) throw (); #pragma empty_line /* Hyperbolic functions. */ #pragma empty_line /* Hyperbolic cosine of X. */ extern double cosh (double __x) throw (); extern double __cosh (double __x) throw (); /* Hyperbolic sine of X. */ extern double sinh (double __x) throw (); extern double __sinh (double __x) throw (); /* Hyperbolic tangent of X. */ extern double tanh (double __x) throw (); extern double __tanh (double __x) throw (); #pragma empty_line #pragma empty_line #pragma empty_line /* Cosine and sine of X. */ extern void sincos (double __x, double *__sinx, double *__cosx) throw (); extern void __sincos (double __x, double *__sinx, double *__cosx) throw (); #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Hyperbolic arc cosine of X. */ extern double acosh (double __x) throw (); extern double __acosh (double __x) throw (); /* Hyperbolic arc sine of X. */ extern double asinh (double __x) throw (); extern double __asinh (double __x) throw (); /* Hyperbolic arc tangent of X. */ extern double atanh (double __x) throw (); extern double __atanh (double __x) throw (); #pragma empty_line #pragma empty_line #pragma empty_line /* Exponential and logarithmic functions. */ #pragma empty_line #pragma empty_line /* Exponential function of X. */ extern double exp (double __x) throw (); extern double __exp (double __x) throw (); #pragma empty_line /* Break VALUE into a normalized fraction and an integral power of 2. */ extern double frexp (double __x, int *__exponent) throw (); extern double __frexp (double __x, int *__exponent) throw (); #pragma empty_line /* X times (two to the EXP power). */ extern double ldexp (double __x, int __exponent) throw (); extern double __ldexp (double __x, int __exponent) throw (); #pragma empty_line /* Natural logarithm of X. */ extern double log (double __x) throw (); extern double __log (double __x) throw (); #pragma empty_line /* Base-ten logarithm of X. */ extern double log10 (double __x) throw (); extern double __log10 (double __x) throw (); #pragma empty_line /* Break VALUE into integral and fractional parts. */ extern double modf (double __x, double *__iptr) throw (); extern double __modf (double __x, double *__iptr) throw () __attribute__ ((__nonnull__ (2))); #pragma empty_line #pragma empty_line #pragma empty_line /* A function missing in all standards: compute exponent to base ten. */ extern double exp10 (double __x) throw (); extern double __exp10 (double __x) throw (); /* Another name occasionally used. */ extern double pow10 (double __x) throw (); extern double __pow10 (double __x) throw (); #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Return exp(X) - 1. */ extern double expm1 (double __x) throw (); extern double __expm1 (double __x) throw (); #pragma empty_line /* Return log(1 + X). */ extern double log1p (double __x) throw (); extern double __log1p (double __x) throw (); #pragma empty_line /* Return the base 2 signed integral exponent of X. */ extern double logb (double __x) throw (); extern double __logb (double __x) throw (); #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Compute base-2 exponential of X. */ extern double exp2 (double __x) throw (); extern double __exp2 (double __x) throw (); #pragma empty_line /* Compute base-2 logarithm of X. */ extern double log2 (double __x) throw (); extern double __log2 (double __x) throw (); #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Power functions. */ #pragma empty_line #pragma empty_line /* Return X to the Y power. */ extern double pow (double __x, double __y) throw (); extern double __pow (double __x, double __y) throw (); #pragma empty_line /* Return the square root of X. */ extern double sqrt (double __x) throw (); extern double __sqrt (double __x) throw (); #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Return `sqrt(X*X + Y*Y)'. */ extern double hypot (double __x, double __y) throw (); extern double __hypot (double __x, double __y) throw (); #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Return the cube root of X. */ extern double cbrt (double __x) throw (); extern double __cbrt (double __x) throw (); #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Nearest integer, absolute value, and remainder functions. */ #pragma empty_line #pragma empty_line /* Smallest integral value not less than X. */ extern double ceil (double __x) throw () __attribute__ ((__const__)); extern double __ceil (double __x) throw () __attribute__ ((__const__)); #pragma empty_line /* Absolute value of X. */ extern double fabs (double __x) throw () __attribute__ ((__const__)); extern double __fabs (double __x) throw () __attribute__ ((__const__)); #pragma empty_line /* Largest integer not greater than X. */ extern double floor (double __x) throw () __attribute__ ((__const__)); extern double __floor (double __x) throw () __attribute__ ((__const__)); #pragma empty_line /* Floating-point modulo remainder of X/Y. */ extern double fmod (double __x, double __y) throw (); extern double __fmod (double __x, double __y) throw (); #pragma empty_line #pragma empty_line /* Return 0 if VALUE is finite or NaN, +1 if it is +Infinity, -1 if it is -Infinity. */ extern int __isinf (double __value) throw () __attribute__ ((__const__)); #pragma empty_line /* Return nonzero if VALUE is finite and not NaN. */ extern int __finite (double __value) throw () __attribute__ ((__const__)); #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Return 0 if VALUE is finite or NaN, +1 if it is +Infinity, -1 if it is -Infinity. */ extern int isinf (double __value) throw () __attribute__ ((__const__)); #pragma empty_line #pragma empty_line /* Return nonzero if VALUE is finite and not NaN. */ extern int finite (double __value) throw () __attribute__ ((__const__)); #pragma empty_line /* Return the remainder of X/Y. */ extern double drem (double __x, double __y) throw (); extern double __drem (double __x, double __y) throw (); #pragma empty_line #pragma empty_line /* Return the fractional part of X after dividing out `ilogb (X)'. */ extern double significand (double __x) throw (); extern double __significand (double __x) throw (); #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Return X with its signed changed to Y's. */ extern double copysign (double __x, double __y) throw () __attribute__ ((__const__)); extern double __copysign (double __x, double __y) throw () __attribute__ ((__const__)); #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Return representation of qNaN for double type. */ extern double nan (const char *__tagb) throw () __attribute__ ((__const__)); extern double __nan (const char *__tagb) throw () __attribute__ ((__const__)); #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Return nonzero if VALUE is not a number. */ extern int __isnan (double __value) throw () __attribute__ ((__const__)); #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Return nonzero if VALUE is not a number. */ extern int isnan (double __value) throw () __attribute__ ((__const__)); #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Bessel functions. */ extern double j0 (double) throw (); extern double __j0 (double) throw (); extern double j1 (double) throw (); extern double __j1 (double) throw (); extern double jn (int, double) throw (); extern double __jn (int, double) throw (); extern double y0 (double) throw (); extern double __y0 (double) throw (); extern double y1 (double) throw (); extern double __y1 (double) throw (); extern double yn (int, double) throw (); extern double __yn (int, double) throw (); #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Error and gamma functions. */ extern double erf (double) throw (); extern double __erf (double) throw (); extern double erfc (double) throw (); extern double __erfc (double) throw (); extern double lgamma (double) throw (); extern double __lgamma (double) throw (); #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* True gamma function. */ extern double tgamma (double) throw (); extern double __tgamma (double) throw (); #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Obsolete alias for `lgamma'. */ extern double gamma (double) throw (); extern double __gamma (double) throw (); #pragma empty_line #pragma empty_line #pragma empty_line /* Reentrant version of lgamma. This function uses the global variable `signgam'. The reentrant version instead takes a pointer and stores the value through it. */ extern double lgamma_r (double, int *__signgamp) throw (); extern double __lgamma_r (double, int *__signgamp) throw (); #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Return the integer nearest X in the direction of the prevailing rounding mode. */ extern double rint (double __x) throw (); extern double __rint (double __x) throw (); #pragma empty_line /* Return X + epsilon if X < Y, X - epsilon if X > Y. */ extern double nextafter (double __x, double __y) throw () __attribute__ ((__const__)); extern double __nextafter (double __x, double __y) throw () __attribute__ ((__const__)); #pragma empty_line extern double nexttoward (double __x, long double __y) throw () __attribute__ ((__const__)); extern double __nexttoward (double __x, long double __y) throw () __attribute__ ((__const__)); #pragma empty_line #pragma empty_line /* Return the remainder of integer divison X / Y with infinite precision. */ extern double remainder (double __x, double __y) throw (); extern double __remainder (double __x, double __y) throw (); #pragma empty_line #pragma empty_line /* Return X times (2 to the Nth power). */ extern double scalbn (double __x, int __n) throw (); extern double __scalbn (double __x, int __n) throw (); #pragma empty_line #pragma empty_line /* Return the binary exponent of X, which must be nonzero. */ extern int ilogb (double __x) throw (); extern int __ilogb (double __x) throw (); #pragma empty_line #pragma empty_line #pragma empty_line /* Return X times (2 to the Nth power). */ extern double scalbln (double __x, long int __n) throw (); extern double __scalbln (double __x, long int __n) throw (); #pragma empty_line /* Round X to integral value in floating-point format using current rounding direction, but do not raise inexact exception. */ extern double nearbyint (double __x) throw (); extern double __nearbyint (double __x) throw (); #pragma empty_line /* Round X to nearest integral value, rounding halfway cases away from zero. */ extern double round (double __x) throw () __attribute__ ((__const__)); extern double __round (double __x) throw () __attribute__ ((__const__)); #pragma empty_line /* Round X to the integral value in floating-point format nearest but not larger in magnitude. */ extern double trunc (double __x) throw () __attribute__ ((__const__)); extern double __trunc (double __x) throw () __attribute__ ((__const__)); #pragma empty_line /* Compute remainder of X and Y and put in *QUO a value with sign of x/y and magnitude congruent `mod 2^n' to the magnitude of the integral quotient x/y, with n >= 3. */ extern double remquo (double __x, double __y, int *__quo) throw (); extern double __remquo (double __x, double __y, int *__quo) throw (); #pragma empty_line #pragma empty_line /* Conversion functions. */ #pragma empty_line /* Round X to nearest integral value according to current rounding direction. */ extern long int lrint (double __x) throw (); extern long int __lrint (double __x) throw (); __extension__ extern long long int llrint (double __x) throw (); extern long long int __llrint (double __x) throw (); #pragma empty_line /* Round X to nearest integral value, rounding halfway cases away from zero. */ extern long int lround (double __x) throw (); extern long int __lround (double __x) throw (); __extension__ extern long long int llround (double __x) throw (); extern long long int __llround (double __x) throw (); #pragma empty_line #pragma empty_line /* Return positive difference between X and Y. */ extern double fdim (double __x, double __y) throw (); extern double __fdim (double __x, double __y) throw (); #pragma empty_line /* Return maximum numeric value from X and Y. */ extern double fmax (double __x, double __y) throw () __attribute__ ((__const__)); extern double __fmax (double __x, double __y) throw () __attribute__ ((__const__)); #pragma empty_line /* Return minimum numeric value from X and Y. */ extern double fmin (double __x, double __y) throw () __attribute__ ((__const__)); extern double __fmin (double __x, double __y) throw () __attribute__ ((__const__)); #pragma empty_line #pragma empty_line /* Classify given number. */ extern int __fpclassify (double __value) throw () __attribute__ ((__const__)); #pragma empty_line /* Test for negative number. */ extern int __signbit (double __value) throw () __attribute__ ((__const__)); #pragma empty_line #pragma empty_line /* Multiply-add function computed as a ternary operation. */ extern double fma (double __x, double __y, double __z) throw (); extern double __fma (double __x, double __y, double __z) throw (); #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Test for signaling NaN. */ extern int __issignaling (double __value) throw () __attribute__ ((__const__)); #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Return X times (2 to the Nth power). */ extern double scalb (double __x, double __n) throw (); extern double __scalb (double __x, double __n) throw (); #pragma line 84 "/usr/include/math.h" 2 3 4 #pragma line 93 "/usr/include/math.h" 3 4 /* Include the file of declarations again, this time using `float' instead of `double' and appending f to each function name. */ #pragma line 104 "/usr/include/math.h" 3 4 #pragma line 1 "/usr/include/x86_64-linux-gnu/bits/mathcalls.h" 1 3 4 /* Prototype declarations for math functions; helper file for <math.h>. Copyright (C) 1996-2016 Free Software Foundation, Inc. This file is part of the GNU C Library. #pragma empty_line The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. #pragma empty_line The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. #pragma empty_line You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ #pragma empty_line /* NOTE: Because of the special way this file is used by <math.h>, this file must NOT be protected from multiple inclusion as header files usually are. #pragma empty_line This file provides prototype declarations for the math functions. Most functions are declared using the macro: #pragma empty_line __MATHCALL (NAME,[_r], (ARGS...)); #pragma empty_line This means there is a function `NAME' returning `double' and a function `NAMEf' returning `float'. Each place `_Mdouble_' appears in the prototype, that is actually `double' in the prototype for `NAME' and `float' in the prototype for `NAMEf'. Reentrant variant functions are called `NAME_r' and `NAMEf_r'. #pragma empty_line Functions returning other types like `int' are declared using the macro: #pragma empty_line __MATHDECL (TYPE, NAME,[_r], (ARGS...)); #pragma empty_line This is just like __MATHCALL but for a function returning `TYPE' instead of `_Mdouble_'. In all of these cases, there is still both a `NAME' and a `NAMEf' that takes `float' arguments. #pragma empty_line Note that there must be no whitespace before the argument passed for NAME, to make token pasting work with -traditional. */ #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Trigonometric functions. */ #pragma empty_line #pragma empty_line /* Arc cosine of X. */ extern float acosf (float __x) throw (); extern float __acosf (float __x) throw (); /* Arc sine of X. */ extern float asinf (float __x) throw (); extern float __asinf (float __x) throw (); /* Arc tangent of X. */ extern float atanf (float __x) throw (); extern float __atanf (float __x) throw (); /* Arc tangent of Y/X. */ extern float atan2f (float __y, float __x) throw (); extern float __atan2f (float __y, float __x) throw (); #pragma empty_line /* Cosine of X. */ extern float cosf (float __x) throw (); extern float __cosf (float __x) throw (); /* Sine of X. */ extern float sinf (float __x) throw (); extern float __sinf (float __x) throw (); /* Tangent of X. */ extern float tanf (float __x) throw (); extern float __tanf (float __x) throw (); #pragma empty_line /* Hyperbolic functions. */ #pragma empty_line /* Hyperbolic cosine of X. */ extern float coshf (float __x) throw (); extern float __coshf (float __x) throw (); /* Hyperbolic sine of X. */ extern float sinhf (float __x) throw (); extern float __sinhf (float __x) throw (); /* Hyperbolic tangent of X. */ extern float tanhf (float __x) throw (); extern float __tanhf (float __x) throw (); #pragma empty_line #pragma empty_line #pragma empty_line /* Cosine and sine of X. */ extern void sincosf (float __x, float *__sinx, float *__cosx) throw (); extern void __sincosf (float __x, float *__sinx, float *__cosx) throw (); #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Hyperbolic arc cosine of X. */ extern float acoshf (float __x) throw (); extern float __acoshf (float __x) throw (); /* Hyperbolic arc sine of X. */ extern float asinhf (float __x) throw (); extern float __asinhf (float __x) throw (); /* Hyperbolic arc tangent of X. */ extern float atanhf (float __x) throw (); extern float __atanhf (float __x) throw (); #pragma empty_line #pragma empty_line #pragma empty_line /* Exponential and logarithmic functions. */ #pragma empty_line #pragma empty_line /* Exponential function of X. */ extern float expf (float __x) throw (); extern float __expf (float __x) throw (); #pragma empty_line /* Break VALUE into a normalized fraction and an integral power of 2. */ extern float frexpf (float __x, int *__exponent) throw (); extern float __frexpf (float __x, int *__exponent) throw (); #pragma empty_line /* X times (two to the EXP power). */ extern float ldexpf (float __x, int __exponent) throw (); extern float __ldexpf (float __x, int __exponent) throw (); #pragma empty_line /* Natural logarithm of X. */ extern float logf (float __x) throw (); extern float __logf (float __x) throw (); #pragma empty_line /* Base-ten logarithm of X. */ extern float log10f (float __x) throw (); extern float __log10f (float __x) throw (); #pragma empty_line /* Break VALUE into integral and fractional parts. */ extern float modff (float __x, float *__iptr) throw (); extern float __modff (float __x, float *__iptr) throw () __attribute__ ((__nonnull__ (2))); #pragma empty_line #pragma empty_line #pragma empty_line /* A function missing in all standards: compute exponent to base ten. */ extern float exp10f (float __x) throw (); extern float __exp10f (float __x) throw (); /* Another name occasionally used. */ extern float pow10f (float __x) throw (); extern float __pow10f (float __x) throw (); #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Return exp(X) - 1. */ extern float expm1f (float __x) throw (); extern float __expm1f (float __x) throw (); #pragma empty_line /* Return log(1 + X). */ extern float log1pf (float __x) throw (); extern float __log1pf (float __x) throw (); #pragma empty_line /* Return the base 2 signed integral exponent of X. */ extern float logbf (float __x) throw (); extern float __logbf (float __x) throw (); #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Compute base-2 exponential of X. */ extern float exp2f (float __x) throw (); extern float __exp2f (float __x) throw (); #pragma empty_line /* Compute base-2 logarithm of X. */ extern float log2f (float __x) throw (); extern float __log2f (float __x) throw (); #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Power functions. */ #pragma empty_line #pragma empty_line /* Return X to the Y power. */ extern float powf (float __x, float __y) throw (); extern float __powf (float __x, float __y) throw (); #pragma empty_line /* Return the square root of X. */ extern float sqrtf (float __x) throw (); extern float __sqrtf (float __x) throw (); #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Return `sqrt(X*X + Y*Y)'. */ extern float hypotf (float __x, float __y) throw (); extern float __hypotf (float __x, float __y) throw (); #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Return the cube root of X. */ extern float cbrtf (float __x) throw (); extern float __cbrtf (float __x) throw (); #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Nearest integer, absolute value, and remainder functions. */ #pragma empty_line #pragma empty_line /* Smallest integral value not less than X. */ extern float ceilf (float __x) throw () __attribute__ ((__const__)); extern float __ceilf (float __x) throw () __attribute__ ((__const__)); #pragma empty_line /* Absolute value of X. */ extern float fabsf (float __x) throw () __attribute__ ((__const__)); extern float __fabsf (float __x) throw () __attribute__ ((__const__)); #pragma empty_line /* Largest integer not greater than X. */ extern float floorf (float __x) throw () __attribute__ ((__const__)); extern float __floorf (float __x) throw () __attribute__ ((__const__)); #pragma empty_line /* Floating-point modulo remainder of X/Y. */ extern float fmodf (float __x, float __y) throw (); extern float __fmodf (float __x, float __y) throw (); #pragma empty_line #pragma empty_line /* Return 0 if VALUE is finite or NaN, +1 if it is +Infinity, -1 if it is -Infinity. */ extern int __isinff (float __value) throw () __attribute__ ((__const__)); #pragma empty_line /* Return nonzero if VALUE is finite and not NaN. */ extern int __finitef (float __value) throw () __attribute__ ((__const__)); #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Return 0 if VALUE is finite or NaN, +1 if it is +Infinity, -1 if it is -Infinity. */ extern int isinff (float __value) throw () __attribute__ ((__const__)); #pragma empty_line #pragma empty_line /* Return nonzero if VALUE is finite and not NaN. */ extern int finitef (float __value) throw () __attribute__ ((__const__)); #pragma empty_line /* Return the remainder of X/Y. */ extern float dremf (float __x, float __y) throw (); extern float __dremf (float __x, float __y) throw (); #pragma empty_line #pragma empty_line /* Return the fractional part of X after dividing out `ilogb (X)'. */ extern float significandf (float __x) throw (); extern float __significandf (float __x) throw (); #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Return X with its signed changed to Y's. */ extern float copysignf (float __x, float __y) throw () __attribute__ ((__const__)); extern float __copysignf (float __x, float __y) throw () __attribute__ ((__const__)); #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Return representation of qNaN for double type. */ extern float nanf (const char *__tagb) throw () __attribute__ ((__const__)); extern float __nanf (const char *__tagb) throw () __attribute__ ((__const__)); #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Return nonzero if VALUE is not a number. */ extern int __isnanf (float __value) throw () __attribute__ ((__const__)); #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Return nonzero if VALUE is not a number. */ extern int isnanf (float __value) throw () __attribute__ ((__const__)); #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Bessel functions. */ extern float j0f (float) throw (); extern float __j0f (float) throw (); extern float j1f (float) throw (); extern float __j1f (float) throw (); extern float jnf (int, float) throw (); extern float __jnf (int, float) throw (); extern float y0f (float) throw (); extern float __y0f (float) throw (); extern float y1f (float) throw (); extern float __y1f (float) throw (); extern float ynf (int, float) throw (); extern float __ynf (int, float) throw (); #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Error and gamma functions. */ extern float erff (float) throw (); extern float __erff (float) throw (); extern float erfcf (float) throw (); extern float __erfcf (float) throw (); extern float lgammaf (float) throw (); extern float __lgammaf (float) throw (); #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* True gamma function. */ extern float tgammaf (float) throw (); extern float __tgammaf (float) throw (); #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Obsolete alias for `lgamma'. */ extern float gammaf (float) throw (); extern float __gammaf (float) throw (); #pragma empty_line #pragma empty_line #pragma empty_line /* Reentrant version of lgamma. This function uses the global variable `signgam'. The reentrant version instead takes a pointer and stores the value through it. */ extern float lgammaf_r (float, int *__signgamp) throw (); extern float __lgammaf_r (float, int *__signgamp) throw (); #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Return the integer nearest X in the direction of the prevailing rounding mode. */ extern float rintf (float __x) throw (); extern float __rintf (float __x) throw (); #pragma empty_line /* Return X + epsilon if X < Y, X - epsilon if X > Y. */ extern float nextafterf (float __x, float __y) throw () __attribute__ ((__const__)); extern float __nextafterf (float __x, float __y) throw () __attribute__ ((__const__)); #pragma empty_line extern float nexttowardf (float __x, long double __y) throw () __attribute__ ((__const__)); extern float __nexttowardf (float __x, long double __y) throw () __attribute__ ((__const__)); #pragma empty_line #pragma empty_line /* Return the remainder of integer divison X / Y with infinite precision. */ extern float remainderf (float __x, float __y) throw (); extern float __remainderf (float __x, float __y) throw (); #pragma empty_line #pragma empty_line /* Return X times (2 to the Nth power). */ extern float scalbnf (float __x, int __n) throw (); extern float __scalbnf (float __x, int __n) throw (); #pragma empty_line #pragma empty_line /* Return the binary exponent of X, which must be nonzero. */ extern int ilogbf (float __x) throw (); extern int __ilogbf (float __x) throw (); #pragma empty_line #pragma empty_line #pragma empty_line /* Return X times (2 to the Nth power). */ extern float scalblnf (float __x, long int __n) throw (); extern float __scalblnf (float __x, long int __n) throw (); #pragma empty_line /* Round X to integral value in floating-point format using current rounding direction, but do not raise inexact exception. */ extern float nearbyintf (float __x) throw (); extern float __nearbyintf (float __x) throw (); #pragma empty_line /* Round X to nearest integral value, rounding halfway cases away from zero. */ extern float roundf (float __x) throw () __attribute__ ((__const__)); extern float __roundf (float __x) throw () __attribute__ ((__const__)); #pragma empty_line /* Round X to the integral value in floating-point format nearest but not larger in magnitude. */ extern float truncf (float __x) throw () __attribute__ ((__const__)); extern float __truncf (float __x) throw () __attribute__ ((__const__)); #pragma empty_line /* Compute remainder of X and Y and put in *QUO a value with sign of x/y and magnitude congruent `mod 2^n' to the magnitude of the integral quotient x/y, with n >= 3. */ extern float remquof (float __x, float __y, int *__quo) throw (); extern float __remquof (float __x, float __y, int *__quo) throw (); #pragma empty_line #pragma empty_line /* Conversion functions. */ #pragma empty_line /* Round X to nearest integral value according to current rounding direction. */ extern long int lrintf (float __x) throw (); extern long int __lrintf (float __x) throw (); __extension__ extern long long int llrintf (float __x) throw (); extern long long int __llrintf (float __x) throw (); #pragma empty_line /* Round X to nearest integral value, rounding halfway cases away from zero. */ extern long int lroundf (float __x) throw (); extern long int __lroundf (float __x) throw (); __extension__ extern long long int llroundf (float __x) throw (); extern long long int __llroundf (float __x) throw (); #pragma empty_line #pragma empty_line /* Return positive difference between X and Y. */ extern float fdimf (float __x, float __y) throw (); extern float __fdimf (float __x, float __y) throw (); #pragma empty_line /* Return maximum numeric value from X and Y. */ extern float fmaxf (float __x, float __y) throw () __attribute__ ((__const__)); extern float __fmaxf (float __x, float __y) throw () __attribute__ ((__const__)); #pragma empty_line /* Return minimum numeric value from X and Y. */ extern float fminf (float __x, float __y) throw () __attribute__ ((__const__)); extern float __fminf (float __x, float __y) throw () __attribute__ ((__const__)); #pragma empty_line #pragma empty_line /* Classify given number. */ extern int __fpclassifyf (float __value) throw () __attribute__ ((__const__)); #pragma empty_line /* Test for negative number. */ extern int __signbitf (float __value) throw () __attribute__ ((__const__)); #pragma empty_line #pragma empty_line /* Multiply-add function computed as a ternary operation. */ extern float fmaf (float __x, float __y, float __z) throw (); extern float __fmaf (float __x, float __y, float __z) throw (); #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Test for signaling NaN. */ extern int __issignalingf (float __value) throw () __attribute__ ((__const__)); #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Return X times (2 to the Nth power). */ extern float scalbf (float __x, float __n) throw (); extern float __scalbf (float __x, float __n) throw (); #pragma line 105 "/usr/include/math.h" 2 3 4 #pragma line 139 "/usr/include/math.h" 3 4 /* Include the file of declarations again, this time using `long double' instead of `double' and appending l to each function name. */ #pragma line 151 "/usr/include/math.h" 3 4 #pragma line 1 "/usr/include/x86_64-linux-gnu/bits/mathcalls.h" 1 3 4 /* Prototype declarations for math functions; helper file for <math.h>. Copyright (C) 1996-2016 Free Software Foundation, Inc. This file is part of the GNU C Library. #pragma empty_line The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. #pragma empty_line The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. #pragma empty_line You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ #pragma empty_line /* NOTE: Because of the special way this file is used by <math.h>, this file must NOT be protected from multiple inclusion as header files usually are. #pragma empty_line This file provides prototype declarations for the math functions. Most functions are declared using the macro: #pragma empty_line __MATHCALL (NAME,[_r], (ARGS...)); #pragma empty_line This means there is a function `NAME' returning `double' and a function `NAMEf' returning `float'. Each place `_Mdouble_' appears in the prototype, that is actually `double' in the prototype for `NAME' and `float' in the prototype for `NAMEf'. Reentrant variant functions are called `NAME_r' and `NAMEf_r'. #pragma empty_line Functions returning other types like `int' are declared using the macro: #pragma empty_line __MATHDECL (TYPE, NAME,[_r], (ARGS...)); #pragma empty_line This is just like __MATHCALL but for a function returning `TYPE' instead of `_Mdouble_'. In all of these cases, there is still both a `NAME' and a `NAMEf' that takes `float' arguments. #pragma empty_line Note that there must be no whitespace before the argument passed for NAME, to make token pasting work with -traditional. */ #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Trigonometric functions. */ #pragma empty_line #pragma empty_line /* Arc cosine of X. */ extern long double acosl (long double __x) throw (); extern long double __acosl (long double __x) throw (); /* Arc sine of X. */ extern long double asinl (long double __x) throw (); extern long double __asinl (long double __x) throw (); /* Arc tangent of X. */ extern long double atanl (long double __x) throw (); extern long double __atanl (long double __x) throw (); /* Arc tangent of Y/X. */ extern long double atan2l (long double __y, long double __x) throw (); extern long double __atan2l (long double __y, long double __x) throw (); #pragma empty_line /* Cosine of X. */ extern long double cosl (long double __x) throw (); extern long double __cosl (long double __x) throw (); /* Sine of X. */ extern long double sinl (long double __x) throw (); extern long double __sinl (long double __x) throw (); /* Tangent of X. */ extern long double tanl (long double __x) throw (); extern long double __tanl (long double __x) throw (); #pragma empty_line /* Hyperbolic functions. */ #pragma empty_line /* Hyperbolic cosine of X. */ extern long double coshl (long double __x) throw (); extern long double __coshl (long double __x) throw (); /* Hyperbolic sine of X. */ extern long double sinhl (long double __x) throw (); extern long double __sinhl (long double __x) throw (); /* Hyperbolic tangent of X. */ extern long double tanhl (long double __x) throw (); extern long double __tanhl (long double __x) throw (); #pragma empty_line #pragma empty_line #pragma empty_line /* Cosine and sine of X. */ extern void sincosl (long double __x, long double *__sinx, long double *__cosx) throw (); extern void __sincosl (long double __x, long double *__sinx, long double *__cosx) throw (); #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Hyperbolic arc cosine of X. */ extern long double acoshl (long double __x) throw (); extern long double __acoshl (long double __x) throw (); /* Hyperbolic arc sine of X. */ extern long double asinhl (long double __x) throw (); extern long double __asinhl (long double __x) throw (); /* Hyperbolic arc tangent of X. */ extern long double atanhl (long double __x) throw (); extern long double __atanhl (long double __x) throw (); #pragma empty_line #pragma empty_line #pragma empty_line /* Exponential and logarithmic functions. */ #pragma empty_line #pragma empty_line /* Exponential function of X. */ extern long double expl (long double __x) throw (); extern long double __expl (long double __x) throw (); #pragma empty_line /* Break VALUE into a normalized fraction and an integral power of 2. */ extern long double frexpl (long double __x, int *__exponent) throw (); extern long double __frexpl (long double __x, int *__exponent) throw (); #pragma empty_line /* X times (two to the EXP power). */ extern long double ldexpl (long double __x, int __exponent) throw (); extern long double __ldexpl (long double __x, int __exponent) throw (); #pragma empty_line /* Natural logarithm of X. */ extern long double logl (long double __x) throw (); extern long double __logl (long double __x) throw (); #pragma empty_line /* Base-ten logarithm of X. */ extern long double log10l (long double __x) throw (); extern long double __log10l (long double __x) throw (); #pragma empty_line /* Break VALUE into integral and fractional parts. */ extern long double modfl (long double __x, long double *__iptr) throw (); extern long double __modfl (long double __x, long double *__iptr) throw () __attribute__ ((__nonnull__ (2))); #pragma empty_line #pragma empty_line #pragma empty_line /* A function missing in all standards: compute exponent to base ten. */ extern long double exp10l (long double __x) throw (); extern long double __exp10l (long double __x) throw (); /* Another name occasionally used. */ extern long double pow10l (long double __x) throw (); extern long double __pow10l (long double __x) throw (); #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Return exp(X) - 1. */ extern long double expm1l (long double __x) throw (); extern long double __expm1l (long double __x) throw (); #pragma empty_line /* Return log(1 + X). */ extern long double log1pl (long double __x) throw (); extern long double __log1pl (long double __x) throw (); #pragma empty_line /* Return the base 2 signed integral exponent of X. */ extern long double logbl (long double __x) throw (); extern long double __logbl (long double __x) throw (); #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Compute base-2 exponential of X. */ extern long double exp2l (long double __x) throw (); extern long double __exp2l (long double __x) throw (); #pragma empty_line /* Compute base-2 logarithm of X. */ extern long double log2l (long double __x) throw (); extern long double __log2l (long double __x) throw (); #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Power functions. */ #pragma empty_line #pragma empty_line /* Return X to the Y power. */ extern long double powl (long double __x, long double __y) throw (); extern long double __powl (long double __x, long double __y) throw (); #pragma empty_line /* Return the square root of X. */ extern long double sqrtl (long double __x) throw (); extern long double __sqrtl (long double __x) throw (); #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Return `sqrt(X*X + Y*Y)'. */ extern long double hypotl (long double __x, long double __y) throw (); extern long double __hypotl (long double __x, long double __y) throw (); #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Return the cube root of X. */ extern long double cbrtl (long double __x) throw (); extern long double __cbrtl (long double __x) throw (); #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Nearest integer, absolute value, and remainder functions. */ #pragma empty_line #pragma empty_line /* Smallest integral value not less than X. */ extern long double ceill (long double __x) throw () __attribute__ ((__const__)); extern long double __ceill (long double __x) throw () __attribute__ ((__const__)); #pragma empty_line /* Absolute value of X. */ extern long double fabsl (long double __x) throw () __attribute__ ((__const__)); extern long double __fabsl (long double __x) throw () __attribute__ ((__const__)); #pragma empty_line /* Largest integer not greater than X. */ extern long double floorl (long double __x) throw () __attribute__ ((__const__)); extern long double __floorl (long double __x) throw () __attribute__ ((__const__)); #pragma empty_line /* Floating-point modulo remainder of X/Y. */ extern long double fmodl (long double __x, long double __y) throw (); extern long double __fmodl (long double __x, long double __y) throw (); #pragma empty_line #pragma empty_line /* Return 0 if VALUE is finite or NaN, +1 if it is +Infinity, -1 if it is -Infinity. */ extern int __isinfl (long double __value) throw () __attribute__ ((__const__)); #pragma empty_line /* Return nonzero if VALUE is finite and not NaN. */ extern int __finitel (long double __value) throw () __attribute__ ((__const__)); #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Return 0 if VALUE is finite or NaN, +1 if it is +Infinity, -1 if it is -Infinity. */ extern int isinfl (long double __value) throw () __attribute__ ((__const__)); #pragma empty_line #pragma empty_line /* Return nonzero if VALUE is finite and not NaN. */ extern int finitel (long double __value) throw () __attribute__ ((__const__)); #pragma empty_line /* Return the remainder of X/Y. */ extern long double dreml (long double __x, long double __y) throw (); extern long double __dreml (long double __x, long double __y) throw (); #pragma empty_line #pragma empty_line /* Return the fractional part of X after dividing out `ilogb (X)'. */ extern long double significandl (long double __x) throw (); extern long double __significandl (long double __x) throw (); #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Return X with its signed changed to Y's. */ extern long double copysignl (long double __x, long double __y) throw () __attribute__ ((__const__)); extern long double __copysignl (long double __x, long double __y) throw () __attribute__ ((__const__)); #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Return representation of qNaN for double type. */ extern long double nanl (const char *__tagb) throw () __attribute__ ((__const__)); extern long double __nanl (const char *__tagb) throw () __attribute__ ((__const__)); #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Return nonzero if VALUE is not a number. */ extern int __isnanl (long double __value) throw () __attribute__ ((__const__)); #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Return nonzero if VALUE is not a number. */ extern int isnanl (long double __value) throw () __attribute__ ((__const__)); #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Bessel functions. */ extern long double j0l (long double) throw (); extern long double __j0l (long double) throw (); extern long double j1l (long double) throw (); extern long double __j1l (long double) throw (); extern long double jnl (int, long double) throw (); extern long double __jnl (int, long double) throw (); extern long double y0l (long double) throw (); extern long double __y0l (long double) throw (); extern long double y1l (long double) throw (); extern long double __y1l (long double) throw (); extern long double ynl (int, long double) throw (); extern long double __ynl (int, long double) throw (); #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Error and gamma functions. */ extern long double erfl (long double) throw (); extern long double __erfl (long double) throw (); extern long double erfcl (long double) throw (); extern long double __erfcl (long double) throw (); extern long double lgammal (long double) throw (); extern long double __lgammal (long double) throw (); #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* True gamma function. */ extern long double tgammal (long double) throw (); extern long double __tgammal (long double) throw (); #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Obsolete alias for `lgamma'. */ extern long double gammal (long double) throw (); extern long double __gammal (long double) throw (); #pragma empty_line #pragma empty_line #pragma empty_line /* Reentrant version of lgamma. This function uses the global variable `signgam'. The reentrant version instead takes a pointer and stores the value through it. */ extern long double lgammal_r (long double, int *__signgamp) throw (); extern long double __lgammal_r (long double, int *__signgamp) throw (); #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Return the integer nearest X in the direction of the prevailing rounding mode. */ extern long double rintl (long double __x) throw (); extern long double __rintl (long double __x) throw (); #pragma empty_line /* Return X + epsilon if X < Y, X - epsilon if X > Y. */ extern long double nextafterl (long double __x, long double __y) throw () __attribute__ ((__const__)); extern long double __nextafterl (long double __x, long double __y) throw () __attribute__ ((__const__)); #pragma empty_line extern long double nexttowardl (long double __x, long double __y) throw () __attribute__ ((__const__)); extern long double __nexttowardl (long double __x, long double __y) throw () __attribute__ ((__const__)); #pragma empty_line #pragma empty_line /* Return the remainder of integer divison X / Y with infinite precision. */ extern long double remainderl (long double __x, long double __y) throw (); extern long double __remainderl (long double __x, long double __y) throw (); #pragma empty_line #pragma empty_line /* Return X times (2 to the Nth power). */ extern long double scalbnl (long double __x, int __n) throw (); extern long double __scalbnl (long double __x, int __n) throw (); #pragma empty_line #pragma empty_line /* Return the binary exponent of X, which must be nonzero. */ extern int ilogbl (long double __x) throw (); extern int __ilogbl (long double __x) throw (); #pragma empty_line #pragma empty_line #pragma empty_line /* Return X times (2 to the Nth power). */ extern long double scalblnl (long double __x, long int __n) throw (); extern long double __scalblnl (long double __x, long int __n) throw (); #pragma empty_line /* Round X to integral value in floating-point format using current rounding direction, but do not raise inexact exception. */ extern long double nearbyintl (long double __x) throw (); extern long double __nearbyintl (long double __x) throw (); #pragma empty_line /* Round X to nearest integral value, rounding halfway cases away from zero. */ extern long double roundl (long double __x) throw () __attribute__ ((__const__)); extern long double __roundl (long double __x) throw () __attribute__ ((__const__)); #pragma empty_line /* Round X to the integral value in floating-point format nearest but not larger in magnitude. */ extern long double truncl (long double __x) throw () __attribute__ ((__const__)); extern long double __truncl (long double __x) throw () __attribute__ ((__const__)); #pragma empty_line /* Compute remainder of X and Y and put in *QUO a value with sign of x/y and magnitude congruent `mod 2^n' to the magnitude of the integral quotient x/y, with n >= 3. */ extern long double remquol (long double __x, long double __y, int *__quo) throw (); extern long double __remquol (long double __x, long double __y, int *__quo) throw (); #pragma empty_line #pragma empty_line /* Conversion functions. */ #pragma empty_line /* Round X to nearest integral value according to current rounding direction. */ extern long int lrintl (long double __x) throw (); extern long int __lrintl (long double __x) throw (); __extension__ extern long long int llrintl (long double __x) throw (); extern long long int __llrintl (long double __x) throw (); #pragma empty_line /* Round X to nearest integral value, rounding halfway cases away from zero. */ extern long int lroundl (long double __x) throw (); extern long int __lroundl (long double __x) throw (); __extension__ extern long long int llroundl (long double __x) throw (); extern long long int __llroundl (long double __x) throw (); #pragma empty_line #pragma empty_line /* Return positive difference between X and Y. */ extern long double fdiml (long double __x, long double __y) throw (); extern long double __fdiml (long double __x, long double __y) throw (); #pragma empty_line /* Return maximum numeric value from X and Y. */ extern long double fmaxl (long double __x, long double __y) throw () __attribute__ ((__const__)); extern long double __fmaxl (long double __x, long double __y) throw () __attribute__ ((__const__)); #pragma empty_line /* Return minimum numeric value from X and Y. */ extern long double fminl (long double __x, long double __y) throw () __attribute__ ((__const__)); extern long double __fminl (long double __x, long double __y) throw () __attribute__ ((__const__)); #pragma empty_line #pragma empty_line /* Classify given number. */ extern int __fpclassifyl (long double __value) throw () __attribute__ ((__const__)); #pragma empty_line /* Test for negative number. */ extern int __signbitl (long double __value) throw () __attribute__ ((__const__)); #pragma empty_line #pragma empty_line /* Multiply-add function computed as a ternary operation. */ extern long double fmal (long double __x, long double __y, long double __z) throw (); extern long double __fmal (long double __x, long double __y, long double __z) throw (); #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Test for signaling NaN. */ extern int __issignalingl (long double __value) throw () __attribute__ ((__const__)); #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Return X times (2 to the Nth power). */ extern long double scalbl (long double __x, long double __n) throw (); extern long double __scalbl (long double __x, long double __n) throw (); #pragma line 152 "/usr/include/math.h" 2 3 4 #pragma line 167 "/usr/include/math.h" 3 4 /* This variable is used by `gamma' and `lgamma'. */ extern int signgam; #pragma empty_line #pragma empty_line #pragma empty_line /* ISO C99 defines some generic macros which work on any data type. */ #pragma empty_line #pragma empty_line /* Get the architecture specific values describing the floating-point evaluation. The following symbols will get defined: #pragma empty_line float_t floating-point type at least as wide as `float' used to evaluate `float' expressions double_t floating-point type at least as wide as `double' used to evaluate `double' expressions #pragma empty_line FLT_EVAL_METHOD Defined to 0 if `float_t' is `float' and `double_t' is `double' 1 if `float_t' and `double_t' are `double' 2 if `float_t' and `double_t' are `long double' else `float_t' and `double_t' are unspecified #pragma empty_line INFINITY representation of the infinity value of type `float' #pragma empty_line FP_FAST_FMA FP_FAST_FMAF FP_FAST_FMAL If defined it indicates that the `fma' function generally executes about as fast as a multiply and an add. This macro is defined only iff the `fma' function is implemented directly with a hardware multiply-add instructions. #pragma empty_line FP_ILOGB0 Expands to a value returned by `ilogb (0.0)'. FP_ILOGBNAN Expands to a value returned by `ilogb (NAN)'. #pragma empty_line DECIMAL_DIG Number of decimal digits supported by conversion between decimal and all internal floating-point formats. #pragma empty_line */ #pragma empty_line /* All floating-point numbers can be put in one of these categories. */ enum { FP_NAN = #pragma empty_line 0, FP_INFINITE = #pragma empty_line 1, FP_ZERO = #pragma empty_line 2, FP_SUBNORMAL = #pragma empty_line 3, FP_NORMAL = #pragma empty_line 4 }; #pragma empty_line /* GCC bug 66462 means we cannot use the math builtins with -fsignaling-nan, so disable builtins if this is enabled. When fixed in a newer GCC, the __SUPPORT_SNAN__ check may be skipped for those versions. */ #pragma empty_line /* Return number of classification appropriate for X. */ #pragma line 248 "/usr/include/math.h" 3 4 /* Return nonzero value if sign of X is negative. */ #pragma line 268 "/usr/include/math.h" 3 4 /* Return nonzero value if X is not +-Inf or NaN. */ #pragma line 282 "/usr/include/math.h" 3 4 /* Return nonzero value if X is neither zero, subnormal, Inf, nor NaN. */ #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Return nonzero value if X is a NaN. We could use `fpclassify' but we already have this functions `__isnan' and it is faster. */ #pragma line 304 "/usr/include/math.h" 3 4 /* Return nonzero value if X is positive or negative infinity. */ #pragma line 318 "/usr/include/math.h" 3 4 /* Bitmasks for the math_errhandling macro. */ #pragma empty_line #pragma empty_line #pragma empty_line /* By default all functions support both errno and exception handling. In gcc's fast math mode and if inline functions are defined this might not be true. */ #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Return nonzero value if X is a signaling NaN. */ #pragma line 346 "/usr/include/math.h" 3 4 /* Support for various different standard error handling behaviors. */ typedef enum { _IEEE_ = -1, /* According to IEEE 754/IEEE 854. */ _SVID_, /* According to System V, release 4. */ _XOPEN_, /* Nowadays also Unix98. */ _POSIX_, _ISOC_ /* Actually this is ISO C99. */ } _LIB_VERSION_TYPE; #pragma empty_line /* This variable can be changed at run-time to any of the values above to affect floating point error handling behavior (it may also be necessary to change the hardware FPU exception settings). */ extern _LIB_VERSION_TYPE _LIB_VERSION; #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* In SVID error handling, `matherr' is called with this description of the exceptional condition. #pragma empty_line We have a problem when using C++ since `exception' is a reserved name in C++. */ #pragma empty_line struct __exception #pragma empty_line #pragma empty_line #pragma empty_line { int type; char *name; double arg1; double arg2; double retval; }; #pragma empty_line #pragma empty_line extern int matherr (struct __exception *__exc) throw (); #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Types of exceptions in the `type' field. */ #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* SVID mode specifies returning this large value instead of infinity. */ #pragma line 411 "/usr/include/math.h" 3 4 /* Some useful constants. */ #pragma line 428 "/usr/include/math.h" 3 4 /* The above constants are not adequate for computation using `long double's. Therefore we provide as an extension constants with similar names as a GNU extension. Provide enough digits for the 128-bit IEEE quad. */ #pragma line 448 "/usr/include/math.h" 3 4 /* When compiling in strict ISO C compatible mode we must not use the inline functions since they, among other things, do not set the `errno' variable correctly. */ #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* ISO C99 defines some macros to compare number while taking care for unordered numbers. Many FPUs provide special instructions to support these operations. Generic support in GCC for these as builtins went in before 3.0.0, but not all cpus added their patterns. We define versions that use the builtins here, and <bits/mathinline.h> will undef/redefine as appropriate for the specific GCC version in use. */ #pragma line 470 "/usr/include/math.h" 3 4 /* Get machine-dependent inline versions (if there are any). */ #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Define special entry points to use when the compiler got told to only expect finite results. */ #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* If we've still got undefined comparison macros, provide defaults. */ #pragma empty_line /* Return nonzero value if X is greater than Y. */ #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Return nonzero value if X is greater than or equal to Y. */ #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Return nonzero value if X is less than Y. */ #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Return nonzero value if X is less than or equal to Y. */ #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Return nonzero value if either X is less than Y or Y is less than X. */ #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line #pragma empty_line /* Return nonzero value if arguments are unordered. */ #pragma line 534 "/usr/include/math.h" 3 4 } #pragma line 4 "VCNN/src/lib/layers/Softmax.cpp" 2 #pragma empty_line #pragma empty_line void Softmax(Layer current, LayerWeight cw, Layer next){ float exp_sum = 0.0; int channels = current.input_channel_num; int height = current.input_feature_map_height; int width = current.input_feature_map_width; int total_input = channels*width*height; #pragma empty_line for(int i=0; i<total_input; i++){ float tmp = exp(*(current.input_data+i)); *(next.input_data+i) = tmp; exp_sum += tmp; } for(int i=0; i<total_input; i++){ *(next.input_data+i) = (*(next.input_data+i))/exp_sum; } }
[ "xiz368@ucsd.edu" ]
xiz368@ucsd.edu
679b83b888cd4112b32f40108c92d8dffd0095af
ad822f849322c5dcad78d609f28259031a96c98e
/SDK/Hazard_Bouncer_Lily_02_parameters.h
ae6eb66b4dd9f84ff5498c6d5af432e84fc1a13d
[]
no_license
zH4x-SDK/zAstroneer-SDK
1cdc9c51b60be619202c0258a0dd66bf96898ac4
35047f506eaef251a161792fcd2ddd24fe446050
refs/heads/main
2023-07-24T08:20:55.346698
2021-08-27T13:33:33
2021-08-27T13:33:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
508
h
#pragma once #include "../SDK.h" // Name: Astroneer-SDK, Version: 1.0.0 #ifdef _MSC_VER #pragma pack(push, 0x8) #endif namespace SDK { //--------------------------------------------------------------------------- // Parameters //--------------------------------------------------------------------------- // Function Hazard_Bouncer_Lily_02.Hazard_Bouncer_Lily_02_C.UserConstructionScript struct AHazard_Bouncer_Lily_02_C_UserConstructionScript_Params { }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "zp2kshield@gmail.com" ]
zp2kshield@gmail.com
acc858fd139d1aad7dfbb20ee046f68115e27274
81f1b38c756cf0f01c4d20dd9d0e1f3eab674e10
/abc165/a.cpp
0fea36433a87080e1d826bc3202f51474a4e1216
[]
no_license
nena-undefined/AtCoder
842a7e18de9ac0c4cdbfb9ec78b82f0388d19200
0b24c37498368244b6d4e859ceb11efe020378e3
refs/heads/master
2022-11-24T01:12:02.769826
2020-07-27T01:53:01
2020-07-27T01:53:01
279,606,966
1
0
null
null
null
null
UTF-8
C++
false
false
1,132
cpp
#include <cstdio> #include <cstdlib> #include <cmath> #include <cstring> #include <climits> #include <vector> #include <map> #include <set> #include <list> #include <stack> #include <queue> #include <algorithm> #include <iostream> #include <string> #define REP(i,n) for(auto i=0;i<n;++i) #define REPR(i,n) for(auto i=n;i>=0;--i) #define REPI(itr,v) for(auto itr=v.begin();itr!=v.end();++itr) #define REPIR(itr,v) for(auto itr=v.rbegin();itr!=v.rend();++itr) #define FOR(i,a,b) for(auto i=a;i<b;++i) #define SORT(v,n) sort(v, v+n) #define SORTV(v) sort(v.begin(), v.end()) #define ALL(v) v.begin(),v.end() #define llong long long #define ll long long #define INF 999999999 #define MOD 1000000007 #define pb push_back #define pf push_front #define MP make_pair #define SV(n,v) {int tmp;for(int i=0;i<n;++i){scanf("%d",&tmp);v.push_back(tmp);}} int dx[] = {0, 0, -1, 1}; int dy[] = {1, -1, 0, 0}; using namespace std; typedef pair<int,int> pii; int main(){ int k, a, b; cin >> k >> a >>b; for(int i = a; i <= b; ++i){ if(i % k == 0){ cout << "OK\n"; return 0; } } cout << "NG\n"; return 0; }
[ "nena0undefined@gmail.com" ]
nena0undefined@gmail.com
7731aebae6b3b29e05d0ec94a66f6b9ac3e1fbe7
e9fff4a1dc086a855dd623edfef3bafaf8185d92
/alib/test/globtest/main.cpp
a8b6f40151bc8b0cbfa8199a2770c399aff46a3a
[ "MIT" ]
permissive
notklaatu/csvfix
bdb7516354f7e14b6de28c9506d2fa51dd3b572f
693d99dfe7ffa06c46fccd9ac3062826e5d9a8fe
refs/heads/master
2022-12-22T03:26:01.599262
2020-09-29T02:20:33
2020-09-29T02:20:33
299,476,931
0
0
MIT
2020-09-29T01:50:50
2020-09-29T01:50:49
null
UTF-8
C++
false
false
494
cpp
#include "a_env.h" #include "a_globswitch.h" #include <iostream> using namespace std; //static ALib::GlobSwitch gs( false ); int _CRT_glob = 1; int main( int argc, char * argv[] ) { ALib::CommandLine cl( argc, argv ); for ( unsigned int i = 0; i < argc; i++ ) { cout << argv[i] << endl; } cout << "----------------------------------" << endl; cl.BuildFileList( 1 ); for ( unsigned int i = 0; i < cl.FileCount(); i++ ) { cout << cl.File( i ) << endl; } }
[ "neilb@cordelia" ]
neilb@cordelia
7190bcf4e2c9801b9bd1eebb1fe4deace12b50d1
04d64f9f25bf786068506f1d3e54c3a1bc3ea4d8
/tests/basis_functions_test.cpp
cc752eb482b86a11e63e4167cc8b002ec64621fc
[]
no_license
sebasutp/promp-cpp
3bb16c1002a68316a4a0ff53f96641a0820e8dd0
cc829afe4e6ea28cb943f4693edf84a586254df5
refs/heads/master
2020-04-30T02:45:45.048509
2019-09-06T10:26:32
2019-09-06T10:26:32
176,569,178
6
0
null
null
null
null
UTF-8
C++
false
false
2,632
cpp
#include "robotics/basis_functions.hpp" #include <armadillo> #define BOOST_TEST_DYN_LINK #include <boost/test/unit_test.hpp> #include <json.hpp> #include <fstream> #include <string> #include <unordered_map> #include <cmath> #include <memory> #include "robotics/utils.hpp" #define EPS 1e-8 using namespace robotics; using namespace arma; using namespace std; using json = nlohmann::json; BOOST_AUTO_TEST_CASE( ScalarPolyBasisTest ) { unsigned int poly_order = 3; ScalarPolyBasis poly(poly_order); //create 3rd order polynomial basis functions [1 x x**2 x**3] BOOST_CHECK( norm(poly.eval(0) - vec{1.0,0,0,0}) < EPS ); BOOST_CHECK( norm(poly.eval(1.0) - vec{1,1,1,1}) < EPS ); BOOST_CHECK( norm(poly.eval(0.5) - vec{1,0.5,0.25,0.125}) < EPS ); BOOST_CHECK( norm(poly.deriv(0.0, 1) - vec{0,1.0,0,0}) < EPS ); BOOST_CHECK( norm(poly.deriv(1.0, 1) - vec{0,1,2,3}) < EPS ); BOOST_CHECK( norm(poly.deriv(0.5, 1) - vec{0,1,2*0.5,3*0.25}) < EPS ); BOOST_CHECK( norm(poly.deriv(0.0, 2) - vec{0,0,2,0}) < EPS ); BOOST_CHECK( norm(poly.deriv(1.0, 2) - vec{0,0,2,6}) < EPS ); BOOST_CHECK( norm(poly.deriv(0.5, 2) - vec{0,0,2,6*0.5}) < EPS ); BOOST_CHECK( poly.dim() == (poly_order+1) ); } BOOST_AUTO_TEST_CASE( ScalarGaussBasisTest ) { ifstream in("tests/gaussian_kernel_test.txt"); json json; in >> json; for (auto &elem : json) { vec phi_t = json2vec(elem["phi_t"]); vec der1 = json2vec(elem["der1"]); vec der2 = json2vec(elem["der2"]); double sigma = elem["sigma"]; double t = elem["t"]; vec centers = json2vec(elem["centers"]); ScalarGaussBasis gauss_basis(centers, sigma); BOOST_CHECK( norm(gauss_basis.eval(t) - phi_t) < EPS ); BOOST_CHECK( norm(gauss_basis.deriv(t,1) - der1) < EPS ); BOOST_CHECK( norm(gauss_basis.deriv(t,2) - der2) < EPS ); } } BOOST_AUTO_TEST_CASE( ScalarCombBasisTest ) { auto rbf = shared_ptr<ScalarGaussBasis>( new ScalarGaussBasis({0.25,0.5,0.75},0.25) ); auto poly = make_shared<ScalarPolyBasis>(1); auto comb = shared_ptr<ScalarCombBasis>( new ScalarCombBasis({rbf, poly}) ); for (double z=0; z<=1; z+=0.1) { vec v1 = comb->eval(z); vec v2 = comb->eval(z + 1e-5); vec num_diff = (v2 - v1) / (1e-5); vec an_diff = comb->deriv(z, 1); for (unsigned int d=0; d<5; d++) { cout << "d: " << d << " -> " << an_diff[d] << " ?= " << num_diff[d] << endl; if (fabs(an_diff[d]) > 1e-8) BOOST_CHECK_CLOSE(an_diff[d], num_diff[d], 1); else BOOST_CHECK(fabs(num_diff[d]) < 1e-3); } BOOST_CHECK(fabs(an_diff[3]) < 1e-6); BOOST_CHECK_CLOSE(1.0, an_diff[4], 0.01); } }
[ "dagudelo@ord.is.localnet" ]
dagudelo@ord.is.localnet
cc7e6b324c5d063277b25b90c6b75aeced414bdf
46d4712c82816290417d611a75b604d51b046ecc
/Samples/Win7Samples/multimedia/mediafoundation/MFPlayer2/winmain.cpp
412edccfa33dd84541091a92920408c076363864
[ "MIT" ]
permissive
ennoherr/Windows-classic-samples
00edd65e4808c21ca73def0a9bb2af9fa78b4f77
a26f029a1385c7bea1c500b7f182d41fb6bcf571
refs/heads/master
2022-12-09T20:11:56.456977
2022-12-04T16:46:55
2022-12-04T16:46:55
156,835,248
1
0
NOASSERTION
2022-12-04T16:46:55
2018-11-09T08:50:41
null
UTF-8
C++
false
false
1,857
cpp
//------------------------------------------------------------------------------ // // File: winmain.cpp // Application entry-point. // // THIS CODE AND INFORMATION IS 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. // // Copyright (c) Microsoft Corporation. All rights reserved. // //------------------------------------------------------------------------------ #include "MFPlayer.h" #include "MainDialog.h" INT WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE /*hPrevInstance*/, LPWSTR /*lpCmdLine*/, INT /*nCmdShow*/) { (void)HeapSetInformation(NULL, HeapEnableTerminationOnCorruption, NULL, 0); // Initialize the COM library. HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE); if (FAILED(hr)) { MessageBox(NULL, L"CoInitialize failed.", NULL, MB_ICONSTOP); return 0; } // Initialize the common control library. INITCOMMONCONTROLSEX icc; icc.dwSize = sizeof(icc); icc.dwICC = ICC_STANDARD_CLASSES | ICC_BAR_CLASSES; if (!InitCommonControlsEx(&icc)) { MessageBox(NULL, L"InitCommonControlsEx failed.", NULL, MB_ICONSTOP); CoUninitialize(); return 0; } // Initialize our custom slider class. hr = Slider_Init(); if (FAILED(hr)) { MessageBox(NULL, L"Slider_Init failed.", NULL, MB_ICONSTOP); CoUninitialize(); return 0; } // Create and show the dialog. MainDialog *pDlg = new (std::nothrow) MainDialog(); if (pDlg == NULL) { MessageBox(NULL, L"Out of memory.", NULL, MB_ICONSTOP); } else { pDlg->ShowDialog(hInstance); delete pDlg; } CoUninitialize(); return 0; }
[ "chrisg@microsoft.com" ]
chrisg@microsoft.com
e21bd1da868b4448886298d3899d4da9062ca200
084f7daed2eafb39035db74463fa9a32057bd479
/lib/extern/mongodb/external-libs/bson/long.cc
b4c45e4b709438bde61c914dc6861f02595d0434
[ "Apache-2.0", "BSD-3-Clause", "MIT" ]
permissive
cloudkick/nodul.es
27a4881e6aaeb4288b4dc5c5386017795db04ee8
187b679a3e6ad920e606cbc6db5a512b862b2cf5
refs/heads/master
2020-06-02T20:38:58.351782
2010-11-28T21:11:39
2010-11-28T21:11:39
883,700
1
0
null
null
null
null
UTF-8
C++
false
false
23,274
cc
#include <assert.h> #include <string.h> #include <stdlib.h> #include <v8.h> #include <node.h> #include <node_events.h> #include <node_buffer.h> #include <cstring> #include <cmath> #include <cstdlib> #include <iostream> #include <limits> #include "long.h" // BSON MAX VALUES const int32_t BSON_INT32_MAX = (int32_t)2147483648L; const int32_t BSON_INT32_MIN = (int32_t)(-1) * 2147483648L; const int64_t BSON_INT32_ = pow(2, 32); const double LN2 = 0.6931471805599453; // Max Values const int64_t BSON_INT64_MAX = (int64_t)9223372036854775807LL; const int64_t BSON_INT64_MIN = (int64_t)(-1)*(9223372036854775807LL); // Constant objects used in calculations Long* MIN_VALUE = Long::fromBits(0, 0x80000000 | 0); Long* MAX_VALUE = Long::fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0); Long* ZERO = Long::fromInt(0); Long* ONE = Long::fromInt(1); Long* NEG_ONE = Long::fromInt(-1); #define max(a,b) ({ typeof (a) _a = (a); typeof (b) _b = (b); _a > _b ? _a : _b; }) static Handle<Value> VException(const char *msg) { HandleScope scope; return ThrowException(Exception::Error(String::New(msg))); }; Persistent<FunctionTemplate> Long::constructor_template; Long::Long(int32_t low_bits, int32_t high_bits) : ObjectWrap() { this->low_bits = low_bits; this->high_bits = high_bits; } Long::~Long() {} Handle<Value> Long::New(const Arguments &args) { HandleScope scope; // Ensure that we have an parameter if(args.Length() == 1 && args[0]->IsNumber()) { // Unpack the value double value = args[0]->NumberValue(); // Create an instance of long Long *l = Long::fromNumber(value); // Wrap it in the object wrap l->Wrap(args.This()); // Return the context return args.This(); } else if(args.Length() == 2 && args[0]->IsNumber() && args[1]->IsNumber()) { // Unpack the value int32_t low_bits = args[0]->Int32Value(); int32_t high_bits = args[1]->Int32Value(); // Create an instance of long Long *l = new Long(low_bits, high_bits); // Wrap it in the object wrap l->Wrap(args.This()); // Return the context return args.This(); } else if(args.Length() == 2 && args[0]->IsString() && args[1]->IsString()) { // Parse the strings into int32_t values int32_t low_bits = 0; int32_t high_bits = 0; char *low_bits_str = (char *)malloc(4 * sizeof(char)); char *high_bits_str = (char *)malloc(4 * sizeof(char)); // Let's write the strings to the bits DecodeWrite(low_bits_str, 4, args[0]->ToString(), BINARY); DecodeWrite(high_bits_str, 4, args[1]->ToString(), BINARY); // Copy the string to the int memcpy(&low_bits, low_bits_str, 4); memcpy(&high_bits, high_bits_str, 4); // Free memory free(low_bits_str); free(high_bits_str); // Create an instance of long Long *l = new Long(low_bits, high_bits); // Wrap it in the object wrap l->Wrap(args.This()); // Return the context return args.This(); } else { return VException("Argument passed in must be either a 64 bit number or two 32 bit numbers."); } } static Persistent<String> low_bits_symbol; static Persistent<String> high_bits_symbol; void Long::Initialize(Handle<Object> target) { // Grab the scope of the call from Node HandleScope scope; // Define a new function template Local<FunctionTemplate> t = FunctionTemplate::New(New); constructor_template = Persistent<FunctionTemplate>::New(t); constructor_template->InstanceTemplate()->SetInternalFieldCount(1); constructor_template->SetClassName(String::NewSymbol("Long")); // Propertry symbols low_bits_symbol = NODE_PSYMBOL("low_"); high_bits_symbol = NODE_PSYMBOL("high_"); // Instance methods NODE_SET_PROTOTYPE_METHOD(constructor_template, "toString", ToString); NODE_SET_PROTOTYPE_METHOD(constructor_template, "isZero", IsZero); NODE_SET_PROTOTYPE_METHOD(constructor_template, "getLowBits", GetLowBits); NODE_SET_PROTOTYPE_METHOD(constructor_template, "getHighBits", GetHighBits); NODE_SET_PROTOTYPE_METHOD(constructor_template, "inspect", Inspect); NODE_SET_PROTOTYPE_METHOD(constructor_template, "greaterThan", GreatherThan); NODE_SET_PROTOTYPE_METHOD(constructor_template, "toInt", ToInt); NODE_SET_PROTOTYPE_METHOD(constructor_template, "toNumber", ToNumber); // Getters for correct serialization of the object constructor_template->InstanceTemplate()->SetAccessor(low_bits_symbol, LowGetter, LowSetter); constructor_template->InstanceTemplate()->SetAccessor(high_bits_symbol, HighGetter, HighSetter); // Class methods NODE_SET_METHOD(constructor_template->GetFunction(), "fromNumber", FromNumber); NODE_SET_METHOD(constructor_template->GetFunction(), "fromInt", FromInt); // Add class to scope target->Set(String::NewSymbol("Long"), constructor_template->GetFunction()); } Handle<Value> Long::ToInt(const Arguments &args) { HandleScope scope; // Let's unpack the Long instance that contains the number in low_bits and high_bits form Long *l = ObjectWrap::Unwrap<Long>(args.This()); // Get lower bits uint32_t low_bits = l->low_bits; // Return the value scope.Close(Int32::New(low_bits)); } Handle<Value> Long::ToNumber(const Arguments &args) { // return this.high_ * exports.Long.TWO_PWR_32_DBL_ + // this.getLowBitsUnsigned(); HandleScope scope;//BSON_INT32_MAX // Let's unpack the Long instance that contains the number in low_bits and high_bits form Long *l = ObjectWrap::Unwrap<Long>(args.This()); // Calculate the approximate value int64_t value = (int64_t)l->high_bits * BSON_INT32_MAX * 2 + (uint32_t)l->low_bits; scope.Close(Number::New(value)); } Handle<Value> Long::LowGetter(Local<String> property, const AccessorInfo& info) { HandleScope scope; // Unpack object reference Local<Object> self = info.Holder(); // Fetch external reference (reference to Long object) Local<External> wrap = Local<External>::Cast(self->GetInternalField(0)); // Get pointer to the object void *ptr = wrap->Value(); // Extract value doing a cast of the pointer to Long and accessing low_bits int32_t low_bits = static_cast<Long *>(ptr)->low_bits; Local<Integer> integer = Integer::New(low_bits); return scope.Close(integer); } void Long::LowSetter(Local<String> property, Local<Value> value, const AccessorInfo& info) { if(value->IsNumber()) { // Unpack object reference Local<Object> self = info.Holder(); // Fetch external reference (reference to Long object) Local<External> wrap = Local<External>::Cast(self->GetInternalField(0)); // Get pointer to the object void *ptr = wrap->Value(); // Set the low bits static_cast<Long *>(ptr)->low_bits = value->Int32Value(); } } Handle<Value> Long::HighGetter(Local<String> property, const AccessorInfo& info) { HandleScope scope; // Unpack object reference Local<Object> self = info.Holder(); // Fetch external reference (reference to Long object) Local<External> wrap = Local<External>::Cast(self->GetInternalField(0)); // Get pointer to the object void *ptr = wrap->Value(); // Extract value doing a cast of the pointer to Long and accessing low_bits int32_t high_bits = static_cast<Long *>(ptr)->high_bits; Local<Integer> integer = Integer::New(high_bits); return scope.Close(integer); } void Long::HighSetter(Local<String> property, Local<Value> value, const AccessorInfo& info) { if(value->IsNumber()) { // Unpack object reference Local<Object> self = info.Holder(); // Fetch external reference (reference to Long object) Local<External> wrap = Local<External>::Cast(self->GetInternalField(0)); // Get pointer to the object void *ptr = wrap->Value(); // Set the low bits static_cast<Long *>(ptr)->high_bits = value->Int32Value(); } } Handle<Value> Long::Inspect(const Arguments &args) { HandleScope scope; // Let's unpack the Long instance that contains the number in low_bits and high_bits form Long *l = ObjectWrap::Unwrap<Long>(args.This()); // Let's create the string from the Long number char *result = l->toString(10); // Package the result in a V8 String object and return Local<Value> str = String::New(result); free(result); return str; } Handle<Value> Long::GetLowBits(const Arguments &args) { HandleScope scope; // Let's unpack the Long instance that contains the number in low_bits and high_bits form Long *l = ObjectWrap::Unwrap<Long>(args.This()); // Let's fetch the low bits int32_t low_bits = l->low_bits; // Package the result in a V8 Integer object and return return Integer::New(low_bits); } Handle<Value> Long::GetHighBits(const Arguments &args) { HandleScope scope; // Let's unpack the Long instance that contains the number in low_bits and high_bits form Long *l = ObjectWrap::Unwrap<Long>(args.This()); // Let's fetch the low bits int32_t high_bits = l->high_bits; // Package the result in a V8 Integer object and return return Integer::New(high_bits); } bool Long::isZero() { int32_t low_bits = this->low_bits; int32_t high_bits = this->high_bits; return low_bits == 0 && high_bits == 0; } bool Long::isNegative() { int32_t low_bits = this->low_bits; int32_t high_bits = this->high_bits; return high_bits < 0; } bool Long::equals(Long *l) { int32_t low_bits = this->low_bits; int32_t high_bits = this->high_bits; return (high_bits == l->high_bits) && (low_bits == l->low_bits); } Handle<Value> Long::IsZero(const Arguments &args) { HandleScope scope; // Let's unpack the Long instance that contains the number in low_bits and high_bits form Long *l = ObjectWrap::Unwrap<Long>(args.This()); return Boolean::New(l->isZero()); } int32_t Long::toInt() { return this->low_bits; } char *Long::toString(int32_t opt_radix) { // Set the radix int32_t radix = opt_radix; // Check if we have a zero value if(this->isZero()) { // Allocate a string to return char *result = (char *)malloc(1 * sizeof(char) + 1); // Set the string to the character 0 *(result) = '0'; // Terminate the C String *(result + 1) = '\0'; return result; } // If the long is negative we need to perform som arithmetics if(this->isNegative()) { // Min value object Long *minLong = new Long(0, 0x80000000 | 0); if(this->equals(minLong)) { // We need to change the exports.Long value before it can be negated, so we remove // the bottom-most digit in this base and then recurse to do the rest. Long *radix_long = Long::fromNumber(radix); Long *div = this->div(radix_long); Long *mul = div->multiply(radix_long); Long *rem = mul->subtract(this); // Fetch div result char *div_result = div->toString(radix); // Unpack the rem result and convert int to string char *int_buf = (char *)malloc(50 * sizeof(char) + 1); *(int_buf) = '\0'; uint32_t rem_int = rem->toInt(); sprintf(int_buf, "%d", rem_int); // Final bufferr char *final_buffer = (char *)malloc(50 * sizeof(char) + 1); *(final_buffer) = '\0'; strncat(final_buffer, div_result, strlen(div_result)); strncat(final_buffer + strlen(div_result), int_buf, strlen(div_result)); // Release some memory free(div_result); free(int_buf); // Delete object delete rem; delete mul; return final_buffer; } else { char *buf = (char *)malloc(50 * sizeof(char) + 1); *(buf) = '\0'; Long *negate = this->negate(); char *result = negate->toString(radix); strncat(buf, "-", 1); strncat(buf + 1, result, strlen(result)); // Release memory free(result); delete negate; return buf; } } // Do several (6) digits each time through the loop, so as to // minimize the calls to the very expensive emulated div. Long *radix_to_power = Long::fromInt(pow(radix, 6)); Long *rem = this; char *result = (char *)malloc(1024 * sizeof(char) + 1); // Ensure the allocated space is null terminated to ensure a proper CString *(result) = '\0'; while(true) { Long *rem_div = rem->div(radix_to_power); Long *mul = rem_div->multiply(radix_to_power); int32_t interval = rem->subtract(mul)->toInt(); // Convert interval into string char digits[50]; sprintf(digits, "%d", interval); // Remove existing object if it's not this if(this != rem) delete rem; rem = rem_div; if(rem->isZero()) { // Join digits and result to create final result int total_length = strlen(digits) + strlen(result); char *new_result = (char *)malloc(total_length * sizeof(char) + 1); *(new_result) = '\0'; strncat(new_result, digits, strlen(digits)); strncat(new_result + strlen(digits), result, strlen(result)); // Free the existing structure free(result); delete rem_div; delete mul; delete radix_to_power; return new_result; } else { // Allocate some new space for the number char *new_result = (char *)malloc(1024 * sizeof(char) + 1); *(new_result) = '\0'; int digits_length = (int)strlen(digits); int index = 0; // Pad with zeros while(digits_length < 6) { strncat(new_result + index, "0", 1); digits_length = digits_length + 1; index = index + 1; } strncat(new_result + index, digits, strlen(digits)); strncat(new_result + strlen(digits) + index, result, strlen(result)); free(result); result = new_result; } // Free memory delete mul; } } Handle<Value> Long::ToString(const Arguments &args) { HandleScope scope; // Let's unpack the Long instance that contains the number in low_bits and high_bits form Long *l = ObjectWrap::Unwrap<Long>(args.This()); // Let's create the string from the Long number char *result = l->toString(10); // Package the result in a V8 String object and return Handle<Value> result_str = String::New(result); // Free memory free(result); // Return string return result_str; } Long *Long::shiftRight(int32_t number_bits) { number_bits &= 63; if(number_bits == 0) { return this; } else { int32_t high_bits = this->high_bits; if(number_bits < 32) { int32_t low_bits = this->low_bits; return Long::fromBits((low_bits >> number_bits) | (high_bits << (32 - number_bits)), high_bits >> number_bits); } else { return Long::fromBits(high_bits >> (number_bits - 32), high_bits >= 0 ? 0 : -1); } } } Long *Long::shiftLeft(int32_t number_bits) { number_bits &= 63; if(number_bits == 0) { return this; } else { int32_t low_bits = this->low_bits; if(number_bits < 32) { int32_t high_bits = this->high_bits; return Long::fromBits(low_bits << number_bits, (high_bits << number_bits) | (low_bits >> (32 - number_bits))); } else { return Long::fromBits(0, low_bits << (number_bits - 32)); } } } Long *Long::div(Long *other) { // If we are about to do a divide by zero throw an exception if(other->isZero()) { throw "division by zero"; } else if(this->isZero()) { return new Long(0, 0); } if(this->equals(MIN_VALUE)) { if(other->equals(ONE) || other->equals(NEG_ONE)) { return Long::fromBits(0, 0x80000000 | 0); } else if(other->equals(MIN_VALUE)) { return Long::fromNumber(1); } else { Long *half_this = this->shiftRight(1); Long *div_obj = half_this->div(other); Long *approx = div_obj->shiftLeft(1); // Free memory delete div_obj; delete half_this; // Check if we are done if(approx->equals(ZERO)) { return other->isNegative() ? Long::fromNumber(0) : Long::fromNumber(-1); } else { Long *mul = other->multiply(approx); Long *rem = this->subtract(mul); Long *rem_div = rem->div(other); Long *result = approx->add(rem_div); // Free memory delete mul; delete rem; delete rem_div; // Return result return result; } } } else if(other->equals(MIN_VALUE)) { return new Long(0, 0); } // If the value is negative if(this->isNegative()) { if(other->isNegative()) { Long *neg = this->negate(); Long *other_neg = other->negate(); Long *result = neg->div(other_neg); // Free memory delete neg; delete other_neg; // Return result return result; } else { Long *neg = this->negate(); Long *neg_result = neg->div(other); Long *result = neg_result->negate(); // Free memory delete neg; delete neg_result; // Return result return result; } } else if(other->isNegative()) { Long *other_neg = other->negate(); Long *div_result = this->div(other_neg); Long *result = div_result->negate(); // Free memory delete other_neg; delete div_result; // Return the result return result; } int64_t this_number = this->toNumber(); int64_t other_number = other->toNumber(); int64_t result = this_number / other_number; // Split into the 32 bit valu int32_t low32, high32; high32 = (uint64_t)result >> 32; low32 = (int32_t)result; return Long::fromBits(low32, high32); } Long *Long::multiply(Long *other) { if(this->isZero() || other->isZero()) { return new Long(0, 0); } int64_t this_number = this->toNumber(); int64_t other_number = other->toNumber(); int64_t result = this_number * other_number; // Split into the 32 bit valu int32_t low32, high32; high32 = (uint64_t)result >> 32; low32 = (int32_t)result; return Long::fromBits(low32, high32); } bool Long::isOdd() { return (this->low_bits & 1) == 1; } int64_t Long::toNumber() { return (int64_t)(this->high_bits * BSON_INT32_ + this->getLowBitsUnsigned()); } int64_t Long::getLowBitsUnsigned() { return (this->low_bits >= 0) ? this->low_bits : BSON_INT32_ + this->low_bits; } int64_t Long::compare(Long *other) { if(this->equals(other)) { return 0; } bool this_neg = this->isNegative(); bool other_neg = other->isNegative(); if(this_neg && !other_neg) { return -1; } if(!this_neg && other_neg) { return 1; } Long *return_value = this->subtract(other); // At this point, the signs are the same, so subtraction will not overflow if(return_value->isNegative()) { delete return_value; return -1; } else { delete return_value; return 1; } } Long *Long::negate() { if(this->equals(MIN_VALUE)) { return MIN_VALUE; } else { Long *not_obj = this->not_(); Long *add = not_obj->add(ONE); delete not_obj; return add; } } Long *Long::not_() { return new Long(~this->low_bits, ~this->high_bits); } Long *Long::add(Long *other) { int64_t this_number = this->toNumber(); int64_t other_number = other->toNumber(); int64_t result = this_number + other_number; // Split into the 32 bit valu int32_t low32, high32; high32 = (uint64_t)result >> 32; low32 = (int32_t)result; return Long::fromBits(low32, high32); } Long *Long::subtract(Long *other) { int64_t this_number = this->toNumber(); int64_t other_number = other->toNumber(); int64_t result = this_number - other_number; // Split into the 32 bit valu int32_t low32, high32; high32 = (uint64_t)result >> 32; low32 = (int32_t)result; return Long::fromBits(low32, high32); } Handle<Value> Long::GreatherThan(const Arguments &args) { HandleScope scope; if(args.Length() != 1 && !Long::HasInstance(args[0])) return VException("One argument of type Long required"); // Let's unpack the Long instance that contains the number in low_bits and high_bits form Long *current_long_obj = ObjectWrap::Unwrap<Long>(args.This()); // Unpack Long Local<Object> obj = args[0]->ToObject(); Long *long_obj = Long::Unwrap<Long>(obj); // Compare the longs bool comparision_result = current_long_obj->greaterThan(long_obj); scope.Close(Boolean::New(comparision_result)); } bool Long::greaterThan(Long *other) { return this->compare(other) > 0; } bool Long::greaterThanOrEqual(Long *other) { return this->compare(other) >= 0; } Handle<Value> Long::FromInt(const Arguments &args) { HandleScope scope; // Validate the arguments if(args.Length() != 1 && !args[0]->IsNumber()) return VException("One argument of type number required"); // Unwrap Number variable Local<Number> number = args[0]->ToNumber(); // Instantiate Long object and return Local<Value> argv[] = {number}; Local<Object> long_obj = constructor_template->GetFunction()->NewInstance(1, argv); return scope.Close(long_obj); } Long *Long::fromInt(int64_t value) { return new Long((value | 0), (value < 0 ? -1 : 0)); } Long *Long::fromBits(int32_t low_bits, int32_t high_bits) { return new Long(low_bits, high_bits); } Long *Long::fromNumber(double value) { // Ensure we have a valid ranged number if(std::isinf(value) || std::isnan(value)) { return Long::fromBits(0, 0); } else if(value <= BSON_INT64_MIN) { return Long::fromBits(0, 0x80000000 | 0); } else if(value >= BSON_INT64_MAX) { return Long::fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0); } else if(value < 0) { return Long::fromNumber(-value)->negate(); } else { int64_t int_value = (int64_t)value; return Long::fromBits((int_value % BSON_INT32_) | 0, (int_value / BSON_INT32_) | 0); } } Handle<Value> Long::FromNumber(const Arguments &args) { HandleScope scope; // Ensure that we have an parameter if(args.Length() != 1) return VException("One argument required - number."); if(!args[0]->IsNumber()) return VException("Arguments passed in must be numbers."); // Unpack the variable as a 64 bit integer int64_t value = args[0]->IntegerValue(); double double_value = args[0]->NumberValue(); // Ensure we have a valid ranged number if(std::isinf(double_value) || std::isnan(double_value)) { Local<Value> argv[] = {Integer::New(0), Integer::New(0)}; Local<Object> long_obj = constructor_template->GetFunction()->NewInstance(2, argv); return scope.Close(long_obj); } else if(double_value <= BSON_INT64_MIN) { Local<Value> argv[] = {Integer::New(0), Integer::New(0x80000000 | 0)}; Local<Object> long_obj = constructor_template->GetFunction()->NewInstance(2, argv); return scope.Close(long_obj); } else if(double_value >= BSON_INT64_MAX) { Local<Value> argv[] = {Integer::New(0xFFFFFFFF | 0), Integer::New(0x7FFFFFFF | 0)}; Local<Object> long_obj = constructor_template->GetFunction()->NewInstance(2, argv); return scope.Close(long_obj); } else if(double_value < 0) { Local<Value> argv[] = {Number::New(double_value)}; Local<Object> long_obj = constructor_template->GetFunction()->NewInstance(1, argv); return scope.Close(long_obj); } else { Local<Value> argv[] = {Integer::New((value % BSON_INT32_) | 0), Integer::New((value / BSON_INT32_) | 0)}; Local<Object> long_obj = constructor_template->GetFunction()->NewInstance(2, argv); return scope.Close(long_obj); } }
[ "kami@k5-storitve.net" ]
kami@k5-storitve.net
1163b58fc096af4d8bcac68ae1a020043f2761c2
a2f6660488fed555d720cc0df72ae2cfd526d0ec
/src/hssh/local_topological/area_detector.h
51937d1bcf5ab563d8833badcb565347f524f791
[ "MIT" ]
permissive
h2ssh/Vulcan
91a517fb89dbed8ec8c126ee8165dc2b2142896f
cc46ec79fea43227d578bee39cb4129ad9bb1603
refs/heads/master
2022-05-03T02:31:24.433878
2019-05-04T17:12:12
2019-05-04T17:12:12
184,834,960
6
11
NOASSERTION
2022-04-29T02:03:07
2019-05-04T00:21:10
C++
UTF-8
C++
false
false
5,830
h
/* Copyright (C) 2010-2019, The Regents of The University of Michigan. All rights reserved. This software was developed as part of the The Vulcan project in the Intelligent Robotics Lab under the direction of Benjamin Kuipers, kuipers@umich.edu. Use of this code is governed by an MIT-style License that can be found at "https://github.com/h2ssh/Vulcan". */ /** * \file area_detector.h * \author Collin Johnson * * Declaration of AreaDetector. */ #ifndef HSSH_LOCAL_TOPOLOGICAL_AREA_DETECTOR_H #define HSSH_LOCAL_TOPOLOGICAL_AREA_DETECTOR_H #include <hssh/local_topological/local_topo_map.h> #include <hssh/local_topological/error.h> #include <hssh/local_topological/event.h> #include <boost/optional.hpp> #include <memory> #include <cassert> namespace vulcan { namespace system { class DebugCommunicator; } namespace utils { class CommandLine; } namespace utils { class ConfigFile; } namespace hssh { // From local_metric class LocalPose; class LocalPerceptualMap; // From local_topological class AreaClassifier; class GatewayLocator; class VoronoiSkeletonBuilder; /** * AreaDetectorResult defines the result of the area detection process. The process is either sucessful, in which * case map != boost::none. Otherwise, result contains the error code for the problem that occurred during the * search for area labels. */ struct AreaDetectorResult { boost::optional<LocalTopoMap> map; LabelingError result; // For success, simply pass the proposals explicit AreaDetectorResult(const LocalTopoMap& map) : map(map) , result(LabelingError::success) { } // For errors, pass the error code. Error can't be success because there must be proposals! explicit AreaDetectorResult(LabelingError error) : map(boost::none) , result(error) { assert(result != LabelingError::success); } }; /** * AreaDetector handles the task of detecting and tracking areas in the LPM. The detector uses a visibility-based * gateway detector to create the initial parsing of the environment into areas. These proposed area are evaluted for * a couple conditions: * * 1) Does it sit at the intersection of paths? * 2) Is it more path-like or place-like? * * After the ambiguous regions are classified via a CSP and maximum likelihood classifier, the final areas are passed to * a tracker that builds consistent models of the areas for the duration of time in which some portion of the area * remains in the LPM. This tracking is needed to ensure that path segments are properly constructed, even in the event * that the start of the path segment scrolls out of the LPM before reaching the end. * * Because the areas in the map are tracked over time, calls to detectAreas() with new maps will build the representation * over time. As such, if the LPM changes in some dramatic way, say a log is restarted, then the areas should be reset * via resetAreas() to ensure that the newly detected areas are invalidated by pre-existing state information. */ class AreaDetector { public: /** * Constructor for AreaDetector. * * \param config ConfigFile containing the parameters to use for initializing the AreaDetector. * \param cmdLine CommandLine containing any provided command-line arguments * \param mapName Name of the map in which the robot is operating */ AreaDetector(const utils::ConfigFile& config, const utils::CommandLine& cmdLine, const std::string& mapName); /** * Destructor for AreaDetector. */ ~AreaDetector(void); /** * detectAreas parses an LPM into a set of distinct areas. The detected areas are integrated with the previous model * of the local topology to form a better model with the updated information. If previously detected areas no * longer have any boundaries within the LPM, then they are erased from the map. * * \param pose Pose of the robot within the LPM * \param map LPM of local surround * \return LocalTopoMap representation of the areas in the LPM. */ AreaDetectorResult detectAreas(const LocalPose& pose, const LocalPerceptualMap& map); /** * processAreaEvents provides feedback to the area detector on the set of local area events that occurred within the * LocalTopoMap created by the latest call to detect areas. * * \param events LocalAreaEvents that occurred within the current LocalTopoMap */ void processAreaEvents(const LocalAreaEventVec& events); /** * resetAreas resets the state of areas being tracked internally. The reset should happen if the map or environment * changes in some way such that any previously existing areas are invalidated. */ void resetAreas(void); /** * sendDebug has the detector send any internally generated debugging information. * * \param communicator Communicator for sending out the data */ void sendDebug(system::DebugCommunicator& communicator); private: std::unique_ptr<VoronoiSkeletonBuilder> skeletonBuilder_; std::unique_ptr<GatewayLocator> gatewayLocator_; std::unique_ptr<AreaClassifier> areaClassifier_; int32_t nextMapId_; bool shouldBuildSkeleton_; bool shouldComputeIsovists_; bool shouldFindGateways_; float maxIsovistRange_; int numIsovistRays_; int gwyFailCount_ = 0; std::vector<Point<float>> pointsOfInterest_; int64_t voronoiTotalTime_ = 0; int64_t gatewayTotalTime_ = 0; int64_t parsingTotalTime_ = 0; int64_t numUpdates_ = 0; // TODO: Create DurationStats class that keeps track of stats about elapsed time for compuation }; } // namespace hssh } // namespace vulcan #endif // HSSH_LOCAL_TOPOLOGICAL_AREA_DETECTOR_H
[ "collinej@umich.edu" ]
collinej@umich.edu
fbd49cc9f85f5a9620c2678c52335be6b9346433
9f8138ef7c6994521ab0142f961e245301bb5c0b
/chapter 12/ex12.2/str_blob.h
384214ee10e7c800dfebdb32b9654f6860c82f24
[]
no_license
OrigenesZhang/cppprimer
39f046748bf761b46cf8197e8abf4710eab06277
f2a9f0ec8940ff612eca165d7d2cbdec824661c0
refs/heads/master
2022-08-26T04:29:18.766139
2022-08-21T16:57:57
2022-08-21T16:57:57
117,434,632
1
0
null
null
null
null
UTF-8
C++
false
false
1,674
h
// // Created by Bin Zhang on 13/6/22. // #ifndef EX12_2_STR_BLOB_H #define EX12_2_STR_BLOB_H #include <vector> #include <string> #include <memory> #include <initializer_list> #include <stdexcept> class StrBlob { public: typedef std::vector<std::string>::size_type size_type; StrBlob(); StrBlob(std::initializer_list<std::string> il); [[nodiscard]] size_type size() const { return data->size(); }; [[nodiscard]] bool empty() const { return data->empty(); }; void push_back(const std::string &t) { data->push_back(t); }; void pop_back(); std::string &front(); [[nodiscard]] const std::string &front() const; std::string &back(); [[nodiscard]] const std::string &back() const; private: std::shared_ptr<std::vector<std::string>> data; void check(size_type i, const std::string &msg) const; }; StrBlob::StrBlob() : data(std::make_shared<std::vector<std::string>>()) {} StrBlob::StrBlob(std::initializer_list<std::string> il) : data(std::make_shared<std::vector<std::string>>(il)) {} void StrBlob::check(size_type i, const std::string &msg) const { if (i >= data->size()) throw std::out_of_range(msg); } std::string& StrBlob::front() { check(0, "front on empty str_blob"); return data->front(); } std::string& StrBlob::back() { check(0, "back on empty str_blob"); return data->back(); } void StrBlob::pop_back() { check(0, "pop_back on empty str_blob"); return data->pop_back(); } const std::string& StrBlob::front() const { check(0, "front on empty str_blob"); return data->front(); } const std::string& StrBlob::back() const { check(0, "back on empty str_blob"); return data->back(); } #endif //EX12_2_STR_BLOB_H
[ "zhangbin199807@gmail.com" ]
zhangbin199807@gmail.com
ac28a40a26ffe2b669d327f352c41021cf4fbec6
7db60111ea6fc001ee0c2c9fd00ec870bfc509d9
/src/yymm_svr/cfg.cpp
3abdbaec754ec0f03716789a1bae0802581d9b1c
[]
no_license
foolishhome/mms-svr
b740e66914b5f540aea958a8044e9228ecf95e40
6c77e43803e6ebab7af68ea6aa264dbee8c14d8e
refs/heads/master
2021-01-19T15:39:44.795950
2015-04-17T03:34:13
2015-04-17T03:34:13
34,094,664
0
0
null
null
null
null
UTF-8
C++
false
false
1,937
cpp
#include "stdafx.h" #include "tinyxml2/tinyxml2.h" #include "cfg.h" using namespace tinyxml2; CFG g_CFG; std::string GetCfg() { std::string path; char buffer[MAX_PATH]; #ifdef WIN32 GetModuleFileNameA(NULL, buffer, sizeof(buffer)); char * p = buffer + strlen(buffer); while(p != buffer && !strchr(p,'\\')) { p--; } *p = '\0'; #else getcwd(buffer, MAX_PATH); #endif path = buffer; path += "/config/cfg.xml"; return path; } bool ParseCfg() { tinyxml2::XMLDocument doc; if (XML_SUCCESS != doc.LoadFile(GetCfg().c_str())) return false; XMLElement* confElement = doc.FirstChildElement("conf"); if (!confElement) return false; XMLElement* serversElement = confElement->FirstChildElement("servers"); if (!serversElement) return false; XMLElement* mmsElement = serversElement->FirstChildElement("mms_service"); if (mmsElement) { g_CFG.server_name = mmsElement->FirstChildElement("name")->GetText(); mmsElement->FirstChildElement("port")->QueryUnsignedText(&g_CFG.port); mmsElement->FirstChildElement("mangport")->QueryUnsignedText(&g_CFG.mangport); mmsElement->FirstChildElement("workthreads")->QueryIntText(&g_CFG.workthreads); } XMLElement* redisElement = serversElement->FirstChildElement("redis"); if (redisElement) { g_CFG.redis_IP = redisElement->FirstChildElement("redis_Ip")->GetText(); redisElement->FirstChildElement("redis_Port")->QueryUnsignedText(&g_CFG.redis_Port); } XMLElement* mysqlElement = serversElement->FirstChildElement("mysql"); if (mysqlElement) { g_CFG.mysql_IP = mysqlElement->FirstChildElement("ip")->GetText(); mysqlElement->FirstChildElement("port")->QueryUnsignedText(&g_CFG.mysql_Port); g_CFG.mysql_user = mysqlElement->FirstChildElement("user")->GetText(); g_CFG.mysql_pwd = mysqlElement->FirstChildElement("pwd")->GetText(); g_CFG.mysql_DB = mysqlElement->FirstChildElement("db")->GetText(); } return true; }
[ "computer-boy@linjamestekiMacBook-Pro.local" ]
computer-boy@linjamestekiMacBook-Pro.local
59e4068aad83686a55e880e1675dfb4be61e9527
24b9e9f202be72b3e2a1f6e2033e1f914bfccb02
/Deious/다이나믹 프로그래밍/이동하기(11048).cpp
45e4b188bf45a225ef57ab247350519011638fb6
[]
no_license
as-is-as/Practice
9e50dd2721664ad007643ff7a9cb89e05770e784
940bb092bd67302fe84877d038e9820c06524326
refs/heads/master
2021-06-30T23:34:55.748236
2020-12-09T13:31:56
2020-12-09T13:31:56
202,956,649
3
3
null
2020-12-09T13:31:58
2019-08-18T03:46:10
C++
UTF-8
C++
false
false
623
cpp
#include <iostream> using namespace std; int candyMap[1001][1001]; int totalCandy[1001][1001]; int MaxCheck(int a, int b, int c) { return a > b ? (a > c ? a : c ) : b > c ? b : c; } int main() { ios_base::sync_with_stdio(false); cin.tie(0); int N, M; cin >> N >> M; for (int i = 1; i <= N; i++) { for (int j = 1; j <= M; j++) { cin >> candyMap[i][j]; } } for (int i = 1; i <= N; i++) { for (int j = 1; j <= M; j++) { totalCandy[i][j] = MaxCheck(totalCandy[i - 1][j], totalCandy[i - 1][j - 1], totalCandy[i][j - 1]) + candyMap[i][j]; } } cout << totalCandy[N][M] << "\n"; return 0; }
[ "gkstjddlekd@naver.com" ]
gkstjddlekd@naver.com
22d1ec235308a3bbd9e2e78c4c0d2cc9ff5ba24c
0c212767060623791f8ecc7dd172f8c9f853f443
/R2DEngine/R2DEngine/Collider.cpp
be684405a82a03e7026755d334a92e65fe0ae389
[]
no_license
rohunb/R2DEngine
bafcb00162eca57fc33c4da3b4a7edefc4a8bb5a
4001c76d1c8bd6ee0d8d63e5075fcb26c76c0543
refs/heads/master
2021-03-12T19:16:52.363914
2015-08-05T23:47:18
2015-08-05T23:47:18
33,456,403
2
2
null
null
null
null
UTF-8
C++
false
false
562
cpp
#include "Collider.h" #include "RDebug.h" using namespace rb; rb::Collider::Collider(Collider&& rhs) { *this = rhs; } Collider::ColliderType rb::Collider::GetType() const { return type; } Collider& rb::Collider::operator=(Collider&& rhs) { *this = rhs; return *this; } void rb::Collider::RegisterCollisionCallback(const CollisionCallback& _OnCollision) { assert(_OnCollision); this->OnCollision = _OnCollision; } void rb::Collider::OnCollisionEnter(Collider& otherCol) { //Debug::Log("collision enter"); if (OnCollision) OnCollision(otherCol); }
[ "rohunb@gmail.com" ]
rohunb@gmail.com
ab947aaddadd3f9cc74e79bbc2f19df5f35c59ae
db111ff94903f0b24658c328d93f5cc28b670b8d
/components/crash/core/app/fallback_crash_handler_win.cc
d26e387db8849568483fc99abb7acbc274727f79
[ "BSD-3-Clause" ]
permissive
nibilin33/chromium
21e505ab4c6dec858d3b0fe2bfbaf56d023d9f0d
3dea9ffa737bc9c9a9f58d4bab7074e3bc84f349
refs/heads/master
2023-01-16T10:54:57.353825
2020-04-02T04:24:11
2020-04-02T04:24:11
252,359,157
1
0
BSD-3-Clause
2020-04-02T04:57:37
2020-04-02T04:57:37
null
UTF-8
C++
false
false
5,812
cc
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/crash/core/app/fallback_crash_handler_win.h" #include <dbghelp.h> #include <psapi.h> #include <algorithm> #include <map> #include <memory> #include <string> #include <vector> #include "base/command_line.h" #include "base/files/file.h" #include "base/macros.h" #include "base/numerics/safe_conversions.h" #include "base/process/process_handle.h" #include "base/strings/string_number_conversions.h" #include "base/win/scoped_handle.h" #include "base/win/win_util.h" #include "components/crash/core/app/minidump_with_crashpad_info.h" namespace crash_reporter { namespace { void AcquireMemoryMetrics(const base::Process& process, StringStringMap* crash_keys) { // Grab the process private memory. // This is best effort, though really shouldn't ever fail. PROCESS_MEMORY_COUNTERS_EX process_memory = {sizeof(process_memory)}; if (GetProcessMemoryInfo( process.Handle(), reinterpret_cast<PROCESS_MEMORY_COUNTERS*>(&process_memory), sizeof(process_memory))) { // This is in units of bytes, re-scale to pages for consistency with // system metrics. const uint64_t kPageSize = 4096; crash_keys->insert(std::make_pair( "ProcessPrivateUsage", base::NumberToString(process_memory.PrivateUsage / kPageSize))); crash_keys->insert(std::make_pair( "ProcessPeakWorkingSetSize", base::NumberToString(process_memory.PeakWorkingSetSize / kPageSize))); crash_keys->insert(std::make_pair( "ProcessPeakPagefileUsage", base::NumberToString(process_memory.PeakPagefileUsage / kPageSize))); } // Grab system commit memory. Also best effort. PERFORMANCE_INFORMATION perf_info = {sizeof(perf_info)}; if (GetPerformanceInfo(&perf_info, sizeof(perf_info))) { // Record the remaining committable memory and the limit. This is in units // of system pages. crash_keys->insert(std::make_pair( "SystemCommitRemaining", base::NumberToString(perf_info.CommitLimit - perf_info.CommitTotal))); crash_keys->insert(std::make_pair( "SystemCommitLimit", base::NumberToString(perf_info.CommitLimit))); } } } // namespace FallbackCrashHandler::FallbackCrashHandler() : thread_id_(base::kInvalidThreadId), exception_ptrs_(0UL) {} FallbackCrashHandler::~FallbackCrashHandler() {} bool FallbackCrashHandler::ParseCommandLine(const base::CommandLine& cmd_line) { // Retrieve the handle to the process to dump. unsigned int uint_process; if (!base::StringToUint(cmd_line.GetSwitchValueASCII("process"), &uint_process)) { return false; } // Before taking ownership of the supposed handle, see whether it's really // a process handle. base::ProcessHandle process_handle = base::win::Uint32ToHandle(uint_process); if (base::GetProcId(process_handle) == base::kNullProcessId) return false; // Retrieve the thread id argument. unsigned int thread_id = 0; if (!base::StringToUint(cmd_line.GetSwitchValueASCII("thread"), &thread_id)) { return false; } thread_id_ = thread_id; // Retrieve the "exception-pointers" argument. uint64_t uint_exc_ptrs = 0; if (!base::StringToUint64(cmd_line.GetSwitchValueASCII("exception-pointers"), &uint_exc_ptrs)) { return false; } exception_ptrs_ = static_cast<uintptr_t>(uint_exc_ptrs); // Retrieve the "database" argument. database_dir_ = cmd_line.GetSwitchValuePath("database"); if (database_dir_.empty()) return false; // Everything checks out, take ownership of the process handle. process_ = base::Process(process_handle); return true; } bool FallbackCrashHandler::GenerateCrashDump(const std::string& product, const std::string& version, const std::string& channel, const std::string& process_type) { MINIDUMP_EXCEPTION_INFORMATION exc_info = {}; exc_info.ThreadId = thread_id_; exc_info.ExceptionPointers = reinterpret_cast<EXCEPTION_POINTERS*>(exception_ptrs_); exc_info.ClientPointers = TRUE; // ExceptionPointers in client. // Mandatory crash keys. These will be read by Crashpad and used as // http request parameters for the upload. Keys and values need to match // server side configuration. #if defined(ARCH_CPU_64_BITS) const char* platform = "Win64"; #else const char* platform = "Win32"; #endif std::map<std::string, std::string> crash_keys = {{"prod", product}, {"ver", version}, {"channel", channel}, {"plat", platform}, {"ptype", process_type}}; // Add memory metrics relating to system-wide and target process memory usage. AcquireMemoryMetrics(process_, &crash_keys); uint32_t minidump_type = MiniDumpWithUnloadedModules | MiniDumpWithProcessThreadData | MiniDumpWithFullMemoryInfo | MiniDumpWithThreadInfo; // Capture more detail for canary and dev channels. The prefix search caters // for the soon to be outdated "-m" suffixed multi-install channels. if (channel.find("canary") == 0 || channel.find("dev") == 0) minidump_type |= MiniDumpWithIndirectlyReferencedMemory; return DumpAndReportProcess(process_, minidump_type, &exc_info, crash_keys, database_dir_); } } // namespace crash_reporter
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
d908ca7b457e1254c4c3fd24fabbd21306a289a7
e8a3c0b3722cacdb99e15693bff0a4333b7ccf16
/Uva Oj/1237...expert enough.cpp
b01edf77e8417efefe5f8e540a78c9fc562e1d4b
[]
no_license
piyush1146115/Competitive-Programming
690f57acd374892791b16a08e14a686a225f73fa
66c975e0433f30539d826a4c2aa92970570b87bf
refs/heads/master
2023-08-18T03:04:24.680817
2023-08-12T19:15:51
2023-08-12T19:15:51
211,923,913
5
0
null
null
null
null
UTF-8
C++
false
false
1,012
cpp
#include<bits/stdc++.h> using namespace std; struct car{ char name[30]; long long int down, up; }c[10005]; int main() { freopen("input.txt", "r", stdin); long long test, j, k, n, m, data; int i; scanf("%lld", &test); while(test--){ scanf("%lld",&data); for(i = 0; i < data; i++){ scanf("%s", c[i].name); scanf("%lld %lld",&c[i].down ,&c[i].up); } /* for(i = 0; i < data; i++) printf("%s\n",c[i].name);*/ int q; cin >> q; while(q--){ scanf("%lld",&n); int cont = 0, ind; for(i = 0; i < data; i++){ if(n >= c[i].down && n <= c[i].up){ cont++; ind = i; } } if(cont == 1){ printf("%s\n",c[ind].name); } else printf("UNDETERMINED\n"); } if(test) printf("\n"); } return 0; }
[ "piyush123kantidas@gmail.com" ]
piyush123kantidas@gmail.com
19f08275b1ec17b395a45e1b4477044dd4d1739f
8380b5eb12e24692e97480bfa8939a199d067bce
/Carberp Botnet/source - absource/pro/all source/BJWJ/include/uriloader/nsIWebProgressListener2.h
de8777860dbec2a3826194219c34fe743c776b2e
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
RamadhanAmizudin/malware
788ee745b5bb23b980005c2af08f6cb8763981c2
62d0035db6bc9aa279b7c60250d439825ae65e41
refs/heads/master
2023-02-05T13:37:18.909646
2023-01-26T08:43:18
2023-01-26T08:43:18
53,407,812
873
291
null
2023-01-26T08:43:19
2016-03-08T11:44:21
C++
UTF-8
C++
false
false
7,390
h
/* * DO NOT EDIT. THIS FILE IS GENERATED FROM e:/builds/moz2_slave/mozilla-1.9.1-win32-xulrunner/build/uriloader/base/nsIWebProgressListener2.idl */ #ifndef __gen_nsIWebProgressListener2_h__ #define __gen_nsIWebProgressListener2_h__ #ifndef __gen_nsIWebProgressListener_h__ #include "nsIWebProgressListener.h" #endif /* For IDL files that don't want to include root IDL files. */ #ifndef NS_NO_VTABLE #define NS_NO_VTABLE #endif /* starting interface: nsIWebProgressListener2 */ #define NS_IWEBPROGRESSLISTENER2_IID_STR "dde39de0-e4e0-11da-8ad9-0800200c9a66" #define NS_IWEBPROGRESSLISTENER2_IID \ {0xdde39de0, 0xe4e0, 0x11da, \ { 0x8a, 0xd9, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66 }} /** * An extended version of nsIWebProgressListener. */ class NS_NO_VTABLE NS_SCRIPTABLE nsIWebProgressListener2 : public nsIWebProgressListener { public: NS_DECLARE_STATIC_IID_ACCESSOR(NS_IWEBPROGRESSLISTENER2_IID) /** * Notification that the progress has changed for one of the requests * associated with aWebProgress. Progress totals are reset to zero when all * requests in aWebProgress complete (corresponding to onStateChange being * called with aStateFlags including the STATE_STOP and STATE_IS_WINDOW * flags). * * This function is identical to nsIWebProgressListener::onProgressChange, * except that this function supports 64-bit values. * * @param aWebProgress * The nsIWebProgress instance that fired the notification. * @param aRequest * The nsIRequest that has new progress. * @param aCurSelfProgress * The current progress for aRequest. * @param aMaxSelfProgress * The maximum progress for aRequest. * @param aCurTotalProgress * The current progress for all requests associated with aWebProgress. * @param aMaxTotalProgress * The total progress for all requests associated with aWebProgress. * * NOTE: If any progress value is unknown, then its value is replaced with -1. * * @see nsIWebProgressListener2::onProgressChange64 */ /* void onProgressChange64 (in nsIWebProgress aWebProgress, in nsIRequest aRequest, in long long aCurSelfProgress, in long long aMaxSelfProgress, in long long aCurTotalProgress, in long long aMaxTotalProgress); */ NS_SCRIPTABLE NS_IMETHOD OnProgressChange64(nsIWebProgress *aWebProgress, nsIRequest *aRequest, PRInt64 aCurSelfProgress, PRInt64 aMaxSelfProgress, PRInt64 aCurTotalProgress, PRInt64 aMaxTotalProgress) = 0; /** * Notification that a refresh or redirect has been requested in aWebProgress * For example, via a <meta http-equiv="refresh"> or an HTTP Refresh: header * * @param aWebProgress * The nsIWebProgress instance that fired the notification. * @param aRefreshURI * The new URI that aWebProgress has requested redirecting to. * @param aMillis * The delay (in milliseconds) before refresh. * @param aSameURI * True if aWebProgress is requesting a refresh of the * current URI. * False if aWebProgress is requesting a redirection to * a different URI. * * @return True if the refresh may proceed. * False if the refresh should be aborted. */ /* boolean onRefreshAttempted (in nsIWebProgress aWebProgress, in nsIURI aRefreshURI, in long aMillis, in boolean aSameURI); */ NS_SCRIPTABLE NS_IMETHOD OnRefreshAttempted(nsIWebProgress *aWebProgress, nsIURI *aRefreshURI, PRInt32 aMillis, PRBool aSameURI, PRBool *_retval NS_OUTPARAM) = 0; }; NS_DEFINE_STATIC_IID_ACCESSOR(nsIWebProgressListener2, NS_IWEBPROGRESSLISTENER2_IID) /* Use this macro when declaring classes that implement this interface. */ #define NS_DECL_NSIWEBPROGRESSLISTENER2 \ NS_SCRIPTABLE NS_IMETHOD OnProgressChange64(nsIWebProgress *aWebProgress, nsIRequest *aRequest, PRInt64 aCurSelfProgress, PRInt64 aMaxSelfProgress, PRInt64 aCurTotalProgress, PRInt64 aMaxTotalProgress); \ NS_SCRIPTABLE NS_IMETHOD OnRefreshAttempted(nsIWebProgress *aWebProgress, nsIURI *aRefreshURI, PRInt32 aMillis, PRBool aSameURI, PRBool *_retval NS_OUTPARAM); /* Use this macro to declare functions that forward the behavior of this interface to another object. */ #define NS_FORWARD_NSIWEBPROGRESSLISTENER2(_to) \ NS_SCRIPTABLE NS_IMETHOD OnProgressChange64(nsIWebProgress *aWebProgress, nsIRequest *aRequest, PRInt64 aCurSelfProgress, PRInt64 aMaxSelfProgress, PRInt64 aCurTotalProgress, PRInt64 aMaxTotalProgress) { return _to OnProgressChange64(aWebProgress, aRequest, aCurSelfProgress, aMaxSelfProgress, aCurTotalProgress, aMaxTotalProgress); } \ NS_SCRIPTABLE NS_IMETHOD OnRefreshAttempted(nsIWebProgress *aWebProgress, nsIURI *aRefreshURI, PRInt32 aMillis, PRBool aSameURI, PRBool *_retval NS_OUTPARAM) { return _to OnRefreshAttempted(aWebProgress, aRefreshURI, aMillis, aSameURI, _retval); } /* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */ #define NS_FORWARD_SAFE_NSIWEBPROGRESSLISTENER2(_to) \ NS_SCRIPTABLE NS_IMETHOD OnProgressChange64(nsIWebProgress *aWebProgress, nsIRequest *aRequest, PRInt64 aCurSelfProgress, PRInt64 aMaxSelfProgress, PRInt64 aCurTotalProgress, PRInt64 aMaxTotalProgress) { return !_to ? NS_ERROR_NULL_POINTER : _to->OnProgressChange64(aWebProgress, aRequest, aCurSelfProgress, aMaxSelfProgress, aCurTotalProgress, aMaxTotalProgress); } \ NS_SCRIPTABLE NS_IMETHOD OnRefreshAttempted(nsIWebProgress *aWebProgress, nsIURI *aRefreshURI, PRInt32 aMillis, PRBool aSameURI, PRBool *_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->OnRefreshAttempted(aWebProgress, aRefreshURI, aMillis, aSameURI, _retval); } #if 0 /* Use the code below as a template for the implementation class for this interface. */ /* Header file */ class nsWebProgressListener2 : public nsIWebProgressListener2 { public: NS_DECL_ISUPPORTS NS_DECL_NSIWEBPROGRESSLISTENER2 nsWebProgressListener2(); private: ~nsWebProgressListener2(); protected: /* additional members */ }; /* Implementation file */ NS_IMPL_ISUPPORTS1(nsWebProgressListener2, nsIWebProgressListener2) nsWebProgressListener2::nsWebProgressListener2() { /* member initializers and constructor code */ } nsWebProgressListener2::~nsWebProgressListener2() { /* destructor code */ } /* void onProgressChange64 (in nsIWebProgress aWebProgress, in nsIRequest aRequest, in long long aCurSelfProgress, in long long aMaxSelfProgress, in long long aCurTotalProgress, in long long aMaxTotalProgress); */ NS_IMETHODIMP nsWebProgressListener2::OnProgressChange64(nsIWebProgress *aWebProgress, nsIRequest *aRequest, PRInt64 aCurSelfProgress, PRInt64 aMaxSelfProgress, PRInt64 aCurTotalProgress, PRInt64 aMaxTotalProgress) { return NS_ERROR_NOT_IMPLEMENTED; } /* boolean onRefreshAttempted (in nsIWebProgress aWebProgress, in nsIURI aRefreshURI, in long aMillis, in boolean aSameURI); */ NS_IMETHODIMP nsWebProgressListener2::OnRefreshAttempted(nsIWebProgress *aWebProgress, nsIURI *aRefreshURI, PRInt32 aMillis, PRBool aSameURI, PRBool *_retval NS_OUTPARAM) { return NS_ERROR_NOT_IMPLEMENTED; } /* End of implementation class template. */ #endif #endif /* __gen_nsIWebProgressListener2_h__ */
[ "fdiskyou@users.noreply.github.com" ]
fdiskyou@users.noreply.github.com
e4169ac66c4a55dcfc37afcbcdab9308eb79c0ca
f9878ed3b5cc55b1951a7e96b7ef65e605a98a1d
/pal/net/ip/socket_option
388339cca367351e01daea5ee2128452c64e4d01
[ "MIT" ]
permissive
svens/pal
f6064877421df42d135b75bf105b708ba7f0065b
f84e64eabe1ad7ed872bb27dbc132b8f763251f2
refs/heads/master
2023-08-03T06:05:34.217203
2022-09-16T19:04:32
2022-09-16T19:04:32
251,578,528
0
0
MIT
2023-03-21T18:08:26
2020-03-31T11:06:12
C++
UTF-8
C++
false
false
514
#pragma once // -*- C++ -*- /** * \file pal/net/ip/socket_option * Internet protocol specific socket options */ #include <pal/__bits/lib> #include <pal/net/socket_option> __pal_begin namespace net::ip { /** * \ingroup socket_option * Determines whether socket created for an IPv6 protocol is restricted to * IPv6 communication only. Initial value for this option depends on operating * system. */ using v6_only = socket_option<bool, IPPROTO_IPV6, IPV6_V6ONLY>; } // namespace net::ip __pal_end
[ "sven@alt.ee" ]
sven@alt.ee
cdca5f153a35e4d5b1b3d86bc005f6e260b161fb
8be7a7efbaa6a4034e435bc8221cc5fb54f8067c
/leocad-18.01/common/lc_global.h
002875bfbd31ad575e84f217fd50cff09be5d55c
[]
no_license
RinatB2017/Qt_github
9faaa54e3c8e7a5f84f742d49f4559dcdd5622dd
5177baa735c0140d39d8b0e84fc6af3dcb581abd
refs/heads/master
2023-08-08T08:36:17.664868
2023-07-28T07:39:35
2023-07-28T07:39:35
163,097,727
2
1
null
null
null
null
UTF-8
C++
false
false
1,314
h
#ifndef LC_GLOBAL_H #define LC_GLOBAL_H #include <QtGlobal> #include <QWidget> #include <QtOpenGL> #include <QGLWidget> #include <QtGui> #include <QPrinter> #if !defined(EGL_VERSION_1_0) && !defined(GL_ES_VERSION_2_0) && !defined(GL_ES_VERSION_3_0) && !defined(QT_OPENGL_ES) #undef GL_LINES_ADJACENCY_EXT #undef GL_LINE_STRIP_ADJACENCY_EXT #undef GL_TRIANGLES_ADJACENCY_EXT #undef GL_TRIANGLE_STRIP_ADJACENCY_EXT #include "lc_glext.h" #else #define LC_OPENGLES 1 #endif // Old defines and declarations. #define LC_MAXPATH 1024 #ifdef Q_OS_WIN char* strcasestr(const char *s, const char *find); #else char* strupr(char* string); char* strlwr(char* string); #endif // Version number. #define LC_VERSION_MAJOR 18 #define LC_VERSION_MINOR 01 #define LC_VERSION_PATCH 0 #define LC_VERSION_TEXT "18.01" // Forward declarations. class Project; class lcModel; class lcObject; class lcPiece; class lcCamera; class lcLight; class lcGroup; class PieceInfo; typedef std::map<const PieceInfo*, std::map<int, int>> lcPartsList; struct lcModelPartsEntry; class lcVector2; class lcVector3; class lcVector4; class lcMatrix33; class lcMatrix44; class lcContext; class lcMesh; struct lcMeshSection; struct lcRenderMesh; class lcTexture; class lcScene; class lcFile; class lcMemFile; class lcDiskFile; #endif // LC_GLOBAL_H
[ "tux4096@gmail.com" ]
tux4096@gmail.com
e380af1478236782a78986395434546ed04665b3
352abb7b0c7cada5248183549d24e1619bbe4dc5
/Arbi6/Arbi6/arbi/commodity.cpp
16a1f832258a3f346b7c370a50f45040ea1a153a
[]
no_license
15831944/arbi6
048c181196305c483e94729356c3d48c57eddb62
86a8e673ef2b9e79c39fa1667e52ee2ffdc4f082
refs/heads/master
2023-03-19T11:56:24.148575
2015-07-13T08:06:11
2015-07-13T08:06:11
null
0
0
null
null
null
null
GB18030
C++
false
false
16,535
cpp
// commodity.cpp: implementation of the Commodity class. // ////////////////////////////////////////////////////////////////////// #include "commodity.h" #include "ArbitrageComparablePriceExpression.h" #include "../LogStore.h" #include <assert.h> #include <fstream> ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// Commodity::Commodity() { memset(debug,0,16); sprintf_s(debug,16,"Commodity_"); } Commodity:: Commodity(string name, enum Market market, double increment) { memset(debug,0,16); sprintf_s(debug,16,"Commodity"); this->name = name; this->market = market; this->increment = increment; this->exchange = Exchange::getInstance(market); assert(exchange != NULL); } Commodity::~Commodity() { } bool Commodity::inited = false; list<Commodity*> Commodity::commodities; void Commodity::initAsNeccissary() { if(inited) return; TRACE_LOG("Commodity::initAsNeccissary"); //inspect why list's head object was flushed. //p = new char[1]; //add heap protection. //TODO: add all commodities addCommodity("IF", ZHONGJIN, 0.2); ArbitrageComparablePriceExpression::add("IF", "510300", "P * 1 * 1 + 0"); addCommodity("IH", ZHONGJIN, 0.2); ArbitrageComparablePriceExpression::add("IH", "510050", "P * 1 * 1 + 0"); addCommodity("IC", ZHONGJIN, 0.2); ArbitrageComparablePriceExpression::add("IC", "510500", "P * 1 * 1 + 0"); //ArbitrageComparablePriceExpression::add("IF", "rb", "P * 300 * 1 + 0"); //addCommodity("TF", ZHONGJIN, 0.01); addCommodity("TF", ZHONGJIN, 0.002); addCommodity("rb", SHANG_HAI, 1.0); //螺纹钢 RB 10吨/手 1元/吨 ArbitrageComparablePriceExpression::add("rb", "j", "P * 40 * 1 + 0"); ArbitrageComparablePriceExpression::add("rb", "i", "P * 10 * 5 + 0"); ArbitrageComparablePriceExpression::add("rb", "ru", "P * 6 * 1 + 0"); ArbitrageComparablePriceExpression::add("rb", "ag", "P * 3 * 10 + 0"); ArbitrageComparablePriceExpression::add("rb", "SI", "P * 150 * 1 + 0"); ArbitrageComparablePriceExpression::add("rb", "FG", "P * 10 * 5 + 0"); ArbitrageComparablePriceExpression::add("rb", "bb", "P * 2 * 10 + 0"); ArbitrageComparablePriceExpression::add("rb", "510500", "P * 1 * 1 + 0"); ArbitrageComparablePriceExpression::add("rb", "510300", "P * 1 * 1 + 0"); ArbitrageComparablePriceExpression::add("rb", "510050", "P * 1 * 1 + 0"); addCommodity("pb", SHANG_HAI, 5.0); //铅 PB 10吨/手 5元/吨 //ArbitrageComparablePriceExpression::add("rb", "j", "P * 50 * 1 + 0"); addCommodity("ru", SHANG_HAI, 5.0); //橡胶 RU 5吨/手 5元/吨 ArbitrageComparablePriceExpression::add("ru", "rb", "P * 1 * 1 + 0"); ArbitrageComparablePriceExpression::add("ru", "bb", "P * 10 * 1 + 0"); //addCommodity("wr", SHANG_HAI, 1.0); //线材 WR 10吨/手 1元/吨 addCommodity("cu", SHANG_HAI, 10.0); //阴极铜 CU 5吨/手 10元/吨 ArbitrageComparablePriceExpression::add("cu", "LCA", "P * 20 * 1 + 0"); ArbitrageComparablePriceExpression::add("cu", "HG", "P * 20 * 1 + 0"); ArbitrageComparablePriceExpression::add("cu", "bb", "P * 5 * 1 + 0"); addCommodity("bu", SHANG_HAI, 2.0); //沥青 bu 10吨/手 2元/吨 addCommodity("al", SHANG_HAI, 5.0); //铝 AL 5吨/手 5元/吨 ArbitrageComparablePriceExpression::add("al", "LAH", "P * 20 * 1 + 0"); //ArbitrageComparablePriceExpression::add("al", "LAH", "P * 25 * 1 + 0"); //ArbitrageComparablePriceExpression::add("al", "LAH", "P * 25 * 1 + 0"); addCommodity("zn", SHANG_HAI, 5.0); //锌 ZN 5吨/手 5元/吨 ArbitrageComparablePriceExpression::add("zn", "LZS", "P * 20 * 1 + 0"); addCommodity("au", SHANG_HAI, 0.05); //黄金 AU 1000克/手 0.01元/克 addCommodity("ag", SHANG_HAI, 1.0); //白银 ag 15千克/手 1元/千克 ArbitrageComparablePriceExpression::add("ag", "SI", "P * 1 * 1 + 0"); ArbitrageComparablePriceExpression::add("ag", "rb", "P * 2 * 15 + 0"); //addCommodity("fu", SHANG_HAI, 1.0); //燃料油 FU 10吨/手 1元/吨 addCommodity("a", DA_LIAN, 1.0); //黄大豆1号 A 10吨/手 1元/吨 ArbitrageComparablePriceExpression::add("a", "m", "P * 1 * 10 + 0"); //addCommodity("b", DA_LIAN, 1.0); //黄大豆2号 B 10吨/手 1元/吨 addCommodity("m", DA_LIAN, 1.0); //豆粕 M 10吨/手 1元/吨 ArbitrageComparablePriceExpression::add("m", "ZS", "P * 140 * 1 + 0"); //ArbitrageComparablePriceExpression::add("m", "y", "P * 1 * 5 + 0"); //ArbitrageComparablePriceExpression::add("m", "y", "P * 1 * 3 + 0"); ArbitrageComparablePriceExpression::add("m", "y", "P * 1 * 20 + 0"); //ArbitrageComparablePriceExpression::add("m", "j", "P * 1 * 50 + 0"); ArbitrageComparablePriceExpression::add("m", "p", "P * 1 * 20 + 0"); ArbitrageComparablePriceExpression::add("m", "ZC", "P * 1 * 70 + 0"); ArbitrageComparablePriceExpression::add("m", "ZM", "P * 90 * 1 + 0"); ArbitrageComparablePriceExpression::add("m", "a", "P * 1 * 13 + 0"); ArbitrageComparablePriceExpression::add("m", "OI", "P * 1 * 2 + 0"); //yue //ArbitrageComparablePriceExpression::add("m", "RM", "P * 1 * 10 + 0"); addCommodity("fb", DA_LIAN, 0.05); ArbitrageComparablePriceExpression::add("fb", "FG", "P * 1 * 1500 + 0"); ArbitrageComparablePriceExpression::add("fb", "bb", "P * 500 * 2 + 0"); addCommodity("bb", DA_LIAN, 0.05); ArbitrageComparablePriceExpression::add("bb", "TA", "P * 500 * 1 + 0"); ArbitrageComparablePriceExpression::add("bb", "rb", "P * 500 * 1 + 0"); ArbitrageComparablePriceExpression::add("bb", "cu", "P * 500 * 4 + 0"); ArbitrageComparablePriceExpression::add("bb", "fb", "P * 500 * 1 + 0"); ArbitrageComparablePriceExpression::add("bb", "y", "P * 500 * 1 + 0"); ArbitrageComparablePriceExpression::add("bb", "TC", "P * 500 * 3 + 0"); ArbitrageComparablePriceExpression::add("bb", "ru", "P * 500 * 2 + 0"); //addCommodity("l", DA_LIAN, 5.0); //线型低密度聚乙烯 L 5吨/手 5元/吨 addCommodity("y", DA_LIAN, 2.0); //豆油 Y 10吨/手 2元/吨 //ArbitrageComparablePriceExpression::add("y", "p", "P * 1 * 100 + 0"); //ArbitrageComparablePriceExpression::add("y", "m", "P * 1 * 1 + 0"); ArbitrageComparablePriceExpression::add("y", "m", "P * 1 * 10 + 0"); //ArbitrageComparablePriceExpression::add("y", "p", "P * 1 * 1 + 0"); ArbitrageComparablePriceExpression::add("y", "KPO", "P * 1 * 15 + 0"); ArbitrageComparablePriceExpression::add("y", "GKPO", "P * 1 * 15 + 0"); ArbitrageComparablePriceExpression::add("y", "OI", "P * 1 * 1 + 0"); ArbitrageComparablePriceExpression::add("y", "RM", "P * 1 * 10 + 0"); ArbitrageComparablePriceExpression::add("y", "bb", "P * 10 * 1 + 0"); ArbitrageComparablePriceExpression::add("y", "FG", "P * 10 * 1 + 0"); ArbitrageComparablePriceExpression::add("y", "jd", "P * 10 * 1 + 0"); addCommodity("c", DA_LIAN, 1.0); //玉米 C 10吨/手 1元/吨 addCommodity("p", DA_LIAN, 2.0); //棕榈油 P 10吨/手 2元/吨 //ArbitrageComparablePriceExpression::add("p", "y", "P * 1 * 130 + 0"); ArbitrageComparablePriceExpression::add("p", "m", "P * 1 * 10 + 0"); ArbitrageComparablePriceExpression::add("p", "RM", "P * 1 * 1 + 0"); ArbitrageComparablePriceExpression::add("p", "KPO", "P * 1 * 20 + 0"); ArbitrageComparablePriceExpression::add("p", "GKPO", "P * 1 * 20 + 0"); ArbitrageComparablePriceExpression::add("p", "ZS", "P * 1 * 60 + 0"); ArbitrageComparablePriceExpression::add("p", "OI", "P * 6 * 10 + 0"); //ArbitrageComparablePriceExpression::add("p", "y", "P * 1 * 1 + 0"); addCommodity("jm", DA_LIAN, 0.5); ArbitrageComparablePriceExpression::add("jm", "jm", "P * 1 * 1 + 0"); ArbitrageComparablePriceExpression::add("jm", "j", "P * 2 * 60 + 0"); ArbitrageComparablePriceExpression::add("jm", "FG", "P * 60 * 2 + 0"); ArbitrageComparablePriceExpression::add("jm", "i", "P * 240 * 1 + 0"); ArbitrageComparablePriceExpression::add("jm", "TC", "P * 2 * 60 + 0"); addCommodity("TC", ZHENG_ZHOU,0.2); ArbitrageComparablePriceExpression::add("TC", "j", "P * 2 * 1 + 0"); ArbitrageComparablePriceExpression::add("TC", "jm", "P * 1 * 200 + 0"); ArbitrageComparablePriceExpression::add("TC", "FG", "P * 1 * 200 + 0"); ArbitrageComparablePriceExpression::add("TC", "bb", "P * 2 * 200 + 0"); //addCommodity("v", DA_LIAN, 5.0); //聚氯乙烯 V 5吨/手 5元/吨 addCommodity("jd", DA_LIAN,1.0); //egg ArbitrageComparablePriceExpression::add("jd", "OI", "P * 10 * 2 + 0"); ArbitrageComparablePriceExpression::add("jd", "y", "P * 10 * 2 + 0"); addCommodity("j", DA_LIAN, 0.5); //焦碳 ArbitrageComparablePriceExpression::add("j", "TC", "P * 1 * 1 + 0"); ArbitrageComparablePriceExpression::add("j", "rb", "P * 100 * 1 + 0"); ArbitrageComparablePriceExpression::add("j", "jm", "P * 1 * 100 + 0"); //ArbitrageComparablePriceExpression::add("j", "m", "P * 1 * 100 + 0"); ArbitrageComparablePriceExpression::add("j", "i", "P * 1 * 100 + 0"); ArbitrageComparablePriceExpression::add("j", "TA", "P * 1 * 100 + 0"); //ArbitrageComparablePriceExpression::add("j", "i", "P * 1 * 200 + 0"); addCommodity("i", DA_LIAN, 0.5); //铁矿石 ArbitrageComparablePriceExpression::add("i", "rb", "P * 100 * 3 + 0"); ArbitrageComparablePriceExpression::add("i", "j", "P * 100 * 2 + 0"); ArbitrageComparablePriceExpression::add("i", "jm", "P * 100 * 3 + 0"); //ArbitrageComparablePriceExpression::add("i", "j", "P * 1 * 300 + 0"); addCommodity("pp", DA_LIAN,1.0); //egg ArbitrageComparablePriceExpression::add("pp", "TA", "P * 5 * 3 + 0"); ArbitrageComparablePriceExpression::add("pp", "MA", "P * 5 * 2 + 0"); addCommodity("hc", DA_LIAN,2.0); //egg //addCommodity("WT", ZHENG_ZHOU, 1.0); //硬麦 WT 10吨/手 1元/吨 addCommodity("WS", ZHENG_ZHOU, 1.0); //强麦 WS 10吨/手 1元/吨 addCommodity("CF", ZHENG_ZHOU, 5.0); //一号棉 CF 5吨/手 5元/吨 ArbitrageComparablePriceExpression::add("CF", "CT", "P * 5 * 4 + 0"); ArbitrageComparablePriceExpression::add("CF", "TA", "P * 5 * 1 + 0"); addCommodity("RM", ZHENG_ZHOU, 1.0); //菜粕 10吨/手 10元/吨 ArbitrageComparablePriceExpression::add("RM", "p", "P * 1 * 2 + 0"); ArbitrageComparablePriceExpression::add("RM", "y", "P * 1 * 30 + 0"); ArbitrageComparablePriceExpression::add("RM", "OI", "P * 1 * 30 + 0"); addCommodity("RS", ZHENG_ZHOU, 1.0); //菜籽 10吨/手 10元/吨 addCommodity("FG", ZHENG_ZHOU, 1.0); //玻璃 20吨/手 1元/吨 //ArbitrageComparablePriceExpression::add("FG", "FG", "P * 1 * 1 + 0"); ArbitrageComparablePriceExpression::add("FG", "rb", "P * 20 * 7 + 0"); ArbitrageComparablePriceExpression::add("FG", "fb", "P * 1 * 80 + 0"); ArbitrageComparablePriceExpression::add("FG", "jm", "P * 5 * 20 + 0"); ArbitrageComparablePriceExpression::add("FG", "y", "P * 20 * 3 + 0"); ArbitrageComparablePriceExpression::add("FG", "OI", "P * 20 * 3 + 0"); ArbitrageComparablePriceExpression::add("FG", "TC", "P * 20 * 5 + 0"); addCommodity("pp", DA_LIAN, 1.0); //PP SR 10吨/手 1元/吨 addCommodity("MA", ZHENG_ZHOU, 1.0); //甲醇 SR 10吨/手 1元/吨 addCommodity("ME", ZHENG_ZHOU, 1.0); //甲醇 SR 10吨/手 1元/吨 ArbitrageComparablePriceExpression::add("ME", "pp", "P * 2 * 50 + 0"); ArbitrageComparablePriceExpression::add("ME", "TA", "P * 1 * 50 + 0"); ArbitrageComparablePriceExpression::add("pp", "ME", "P * 5 * 5 + 0"); addCommodity("SR", ZHENG_ZHOU, 1.0); //白糖 SR 10吨/手 1元/吨 ArbitrageComparablePriceExpression::add("SR", "SB", "P * 1 * 35 + 0"); addCommodity("SF", ZHENG_ZHOU, 2.0); //硅铁 SF 5吨/手 2元/吨 addCommodity("SM", ZHENG_ZHOU, 2.0); //锰硅 SM 5吨/手 2元/吨 addCommodity("TA", ZHENG_ZHOU, 2.0); //PTA TA 5吨/手 2元/吨 //ArbitrageComparablePriceExpression::add("TA", "CL", "P * 75 * 1 + 0"); ArbitrageComparablePriceExpression::add("TA", "bb", "P * 2 * 5 + 0"); ArbitrageComparablePriceExpression::add("TA", "CF", "P * 10 * 1 + 0"); //ArbitrageComparablePriceExpression::add("TA", "CL", "P * 80 * 1 + 0"); ArbitrageComparablePriceExpression::add("TA", "CL", "P * 85 * 1 + 0"); //ArbitrageComparablePriceExpression::add("TA", "CL", "P * 85 * 1 + 0"); //ArbitrageComparablePriceExpression::add("TA", "CL", "P * 90 * 1 + 0"); //ArbitrageComparablePriceExpression::add("TA", "rb", "P * 5 * 34 + 0"); ArbitrageComparablePriceExpression::add("TA", "l", "P * 5 * 2 + 0"); ArbitrageComparablePriceExpression::add("TA", "pp", "P * 5 * 5 + 0"); ArbitrageComparablePriceExpression::add("TA", "ME", "P * 5 * 4 + 0"); ArbitrageComparablePriceExpression::add("TA", "MA", "P * 5 * 1 + 0"); ArbitrageComparablePriceExpression::add("TA", "j", "P * 5 * 4 + 0"); addCommodity("MA", ZHENG_ZHOU, 1.0); //PTA TA 5吨/手 2元/吨 ArbitrageComparablePriceExpression::add("MA", "TA", "P * 10 * 1 + 0"); ArbitrageComparablePriceExpression::add("MA", "pp", "P * 10 * 3 + 0"); addCommodity("l", DA_LIAN,5.0); //塑料 ArbitrageComparablePriceExpression::add("l", "TA", "P * 5 * 1 + 0"); //addCommodity("RO", ZHENG_ZHOU, 2.0); //菜子油 RO 5吨/手 2元/吨 //addCommodity("ER", ZHENG_ZHOU, 1.0); //早籼稻 ER 10吨/手 1元/吨 addCommodity("OI", ZHENG_ZHOU, 2.0); ArbitrageComparablePriceExpression::add("OI", "y", "P * 1 * 1 + 0"); //ArbitrageComparablePriceExpression::add("OI", "p", "P * 1 * 3 + 0"); ArbitrageComparablePriceExpression::add("OI", "m", "P * 1 * 1 + 0"); ArbitrageComparablePriceExpression::add("OI", "RM", "P * 1 * 10 + 0"); ArbitrageComparablePriceExpression::add("OI", "FG", "P * 1 * 10 + 0"); ArbitrageComparablePriceExpression::add("OI", "jd", "P * 1 * 10 + 0"); ArbitrageComparablePriceExpression::add("OI", "p", "P * 5 * 10 + 0"); //addCommodity("ZW", CBOT, ); //美小麦 addCommodity("ZS", CBOT,0.25); //美大豆 ArbitrageComparablePriceExpression::add("ZS", "ZC", "P * 50 * 1 + 0"); ArbitrageComparablePriceExpression::add("ZS", "m", "P * 50 * 6.25 + 0"); ArbitrageComparablePriceExpression::add("ZS", "p", "P * 50 * 6.25 + 0"); addCommodity("510050", SH,0.001); //上证50 ArbitrageComparablePriceExpression::add("510050", "IH", "P * 1000 * 1 + 0"); ArbitrageComparablePriceExpression::add("510050", "rb", "P * 1000 * 1 + 0"); addCommodity("510500", SH,0.001); //中证500 ArbitrageComparablePriceExpression::add("510500", "IC", "P * 1000 * 1 + 0"); ArbitrageComparablePriceExpression::add("510500", "rb", "P * 1000 * 1 + 0"); addCommodity("510300", SH,0.001); //沪深300 ArbitrageComparablePriceExpression::add("510300", "IF", "P * 1000 * 1 + 0"); ArbitrageComparablePriceExpression::add("510300", "rb", "P * 1000 * 1 + 0"); inited = true; } void Commodity::addCommodity(string name, enum Market market, double increment) { commodities.push_back(new Commodity(name, market, increment)); } Commodity * Commodity::get(string name) { return findFor(name); } bool startWith(const char * s1, const char * s2) { assert(strlen(s1) < 1000); assert(strlen(s2) < 1000); char string1[1000]; char string2[1000]; strcpy_s(string1, s1); strcpy_s(string2, s2); char * cp1 = string1; char * cp2 = string2; while(*cp2 != '\0') { if (*cp1 == *cp2) { cp1++; cp2++; } else { return false; } } return true; } Commodity * Commodity::findFor(string contract) { initAsNeccissary(); list<Commodity *>::iterator it; for ( it = commodities.begin(); it != commodities.end(); it++ ) { if (startWith(contract.c_str(), (*it)->name.c_str())) return *it; } TRACE_LOG("commodities.size = %d", commodities.size()); TRACE_LOG("Unknown Commodity for %s\n", contract.c_str()); for ( it = commodities.begin(); it != commodities.end(); it++ ) { TRACE_LOG("%p %s ",(*it),(*it)->name.c_str()); } assert(false); exit(1); return NULL; } double Commodity::calcArbitrageComparablePriceFor(double p, Commodity * comparedCommodity) { ArbitrageComparablePriceExpression * exp = ArbitrageComparablePriceExpression::find(this->name, comparedCommodity->name); return exp->getValueFor(p); } bool Commodity::isDomestic() { if(market == SHANG_HAI || market == ZHENG_ZHOU || market == DA_LIAN || market == ZHONGJIN) return true; return false; } bool Commodity::isOversea() { return !isDomestic(); } string Commodity::getName() { return name; } bool Commodity::inTrading(time_t t) { return this->exchange->inTrading(t); } char Commodity::getExchangeNumberForYiSheng() { switch (market) { case SHANG_HAI: return '3'; case ZHENG_ZHOU : return '1'; case DA_LIAN : return '2'; case ZHONGJIN : return '5'; default: return '0'; } }
[ "sunhao@sanss.com" ]
sunhao@sanss.com
7c4234e273a7f36081611026da3eeb51fe2046de
c4248cf9ba14916500ccf6227e35db2a9744dde9
/main.cpp
ab57e25aa17123f56f1b5e950a84857a59614a5d
[]
no_license
pencilmonster/Remuxer
57c7bc6fb3266405608986c330830624a4221db2
e71d34a3f2b44e833c83800f622c2cd38e946fc1
refs/heads/master
2021-01-19T08:32:42.123576
2017-04-08T15:56:10
2017-04-08T15:56:10
87,644,243
1
0
null
null
null
null
UTF-8
C++
false
false
249
cpp
#include "dialog.h" #include <QApplication> #include "ffmpeg.h" int main(int argc, char *argv[]) { avcodec_register_all(); av_register_all(); QApplication a(argc, argv); Dialog w; w.show(); return a.exec(); }
[ "775848471@qq.com" ]
775848471@qq.com
4e282b56cdd6259b0a1c6ee0d5bace8e829c4cd4
d5e7be201e43daeeb159b00e5d279445ffaa44b2
/APIs/vcppTestAPIs/vcppTestAPIs/vcppTestAPIs.cpp
faee28c7b080f9fb0f20a00a017c9ee4646b2a60
[]
no_license
shounakG/easyhci
0d952adebd7bd62a53941b1908ec73d4f72c36ba
b51c34bc95992274b151e96eb85ccc553f4d448c
refs/heads/master
2021-01-20T21:29:47.680363
2019-11-01T02:12:16
2019-11-01T02:12:16
50,868,748
0
0
null
2016-02-01T20:29:40
2016-02-01T20:29:39
null
UTF-8
C++
false
false
910
cpp
// vcppTestAPIs.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> #include <Windows.h> #using "SwitchWindows.dll" using namespace SwitchWindows; using namespace std; using namespace AllExplorerWindowOperations; using namespace System; using namespace MiscellaniousAPI; int _tmain(int argc, _TCHAR* argv[]) { /*int switchProc; switchwin^ nwin = gcnew switchwin(); nwin->procArray = nwin->getAllWindowNames(); for(int i=0 ; i< nwin->proNum ; i++) printf("%d. %s\n",i+1,nwin->procArray[i].prName); for(int i=0;; i++) { if(i==nwin->proNum-1) i=0; nwin->switchWindow(i); printf("Continue?"); scanf("%d",&switchProc); if(switchProc==0) break; }*/ clsMisc^ nmisc = gcnew clsMisc(); IntPtr hwnd(FindWindow(NULL,TEXT("Calculator"))); nmisc->muteUnmute(hwnd); getchar(); return 0; }
[ "the.reviews92@gmail.com" ]
the.reviews92@gmail.com
9eaeff48e5f29da1be1cf23c8009ed6d8c094b35
7e929de29b66e99fd2003d1cd4ea7d2eac227f80
/포켓몬비행슈팅게임/Pokemon_Shooting/FireBird.h
8709c6bab8eaa12a0beb0d5891ce1082baccfb8a
[]
no_license
jeewook0427/MyProject
57b6003c147f79995584edc85fe0b0c5c858cb98
ddf2cd580d3c4f127c24f4415763910c1bcd1147
refs/heads/master
2023-01-01T01:09:09.192821
2020-10-22T18:29:13
2020-10-22T18:29:13
304,529,708
0
0
null
null
null
null
IBM852
C++
false
false
1,374
h
#pragma once #include "GameNode.h" #include "MissileManager.h" class Image; class MissileManager; class Ash; class Missile; class FireBird : public GameNode { private: // 200518 Enemy╝÷┴Ą Image* image; Image* gotchaball; //FPOINT pos; int HP; int currentFrameX, currentFrameY; int updateCount; int size; int width, height; float angle; float speed; float degree; int alpha; int block; int fireTime; bool isHit; bool onHit; char szText[60]; int fireDelay; int fireCount; FireBirdMissileManager missileMgr; MissileManager* missileMgr2; Ash* ash; vector<Missile*> ownmissile; vector<Missile*>::iterator itwonmissile; vector<Missile*> missile; vector<Missile*>::iterator itmissile; int soundcount; bool horizonDir; bool verticalDir; int touchCount = 0; FPOINT centerPos; int moveAngle; float frameTime; float MoveTime; float scale; bool hasSmall; bool isDie = false; bool isgotcha = false; public: virtual HRESULT Init(); virtual HRESULT Init(float posX, float posY); virtual void Release(); virtual void Update(); virtual void Render(HDC hdc); void SetAsh(Ash* _ash); void CheckCrash(bool* ishit, bool* onhit); bool GetIsDie() { return isDie; } int GetHP() { return HP; } void Move(); void Move2(); //FPOINT GetPos() { return pos; } //FPOINT GetPos() { return pos; } FireBird(); ~FireBird(); };
[ "jeewook2@gmail.com" ]
jeewook2@gmail.com
6c9592c003987292dd03ddc163c8d43fece6dca9
57bd019745ec5311e2a78f93e73039efdf71c5b8
/ros_lib/pal_video_recording_msgs/StartRecording.h
f95de2c44a228839946ef5d47681430b976bff0c
[]
no_license
makabe0510/jsk_imu_mini
138eb8391384af671b53469cacc87803157aa2fe
97befccdb4fb82bbb1dab5941da66d5acafdd996
refs/heads/master
2020-03-11T02:11:00.781652
2018-04-16T08:49:36
2018-04-16T08:49:36
129,712,715
0
0
null
2018-04-16T08:47:00
2018-04-16T08:47:00
null
UTF-8
C++
false
false
1,343
h
#ifndef _ROS_SERVICE_StartRecording_h #define _ROS_SERVICE_StartRecording_h #include <stdint.h> #include <string.h> #include <stdlib.h> #include "ros/msg.h" namespace pal_video_recording_msgs { static const char STARTRECORDING[] = "pal_video_recording_msgs/StartRecording"; class StartRecordingRequest : public ros::Msg { public: StartRecordingRequest() { } virtual int serialize(unsigned char *outbuffer) const { int offset = 0; return offset; } virtual int deserialize(unsigned char *inbuffer) { int offset = 0; return offset; } const char * getType(){ return STARTRECORDING; }; const char * getMD5(){ return "d41d8cd98f00b204e9800998ecf8427e"; }; }; class StartRecordingResponse : public ros::Msg { public: StartRecordingResponse() { } virtual int serialize(unsigned char *outbuffer) const { int offset = 0; return offset; } virtual int deserialize(unsigned char *inbuffer) { int offset = 0; return offset; } const char * getType(){ return STARTRECORDING; }; const char * getMD5(){ return "d41d8cd98f00b204e9800998ecf8427e"; }; }; class StartRecording { public: typedef StartRecordingRequest Request; typedef StartRecordingResponse Response; }; } #endif
[ "xychen@jsk.imi.i.u-tokyo.ac.jp" ]
xychen@jsk.imi.i.u-tokyo.ac.jp
8f92316e7a258abdfc2d06dff040cc4b36ce7774
dd01b1e0fd15c8ee12f7e39222020f886b456a14
/Door_Security/Keypad.h
19965488d0c22749d069f62700534b4922eda9a7
[]
no_license
sighchen/Arduino_Door_security
2db6d04f6a3902c78bf7446fb73fa6962f451e5e
b9c17b1beaa716f57757187421644868fbf6e340
refs/heads/master
2021-01-18T14:13:52.087650
2013-04-24T10:19:44
2013-04-24T10:19:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,270
h
/* || || @file Keypad.h || @version 3.0 || @author Mark Stanley, Alexander Brevig || @contact mstanley@technologist.com, alexanderbrevig@gmail.com || || @description || | This library provides a simple interface for using matrix || | keypads. It supports the use of multiple keypads with the || | same or different sets of keys. It also supports user || | selectable pins and definable keymaps. || # || || @license || | This library is free software; you can redistribute it and/or || | modify it under the terms of the GNU Lesser General Public || | License as published by the Free Software Foundation; version || | 2.1 of the License. || | || | This library is distributed in the hope that it will be useful, || | but WITHOUT ANY WARRANTY; without even the implied warranty of || | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU || | Lesser General Public License for more details. || | || | You should have received a copy of the GNU Lesser General Public || | License along with this library; if not, write to the Free Software || | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA || # || */ #ifndef KEYPAD_H #define KEYPAD_H #include "utility/Key.h" // Arduino versioning. #if defined(ARDUINO) && ARDUINO >= 100 #include "Arduino.h" #else #include "WProgram.h" #endif // See http://code.google.com/p/arduino/issues/detail?id=246 #if defined(ARDUINO) && ARDUINO < 101 #define INPUT_PULLUP INPUT #endif #define OPEN LOW #define CLOSED HIGH typedef char KeypadEvent; typedef unsigned int uint; typedef unsigned long ulong; // Made changes according to this post http://arduino.cc/forum/index.php?topic=58337.0 // by Nick Gammon. Thanks for the input Nick. It actually saved 78 bytes for me. :) typedef struct { byte rows; byte columns; } KeypadSize; #define LIST_MAX 10 // Max number of keys on the active list. #define MAPSIZE 10 // MAPSIZE is the number of rows (times 16 columns) #define makeKeymap(x) ((char*)x) //class Keypad : public Key, public HAL_obj { class Keypad : public Key { public: Keypad(char *userKeymap, byte *row, byte *col, byte numRows, byte numCols); virtual void pin_mode(byte pinNum, byte mode) { pinMode(pinNum, mode); } virtual void pin_write(byte pinNum, boolean level) { digitalWrite(pinNum, level); } virtual int pin_read(byte pinNum) { return digitalRead(pinNum); } uint bitMap[MAPSIZE]; // 10 row x 16 column array of bits. Key key[LIST_MAX]; unsigned long holdTimer; String getKey(); bool getKeys(); KeyState getState(); void begin(char *userKeymap); bool isPressed(char keyChar); void setDebounceTime(uint); void setHoldTime(uint); void addEventListener(void (*listener)(char)); int findInList(char keyChar); char waitForKey(); bool keyStateChanged(); byte numKeys(); private: unsigned long startTime; char *keymap; byte *rowPins; byte *columnPins; KeypadSize sizeKpd; uint debounceTime; uint holdTime; bool scanKeys(); void updateList(); void setKeyState(byte n, boolean button); void transitionTo(byte n, KeyState nextState); void initializePins(); void (*keypadEventListener)(char); }; #endif /* || @changelog || | 3.0 2012-07-12 - Mark Stanley : Made library multi-keypress by default. (Backwards compatible) || | 3.0 2012-07-12 - Mark Stanley : Modified pin functions to support Keypad_I2C || | 3.0 2012-07-12 - Stanley & Young : Removed static variables. Fix for multiple keypad objects. || | 3.0 2012-07-12 - Mark Stanley : Fixed bug that caused shorted pins when pressing multiple keys. || | 2.0 2011-12-29 - Mark Stanley : Added waitForKey(). || | 2.0 2011-12-23 - Mark Stanley : Added the public function keyStateChanged(). || | 2.0 2011-12-23 - Mark Stanley : Added the private function scanKeys(). || | 2.0 2011-12-23 - Mark Stanley : Moved the Finite State Machine into the function getKeyState(). || | 2.0 2011-12-23 - Mark Stanley : Removed the member variable lastUdate. Not needed after rewrite. || | 1.8 2011-11-21 - Mark Stanley : Added test to determine which header file to compile, || | WProgram.h or Arduino.h. || | 1.8 2009-07-08 - Alexander Brevig : No longer uses arrays || | 1.7 2009-06-18 - Alexander Brevig : This library is a Finite State Machine every time a state changes || | the keypadEventListener will trigger, if set || | 1.7 2009-06-18 - Alexander Brevig : Added setDebounceTime setHoldTime specifies the amount of || | microseconds before a HOLD state triggers || | 1.7 2009-06-18 - Alexander Brevig : Added transitionTo || | 1.6 2009-06-15 - Alexander Brevig : Added getState() and state variable || | 1.5 2009-05-19 - Alexander Brevig : Added setHoldTime() || | 1.4 2009-05-15 - Alexander Brevig : Added addEventListener || | 1.3 2009-05-12 - Alexander Brevig : Added lastUdate, in order to do simple debouncing || | 1.2 2009-05-09 - Alexander Brevig : Changed getKey() || | 1.1 2009-04-28 - Alexander Brevig : Modified API, and made variables private || | 1.0 2007-XX-XX - Mark Stanley : Initial Release || # */
[ "simonchensigh@gmail.com" ]
simonchensigh@gmail.com
e7652c049e42d2a80db99192d85260b6254d9ded
df86a9ba025b3af9e78dc09b9536151c3aa80bb2
/AFW/AFC/09.Flow/inc/DataFlow.hpp
313a051ba8dafb10cb842838bab0a6c2728b5601
[]
no_license
nightstyles/focp
eefc2da0d2d7b249071a5bad2139cee3b6c5b2f7
71ba2c02278874329e4a4a1bf4611524694636de
refs/heads/master
2021-01-18T20:20:18.531352
2014-07-18T05:15:25
2014-07-18T05:15:25
38,699,174
0
0
null
null
null
null
GB18030
C++
false
false
8,449
hpp
#include "FlowDef.hpp" #ifndef _FLW_DataFlow_Hpp_ #define _FLW_DataFlow_Hpp_ FOCP_BEGIN(); /************************************* * 数据收发返回码定义 *************************************/ enum { FOCP_DFLOW_SUCCESS, //接收、发送数据成功 FOCP_DFLOW_BLOCKED, //因阻塞而导致接收、发送数据失败 FOCP_DFLOW_SORRY, //不支持该功能,只有数据流节点才可能返回该结果。 }; /************************************* * 数据流原型定义 *************************************/ class CDataFlowNode; class CTrashBinNode; class CQueueNode; class CListNode; class CSwitchNode; class CRelayNode; class CProcessNode; class CDataFlow; class CPortFunctor; class CPortNode; /************************************* * CDataFlowNode,基本的数据流节点 *************************************/ class FLW_API CDataFlowNode { FOCP_FORBID_COPY(CDataFlowNode); friend class CDataFlow; friend class CDispatchNode; friend class CSwitchNode; friend class CRelayNode; friend class CProcessNode; private: uint32 m_nLinkCounter; public: CDataFlowNode(); virtual ~CDataFlowNode(); virtual bool Check(); virtual bool HaveGetInterface(); virtual bool HavePutInterface(); virtual bool HaveActiveInterface(); virtual bool CanLinkFrom(); virtual bool CanLinkTo(); virtual bool CanLinkToMore(); virtual bool CanLinkToPort(); virtual uint32 GetData(CAny& oData); virtual uint32 PutData(CAny& oData); virtual bool LinkFrom(CDataFlowNode* pFrom); virtual bool LinkTo(CDataFlowNode* pTo); virtual bool LinkTo(CDataFlowNode* pTo, uint32 nDataType); virtual bool LinkToPort(void* pPort); virtual void UnLink(); uint32 GetLinkCounter(); virtual void Start(); virtual void Stop(); protected: void AddLinkCounter(); void DelLinkCounter(); }; /************************************* * 回收站节点 *************************************/ class FLW_API CTrashBinNode: public CDataFlowNode { FOCP_FORBID_COPY(CTrashBinNode); public: CTrashBinNode(); virtual ~CTrashBinNode(); virtual bool HavePutInterface(); virtual uint32 PutData(CAny& oData); }; /************************************* * CQueueNode,队列形式的容器节点 *************************************/ class FLW_API CQueueNode: public CDataFlowNode { FOCP_FORBID_COPY(CQueueNode); private: CMutex m_oMutex; CEvent m_oGetEvent, m_oPutEvent; uint32 m_nSize, m_nCapacity, m_nHead, m_nTail; CAny* m_pQueue; public: CQueueNode(uint32 nCapacity=0, bool bThread=true); virtual ~CQueueNode(); virtual bool HaveGetInterface(); virtual bool HavePutInterface(); virtual uint32 GetData(CAny& oData); virtual uint32 PutData(CAny& oData); }; /************************************* * CListNode,列表形式的容器节点 *************************************/ class FLW_API CListNode: public CDataFlowNode { FOCP_FORBID_COPY(CListNode); private: CMutex m_oMutex; CEvent m_oGetEvent; void *m_pHead, *m_pTail; public: CListNode(bool bThread=true); virtual ~CListNode(); virtual bool HaveGetInterface(); virtual bool HavePutInterface(); virtual uint32 GetData(CAny& oData); virtual uint32 PutData(CAny& oData); }; /************************************* * CSwitchNode,数据分发节点,应用还可以定制分发模型, * 通过FGetDataType来实现,该函使用oData.GetType(); *************************************/ typedef uint32 (*FGetDataType)(const CAny& oData); class FLW_API CSwitchNode: public CDataFlowNode { FOCP_FORBID_COPY(CSwitchNode); private: FGetDataType m_fGetDataType; CRbMap<uint32, CDataFlowNode*> m_oDispTable; public: CSwitchNode(FGetDataType fGetDataType=NULL); virtual ~CSwitchNode(); virtual bool HavePutInterface(); virtual uint32 PutData(CAny& oData); virtual bool CanLinkToMore(); virtual bool LinkTo(CDataFlowNode* pTo, uint32 nDataType); virtual void UnLink(); }; /************************************* * CSwitchNode,数据分发节点,应用还可以定制分发模型, * 通过FGetDataType来实现,该函使用oData.GetType(); *************************************/ typedef uint32 (*FGetDataType)(const CAny& oData); class FLW_API CDispatchNode: public CDataFlowNode { FOCP_FORBID_COPY(CDispatchNode); private: CMutex m_oMutex; bool m_bStarted; FGetDataType m_fGetDataType; CRbMap<uint32, CDataFlowNode*> m_oDispTable; public: CDispatchNode(bool bThread, FGetDataType fGetDataType=NULL); virtual ~CDispatchNode(); virtual bool HavePutInterface(); virtual uint32 PutData(CAny& oData); virtual bool CanLinkToMore(); virtual bool LinkTo(CDataFlowNode* pTo, uint32 nDataType); virtual void UnLink(); virtual bool HaveActiveInterface(); virtual void Start(); virtual void Stop(); }; /************************************* * CRelayNode,中继节点,具有计算资源 * 自动从源读取数据,并发到目的节点 *************************************/ class FLW_API CRelayNode: public CDataFlowNode, public CCooperateFunction { FOCP_FORBID_COPY(CRelayNode); private: CCooperator m_oCooperator; CDataFlowNode* m_pFrom, *m_pTo; CEvent m_hEvent; bool m_bStarted; public: CRelayNode(bool bThread); virtual ~CRelayNode(); virtual bool Check(); virtual bool CanLinkFrom(); virtual bool LinkFrom(CDataFlowNode* pFrom); virtual bool CanLinkTo(); virtual bool LinkTo(CDataFlowNode* pTo); virtual void UnLink(); virtual bool HaveActiveInterface(); virtual void Start(); virtual void Stop(); void Resume(); protected: virtual void MainProc(CCooperator* pCooperator, bool &bRunning); }; /************************************* * CProcessNode,数据处理节点,应用从这里继承,重载ProcessData函数。 * 如果返回真,表示有数据要下发,至于如何下发由m_pTo决定 *************************************/ class FLW_API CProcessNode: public CDataFlowNode { FOCP_FORBID_COPY(CProcessNode); private: CDataFlowNode* m_pTo; public: CProcessNode(); virtual ~CProcessNode(); virtual bool Check(); virtual bool CanLinkTo(); virtual bool LinkTo(CDataFlowNode* pTo); virtual void UnLink(); virtual bool HavePutInterface(); virtual uint32 PutData(CAny& oData); protected: virtual bool ProcessData(CAny& oData); void ForwardData(CAny& oData); }; /************************************* * CDataFlow 数据流 *************************************/ class FLW_API CDataFlow: public CDataFlowNode { FOCP_FORBID_COPY(CDataFlow); private: CVector<CDataFlowNode*> m_oNodes; CDataFlowNode* m_pPutNode, *m_pGetNode; bool m_bHaveActiveInterface, m_bStarted; public: CDataFlow(); virtual ~CDataFlow(); bool LinkFrom(CDataFlowNode &oNode, CDataFlowNode &oFrom); bool LinkTo(CDataFlowNode &oNode, CDataFlowNode &oTo); bool LinkTo(CDataFlowNode &oNode, CDataFlowNode &oTo, uint32 nDataType); bool LinkToPort(CDataFlowNode &oNode, void* pPort); virtual void UnLink(); bool MakePutNode(CDataFlowNode &oNode); bool MakeGetNode(CDataFlowNode &oNode); virtual bool Check(); virtual bool HaveGetInterface(); virtual bool HavePutInterface(); virtual bool HaveActiveInterface(); virtual uint32 PutData(CAny& oData); virtual uint32 GetData(CAny& oData); virtual void Start(); virtual void Stop(); private: uint32 FindNode(CDataFlowNode* pNode); }; /************************************* * CPortNode,IO节点,应用需要派生特定的 * 节点以实现数据的读写,文件出错的将发生异常。数据流 * 捕获并处理该异常。并需要重启 *************************************/ enum { FOCP_DPORT_SUCCESS, FOCP_DPORT_BLOCKED, FOCP_DPORT_BROKEN }; class FLW_API CPortFunctor { FOCP_FORBID_COPY(CPortFunctor); public: CPortFunctor(); virtual ~CPortFunctor(); virtual uint32 Read(void* pPort, CAny& oData); virtual uint32 Write(void* pPort, CAny& oData); virtual void Mend(CRelayNode* pRelayNode, CPortNode* pPortNode); }; class FLW_API CPortNode: public CDataFlowNode { FOCP_FORBID_COPY(CPortNode); private: void * m_pPort; CPortFunctor* m_pFunctor; bool m_bExceptional; public: CPortNode(CPortFunctor* pFunctor); virtual ~CPortNode(); virtual bool CanLinkToPort(); virtual bool LinkToPort(void* pPort); virtual bool Check(); virtual bool HaveGetInterface(); virtual bool HavePutInterface(); virtual uint32 GetData(CAny& oData); virtual uint32 PutData(CAny& oData); bool IsExceptional(); void* GetPort(); void Mend(CRelayNode* pRelayNode); }; FOCP_END(); #endif
[ "vncorecao@22dc3026-6bb5-472c-94d3-b6806930ea95" ]
vncorecao@22dc3026-6bb5-472c-94d3-b6806930ea95
385eb55f0bfe36b23380c0d54f7bf89843d3a0ff
9c451121eaa5e0131110ad0b969d75d9e6630adb
/Codeforces/Codeforces Round 620/1304F2 - Animal Observation (hard version).cpp
3d4a7f0302af58c85667613be1e3d08e8faf753d
[]
no_license
tokitsu-kaze/ACM-Solved-Problems
69e16c562a1c72f2a0d044edd79c0ab949cc76e3
77af0182401904f8d2f8570578e13d004576ba9e
refs/heads/master
2023-09-01T11:25:12.946806
2023-08-25T03:26:50
2023-08-25T03:26:50
138,472,754
5
1
null
null
null
null
UTF-8
C++
false
false
6,206
cpp
#include <bits/stdc++.h> using namespace std; namespace fastIO{ #define BUF_SIZE 100000 #define OUT_SIZE 100000 //fread->read bool IOerror=0; //inline char nc(){char ch=getchar();if(ch==-1)IOerror=1;return ch;} inline char nc(){ static char buf[BUF_SIZE],*p1=buf+BUF_SIZE,*pend=buf+BUF_SIZE; if(p1==pend){ p1=buf;pend=buf+fread(buf,1,BUF_SIZE,stdin); if(pend==p1){IOerror=1;return -1;} } return *p1++; } inline bool blank(char ch){return ch==' '||ch=='\n'||ch=='\r'||ch=='\t';} template<class T> inline bool read(T &x){ bool sign=0;char ch=nc();x=0; for(;blank(ch);ch=nc()); if(IOerror)return false; if(ch=='-')sign=1,ch=nc(); for(;ch>='0'&&ch<='9';ch=nc())x=x*10+ch-'0'; if(sign)x=-x; return true; } inline bool read(double &x){ bool sign=0;char ch=nc();x=0; for(;blank(ch);ch=nc()); if(IOerror)return false; if(ch=='-')sign=1,ch=nc(); for(;ch>='0'&&ch<='9';ch=nc())x=x*10+ch-'0'; if(ch=='.'){ double tmp=1; ch=nc(); for(;ch>='0'&&ch<='9';ch=nc())tmp/=10.0,x+=tmp*(ch-'0'); } if(sign)x=-x; return true; } inline bool read(char *s){ char ch=nc(); for(;blank(ch);ch=nc()); if(IOerror)return false; for(;!blank(ch)&&!IOerror;ch=nc())*s++=ch; *s=0; return true; } inline bool read(char &c){ for(c=nc();blank(c);c=nc()); if(IOerror){c=-1;return false;} return true; } template<class T,class... U>bool read(T& h,U&... t){return read(h)&&read(t...);} #undef OUT_SIZE #undef BUF_SIZE }; using namespace fastIO; /************* debug begin *************/ string to_string(string s){return '"'+s+'"';} string to_string(const char* s){return to_string((string)s);} string to_string(const bool& b){return(b?"true":"false");} template<class T>string to_string(T x){ostringstream sout;sout<<x;return sout.str();} template<class A,class B>string to_string(pair<A,B> p){return "("+to_string(p.first)+", "+to_string(p.second)+")";} template<class A>string to_string(const vector<A> v){ int f=1;string res="{";for(const auto x:v){if(!f)res+= ", ";f=0;res+=to_string(x);}res+="}"; return res; } void debug_out(){puts("");} template<class T,class... U>void debug_out(const T& h,const U&... t){cout<<" "<<to_string(h);debug_out(t...);} #ifdef tokitsukaze #define debug(...) cout<<"["<<#__VA_ARGS__<<"]:",debug_out(__VA_ARGS__); #else #define debug(...) 233; #endif /************* debug end *************/ #define mem(a,b) memset((a),(b),sizeof(a)) #define MP make_pair #define pb push_back #define fi first #define se second #define sz(x) (int)x.size() #define all(x) x.begin(),x.end() #define sqr(x) (x)*(x) using namespace __gnu_cxx; typedef long long ll; typedef unsigned long long ull; typedef pair<int,int> PII; typedef pair<ll,ll> PLL; typedef pair<int,ll> PIL; typedef pair<ll,int> PLI; typedef vector<int> VI; typedef vector<ll> VL; typedef vector<PII > VPII; /************* define end *************/ void read(int *x,int l,int r){for(int i=l;i<=r;i++) read(x[i]);} void read(ll *x,int l,int r){for(int i=l;i<=r;i++) read(x[i]);} void read(double *x,int l,int r){for(int i=l;i<=r;i++) read(x[i]);} void println(VI x){for(int i=0;i<sz(x);i++) printf("%d%c",x[i]," \n"[i==sz(x)-1]);} void println(VL x){for(int i=0;i<sz(x);i++) printf("%lld%c",x[i]," \n"[i==sz(x)-1]);} void println(int *x,int l,int r){for(int i=l;i<=r;i++) printf("%d%c",x[i]," \n"[i==r]);} void println(ll *x,int l,int r){for(int i=l;i<=r;i++) printf("%lld%c",x[i]," \n"[i==r]);} /*************** IO end ***************/ void go(); int main(){ #ifdef tokitsukaze freopen("TEST.txt","r",stdin); #endif go();return 0; } const int INF=0x3f3f3f3f; const ll LLINF=0x3f3f3f3f3f3f3f3fLL; const double PI=acos(-1.0); const double eps=1e-8; const int MAX=2e4+10; const ll mod=998244353; /********************************* head *********************************/ struct Segment_Tree { #define type ll #define ls (id<<1) #define rs (id<<1|1) int n,ql,qr; type a[MAX],v[MAX<<2],tag[MAX<<2],qv; void pushup(int id) { v[id]=max(v[ls],v[rs]); } void pushdown(int id) { if(!tag[id]) return; tag[ls]+=tag[id]; tag[rs]+=tag[id]; v[ls]+=tag[id]; v[rs]+=tag[id]; tag[id]=0; } void build(int l,int r,int id) { tag[id]=0; v[id]=-LLINF; if(l==r) { v[id]=a[l]; return; } int mid=(l+r)>>1; build(l,mid,ls); build(mid+1,r,rs); pushup(id); } void update(int l,int r,int id) { if(l>=ql&&r<=qr) { v[id]+=qv; tag[id]+=qv; return; } pushdown(id); int mid=(l+r)>>1; if(ql<=mid) update(l,mid,ls); if(qr>mid) update(mid+1,r,rs); pushup(id); } type res; void query(int l,int r,int id) { if(l>=ql&&r<=qr) { res=max(res,v[id]); return; } pushdown(id); int mid=(l+r)>>1; if(ql<=mid) query(l,mid,ls); if(qr>mid) query(mid+1,r,rs); } void build(int _n){n=_n;build(1,n,1);} void upd(int l,int r,type v) { ql=l; qr=r; qv=v; update(1,n,1); } type ask(int l,int r) { ql=l; qr=r; res=-LLINF; query(1,n,1); return res; } #undef type #undef ls #undef rs }tr; ll dp[55][MAX]; ll mp[55][MAX],suf[MAX],bit[MAX]; ll sum[55][MAX]; void go() { int n,m,k,i,j,l,x,y; ll tmp,tmp2,ans; while(read(n,m,k)) { mem(sum,0); for(i=1;i<=n;i++) { read(mp[i],1,m); sum[i][0]=0; for(j=1;j<=m;j++) sum[i][j]=sum[i][j-1]+mp[i][j]; } for(i=1;i<=m;i++) mp[n+1][i]=0; mem(dp,0); for(i=1;i<=n;i++) { suf[m+1]=0; for(j=m;j;j--) suf[j]=max(suf[j+1],dp[i-1][j]); bit[0]=0; for(j=1;j<=m;j++) bit[j]=max(bit[j-1],dp[i-1][j]); for(j=1;j<=m-k+1;j++) tr.a[j]=dp[i-1][j]; tr.build(m-k+1); for(j=l=1;j<=m-k+1;j++) { tmp=(sum[i][j+k-1]-sum[i][j-1])+(sum[i+1][j+k-1]-sum[i+1][j-1]); if(j+k<=m) dp[i][j]=max(dp[i][j],tmp+suf[j+k]); if(j-k>=1) dp[i][j]=max(dp[i][j],tmp+bit[j-k]); dp[i][j]=max(dp[i][j],tmp); if(i==1) continue; while(l<=j+k-1) { tr.upd(max(1,l-k+1),min(l,m-k+1),-mp[i][l]); l++; } dp[i][j]=max(dp[i][j],tr.ask(max(1,j-k+1),min(m-k+1,j+k-1))+tmp); // debug(i,j,tr.ask(max(1,j-k+1),min(m-k+1,j+k-1)),tmp) // debug(max(1,j-k+1),min(m-k+1,j+k-1),tr.v[1]) tr.upd(max(1,j-k+1),j,mp[i][j]); } } ans=0; for(i=1;i<=m-k+1;i++) ans=max(ans,dp[n][i]); printf("%d\n",ans); } }
[ "861794979@qq.com" ]
861794979@qq.com
d8534565f7865b012ae50d8b425cc2d004e47575
2e1f6e32d25de6ce108efa6bedf1e289d9c822b8
/Stuff02_VulkanSurface/VulkanSurface/code/application.cpp
a09841437a436bf478b4660ab3a4c20220b7d09e
[ "MIT" ]
permissive
ghodges413/VulkanStuff
bb40bbe0d2119a1037b40c383a58bd464814a596
9bc8def3796d109f92267a1e67d81dc1c3f57f13
refs/heads/master
2020-04-20T21:54:48.748592
2019-03-25T00:46:58
2019-03-25T00:46:58
169,122,504
0
0
null
null
null
null
UTF-8
C++
false
false
7,474
cpp
// // application.cpp // #include "application.h" #include <assert.h> const std::vector< const char * > Application::m_ValidationLayers = { "VK_LAYER_LUNARG_standard_validation" }; /* ==================================================== CreateDebugReportCallbackEXT ==================================================== */ VkResult CreateDebugReportCallbackEXT( VkInstance instance, const VkDebugReportCallbackCreateInfoEXT * pCreateInfo, const VkAllocationCallbacks * pAllocator, VkDebugReportCallbackEXT * pCallback ) { PFN_vkCreateDebugReportCallbackEXT functor = (PFN_vkCreateDebugReportCallbackEXT) vkGetInstanceProcAddr( instance, "vkCreateDebugReportCallbackEXT" ); if ( functor != nullptr ) { return functor( instance, pCreateInfo, pAllocator, pCallback ); } else { return VK_ERROR_EXTENSION_NOT_PRESENT; } } /* ==================================================== DestroyDebugReportCallbackEXT ==================================================== */ void DestroyDebugReportCallbackEXT( VkInstance instance, VkDebugReportCallbackEXT callback, const VkAllocationCallbacks * pAllocator ) { PFN_vkDestroyDebugReportCallbackEXT functor = (PFN_vkDestroyDebugReportCallbackEXT) vkGetInstanceProcAddr( instance, "vkDestroyDebugReportCallbackEXT" ); if ( functor != nullptr ) { functor( instance, callback, pAllocator ); } } /* ======================================================================================================== Application ======================================================================================================== */ /* ==================================================== Application::Application ==================================================== */ Application::Application() { InitializeGLFW(); InitializeVulkan(); } /* ==================================================== Application::~Application ==================================================== */ Application::~Application() { Cleanup(); } /* ==================================================== Application::InitializeGLFW ==================================================== */ void Application::InitializeGLFW() { glfwInit(); glfwWindowHint( GLFW_CLIENT_API, GLFW_NO_API ); m_glfwWindow = glfwCreateWindow( WINDOW_WIDTH, WINDOW_HEIGHT, "Vulkan", nullptr, nullptr ); glfwSetWindowUserPointer( m_glfwWindow, this ); glfwSetWindowSizeCallback( m_glfwWindow, Application::OnWindowResized ); } /* ==================================================== Application::CheckValidationLayerSupport ==================================================== */ bool Application::CheckValidationLayerSupport() const { uint32_t layerCount; vkEnumerateInstanceLayerProperties( &layerCount, nullptr ); std::vector< VkLayerProperties > availableLayers( layerCount ); vkEnumerateInstanceLayerProperties( &layerCount, availableLayers.data() ); for ( int i = 0; i < m_ValidationLayers.size(); i++ ) { const char * layerName = m_ValidationLayers[ i ]; bool layerFound = false; for ( const VkLayerProperties & layerProperties : availableLayers ) { if ( 0 == strcmp( layerName, layerProperties.layerName ) ) { layerFound = true; break; } } if ( !layerFound ) { return false; } } return true; } /* ==================================================== Application::GetGLFWRequiredExtensions ==================================================== */ std::vector< const char * > Application::GetGLFWRequiredExtensions() const { std::vector< const char * > extensions; const char ** glfwExtensions; uint32_t glfwExtensionCount = 0; glfwExtensions = glfwGetRequiredInstanceExtensions( &glfwExtensionCount ); for ( uint32_t i = 0; i < glfwExtensionCount; i++ ) { extensions.push_back( glfwExtensions[ i ] ); } if ( m_enableLayers ) { extensions.push_back( VK_EXT_DEBUG_REPORT_EXTENSION_NAME ); } return extensions; } /* ==================================================== Application::InitializeVulkan ==================================================== */ bool Application::InitializeVulkan() { if ( m_enableLayers && !CheckValidationLayerSupport() ) { printf( "validation layers requested, but not available!" ); assert( 0 ); return false; } VkApplicationInfo appInfo = {}; appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO; appInfo.pApplicationName = "Vulkan Stuff"; appInfo.applicationVersion = VK_MAKE_VERSION( 1, 0, 0 ); appInfo.pEngineName = "Experimental"; appInfo.engineVersion = VK_MAKE_VERSION( 1, 0, 0 ); appInfo.apiVersion = VK_API_VERSION_1_0; VkInstanceCreateInfo createInfo = {}; createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; createInfo.pApplicationInfo = &appInfo; std::vector< const char * > extensions = GetGLFWRequiredExtensions(); createInfo.enabledExtensionCount = static_cast< uint32_t >( extensions.size() ); createInfo.ppEnabledExtensionNames = extensions.data(); if ( m_enableLayers ) { createInfo.enabledLayerCount = static_cast< uint32_t >( m_ValidationLayers.size() ); createInfo.ppEnabledLayerNames = m_ValidationLayers.data(); } else { createInfo.enabledLayerCount = 0; } if ( vkCreateInstance( &createInfo, nullptr, &m_vkInstance ) != VK_SUCCESS ) { printf( "failed to create instance!" ); assert( 0 ); return false; } if ( m_enableLayers ) { VkDebugReportCallbackCreateInfoEXT createInfo = {}; createInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT; createInfo.flags = VK_DEBUG_REPORT_ERROR_BIT_EXT | VK_DEBUG_REPORT_WARNING_BIT_EXT; createInfo.pfnCallback = DebugCallback; if ( CreateDebugReportCallbackEXT( m_vkInstance, &createInfo, nullptr, &m_vkDebugCallback ) != VK_SUCCESS ) { printf( "failed to set up debug callback!" ); assert( 0 ); return false; } } if ( glfwCreateWindowSurface( m_vkInstance, m_glfwWindow, nullptr, &m_vkSurface ) != VK_SUCCESS ) { printf( "failed to create window surface!" ); assert( 0 ); return false; } return true; } /* ==================================================== Application::Cleanup ==================================================== */ void Application::Cleanup() { // Destroy Vulkan Instance DestroyDebugReportCallbackEXT( m_vkInstance, m_vkDebugCallback, nullptr ); vkDestroySurfaceKHR( m_vkInstance, m_vkSurface, nullptr ); vkDestroyInstance( m_vkInstance, nullptr ); // Destroy GLFW glfwDestroyWindow( m_glfwWindow ); glfwTerminate(); } /* ==================================================== Application::OnWindowResized ==================================================== */ void Application::OnWindowResized( GLFWwindow * window, int width, int height ) { if ( 0 == width || 0 == height ) { return; } // Application * app = reinterpret_cast< Application * >( glfwGetWindowUserPointer( window ) ); } /* ==================================================== Application::DebugCallback ==================================================== */ VKAPI_ATTR VkBool32 VKAPI_CALL Application::DebugCallback( VkDebugReportFlagsEXT flags, VkDebugReportObjectTypeEXT objType, uint64_t obj, size_t location, int32_t code, const char * layerPrefix, const char * msg, void * userData ) { printf( "Validation layer: %s\n", msg ); assert( 0 ); return VK_FALSE; } /* ==================================================== Application::MainLoop ==================================================== */ void Application::MainLoop() { while ( !glfwWindowShouldClose( m_glfwWindow ) ) { glfwPollEvents(); } }
[ "38189889+ghodges413@users.noreply.github.com" ]
38189889+ghodges413@users.noreply.github.com
e7814ec5ce483248b048ddff7468de6c9164113f
e28a86a134ed5983c47ce25a788fd9988a7c1b97
/k2asm/NamedValue.h
14f0dfd5c7f65a7dadde5fd36ce8c4f7f5e0cb07
[ "Artistic-1.0" ]
permissive
b0rje/k2xtools
ab3d0cd1e9602d371d7f671e35409faaab746ad1
c81a8ef4b93119b38d88ceb4fe371dd22e2f7a1a
refs/heads/master
2020-05-17T15:41:31.467646
2015-04-09T20:59:28
2015-04-09T20:59:28
33,531,197
1
0
null
null
null
null
UTF-8
C++
false
false
268
h
#ifndef _NAMED_VALUE_HEADER #define _NAMED_VALUE_HEADER #include "Value.h" class NamedValue : public Value { NamedValue *next; protected: int vName; NamedValue(int name); public: void setNext(NamedValue *next); NamedValue *getNext(); }; #endif
[ "boerje@flaregames.com" ]
boerje@flaregames.com
a4a1bfbee8a64b2a6bdcbfb5ca7457e6f8ef08f6
88ae8695987ada722184307301e221e1ba3cc2fa
/ui/compositor/test/test_layer_animation_observer.h
e593c2c2ffa233a7f7e77d6f249abaa4596ea901
[ "BSD-3-Clause" ]
permissive
iridium-browser/iridium-browser
71d9c5ff76e014e6900b825f67389ab0ccd01329
5ee297f53dc7f8e70183031cff62f37b0f19d25f
refs/heads/master
2023-08-03T16:44:16.844552
2023-07-20T15:17:00
2023-07-23T16:09:30
220,016,632
341
40
BSD-3-Clause
2021-08-13T13:54:45
2019-11-06T14:32:31
null
UTF-8
C++
false
false
4,508
h
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_COMPOSITOR_TEST_TEST_LAYER_ANIMATION_OBSERVER_H_ #define UI_COMPOSITOR_TEST_TEST_LAYER_ANIMATION_OBSERVER_H_ #include "base/memory/raw_ptr.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/compositor/layer_animation_observer.h" namespace ui { class LayerAnimationSequence; // Listens to animation ended notifications. Remembers the last sequence that // it was notified about. class TestLayerAnimationObserver : public LayerAnimationObserver { public: TestLayerAnimationObserver(); ~TestLayerAnimationObserver() override; // Resets all the data tracking LayerAnimationObserver observations. void ResetLayerAnimationObserverations(); // LayerAnimationObserver: void OnLayerAnimationScheduled(LayerAnimationSequence* sequence) override; void OnLayerAnimationStarted(LayerAnimationSequence* sequence) override; void OnLayerAnimationAborted(LayerAnimationSequence* sequence) override; void OnLayerAnimationEnded(LayerAnimationSequence* sequence) override; void OnLayerAnimationWillRepeat(LayerAnimationSequence* sequence) override; bool RequiresNotificationWhenAnimatorDestroyed() const override; const LayerAnimationSequence* last_attached_sequence() const { return last_attached_sequence_; } int last_attached_sequence_epoch() const { return last_attached_sequence_epoch_; } const LayerAnimationSequence* last_scheduled_sequence() const { return last_scheduled_sequence_; } int last_scheduled_sequence_epoch() const { return last_scheduled_sequence_epoch_; } const LayerAnimationSequence* last_started_sequence() const { return last_started_sequence_; } int last_started_sequence_epoch() const { return last_started_sequence_epoch_; } const LayerAnimationSequence* last_aborted_sequence() const { return last_aborted_sequence_; } int last_aborted_sequence_epoch() const { return last_aborted_sequence_epoch_; } const LayerAnimationSequence* last_ended_sequence() const { return last_ended_sequence_; } int last_ended_sequence_epoch() const { return last_ended_sequence_epoch_; } const LayerAnimationSequence* last_repetition_ended_sequence() const { return last_repetition_ended_sequence_; } int last_repetition_ended_sequence_epoch() const { return last_repetition_ended_sequence_epoch_; } const LayerAnimationSequence* last_detached_sequence() const { return last_detached_sequence_; } int last_detached_sequence_epoch() const { return last_detached_sequence_epoch_; } void set_requires_notification_when_animator_destroyed(bool value) { requires_notification_when_animator_destroyed_ = value; } testing::AssertionResult NoEventsObserved(); testing::AssertionResult AttachedEpochIsBeforeScheduledEpoch(); testing::AssertionResult ScheduledEpochIsBeforeStartedEpoch(); testing::AssertionResult StartedEpochIsBeforeEndedEpoch(); testing::AssertionResult StartedEpochIsBeforeAbortedEpoch(); testing::AssertionResult AbortedEpochIsBeforeStartedEpoch(); testing::AssertionResult AbortedEpochIsBeforeDetachedEpoch(); testing::AssertionResult EndedEpochIsBeforeStartedEpoch(); testing::AssertionResult EndedEpochIsBeforeDetachedEpoch(); protected: // LayerAnimationObserver: void OnAttachedToSequence(LayerAnimationSequence* sequence) override; void OnDetachedFromSequence(LayerAnimationSequence* sequence) override; private: int next_epoch_; raw_ptr<const LayerAnimationSequence> last_attached_sequence_; int last_attached_sequence_epoch_; raw_ptr<const LayerAnimationSequence> last_scheduled_sequence_; int last_scheduled_sequence_epoch_; raw_ptr<const LayerAnimationSequence> last_started_sequence_; int last_started_sequence_epoch_; raw_ptr<const LayerAnimationSequence> last_aborted_sequence_; int last_aborted_sequence_epoch_; raw_ptr<const LayerAnimationSequence> last_ended_sequence_; int last_ended_sequence_epoch_; raw_ptr<const LayerAnimationSequence> last_repetition_ended_sequence_; int last_repetition_ended_sequence_epoch_; raw_ptr<const LayerAnimationSequence> last_detached_sequence_; int last_detached_sequence_epoch_; bool requires_notification_when_animator_destroyed_; // Copy and assign are allowed. }; } // namespace ui #endif // UI_COMPOSITOR_TEST_TEST_LAYER_ANIMATION_OBSERVER_H_
[ "jengelh@inai.de" ]
jengelh@inai.de
e1c66110f5d18c59a8620209a17516d4efb8be8c
b714a6b72a4e100f32fbb36bfeb385d0c5c9a4b5
/LearnOpenGL/HelloPBRLighting.cpp
65d58a8a3c099bec15ed03bed12dfbfd9abd3f15
[]
no_license
xuchdong/LearnOpenGL
32da247ecb01692b3fc1d11e8a20532660691996
490843837bbc2847e48937759b598507051c2025
refs/heads/master
2020-03-23T13:56:09.937450
2018-09-13T01:49:04
2018-09-13T01:49:04
141,646,020
0
0
null
null
null
null
UTF-8
C++
false
false
7,936
cpp
// // HelloPBRLighting.cpp // LearnOpenGL // // Created by xuchdong on 2018/9/2. // Copyright © 2018年 com.xuchdong. All rights reserved. // #include <stdio.h> #include "LearnOpenGL.h" #ifdef HELLO_PBRLIGHTING #include <iostream> #include <vector> #include "shader_m.h" #include "camera.h" using namespace std; void mouse_callback(GLFWwindow* window, double xpos, double ypos); void scroll_callback(GLFWwindow* window, double xoffset, double yoffset); void process_input(GLFWwindow* window); void renderSphere(); Camera camera(glm::vec3(0.0f, 0.0f, 3.0f)); float lastX = SRC_WIDTH / 2; float lastY = SRC_HEIGHT / 2; bool firstMouse = true; float deltaTime = 0.0f; float lastFrame = 0.0f; Shader *shader; GLFWwindow* mainWin; vector<glm::vec3> lightPositions; vector<glm::vec3> lightColors; int nrRows = 7; int nrColumns = 7; float spacing = 2.5; void init(GLFWwindow* window) { mainWin = window; glfwSetCursorPosCallback(window, mouse_callback); glfwSetScrollCallback(window, scroll_callback); glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); glEnable(GL_DEPTH_TEST); shader = new Shader("pbr.vert", "pbr.frag"); shader->use(); shader->setVec3("albedo", 0.5f, 0.0f, 0.0f); shader->setFloat("ao", 1.0f); lightPositions.push_back(glm::vec3(-10.0f, 10.0f, 10.0f)); lightPositions.push_back(glm::vec3( 10.0f, 10.0f, 10.0f)); lightPositions.push_back(glm::vec3(-10.0f, -10.0f, 10.0f)); lightPositions.push_back(glm::vec3( 10.0f, -10.0f, 10.0f)); lightColors.push_back(glm::vec3(300.0f, 300.0f, 300.0f)); lightColors.push_back(glm::vec3(300.0f, 300.0f, 300.0f)); lightColors.push_back(glm::vec3(300.0f, 300.0f, 300.0f)); lightColors.push_back(glm::vec3(300.0f, 300.0f, 300.0f)); glm::mat4 projection = glm::perspective(glm::radians(camera.Zoom), (float) SRC_WIDTH / SRC_HEIGHT, 0.1f, 100.0f); shader->setMat4("projection", projection); } void draw() { float currentFrame = glfwGetTime(); deltaTime = currentFrame - lastFrame; lastFrame = currentFrame; process_input(mainWin); glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT); shader->use(); glm::mat4 view = camera.GetViewMatrix(); shader->setMat4("view", view); shader->setVec3("camPos", camera.Position); glm::mat4 model = glm::mat4(1.0f); for(int row = 0; row < nrRows; ++row) { shader->setFloat("metallic", (float) row / (float)nrRows); for(int col = 0; col < nrColumns; ++col) { shader->setFloat("roughness", glm::clamp((float) col / nrColumns, 0.05f, 1.0f)); model = glm::mat4(1.0f); model = glm::translate(model, glm::vec3( (col - (nrColumns / 2)) * spacing, (row - (nrRows / 2)) * spacing, 0.0f )); shader->setMat4("model", model); renderSphere(); } } for(unsigned int i = 0; i < lightPositions.size(); ++i) { glm::vec3 newPos = lightPositions[i]; shader->setVec3("lightPositions[" + to_string(i) + "]", newPos); shader->setVec3("lightColors[" + to_string(i) + "]", lightColors[i]); model = glm::mat4(1.0f); model = glm::translate(model, newPos); model = glm::scale(model, glm::vec3(0.5f)); shader->setMat4("model", model); renderSphere(); } } unsigned int sphereVAO = 0; unsigned int indexCount; void renderSphere() { if(sphereVAO == 0) { glGenVertexArrays(1, &sphereVAO); unsigned int vbo, ebo; glGenBuffers(1, &vbo); glGenBuffers(1, &ebo); vector<glm::vec3> positions; vector<glm::vec2> uv; vector<glm::vec3> normals; vector<unsigned int> indices; const unsigned int X_SEGMENTS = 64; const unsigned int Y_SEGMENTS = 64; const float PI = 3.14159265359; for(unsigned int y = 0; y <= Y_SEGMENTS; ++y) { for(unsigned int x = 0; x <= X_SEGMENTS; ++x) { float xSegment = (float) x / (float)X_SEGMENTS; float ySegment = (float) y / (float)Y_SEGMENTS; float xPos = cos(xSegment * 2.0f * PI) * sin(ySegment * PI); float yPos = cos(ySegment * PI); float zPos = sin(xSegment * 2.0f * PI) * sin(ySegment * PI); positions.push_back(glm::vec3(xPos, yPos, zPos)); uv.push_back(glm::vec2(xSegment, ySegment)); normals.push_back(glm::vec3(xPos, yPos, zPos)); } } bool oddRow = false; for(int y = 0; y < Y_SEGMENTS; ++y) { if(!oddRow) { for(int x = 0; x <= X_SEGMENTS; ++x) { indices.push_back(y * (X_SEGMENTS + 1) + x); indices.push_back((y + 1) * (X_SEGMENTS + 1) + x); } } else { for(int x = X_SEGMENTS; x >= 0; --x) { indices.push_back((y + 1) * (X_SEGMENTS + 1) + x); indices.push_back(y * (X_SEGMENTS + 1) + x); } } oddRow = !oddRow; } indexCount = indices.size(); vector<float> data; for(int i = 0; i < positions.size(); ++i) { data.push_back(positions[i].x); data.push_back(positions[i].y); data.push_back(positions[i].z); if(uv.size() > 0) { data.push_back(uv[i].x); data.push_back(uv[i].y); } if(normals.size() > 0) { data.push_back(normals[i].x); data.push_back(normals[i].y); data.push_back(normals[i].z); } } glBindVertexArray(sphereVAO); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, data.size() * sizeof(float), &data[0], GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo); glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned int), &indices[0], GL_STATIC_DRAW); float stride = (3 + 2 + 3) * sizeof(float); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, stride, (void*) 0); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, stride, (void*)(3 * sizeof(float))); glEnableVertexAttribArray(2); glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, stride, (void*)(5 * sizeof(float))); } glBindVertexArray(sphereVAO); glDrawElements(GL_TRIANGLE_STRIP, indexCount, GL_UNSIGNED_INT, 0); } void clean() { } void mouse_callback(GLFWwindow* window, double xpos, double ypos) { if (firstMouse) { lastX = xpos; lastY = ypos; firstMouse = false; } float xoffset = xpos - lastX; float yoffset = lastY - ypos; // reversed since y-coordinates go from bottom to top lastX = xpos; lastY = ypos; camera.ProcessMouseMovement(xoffset, yoffset); } void scroll_callback(GLFWwindow* window, double xoffset, double yoffset) { camera.ProcessMouseScroll(yoffset); } void process_input(GLFWwindow *window) { if(glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) { glfwSetWindowShouldClose(window, true); } if(glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) { camera.ProcessKeyboard(FORWARD, deltaTime); } if(glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) { camera.ProcessKeyboard(BACKWARD, deltaTime); } if(glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) { camera.ProcessKeyboard(LEFT, deltaTime); } if(glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS) { camera.ProcessKeyboard(RIGHT, deltaTime); } } #endif
[ "xuchdong@gmail.com" ]
xuchdong@gmail.com
6f3d6eb053461a9268424d9d7f3fcc0db316141e
6de292ca2364e7edae55797171a1d01381015124
/Code/client/PropertyModule/SingleProItem.h
bf9b69768b9742c8c2171485301c2e7ee580f14b
[]
no_license
lixufeng2014/Work2016
840ed88cc18eb7fda4e45debccdd4ec2548bec36
7753e19b60f47813a6c5d3f8ea4e6925a534b568
refs/heads/master
2020-05-30T01:36:04.318674
2016-11-24T09:51:22
2016-11-24T09:51:22
null
0
0
null
null
null
null
GB18030
C++
false
false
2,327
h
#ifndef SINGLE_PRO_ITEM_CONTROL_HEAD #define SINGLE_PRO_ITEM_CONTROL_HEAD #pragma once #include "..\GameFrame\GameFrame.h" #include "PropertyModule.h" ////////////////////////////////////////////////////////////////////////// //啦八道具 class PROPERTY_MODULE_CLASS CBugleDlg : public CSkinDialogEx { //变量定义 protected: tagUserData *m_pMeUserData; //用户信息 COLORREF m_crChatTX; //字体颜色 CString m_strInuptChat; //输入信息 int m_nMaxChar; //最大个数 CString m_strPropertyInfo; //道具信息 //控件变量 protected: CExpression m_Expression; //表情窗口 CSkinButton m_btOK; //确定按钮 CSkinButton m_btCancel; //关闭按钮 CSkinButton m_btExpression; //表情按钮 CSkinButton m_btColorSet; //颜色设置 CEdit m_InputChat; //聊天框 //组件变量 protected: IClientKernel * m_pIClientKernel; //内核接口 ITCPSocket * m_pClientSocket; //网络接口 public: //构造函数 CBugleDlg(CWnd* pParent = NULL); //析构函数 virtual ~CBugleDlg(); protected: //控件绑定 virtual void DoDataExchange(CDataExchange* pDX); //功能函数 public: //更新资源 bool UpdateSkinResource(); //设置组件 void SetSendInfo(IClientKernel *pClientKernel,ITCPSocket *pClientSocket,tagUserData *pMeUserData); //发送信息 void SendData(WORD wMainCmdID, WORD wSubCmdID, void * pBuffer, WORD wDataSize); //消息处理 protected: //颜色按钮 afx_msg void OnBnClickedColorSet(); //表情消息 LRESULT OnHitExpression(WPARAM wParam, LPARAM lParam); //表情按钮 afx_msg void OnBnClickedExpression(); //初始框架 virtual BOOL OnInitDialog(); //确认消息 afx_msg void OnBnClickedOk(); //控件颜色 afx_msg HBRUSH OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor); //时间消息 afx_msg void OnTimer(UINT nIDEvent); //绘画函数 afx_msg void OnPaint(); DECLARE_MESSAGE_MAP() }; ////////////////////////////////////////////////////////////////////////// //啦八道具 extern "C" PROPERTY_MODULE_CLASS VOID __cdecl ShowBugleDlg(IClientKernel *pIClientKernel,ITCPSocket *pClientSocket,tagUserData *pMeUserData); ////////////////////////////////////////////////////////////////////////// #endif
[ "sxd616616@163.com" ]
sxd616616@163.com
41032bb0b9fa44fc4410220c5eb00b76f748d951
1cc34d6e5a4835175ec2bf3709784885717154c4
/Classes/MonsterBoss2.cpp
98e4a93223cd61d0b454a1974ebd6bf970d62842
[]
no_license
thonn96/The-World-End-Game
6e4779a24eff7b892ccaa03b289211c0dc7f91d3
f20ed0ed49e8162596d898b9327a86aff1b3a70c
refs/heads/master
2022-07-17T16:14:37.262962
2020-05-12T07:33:26
2020-05-12T07:33:26
263,265,796
0
0
null
null
null
null
UTF-8
C++
false
false
5,284
cpp
#include "MonsterBoss2.h" #include"math.h" #include"cocos2d.h" USING_NS_CC; MonsterBoss2::MonsterBoss2(cocos2d::Layer* layer, float iMinPos, float iMaxPos) { mBlood = BLOOD_MAX_BOSS2; mCurrentState = STATE_IDLE; mIsMcLeft = true; minPos = iMinPos; maxPos = iMaxPos; typeMonster = MODLE_TYPE_MONSTER7; mSprite = Sprite::create("crep/Boss2.png", Rect(24, 11, 225, 95)); mSprite->setAnchorPoint(Vec2(0.5, 0)); mSprite->setScale(1.0f); mSprite->setFlippedX(mIsMcLeft); //physics body mPhysicsBody = PhysicsBody::createBox(Size(120,100), PhysicsMaterial(1.0f, 0.0f, 1.0f)); mPhysicsBody->setPositionOffset(Vec2(20, 0)); mPhysicsBody->setRotationEnable(false); mPhysicsBody->setCollisionBitmask(Model::BITMASK_MONSTER); mPhysicsBody->setGravityEnable(true); mPhysicsBody->setContactTestBitmask(true); mPhysicsBody->setMass(50); mSprite->setPhysicsBody(mPhysicsBody); layer->addChild(mSprite); //create heaart monster loadingHeartM7 = Sprite::create("heartM1.png"); loadingHeartM7->setPosition(mSprite->getPosition() + Vec2(15, 70)); /*loadingHeartM7->setScale(0.8f);*/ mSprite->addChild(loadingHeartM7); loadingHM7 = ui::LoadingBar::create("heartMonster.png"); loadingHM7->setPosition(loadingHeartM7->getPosition()); loadingHM7->setDirection(ui::LoadingBar::Direction::LEFT); /*loadingHM7->setScale(0.8f);*/ loadingHM7->setPercent(100); mSprite->addChild(loadingHM7); //create animate Vector<SpriteFrame*> animFrames; //idle animFrames.pushBack(SpriteFrame::create("crep/Boss2.png", Rect(7, 121, 217, 95))); mAnimation[ANIM_IDLE] = Repeat::create(Animate::create(Animation::createWithSpriteFrames(animFrames, 0.1f)), 1); //walk animFrames.clear(); animFrames.pushBack(SpriteFrame::create("crep/Boss2.png", Rect(7, 121, 217, 95))); animFrames.pushBack(SpriteFrame::create("crep/Boss2.png", Rect(235, 122, 220, 94))); animFrames.pushBack(SpriteFrame::create("crep/Boss2.png", Rect(469, 122, 230, 94))); animFrames.pushBack(SpriteFrame::create("crep/Boss2.png", Rect(712, 125, 223, 91))); animFrames.pushBack(SpriteFrame::create("crep/Boss2.png", Rect(5, 241, 218, 95))); animFrames.pushBack(SpriteFrame::create("crep/Boss2.png", Rect(239, 238, 227, 98))); animFrames.pushBack(SpriteFrame::create("crep/Boss2.png", Rect(474, 237, 235, 101))); animFrames.pushBack(SpriteFrame::create("crep/Boss2.png", Rect(725, 240, 221, 98))); /*animFrames.pushBack(SpriteFrame::create("crep/Boss2.png", Rect(244, 518, 227, 73))); animFrames.pushBack(SpriteFrame::create("crep/Boss2.png", Rect(487, 486, 205, 103))); animFrames.pushBack(SpriteFrame::create("crep/Boss2.png", Rect(704, 477, 200, 97))); animFrames.pushBack(SpriteFrame::create("crep/Boss2.png", Rect(927, 495, 225, 100))); animFrames.pushBack(SpriteFrame::create("crep/Boss2.png", Rect(2, 504, 221, 92)));*/ mAnimation[ANIM_WALK] = Repeat::create(Animate::create(Animation::createWithSpriteFrames(animFrames, 0.1f)), 1); //eat bullet animFrames.clear(); animFrames.pushBack(SpriteFrame::create("crep/Boss2.png", Rect(7, 121, 217, 95))); animFrames.pushBack(SpriteFrame::create("crep/Boss2.png", Rect(235, 122, 220, 94))); animFrames.pushBack(SpriteFrame::create("crep/Boss2.png", Rect(469, 122, 230, 94))); animFrames.pushBack(SpriteFrame::create("crep/Boss2.png", Rect(712, 125, 223, 91))); animFrames.pushBack(SpriteFrame::create("crep/Boss2.png", Rect(5, 241, 218, 95))); animFrames.pushBack(SpriteFrame::create("crep/Boss2.png", Rect(239, 238, 227, 98))); animFrames.pushBack(SpriteFrame::create("crep/Boss2.png", Rect(474, 237, 235, 101))); animFrames.pushBack(SpriteFrame::create("crep/Boss2.png", Rect(725, 240, 221, 98))); mAnimation[ANIM_BE_HIT] = Repeat::create(Animate::create(Animation::createWithSpriteFrames(animFrames, 0.1f)), 1); //attack animFrames.clear(); animFrames.pushBack(SpriteFrame::create("crep/Boss2.png", Rect(3, 749, 208, 99))); animFrames.pushBack(SpriteFrame::create("crep/Boss2.png", Rect(230, 739, 201, 109))); animFrames.pushBack(SpriteFrame::create("crep/Boss2.png", Rect(444, 748, 244, 100))); animFrames.pushBack(SpriteFrame::create("crep/Boss2.png", Rect(701, 748, 268, 100))); animFrames.pushBack(SpriteFrame::create("crep/Boss2.png", Rect(981, 748, 262, 100))); animFrames.pushBack(SpriteFrame::create("crep/Boss2.png", Rect(1253, 748, 245, 110))); animFrames.pushBack(SpriteFrame::create("crep/Boss2.png", Rect(1506, 748, 208, 99))); mAnimation[ANIM_ATTACK] = Repeat::create(Animate::create(Animation::createWithSpriteFrames(animFrames, 0.09f)), 1); // CC_SAFE_RETAIN(mAnimation[ANIM_IDLE]); CC_SAFE_RETAIN(mAnimation[ANIM_WALK]); CC_SAFE_RETAIN(mAnimation[ANIM_BE_HIT]); CC_SAFE_RETAIN(mAnimation[ANIM_ATTACK]); setState(STATE_IDLE); //bullet auto sprite = Sprite::create("crep/bullet.png", Rect(39, 221, 21, 12)); sprite->setScale(1.5f); mBullet = new Bullet(layer, sprite, Model::BITMASK_MONSTER_BULLET, mSprite); mBullet->setScale(1.5f); mBullet->setAlive(false); } MonsterBoss2::~MonsterBoss2() { for (int i = 0; i < ANIM_TOTAl; i++) { if (mAnimation[i]) { mAnimation[i]->autorelease(); } } CC_SAFE_DELETE(mBullet); } void MonsterBoss2::update(Vec2 player) { Monster::update(player); loadingHM7->setPercent(getHP()/30); } int MonsterBoss2::getDamage() { return DAMAGE_BOSS2; }
[ "thonn296@gmail.com" ]
thonn296@gmail.com
602ef6840dff0b9fba5db03c2dd7f0598a68efa2
0867b2edd2811a8c8b59e164665ba71024c1f238
/include/replay.hpp
3c069044840431f5fd189e729dbd2280db6fcd18
[]
no_license
dualword/FastTyper
98528a2cc6e7569b3e39acde7076ce548c44bbb1
51ee6aa9a31bf7a91842932c94de444088f0910c
refs/heads/master
2023-04-04T07:23:43.560256
2021-04-06T16:44:26
2021-04-06T16:44:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,629
hpp
#pragma once #include <string> #include <vector> #include <sstream> #include<fstream> struct ReplayAction { enum ActionType { None, AddChar, NextWord, RemoveChar, }; ReplayAction() : action(ActionType::None) , char_code(0) , timestamp(0) {} ReplayAction(ActionType action_type, int32_t code, uint32_t ms_timestamp) : action(action_type) , char_code(code) , timestamp(ms_timestamp) {} const std::string toString() const { std::stringstream sx; sx << timestamp << " "; if (action == ActionType::AddChar) { sx << "ADD " << char_code; } else if (action == ActionType::NextWord) { sx << "NXT " << 0; } else if (action == ActionType::RemoveChar) { sx << "REM " << 0; } return sx.str(); } ActionType action; int32_t char_code; uint32_t timestamp; }; class ChallengeRecorder { public: ChallengeRecorder() : m_exported(false) { } void clear() { m_words.clear(); m_actions.clear(); m_exported = false; } void addWord(const std::string& word) { m_words.push_back(word); } void addChar(int32_t code, uint32_t timestamp) { m_actions.emplace_back(ReplayAction::ActionType::AddChar, code, timestamp); } void removeChar(uint32_t timestamp) { m_actions.emplace_back(ReplayAction::ActionType::RemoveChar, 0, timestamp); } void nextWord(uint32_t timestamp) { m_actions.emplace_back(ReplayAction::ActionType::NextWord, 0, timestamp); } bool isExported() const { return m_exported; } void toFile() const { uint32_t i(0); std::string filename("replay_0.rpl"); while (exists(filename)) { filename = "replay_" + toString(++i, 0) + ".rpl"; } std::ofstream file; file.open(filename); for (const std::string& word : m_words) { file << word << " "; } file << std::endl; for (const ReplayAction& ra : m_actions) { file << ra.toString() << std::endl; } file.close(); m_exported = true; } void loadFromFile(const std::string& filename) { std::ifstream file; file.open(filename); if (!file) { std::cout << "Invalid replay file" << std::endl; return; } m_words.clear(); std::string line; std::getline(file, line); loadWords(line); uint32_t timestamp; std::string action_str; uint32_t unicode; while (file >> timestamp >> action_str >> unicode) { std::cout << "TS " << timestamp << " Action " << action_str << std::endl; if (action_str == "ADD") m_actions.emplace_back(ReplayAction::ActionType::AddChar, unicode, timestamp); else if (action_str == "NXT") m_actions.emplace_back(ReplayAction::ActionType::NextWord, unicode, timestamp); else if (action_str == "REM") m_actions.emplace_back(ReplayAction::ActionType::RemoveChar, unicode, timestamp); } } const ReplayAction& getAction(uint32_t i) const { return m_actions[i]; } std::size_t actionCount() const { return m_actions.size(); } const std::vector<std::string>& getWords() const { return m_words; } bool isEmpty() const { return m_actions.empty(); } private: std::vector<std::string> m_words; std::vector<ReplayAction> m_actions; mutable bool m_exported; void loadWords(const std::string& line) { const char sep(' '); std::size_t last_index(0); std::size_t index(line.find(sep)); while (index != std::string::npos) { const std::size_t word_length(index - last_index); if (word_length) { const std::string word(line.substr(last_index, word_length)); std::cout << "Found '" << word << "'" << std::endl; m_words.push_back(word); } last_index = index + 1; index = line.find(sep, last_index); } } };
[ "jean.tampon@gmail.com" ]
jean.tampon@gmail.com
0cc49e8251baa03390c9fd3b9c0c4566c0d903b1
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/rsync/gumtree/rsync_repos_function_94_rsync-2.0.18.cpp
813ef69df081fbce91ac803c99fa31e460d6d5a5
[]
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
369
cpp
static void simple_send_token(int f,int token, struct map_struct *buf,OFF_T offset,int n) { if (n > 0) { int l = 0; while (l < n) { int n1 = MIN(CHUNK_SIZE,n-l); write_int(f,n1); write_buf(f,map_ptr(buf,offset+l,n1),n1); l += n1; } } /* a -2 token means to send data only and no token */ if (token != -2) { write_int(f,-(token+1)); } }
[ "993273596@qq.com" ]
993273596@qq.com
babb09effece5adabe768aab757ecabd94b7e8ab
339927d079c0bd8cfb4ac97cbc9f007ccbcaf9c6
/cloudDiskClient/common/uploadtask.cpp
12069d40519a556129f94dc5959e1f70619ae633
[]
no_license
Jsondp/CloudDisk
9fa565e1f3f6eeb065edf9b9870615edc4333cf4
a121ecb74392d53c3f8bc3ebc707301dfd0f1d57
refs/heads/master
2021-07-25T21:10:12.563577
2020-05-03T11:05:35
2020-05-03T11:05:35
163,037,243
2
0
null
null
null
null
UTF-8
C++
false
false
4,183
cpp
#include "uploadtask.h" #include <QFileInfo> #include "uploadlayout.h" #include "common/common.h" //静态数据成员,类中声明,类外必须定义 UploadTask * UploadTask::instance = new UploadTask; //static类的析构函数在main()退出后调用 UploadTask::Garbo UploadTask::temp; //静态数据成员,类中声明,类外定义 UploadTask * UploadTask::getInstance() { return instance; } //追加上传文件到上传列表中 //参数:path 上传文件路径 //失败: // -1: 文件大于30m // -2:上传的文件是否已经在上传队列中 // -3: 打开文件失败 // -4: 获取布局失败 int UploadTask::appendUploadList(QString path) { qint64 size = QFileInfo( path ).size(); if(size > 30*1024*1024) //最大文件只能是30M { cout << "file is to big\n"; return -1; } //遍历查看一下,下载的文件是否已经在上传队列中 for(int i = 0; i != list.size(); ++i) { if( list.at(i)->path == path) //list[i]->path { cout << QFileInfo( path ).fileName() << " 已经在上传队列中 "; return -2; } } QFile *file = new QFile(path); //文件指针分配空间 if(!file->open(QIODevice::ReadOnly)) { //如果打开文件失败,则删除 file,并使 file 指针为 0,然后返回 cout << "file open error"; delete file; file = NULL; return -3; } //获取文件属性信息 QFileInfo info(path); //动态创建节点 Common mc; UploadFileInfo *tmp = new UploadFileInfo; tmp->md5 = mc.getFileMd5(path); //获取文件的md5码, common.h tmp->file = file; //文件指针 tmp->fileName = info.fileName();//文件名字 tmp->size = size; //文件大小 tmp->path = path; //文件路径 tmp->isUpload = false;//当前文件没有被上传 DataProgress *p = new DataProgress; //创建进度条 p->setFileName(tmp->fileName); //设置文件名字 tmp->dp = p; //获取布局 UploadLayout *pUpload = UploadLayout::getInstance(); if(pUpload == NULL) { cout << "UploadTask::getInstance() == NULL"; return -4; } QVBoxLayout *layout = (QVBoxLayout*)pUpload->getUploadLayout(); // 添加到布局, 最后一个是弹簧, 插入到弹簧上边 layout->insertWidget(layout->count()-1, p); cout << tmp->fileName.toUtf8().data() << "已经放在上传列表"; //插入节点 list.append(tmp); return 0; } bool UploadTask::isEmpty() //判断上传队列释放为空 { return list.isEmpty(); } bool UploadTask::isUpload() //是否有文件正在上传 { //遍历队列 for(int i = 0; i != list.size(); ++i) { if( list.at(i)->isUpload == true) //说明有上传任务,不能添加新任务 { return true; } } return false; } // 取出第0个上传任务,如果任务队列没有任务在上传,设置第0个任务上传 UploadFileInfo *UploadTask::takeTask() { //取出第一个任务 UploadFileInfo *tmp = list.at(0); list.at(0)->isUpload = true; //标志位,设置此文件在上传 return tmp; } //删除上传完成的任务 void UploadTask::dealUploadTask() { //遍历队列 for(int i = 0; i != list.size(); ++i) { if( list.at(i)->isUpload == true) //说明有下载任务 { //移除此文件,因为已经上传完成了 UploadFileInfo *tmp = list.takeAt(i); //获取布局 UploadLayout *pUpload = UploadLayout::getInstance(); QLayout *layout = pUpload->getUploadLayout(); layout->removeWidget(tmp->dp); //从布局中移除控件 //关闭打开的文件指针 QFile *file = tmp->file; file->close(); delete file; delete tmp->dp; delete tmp; //释放空间 return; } } } //清空上传列表 void UploadTask::clearList() { int n = list.size(); for(int i = 0; i < n; ++i) { UploadFileInfo *tmp = list.takeFirst(); delete tmp; } }
[ "39818691+Jsondp@users.noreply.github.com" ]
39818691+Jsondp@users.noreply.github.com
819b5fa262af34a10ee7b44993baac2cb6b3992b
71d6a4b17a2f7ab8e86f81874150b9b9aee7cead
/battle_engine.cpp
ab5bee683ff11d72bb22167dc055a0d546fa7e0b
[]
no_license
EgyptFalcon/cpphead
a2ab642553d2432d76c9d48ae2b300fcb9e51c11
bc69fb15fe2135bc1159d9b646c26b9758aaff9f
refs/heads/master
2021-03-28T17:06:31.442714
2012-01-30T23:31:43
2012-01-30T23:31:43
247,879,609
0
0
null
2020-03-17T04:32:01
2020-03-17T04:32:00
null
UTF-8
C++
false
false
4,146
cpp
#include <iostream> #include <iomanip> #include <vector> #include <memory> #include "engines.hpp" #include "game.hpp" #include "player_interaction.hpp" #include "util.hpp" using namespace std; BattleEngine::BattleEngine(const int numGames) : numGames_(numGames), stalemates_(0) { // initialise player list pVec_.push_back(make_pair('r', "RandomPlayer")); pVec_.push_back(make_pair('l', "LowCardPlayer")); pVec_.push_back(make_pair('p', "Pyromaniac")); // initialise shithead map vector<typeName_t>::const_iterator tnIter; for (tnIter = pVec_.begin(); tnIter!=pVec_.end(); tnIter++) { shMap_[tnIter->second] = 0; } } BattleEngine::~BattleEngine() { pVec_.clear(); shMap_.clear(); } void BattleEngine::run() { clock_t start = clock(); int ngame; for (ngame = 0; ngame < numGames_; ngame++) { // make sure players in different order for each game util::shuffle<typeName_t>(pVec_); // set up player names and types for game creation vector<string> names; vector<char> types; vector<typeName_t>::const_iterator iter; for (iter = pVec_.begin(); iter!=pVec_.end(); iter++) { types.push_back(iter->first); names.push_back(iter->second); } auto_ptr<Game> game(new Game(names, types, NUM_CARDS)); game->deal(); // ask players to swap vector<Player *> players = game->players(); vector<Player *>::const_iterator piter; for (piter = players.begin(); piter!=players.end(); piter++) interact::swap(**piter, *game); game->firstMove(); // main game play, count moves for stalemates int moves = 0; while (game->canContinue() && moves < THRESHOLD) { const Player *currentPlayer = game->currentPlayer(); if (game->playingFromFaceDown()) interact::facedown_move(*currentPlayer, *game); else interact::move(*currentPlayer, *game); moves++; } // log stalemates if game didn't complete if (moves == THRESHOLD) { stalemates_++; } else { // add to shithead count for loser string loser = game->getCppHead(); ++shMap_[loser]; } } clock_t end = clock(); showStats(start, end); } void BattleEngine::showStats(const clock_t start, const clock_t end) const { cout << endl; showSummary(start, end); cout << endl; showScores(); cout << endl; } void BattleEngine::showSummary(const clock_t start, const clock_t end) const { double totalMillis = (end - start) / (CLOCKS_PER_SEC / 1000); float avgGameMillis = totalMillis / numGames_; float stalematePercent = ((double)stalemates_ / (double)numGames_) * 100.0; cout << "SUMMARY" << endl; cout << "Total games : " << numGames_ << endl; cout << "Total time : " << util::formatMillis(totalMillis) << endl; cout << "Average game: " << avgGameMillis << " milliseconds" << endl; cout << "Stalemates: " << stalemates_ << ", " << stalematePercent << "%" << endl; } void BattleEngine::showScores() const { shVec_t shVec; copy(shMap_.begin(), shMap_.end(), back_inserter(shVec)); sort(shVec.begin(), shVec.end(), engine::scoreOrder); cout << "SCORES" << endl; cout << left; cout << setw(20) << "Name"; cout << setw(10) << "Shithead"; cout << setw(10) << "Lose rate"; cout << endl; cout << setw(40) << setfill('-') << "-" << endl; cout << setfill(' '); shVec_t::const_iterator iter; for (iter = shVec.begin(); iter!=shVec.end(); iter++) { float percentSh = ((double)iter->second / (double)numGames_) * 100.0; cout << setw(20) << iter->first; cout << setw(10) << iter->second; cout << setprecision(2); cout << percentSh << "%" << endl; } } namespace engine { bool scoreOrder(const pair<string, int>& player1, const pair<string, int>& player2) { return player1.second < player2.second; } } // namespace engine
[ "boothj5@gmail.com" ]
boothj5@gmail.com
603a58ba933624084167e351ab5cd5d7a787d8a9
3b9b4049a8e7d38b49e07bb752780b2f1d792851
/src/chrome/browser/storage/durable_storage_browsertest.cc
4327cd3fdc3648bfc9b6b07e7a7e9c70149593e0
[ "BSD-3-Clause", "Apache-2.0" ]
permissive
webosce/chromium53
f8e745e91363586aee9620c609aacf15b3261540
9171447efcf0bb393d41d1dc877c7c13c46d8e38
refs/heads/webosce
2020-03-26T23:08:14.416858
2018-08-23T08:35:17
2018-09-20T14:25:18
145,513,343
0
2
Apache-2.0
2019-08-21T22:44:55
2018-08-21T05:52:31
null
UTF-8
C++
false
false
6,575
cc
// Copyright 2015 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 <string> #include "base/command_line.h" #include "base/macros.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/bookmarks/bookmark_model_factory.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_commands.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "components/bookmarks/browser/bookmark_model.h" #include "components/bookmarks/browser/bookmark_utils.h" #include "components/bookmarks/test/bookmark_test_helpers.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/web_contents.h" #include "content/public/common/content_switches.h" #include "content/public/test/browser_test_utils.h" #include "net/test/embedded_test_server/embedded_test_server.h" class DurableStorageBrowserTest : public InProcessBrowserTest { public: DurableStorageBrowserTest() = default; ~DurableStorageBrowserTest() override = default; void SetUpCommandLine(base::CommandLine*) override; void SetUpOnMainThread() override; protected: content::RenderFrameHost* GetRenderFrameHost(Browser* browser) { return browser->tab_strip_model()->GetActiveWebContents()->GetMainFrame(); } content::RenderFrameHost* GetRenderFrameHost() { return GetRenderFrameHost(browser()); } void Bookmark(Browser* browser) { bookmarks::BookmarkModel* bookmark_model = BookmarkModelFactory::GetForProfile(browser->profile()); bookmarks::test::WaitForBookmarkModelToLoad(bookmark_model); bookmarks::AddIfNotBookmarked(bookmark_model, url_, base::ASCIIToUTF16("")); } void Bookmark() { Bookmark(browser()); } GURL url_; private: DISALLOW_COPY_AND_ASSIGN(DurableStorageBrowserTest); }; void DurableStorageBrowserTest::SetUpCommandLine( base::CommandLine* command_line) { command_line->AppendSwitch( switches::kEnableExperimentalWebPlatformFeatures); } void DurableStorageBrowserTest::SetUpOnMainThread() { if (embedded_test_server()->Started()) return; ASSERT_TRUE(embedded_test_server()->Start()); url_ = embedded_test_server()->GetURL("/durable/durability-permissions.html"); } IN_PROC_BROWSER_TEST_F(DurableStorageBrowserTest, QueryNonBookmarkedPage) { ui_test_utils::NavigateToURL(browser(), url_); bool is_persistent = false; EXPECT_TRUE(content::ExecuteScriptAndExtractBool( GetRenderFrameHost(), "checkPermission()", &is_persistent)); EXPECT_FALSE(is_persistent); } IN_PROC_BROWSER_TEST_F(DurableStorageBrowserTest, RequestNonBookmarkedPage) { ui_test_utils::NavigateToURL(browser(), url_); bool is_persistent = false; EXPECT_TRUE(content::ExecuteScriptAndExtractBool( GetRenderFrameHost(), "requestPermission()", &is_persistent)); EXPECT_FALSE(is_persistent); } IN_PROC_BROWSER_TEST_F(DurableStorageBrowserTest, QueryBookmarkedPage) { // Documents that the current behavior is to return "default" if script // hasn't requested the durable permission, even if it would be autogranted. Bookmark(); ui_test_utils::NavigateToURL(browser(), url_); bool is_persistent = false; EXPECT_TRUE(content::ExecuteScriptAndExtractBool( GetRenderFrameHost(), "checkPermission()", &is_persistent)); EXPECT_FALSE(is_persistent); } IN_PROC_BROWSER_TEST_F(DurableStorageBrowserTest, RequestBookmarkedPage) { Bookmark(); ui_test_utils::NavigateToURL(browser(), url_); bool is_persistent = false; EXPECT_TRUE(content::ExecuteScriptAndExtractBool( GetRenderFrameHost(), "requestPermission()", &is_persistent)); EXPECT_TRUE(is_persistent); } IN_PROC_BROWSER_TEST_F(DurableStorageBrowserTest, BookmarkThenUnbookmark) { Bookmark(); ui_test_utils::NavigateToURL(browser(), url_); bool is_persistent = false; EXPECT_TRUE(content::ExecuteScriptAndExtractBool( GetRenderFrameHost(), "requestPermission()", &is_persistent)); EXPECT_TRUE(is_persistent); EXPECT_TRUE(content::ExecuteScriptAndExtractBool( GetRenderFrameHost(), "checkPermission()", &is_persistent)); EXPECT_TRUE(is_persistent); bookmarks::BookmarkModel* bookmark_model = BookmarkModelFactory::GetForProfile(browser()->profile()); bookmarks::RemoveAllBookmarks(bookmark_model, url_); // Unbookmarking doesn't change the permission. EXPECT_TRUE(content::ExecuteScriptAndExtractBool( GetRenderFrameHost(), "checkPermission()", &is_persistent)); EXPECT_TRUE(is_persistent); // Requesting after unbookmarking doesn't change the default box. EXPECT_TRUE(content::ExecuteScriptAndExtractBool( GetRenderFrameHost(), "requestPermission()", &is_persistent)); EXPECT_TRUE(is_persistent); // Querying after requesting after unbookmarking still reports "granted". EXPECT_TRUE(content::ExecuteScriptAndExtractBool( GetRenderFrameHost(), "checkPermission()", &is_persistent)); EXPECT_TRUE(is_persistent); } IN_PROC_BROWSER_TEST_F(DurableStorageBrowserTest, FirstTabSeesResult) { ui_test_utils::NavigateToURL(browser(), url_); bool is_persistent = false; EXPECT_TRUE(content::ExecuteScriptAndExtractBool( GetRenderFrameHost(), "checkPermission()", &is_persistent)); EXPECT_FALSE(is_persistent); chrome::NewTab(browser()); ui_test_utils::NavigateToURL(browser(), url_); Bookmark(); EXPECT_TRUE(content::ExecuteScriptAndExtractBool( GetRenderFrameHost(), "requestPermission()", &is_persistent)); EXPECT_TRUE(is_persistent); browser()->tab_strip_model()->ActivateTabAt(0, false); EXPECT_TRUE(content::ExecuteScriptAndExtractBool( GetRenderFrameHost(), "checkPermission()", &is_persistent)); EXPECT_TRUE(is_persistent); } IN_PROC_BROWSER_TEST_F(DurableStorageBrowserTest, Incognito) { Browser* browser = CreateIncognitoBrowser(); ui_test_utils::NavigateToURL(browser, url_); Bookmark(browser); bool is_persistent = false; EXPECT_TRUE(content::ExecuteScriptAndExtractBool(GetRenderFrameHost(browser), "requestPermission()", &is_persistent)); EXPECT_TRUE(is_persistent); EXPECT_TRUE(content::ExecuteScriptAndExtractBool( GetRenderFrameHost(browser), "checkPermission()", &is_persistent)); EXPECT_TRUE(is_persistent); }
[ "changhyeok.bae@lge.com" ]
changhyeok.bae@lge.com
ab29caa15c903d2cd44bd8ef859f2188f7709b09
75f94687e9df7bde68f4b41b0b0143c1a59d420e
/src/transport/Equation_SC_MOC.hh
68e1fc698eb73cbd49ac31a8aec26143a8491231
[ "MIT" ]
permissive
Relzohery/libdetran
d2a7a5604b97303d27c06cfd4e811a57f277fc55
77637c788823e0a14aae7e40e476a291f6f3184b
refs/heads/master
2023-02-06T10:32:34.242165
2013-11-11T15:56:52
2013-11-11T15:56:52
242,563,346
0
0
MIT
2020-10-13T23:18:47
2020-02-23T17:50:00
null
UTF-8
C++
false
false
3,951
hh
//----------------------------------*-C++-*----------------------------------// /** * @file Equation_SC_MOC.hh * @author Jeremy Roberts * @date Mar 31, 2012 * @brief Equation_SC_MOC class definition. */ //---------------------------------------------------------------------------// #ifndef detran_EQUATION_SC_MOC_HH_ #define detran_EQUATION_SC_MOC_HH_ #include "Equation_MOC.hh" namespace detran { //---------------------------------------------------------------------------// /** * @class Equation_SC_MOC * @brief Step characteristic discretization for MOC * * In the method of characteristics, the flux is solved for along a * track assuming a flat source. For a given incident flux into * a track segment, we can define the outgoing segment flux * @f[ * \psi_{out} = A\psi_{in} + B Q \, , * @f] * and average segment flux * @f[ * \bar{\psi} = \frac{1}{l} \Big ( B \psi_{in} + C Q \Big ) \, , * @f] * where * @f[ * A = e^{-\Sigma_t \tau} \, , * @f] * @f[ * B = \frac{1}{\Sigma_t} ( 1- A ) \, , * @f] * and * @f[ * C = \frac{l}{\Sigma_t} \Big( 1- \frac{1-A}{\tau} \Big ) \, , * @f] * where \f$ l \f$ is the segment length and * @f$ \tau = \Sigma_t l \f$ is optical path length. * * The step characteristic method is positive but only first-order * accurate in space. * * Reference: A. Hebert, <em>Applied Reactor Physics</em>. * * \sa Equation_DD_MOC * */ //---------------------------------------------------------------------------// class TRANSPORT_EXPORT Equation_SC_MOC: public Equation_MOC { public: //-------------------------------------------------------------------------// // TYPEDEFS //-------------------------------------------------------------------------// typedef Equation_MOC Base; //-------------------------------------------------------------------------// // CONSTRUCTOR & DESTRUCTOR //-------------------------------------------------------------------------// /// Constructor Equation_SC_MOC(SP_mesh mesh, SP_material material, SP_quadrature quadrature, const bool update_psi); //-------------------------------------------------------------------------// // ABSTRACT INTERFACE -- ALL MOC EQUATION TYPES MUST IMPLEMENT THESE //-------------------------------------------------------------------------// /// Solve for the cell-center and outgoing edge fluxes. inline void solve(const size_t region, const double length, moments_type &source, double &psi_in, double &psi_out, moments_type &phi, angular_flux_type &psi); /// Setup the equations for a group. void setup_group(const size_t g); /// Setup the equations for an octant. void setup_octant(const size_t o); /// Setup the equations for an azimuth. void setup_azimuth(const size_t a); /// Setup the equations for a polar angle. void setup_polar(const size_t p); private: //-------------------------------------------------------------------------// // DATA //-------------------------------------------------------------------------// /// Angular quadrature weights for an azimuth and all polar angles. detran_utilities::vec_dbl d_weights; /// Inverse polar sines detran_utilities::vec_dbl d_inv_sin; }; } // end namespace detran //---------------------------------------------------------------------------// // INLINE FUNCTIONS //---------------------------------------------------------------------------// #include "Equation_SC_MOC.i.hh" #endif /* detran_EQUATION_SC_MOC_HH_ */ //---------------------------------------------------------------------------// // end of Equation_SC_MOC.hh //---------------------------------------------------------------------------//
[ "robertsj@mit.edu" ]
robertsj@mit.edu
add909e030ed519289c789c3dba32277554400d5
67f61e55d4d74a76deef5b826e9cb6c1d9e53c58
/externals/skia/third_party/externals/angle2/src/libANGLE/renderer/ProgramImpl.h
4f427b35e0505d035d3d429235b163c96a77e21a
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
mono/linux-packaging-skiasharp
e7d0478b0c34c80f341e0224041e3dc076e13d41
47dbb2ff9ae01305b190f409ccea00b3b4f0bc79
refs/heads/master
2023-08-23T10:22:57.751473
2017-04-25T14:28:46
2017-04-25T14:28:46
89,267,865
1
5
MIT
2020-04-08T02:40:44
2017-04-24T17:23:42
C++
UTF-8
C++
false
false
4,537
h
// // Copyright 2014 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // ProgramImpl.h: Defines the abstract rx::ProgramImpl class. #ifndef LIBANGLE_RENDERER_PROGRAMIMPL_H_ #define LIBANGLE_RENDERER_PROGRAMIMPL_H_ #include "common/angleutils.h" #include "libANGLE/BinaryStream.h" #include "libANGLE/Constants.h" #include "libANGLE/Program.h" #include "libANGLE/Shader.h" #include <map> namespace gl { class VaryingPacking; } namespace sh { struct BlockMemberInfo; } namespace rx { using LinkResult = gl::ErrorOrResult<bool>; class ContextImpl; class ProgramImpl : angle::NonCopyable { public: ProgramImpl(const gl::ProgramState &state) : mState(state) {} virtual ~ProgramImpl() {} virtual LinkResult load(const ContextImpl *contextImpl, gl::InfoLog &infoLog, gl::BinaryInputStream *stream) = 0; virtual gl::Error save(gl::BinaryOutputStream *stream) = 0; virtual void setBinaryRetrievableHint(bool retrievable) = 0; virtual LinkResult link(const gl::ContextState &data, const gl::VaryingPacking &packing, gl::InfoLog &infoLog) = 0; virtual GLboolean validate(const gl::Caps &caps, gl::InfoLog *infoLog) = 0; virtual void setUniform1fv(GLint location, GLsizei count, const GLfloat *v) = 0; virtual void setUniform2fv(GLint location, GLsizei count, const GLfloat *v) = 0; virtual void setUniform3fv(GLint location, GLsizei count, const GLfloat *v) = 0; virtual void setUniform4fv(GLint location, GLsizei count, const GLfloat *v) = 0; virtual void setUniform1iv(GLint location, GLsizei count, const GLint *v) = 0; virtual void setUniform2iv(GLint location, GLsizei count, const GLint *v) = 0; virtual void setUniform3iv(GLint location, GLsizei count, const GLint *v) = 0; virtual void setUniform4iv(GLint location, GLsizei count, const GLint *v) = 0; virtual void setUniform1uiv(GLint location, GLsizei count, const GLuint *v) = 0; virtual void setUniform2uiv(GLint location, GLsizei count, const GLuint *v) = 0; virtual void setUniform3uiv(GLint location, GLsizei count, const GLuint *v) = 0; virtual void setUniform4uiv(GLint location, GLsizei count, const GLuint *v) = 0; virtual void setUniformMatrix2fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value) = 0; virtual void setUniformMatrix3fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value) = 0; virtual void setUniformMatrix4fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value) = 0; virtual void setUniformMatrix2x3fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value) = 0; virtual void setUniformMatrix3x2fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value) = 0; virtual void setUniformMatrix2x4fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value) = 0; virtual void setUniformMatrix4x2fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value) = 0; virtual void setUniformMatrix3x4fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value) = 0; virtual void setUniformMatrix4x3fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat *value) = 0; // TODO: synchronize in syncState when dirty bits exist. virtual void setUniformBlockBinding(GLuint uniformBlockIndex, GLuint uniformBlockBinding) = 0; // May only be called after a successful link operation. // Return false for inactive blocks. virtual bool getUniformBlockSize(const std::string &blockName, size_t *sizeOut) const = 0; // May only be called after a successful link operation. // Returns false for inactive members. virtual bool getUniformBlockMemberInfo(const std::string &memberUniformName, sh::BlockMemberInfo *memberInfoOut) const = 0; // CHROMIUM_path_rendering // Set parameters to control fragment shader input variable interpolation virtual void setPathFragmentInputGen(const std::string &inputName, GLenum genMode, GLint components, const GLfloat *coeffs) = 0; protected: const gl::ProgramState &mState; }; } #endif // LIBANGLE_RENDERER_PROGRAMIMPL_H_
[ "joshield@microsoft.com" ]
joshield@microsoft.com
d2a2910c24cc4fbb5a207e392453871c5d8825b6
13b105912c887ef60157e0cb87090c1ea78e2072
/ui_gui_cartaporte_crear_2.h
91e58bc4d23e1445f2998d7f88fddb611d5af9cf
[]
no_license
Jose-Cisneros/MoliTec
6d737b058324a01f1dbb3b3745a3515794757da3
189aed4de77a0f979e8920a92871e7ef2476300a
refs/heads/master
2021-09-10T13:36:16.104054
2018-03-27T02:56:06
2018-03-27T02:56:06
107,582,154
0
0
null
null
null
null
UTF-8
C++
false
false
12,543
h
/******************************************************************************** ** Form generated from reading UI file 'gui_cartaporte_crear_2.ui' ** ** Created by: Qt User Interface Compiler version 5.8.0 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_GUI_CARTAPORTE_CREAR_2_H #define UI_GUI_CARTAPORTE_CREAR_2_H #include <QtCore/QVariant> #include <QtWidgets/QAction> #include <QtWidgets/QApplication> #include <QtWidgets/QButtonGroup> #include <QtWidgets/QCheckBox> #include <QtWidgets/QComboBox> #include <QtWidgets/QFormLayout> #include <QtWidgets/QFrame> #include <QtWidgets/QHeaderView> #include <QtWidgets/QLabel> #include <QtWidgets/QLineEdit> #include <QtWidgets/QPushButton> #include <QtWidgets/QTextEdit> #include <QtWidgets/QWidget> QT_BEGIN_NAMESPACE class Ui_GUI_CartaPorte_Crear_2 { public: QPushButton *pushButton; QLabel *label; QWidget *formLayoutWidget; QFormLayout *formLayout; QLabel *label_2; QLabel *label_3; QLabel *label_4; QLabel *label_5; QLabel *label_6; QLabel *label_7; QLabel *label_8; QLabel *label_10; QLabel *label_11; QLabel *label_9; QLineEdit *lineEdit; QLineEdit *lineEdit_2; QCheckBox *checkBox; QLineEdit *lineEdit_3; QCheckBox *checkBox_2; QCheckBox *checkBox_3; QCheckBox *checkBox_4; QLineEdit *lineEdit_4; QLineEdit *lineEdit_5; QLineEdit *lineEdit_6; QLabel *label_12; QTextEdit *textEdit; QPushButton *pushButton_2; QLabel *label_13; QFrame *line; QWidget *formLayoutWidget_2; QFormLayout *formLayout_2; QLabel *label_14; QLabel *label_15; QLabel *label_16; QLineEdit *lineEdit_7; QLineEdit *lineEdit_8; QComboBox *comboBox; void setupUi(QWidget *GUI_CartaPorte_Crear_2) { if (GUI_CartaPorte_Crear_2->objectName().isEmpty()) GUI_CartaPorte_Crear_2->setObjectName(QStringLiteral("GUI_CartaPorte_Crear_2")); GUI_CartaPorte_Crear_2->resize(799, 601); pushButton = new QPushButton(GUI_CartaPorte_Crear_2); pushButton->setObjectName(QStringLiteral("pushButton")); pushButton->setGeometry(QRect(580, 550, 75, 23)); label = new QLabel(GUI_CartaPorte_Crear_2); label->setObjectName(QStringLiteral("label")); label->setGeometry(QRect(20, -10, 411, 71)); QFont font; font.setPointSize(18); label->setFont(font); formLayoutWidget = new QWidget(GUI_CartaPorte_Crear_2); formLayoutWidget->setObjectName(QStringLiteral("formLayoutWidget")); formLayoutWidget->setGeometry(QRect(20, 50, 371, 371)); formLayout = new QFormLayout(formLayoutWidget); formLayout->setObjectName(QStringLiteral("formLayout")); formLayout->setVerticalSpacing(20); formLayout->setContentsMargins(0, 0, 40, 0); label_2 = new QLabel(formLayoutWidget); label_2->setObjectName(QStringLiteral("label_2")); QFont font1; font1.setPointSize(11); label_2->setFont(font1); formLayout->setWidget(0, QFormLayout::LabelRole, label_2); label_3 = new QLabel(formLayoutWidget); label_3->setObjectName(QStringLiteral("label_3")); label_3->setFont(font1); formLayout->setWidget(1, QFormLayout::LabelRole, label_3); label_4 = new QLabel(formLayoutWidget); label_4->setObjectName(QStringLiteral("label_4")); QFont font2; font2.setPointSize(10); label_4->setFont(font2); formLayout->setWidget(2, QFormLayout::LabelRole, label_4); label_5 = new QLabel(formLayoutWidget); label_5->setObjectName(QStringLiteral("label_5")); label_5->setFont(font1); formLayout->setWidget(3, QFormLayout::LabelRole, label_5); label_6 = new QLabel(formLayoutWidget); label_6->setObjectName(QStringLiteral("label_6")); label_6->setFont(font2); formLayout->setWidget(4, QFormLayout::LabelRole, label_6); label_7 = new QLabel(formLayoutWidget); label_7->setObjectName(QStringLiteral("label_7")); label_7->setFont(font1); formLayout->setWidget(5, QFormLayout::LabelRole, label_7); label_8 = new QLabel(formLayoutWidget); label_8->setObjectName(QStringLiteral("label_8")); label_8->setFont(font1); formLayout->setWidget(6, QFormLayout::LabelRole, label_8); label_10 = new QLabel(formLayoutWidget); label_10->setObjectName(QStringLiteral("label_10")); label_10->setFont(font1); formLayout->setWidget(7, QFormLayout::LabelRole, label_10); label_11 = new QLabel(formLayoutWidget); label_11->setObjectName(QStringLiteral("label_11")); label_11->setFont(font1); formLayout->setWidget(8, QFormLayout::LabelRole, label_11); label_9 = new QLabel(formLayoutWidget); label_9->setObjectName(QStringLiteral("label_9")); label_9->setFont(font1); formLayout->setWidget(9, QFormLayout::LabelRole, label_9); lineEdit = new QLineEdit(formLayoutWidget); lineEdit->setObjectName(QStringLiteral("lineEdit")); formLayout->setWidget(0, QFormLayout::FieldRole, lineEdit); lineEdit_2 = new QLineEdit(formLayoutWidget); lineEdit_2->setObjectName(QStringLiteral("lineEdit_2")); formLayout->setWidget(1, QFormLayout::FieldRole, lineEdit_2); checkBox = new QCheckBox(formLayoutWidget); checkBox->setObjectName(QStringLiteral("checkBox")); formLayout->setWidget(2, QFormLayout::FieldRole, checkBox); lineEdit_3 = new QLineEdit(formLayoutWidget); lineEdit_3->setObjectName(QStringLiteral("lineEdit_3")); formLayout->setWidget(3, QFormLayout::FieldRole, lineEdit_3); checkBox_2 = new QCheckBox(formLayoutWidget); checkBox_2->setObjectName(QStringLiteral("checkBox_2")); formLayout->setWidget(4, QFormLayout::FieldRole, checkBox_2); checkBox_3 = new QCheckBox(formLayoutWidget); checkBox_3->setObjectName(QStringLiteral("checkBox_3")); formLayout->setWidget(5, QFormLayout::FieldRole, checkBox_3); checkBox_4 = new QCheckBox(formLayoutWidget); checkBox_4->setObjectName(QStringLiteral("checkBox_4")); formLayout->setWidget(6, QFormLayout::FieldRole, checkBox_4); lineEdit_4 = new QLineEdit(formLayoutWidget); lineEdit_4->setObjectName(QStringLiteral("lineEdit_4")); formLayout->setWidget(7, QFormLayout::FieldRole, lineEdit_4); lineEdit_5 = new QLineEdit(formLayoutWidget); lineEdit_5->setObjectName(QStringLiteral("lineEdit_5")); formLayout->setWidget(8, QFormLayout::FieldRole, lineEdit_5); lineEdit_6 = new QLineEdit(formLayoutWidget); lineEdit_6->setObjectName(QStringLiteral("lineEdit_6")); formLayout->setWidget(9, QFormLayout::FieldRole, lineEdit_6); label_12 = new QLabel(GUI_CartaPorte_Crear_2); label_12->setObjectName(QStringLiteral("label_12")); label_12->setGeometry(QRect(30, 440, 101, 16)); QFont font3; font3.setPointSize(12); label_12->setFont(font3); textEdit = new QTextEdit(GUI_CartaPorte_Crear_2); textEdit->setObjectName(QStringLiteral("textEdit")); textEdit->setGeometry(QRect(20, 460, 391, 91)); textEdit->viewport()->setProperty("cursor", QVariant(QCursor(Qt::IBeamCursor))); pushButton_2 = new QPushButton(GUI_CartaPorte_Crear_2); pushButton_2->setObjectName(QStringLiteral("pushButton_2")); pushButton_2->setGeometry(QRect(690, 550, 75, 23)); label_13 = new QLabel(GUI_CartaPorte_Crear_2); label_13->setObjectName(QStringLiteral("label_13")); label_13->setGeometry(QRect(490, -10, 361, 71)); QFont font4; font4.setPointSize(16); label_13->setFont(font4); line = new QFrame(GUI_CartaPorte_Crear_2); line->setObjectName(QStringLiteral("line")); line->setGeometry(QRect(410, -10, 20, 621)); line->setFrameShape(QFrame::VLine); line->setFrameShadow(QFrame::Sunken); formLayoutWidget_2 = new QWidget(GUI_CartaPorte_Crear_2); formLayoutWidget_2->setObjectName(QStringLiteral("formLayoutWidget_2")); formLayoutWidget_2->setGeometry(QRect(490, 90, 271, 171)); formLayout_2 = new QFormLayout(formLayoutWidget_2); formLayout_2->setObjectName(QStringLiteral("formLayout_2")); formLayout_2->setVerticalSpacing(50); formLayout_2->setContentsMargins(0, 0, 40, 0); label_14 = new QLabel(formLayoutWidget_2); label_14->setObjectName(QStringLiteral("label_14")); label_14->setFont(font3); formLayout_2->setWidget(0, QFormLayout::LabelRole, label_14); label_15 = new QLabel(formLayoutWidget_2); label_15->setObjectName(QStringLiteral("label_15")); label_15->setFont(font3); formLayout_2->setWidget(1, QFormLayout::LabelRole, label_15); label_16 = new QLabel(formLayoutWidget_2); label_16->setObjectName(QStringLiteral("label_16")); label_16->setFont(font3); formLayout_2->setWidget(2, QFormLayout::LabelRole, label_16); lineEdit_7 = new QLineEdit(formLayoutWidget_2); lineEdit_7->setObjectName(QStringLiteral("lineEdit_7")); formLayout_2->setWidget(0, QFormLayout::FieldRole, lineEdit_7); lineEdit_8 = new QLineEdit(formLayoutWidget_2); lineEdit_8->setObjectName(QStringLiteral("lineEdit_8")); formLayout_2->setWidget(1, QFormLayout::FieldRole, lineEdit_8); comboBox = new QComboBox(formLayoutWidget_2); comboBox->setObjectName(QStringLiteral("comboBox")); formLayout_2->setWidget(2, QFormLayout::FieldRole, comboBox); retranslateUi(GUI_CartaPorte_Crear_2); QMetaObject::connectSlotsByName(GUI_CartaPorte_Crear_2); } // setupUi void retranslateUi(QWidget *GUI_CartaPorte_Crear_2) { GUI_CartaPorte_Crear_2->setWindowTitle(QApplication::translate("GUI_CartaPorte_Crear_2", "Form", Q_NULLPTR)); pushButton->setText(QApplication::translate("GUI_CartaPorte_Crear_2", "siguiente", Q_NULLPTR)); label->setText(QApplication::translate("GUI_CartaPorte_Crear_2", "Datos de los granos transportados", Q_NULLPTR)); label_2->setText(QApplication::translate("GUI_CartaPorte_Crear_2", "Grano", Q_NULLPTR)); label_3->setText(QApplication::translate("GUI_CartaPorte_Crear_2", "Tipo", Q_NULLPTR)); label_4->setText(QApplication::translate("GUI_CartaPorte_Crear_2", "Carga pesada en destino", Q_NULLPTR)); label_5->setText(QApplication::translate("GUI_CartaPorte_Crear_2", "kg estimados", Q_NULLPTR)); label_6->setText(QApplication::translate("GUI_CartaPorte_Crear_2", "Declaracion de calidad", Q_NULLPTR)); label_7->setText(QApplication::translate("GUI_CartaPorte_Crear_2", "Conforme", Q_NULLPTR)); label_8->setText(QApplication::translate("GUI_CartaPorte_Crear_2", "condicional", Q_NULLPTR)); label_10->setText(QApplication::translate("GUI_CartaPorte_Crear_2", "Peso bruto (Kgrs)", Q_NULLPTR)); label_11->setText(QApplication::translate("GUI_CartaPorte_Crear_2", "Peso tara (Kgrs)", Q_NULLPTR)); label_9->setText(QApplication::translate("GUI_CartaPorte_Crear_2", "Peso Neto (kgrs)", Q_NULLPTR)); checkBox->setText(QString()); checkBox_2->setText(QString()); checkBox_3->setText(QString()); checkBox_4->setText(QString()); label_12->setText(QApplication::translate("GUI_CartaPorte_Crear_2", "Observaciones", Q_NULLPTR)); pushButton_2->setText(QApplication::translate("GUI_CartaPorte_Crear_2", "cancelar", Q_NULLPTR)); label_13->setText(QApplication::translate("GUI_CartaPorte_Crear_2", "Procedencia de la mercaderia", Q_NULLPTR)); label_14->setText(QApplication::translate("GUI_CartaPorte_Crear_2", "Direccion", Q_NULLPTR)); label_15->setText(QApplication::translate("GUI_CartaPorte_Crear_2", "Localidad", Q_NULLPTR)); label_16->setText(QApplication::translate("GUI_CartaPorte_Crear_2", "Provincia", Q_NULLPTR)); } // retranslateUi }; namespace Ui { class GUI_CartaPorte_Crear_2: public Ui_GUI_CartaPorte_Crear_2 {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_GUI_CARTAPORTE_CREAR_2_H
[ "josecisneros654@gmail.com" ]
josecisneros654@gmail.com
4e98e3fa3c856a5f6573e25422b38413716012d4
ea48f6221c2710d188fd7592c27db862a308ef59
/175周赛/4/main.cc
fbc3f010b3af2faf4854cf51987e66c2c4bee203
[]
no_license
bhhbazinga/leetcode
292423bdc2e3a7a8665ba484ed0a5d5c65db5fb5
cf6bf41c68b54b002c8aa60606ff65e7058ec0df
refs/heads/master
2020-09-04T15:24:39.730347
2020-05-17T02:02:31
2020-05-17T02:02:31
219,767,513
0
0
null
null
null
null
UTF-8
C++
false
false
596
cc
#include <algorithm> #include <climits> #include <cstdio> #include <cstdlib> #include <cstring> #include <functional> #include <list> #include <map> #include <memory> #include <queue> #include <set> #include <stack> #include <string> #include <unordered_map> #include <unordered_set> #include <vector> #define log(fmt, ...) \ do { \ fprintf(stderr, fmt, __VA_ARGS__); \ } while (0) using namespace std; class Solution { public: int maxStudents(vector<vector<char>>& seats) {} }; int main(int argc, char const* argv[]) { return 0; }
[ "77611355@qq.com" ]
77611355@qq.com
c003eb57c14eec1383e8ec7a5a71f3c21c980ae2
4902accffd4236a845a75a2542063f4795efb99f
/menu/elements/form.h
bfe616ab19c783e024ecd09c52b43c982e5b06fc
[]
no_license
VottonDev/LoliSmasherOld
1a8b15cb59e11ae737614e34d759aee38877913e
7480dc62f10a1de57bd9742c36a7c6416fe2c85e
refs/heads/master
2023-04-28T02:35:48.147875
2021-05-09T19:08:57
2021-05-09T19:08:57
46,590,294
0
0
null
null
null
null
UTF-8
C++
false
false
503
h
class LForm : public LBaseObject { protected: int Padding = 30; std::vector<LBaseObject*> ObjectList; public: void Paint(); void AddItem( LBaseObject* ); }; void LForm::Paint() { int X, Y; GetPos(&X,&Y); Interfaces.Surface->DrawSetColor( LMenuFG ); Interfaces.Surface->DrawOutlinedRect( X, Y, X + w, Y + h ); } void LForm::AddItem( LBaseObject* Item ) { Item->SetParent(this); int Height = 10; Height += ObjectList.size()*Padding; Item->SetPos(10, Height); ObjectList.push_back(Item); }
[ "votton.hooper@gmail.com" ]
votton.hooper@gmail.com
27bd2c3e543949e51a0f30e5a3ae83d40f59af80
bf798d5af7effdb06f373ac653e98cb4dd145a5c
/src/qif191/QIFDocument/type_t.CPrintedDrawingType.h
187ff41694e8a8f6054141b60c03631a2e770864
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
QualityInformationFramework/QIFResourcesEditor
73387fca4f4280cc1145fae32438c5d2fdc63cd5
4ff1de9d1dd20d9c43eaa9cc320caeff1c57760e
refs/heads/master
2022-07-29T15:57:04.341916
2021-08-04T16:36:42
2021-08-04T16:36:42
298,856,948
0
0
null
null
null
null
UTF-8
C++
false
false
1,899
h
#pragma once namespace qif191 { namespace t { class CPrintedDrawingType : public TypeBase { public: QIF191_EXPORT CPrintedDrawingType(xercesc::DOMNode* const& init); QIF191_EXPORT CPrintedDrawingType(CPrintedDrawingType const& init); void operator=(CPrintedDrawingType const& other) { m_node = other.m_node; } static altova::meta::ComplexType StaticInfo() { return altova::meta::ComplexType(types + _altova_ti_t_altova_CPrintedDrawingType); } MemberAttribute<unsigned,_altova_mi_t_altova_CPrintedDrawingType_altova_id, 0, 0> id; // id CQIFIdType MemberElement<xs::CstringType, _altova_mi_t_altova_CPrintedDrawingType_altova_Name> Name; struct Name { typedef Iterator<xs::CstringType> iterator; }; MemberElement<xs::CstringType, _altova_mi_t_altova_CPrintedDrawingType_altova_Version> Version; struct Version { typedef Iterator<xs::CstringType> iterator; }; MemberElement<xs::CstringType, _altova_mi_t_altova_CPrintedDrawingType_altova_Description> Description; struct Description { typedef Iterator<xs::CstringType> iterator; }; MemberElement<t::CAuthorType, _altova_mi_t_altova_CPrintedDrawingType_altova_Author> Author; struct Author { typedef Iterator<t::CAuthorType> iterator; }; MemberElement<xs::CstringType, _altova_mi_t_altova_CPrintedDrawingType_altova_DrawingNumber> DrawingNumber; struct DrawingNumber { typedef Iterator<xs::CstringType> iterator; }; MemberElement<xs::CstringType, _altova_mi_t_altova_CPrintedDrawingType_altova_AdditionalChanges> AdditionalChanges; struct AdditionalChanges { typedef Iterator<xs::CstringType> iterator; }; MemberElement<xs::CstringType, _altova_mi_t_altova_CPrintedDrawingType_altova_Location> Location; struct Location { typedef Iterator<xs::CstringType> iterator; }; QIF191_EXPORT void SetXsiType(); }; } // namespace t } // namespace qif191 //#endif // _ALTOVA_INCLUDED_QIFDocument_ALTOVA_t_ALTOVA_CPrintedDrawingType
[ "dc@capvidia.com" ]
dc@capvidia.com
7dab30fa1e272efaa5a42ae58ee418b181750ee3
7633024d83d9ade04a4f00d08dfe8ff3897989b1
/include/Turret.h
bc5f2d76d5f62be184604f2fa82979959672885d
[]
no_license
dividedbyxiro/TurretGame
064a4bf96c0cd02c749d540e9a85179659de077b
1529dbfde1f86b7d32fe2e7eb10439aed0ce7482
refs/heads/master
2020-03-11T17:48:16.248782
2018-06-03T19:59:26
2018-06-03T19:59:26
130,157,296
0
0
null
null
null
null
UTF-8
C++
false
false
636
h
#ifndef TURRET_H #define TURRET_H class Turret { public: Turret(); virtual ~Turret(); void move(); void stop(); void start(); void setPosition(int x, int y); void setDirection(double newDirection); int getXPos(); int getYPos(); double getAngle(); int getWidth(); int getHeight(); double getDirection(); bool isStopped(); protected: private: double angle; int xPos; int yPos; double direction; bool stopped; int width; int height; }; #endif // TURRET_H
[ "dividedbyxiro@gmail.com" ]
dividedbyxiro@gmail.com
4374afbdc16833ff6c6ad7df3152c1f6edec61fc
a000c3f08636667abd6db8bd51de6d8b1cedd22d
/ExternalLibs/GeoTools/Mathematics/NURBSVolume.h
ada6f6d5173d49aed46978811008adfda3968689
[ "BSL-1.0" ]
permissive
teshaTe/2D-heterogeneous-metamorphosis
fd8600b02496282cf332a1c6def17f9f523751c2
66848a3684bc8d3659ada4bf6a37dd6c72e83839
refs/heads/master
2023-05-01T09:15:15.390011
2021-05-24T21:52:15
2021-05-24T21:52:15
135,857,976
3
0
null
null
null
null
UTF-8
C++
false
false
9,651
h
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2021 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 4.0.2019.12.28 #pragma once #include <Mathematics/BasisFunction.h> #include <Mathematics/Vector.h> namespace gte { template <int N, typename Real> class NURBSVolume { public: // Construction. If the input controls is non-null, a copy is made of // the controls. To defer setting the control points or weights, pass // null pointers and later access the control points or weights via // GetControls(), GetWeights(), SetControl(), or SetWeight() member // functions. The 'controls' and 'weights' must be stored in // lexicographical order, // attribute[i0 + numControls0 * (i1 + numControls1 * i2)] // As a 3D array, this corresponds to attribute3D[i2][i1][i0]. NURBSVolume(BasisFunctionInput<Real> const& input0, BasisFunctionInput<Real> const& input1, BasisFunctionInput<Real> const& input2, Vector<N, Real> const* controls, Real const* weights) : mConstructed(false) { BasisFunctionInput<Real> const* input[3] = { &input0, &input1, &input2 }; for (int i = 0; i < 3; ++i) { mNumControls[i] = input[i]->numControls; mBasisFunction[i].Create(*input[i]); } // The replication of control points for periodic splines is // avoided by wrapping the i-loop index in Evaluate. int numControls = mNumControls[0] * mNumControls[1] * mNumControls[2]; mControls.resize(numControls); mWeights.resize(numControls); if (controls) { std::copy(controls, controls + numControls, mControls.begin()); } else { Vector<N, Real> zero{ (Real)0 }; std::fill(mControls.begin(), mControls.end(), zero); } if (weights) { std::copy(weights, weights + numControls, mWeights.begin()); } else { std::fill(mWeights.begin(), mWeights.end(), (Real)0); } mConstructed = true; } // To validate construction, create an object as shown: // NURBSVolume<N, Real> volume(parameters); // if (!volume) { <constructor failed, handle accordingly>; } inline operator bool() const { return mConstructed; } // Member access. The index 'dim' must be in {0,1,2}. inline BasisFunction<Real> const& GetBasisFunction(int dim) const { return mBasisFunction[dim]; } inline Real GetMinDomain(int dim) const { return mBasisFunction[dim].GetMinDomain(); } inline Real GetMaxDomain(int dim) const { return mBasisFunction[dim].GetMaxDomain(); } inline int GetNumControls(int dim) const { return mNumControls[dim]; } inline Vector<N, Real> const* GetControls() const { return mControls.data(); } inline Vector<N, Real>* GetControls() { return mControls.data(); } inline Real const* GetWeights() const { return mWeights.data(); } inline Real* GetWeights() { return mWeights.data(); } // Evaluation of the volume. The function supports derivative // calculation through order 2; that is, order <= 2 is required. If // you want only the position, pass in order of 0. If you want the // position and first-order derivatives, pass in order of 1, and so // on. The output array 'jet' muist have enough storage to support // the maximum order. The values are ordered as: position X; // first-order derivatives dX/du, dX/dv, dX/dw; second-order // derivatives d2X/du2, d2X/dv2, d2X/dw2, d2X/dudv, d2X/dudw, // d2X/dvdw. enum { SUP_ORDER = 10 }; void Evaluate(Real u, Real v, Real w, unsigned int order, Vector<N, Real>* jet) const { if (!mConstructed || order >= SUP_ORDER) { // Errors were already generated during construction. for (unsigned int i = 0; i < SUP_ORDER; ++i) { jet[i].MakeZero(); } return; } int iumin, iumax, ivmin, ivmax, iwmin, iwmax; mBasisFunction[0].Evaluate(u, order, iumin, iumax); mBasisFunction[1].Evaluate(v, order, ivmin, ivmax); mBasisFunction[2].Evaluate(w, order, iwmin, iwmax); // Compute position. Vector<N, Real> X; Real h; Compute(0, 0, 0, iumin, iumax, ivmin, ivmax, iwmin, iwmax, X, h); Real invH = (Real)1 / h; jet[0] = invH * X; if (order >= 1) { // Compute first-order derivatives. Vector<N, Real> XDerU; Real hDerU; Compute(1, 0, 0, iumin, iumax, ivmin, ivmax, iwmin, iwmax, XDerU, hDerU); jet[1] = invH * (XDerU - hDerU * jet[0]); Vector<N, Real> XDerV; Real hDerV; Compute(0, 1, 0, iumin, iumax, ivmin, ivmax, iwmin, iwmax, XDerV, hDerV); jet[2] = invH * (XDerV - hDerV * jet[0]); Vector<N, Real> XDerW; Real hDerW; Compute(0, 0, 1, iumin, iumax, ivmin, ivmax, iwmin, iwmax, XDerW, hDerW); jet[3] = invH * (XDerW - hDerW * jet[0]); if (order >= 2) { // Compute second-order derivatives. Vector<N, Real> XDerUU; Real hDerUU; Compute(2, 0, 0, iumin, iumax, ivmin, ivmax, iwmin, iwmax, XDerUU, hDerUU); jet[4] = invH * (XDerUU - (Real)2 * hDerU * jet[1] - hDerUU * jet[0]); Vector<N, Real> XDerVV; Real hDerVV; Compute(0, 2, 0, iumin, iumax, ivmin, ivmax, iwmin, iwmax, XDerVV, hDerVV); jet[5] = invH * (XDerVV - (Real)2 * hDerV * jet[2] - hDerVV * jet[0]); Vector<N, Real> XDerWW; Real hDerWW; Compute(0, 0, 2, iumin, iumax, ivmin, ivmax, iwmin, iwmax, XDerWW, hDerWW); jet[6] = invH * (XDerWW - (Real)2 * hDerW * jet[3] - hDerWW * jet[0]); Vector<N, Real> XDerUV; Real hDerUV; Compute(1, 1, 0, iumin, iumax, ivmin, ivmax, iwmin, iwmax, XDerUV, hDerUV); jet[7] = invH * (XDerUV - hDerU * jet[2] - hDerV * jet[1] - hDerUV * jet[0]); Vector<N, Real> XDerUW; Real hDerUW; Compute(1, 0, 1, iumin, iumax, ivmin, ivmax, iwmin, iwmax, XDerUW, hDerUW); jet[8] = invH * (XDerUW - hDerU * jet[3] - hDerW * jet[1] - hDerUW * jet[0]); Vector<N, Real> XDerVW; Real hDerVW; Compute(0, 1, 1, iumin, iumax, ivmin, ivmax, iwmin, iwmax, XDerVW, hDerVW); jet[9] = invH * (XDerVW - hDerV * jet[3] - hDerW * jet[2] - hDerVW * jet[0]); } } } private: // Support for Evaluate(...). void Compute(unsigned int uOrder, unsigned int vOrder, unsigned int wOrder, int iumin, int iumax, int ivmin, int ivmax, int iwmin, int iwmax, Vector<N, Real>& X, Real& h) const { // The j*-indices introduce a tiny amount of overhead in order to // handle both aperiodic and periodic splines. For aperiodic // splines, j* = i* always. int const numControls0 = mNumControls[0]; int const numControls1 = mNumControls[1]; int const numControls2 = mNumControls[2]; X.MakeZero(); h = (Real)0; for (int iw = iwmin; iw <= iwmax; ++iw) { Real tmpw = mBasisFunction[2].GetValue(wOrder, iw); int jw = (iw >= numControls2 ? iw - numControls2 : iw); for (int iv = ivmin; iv <= ivmax; ++iv) { Real tmpv = mBasisFunction[1].GetValue(vOrder, iv); Real tmpvw = tmpv * tmpw; int jv = (iv >= numControls1 ? iv - numControls1 : iv); for (int iu = iumin; iu <= iumax; ++iu) { Real tmpu = mBasisFunction[0].GetValue(uOrder, iu); int ju = (iu >= numControls0 ? iu - numControls0 : iu); int index = ju + numControls0 * (jv + numControls1 * jw); Real tmp = (tmpu * tmpvw) * mWeights[index]; X += tmp * mControls[index]; h += tmp; } } } } std::array<BasisFunction<Real>, 3> mBasisFunction; std::array<int, 3> mNumControls; std::vector<Vector<N, Real>> mControls; std::vector<Real> mWeights; bool mConstructed; }; }
[ "alexander@m-xr.com" ]
alexander@m-xr.com
0b2f3ca35b484a0110b3d66d2a76eaa49f47f660
e1dff43a48cf75072b1b355c4f50fcce7284790b
/udt/src/buffer.cpp
29889d262e68c6ef0793d9e56b6c26f6f6272a20
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
jwagnerhki/UDR
3e3b9d420ce7758c2316645e09f29cb90f20e72b
351afc727d9e8d6d136f8c65bd69a39a7aa2a4f4
refs/heads/master
2021-06-24T21:59:11.266508
2021-01-18T11:02:30
2021-01-18T11:02:30
195,785,516
7
1
NOASSERTION
2019-07-08T10:00:09
2019-07-08T10:00:09
null
UTF-8
C++
false
false
14,918
cpp
/***************************************************************************** Copyright (c) 2001 - 2011, The Board of Trustees of the University of Illinois. 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 University of Illinois nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *****************************************************************************/ /***************************************************************************** written by Yunhong Gu, last updated 03/12/2011 *****************************************************************************/ #include <cstring> #include <cmath> #include "buffer.h" using namespace std; CSndBuffer::CSndBuffer(const int& size, const int& mss): m_BufLock(), m_pBlock(NULL), m_pFirstBlock(NULL), m_pCurrBlock(NULL), m_pLastBlock(NULL), m_pBuffer(NULL), m_iNextMsgNo(1), m_iSize(size), m_iMSS(mss), m_iCount(0) { // initial physical buffer of "size" m_pBuffer = new Buffer; m_pBuffer->m_pcData = new char [m_iSize * m_iMSS]; m_pBuffer->m_iSize = m_iSize; m_pBuffer->m_pNext = NULL; // circular linked list for out bound packets m_pBlock = new Block; Block* pb = m_pBlock; for (int i = 1; i < m_iSize; ++ i) { pb->m_pNext = new Block; pb->m_iMsgNo = 0; pb = pb->m_pNext; } pb->m_pNext = m_pBlock; pb = m_pBlock; char* pc = m_pBuffer->m_pcData; for (int i = 0; i < m_iSize; ++ i) { pb->m_pcData = pc; pb = pb->m_pNext; pc += m_iMSS; } m_pFirstBlock = m_pCurrBlock = m_pLastBlock = m_pBlock; #ifndef WIN32 pthread_mutex_init(&m_BufLock, NULL); #else m_BufLock = CreateMutex(NULL, false, NULL); #endif } CSndBuffer::~CSndBuffer() { Block* pb = m_pBlock->m_pNext; while (pb != m_pBlock) { Block* temp = pb; pb = pb->m_pNext; delete temp; } delete m_pBlock; while (m_pBuffer != NULL) { Buffer* temp = m_pBuffer; m_pBuffer = m_pBuffer->m_pNext; delete [] temp->m_pcData; delete temp; } #ifndef WIN32 pthread_mutex_destroy(&m_BufLock); #else CloseHandle(m_BufLock); #endif } void CSndBuffer::addBuffer(const char* data, const int& len, const int& ttl, const bool& order) { int size = len / m_iMSS; if ((len % m_iMSS) != 0) size ++; // dynamically increase sender buffer while (size + m_iCount >= m_iSize) increase(); uint64_t time = CTimer::getTime(); int32_t inorder = order; inorder <<= 29; Block* s = m_pLastBlock; for (int i = 0; i < size; ++ i) { int pktlen = len - i * m_iMSS; if (pktlen > m_iMSS) pktlen = m_iMSS; memcpy(s->m_pcData, data + i * m_iMSS, pktlen); s->m_iLength = pktlen; s->m_iMsgNo = m_iNextMsgNo | inorder; if (i == 0) s->m_iMsgNo |= 0x80000000; if (i == size - 1) s->m_iMsgNo |= 0x40000000; s->m_OriginTime = time; s->m_iTTL = ttl; s = s->m_pNext; } m_pLastBlock = s; CGuard::enterCS(m_BufLock); m_iCount += size; CGuard::leaveCS(m_BufLock); m_iNextMsgNo ++; if (m_iNextMsgNo == CMsgNo::m_iMaxMsgNo) m_iNextMsgNo = 1; } int CSndBuffer::addBufferFromFile(fstream& ifs, const int& len) { int size = len / m_iMSS; if ((len % m_iMSS) != 0) size ++; // dynamically increase sender buffer while (size + m_iCount >= m_iSize) increase(); Block* s = m_pLastBlock; int total = 0; for (int i = 0; i < size; ++ i) { if (ifs.bad() || ifs.fail() || ifs.eof()) break; int pktlen = len - i * m_iMSS; if (pktlen > m_iMSS) pktlen = m_iMSS; ifs.read(s->m_pcData, pktlen); if ((pktlen = ifs.gcount()) <= 0) break; // currently file transfer is only available in streaming mode, message is always in order, ttl = infinite s->m_iMsgNo = m_iNextMsgNo | 0x20000000; if (i == 0) s->m_iMsgNo |= 0x80000000; if (i == size - 1) s->m_iMsgNo |= 0x40000000; s->m_iLength = pktlen; s->m_iTTL = -1; s = s->m_pNext; total += pktlen; } m_pLastBlock = s; CGuard::enterCS(m_BufLock); m_iCount += size; CGuard::leaveCS(m_BufLock); m_iNextMsgNo ++; if (m_iNextMsgNo == CMsgNo::m_iMaxMsgNo) m_iNextMsgNo = 1; return total; } int CSndBuffer::readData(char** data, int32_t& msgno) { // No data to read if (m_pCurrBlock == m_pLastBlock) return 0; *data = m_pCurrBlock->m_pcData; int readlen = m_pCurrBlock->m_iLength; msgno = m_pCurrBlock->m_iMsgNo; m_pCurrBlock = m_pCurrBlock->m_pNext; return readlen; } int CSndBuffer::readData(char** data, const int offset, int32_t& msgno, int& msglen) { CGuard bufferguard(m_BufLock); Block* p = m_pFirstBlock; for (int i = 0; i < offset; ++ i) p = p->m_pNext; if ((p->m_iTTL >= 0) && ((CTimer::getTime() - p->m_OriginTime) / 1000 > (uint64_t)p->m_iTTL)) { msgno = p->m_iMsgNo & 0x1FFFFFFF; msglen = 1; p = p->m_pNext; bool move = false; while (msgno == (p->m_iMsgNo & 0x1FFFFFFF)) { if (p == m_pCurrBlock) move = true; p = p->m_pNext; if (move) m_pCurrBlock = p; msglen ++; } return -1; } *data = p->m_pcData; int readlen = p->m_iLength; msgno = p->m_iMsgNo; return readlen; } void CSndBuffer::ackData(const int& offset) { CGuard bufferguard(m_BufLock); for (int i = 0; i < offset; ++ i) m_pFirstBlock = m_pFirstBlock->m_pNext; m_iCount -= offset; CTimer::triggerEvent(); } int CSndBuffer::getCurrBufSize() const { return m_iCount; } void CSndBuffer::increase() { int unitsize = m_pBuffer->m_iSize; // new physical buffer Buffer* nbuf = NULL; try { nbuf = new Buffer; nbuf->m_pcData = new char [unitsize * m_iMSS]; } catch (...) { delete nbuf; throw CUDTException(3, 2, 0); } nbuf->m_iSize = unitsize; nbuf->m_pNext = NULL; // insert the buffer at the end of the buffer list Buffer* p = m_pBuffer; while (NULL != p->m_pNext) p = p->m_pNext; p->m_pNext = nbuf; // new packet blocks Block* nblk = NULL; try { nblk = new Block; } catch (...) { delete nblk; throw CUDTException(3, 2, 0); } Block* pb = nblk; for (int i = 1; i < unitsize; ++ i) { pb->m_pNext = new Block; pb = pb->m_pNext; } // insert the new blocks onto the existing one pb->m_pNext = m_pLastBlock->m_pNext; m_pLastBlock->m_pNext = nblk; pb = nblk; char* pc = nbuf->m_pcData; for (int i = 0; i < unitsize; ++ i) { pb->m_pcData = pc; pb = pb->m_pNext; pc += m_iMSS; } m_iSize += unitsize; } //////////////////////////////////////////////////////////////////////////////// CRcvBuffer::CRcvBuffer(CUnitQueue* queue, const int& bufsize): m_pUnit(NULL), m_iSize(bufsize), m_pUnitQueue(queue), m_iStartPos(0), m_iLastAckPos(0), m_iMaxPos(0), m_iNotch(0) { m_pUnit = new CUnit* [m_iSize]; for (int i = 0; i < m_iSize; ++ i) m_pUnit[i] = NULL; } CRcvBuffer::~CRcvBuffer() { for (int i = 0; i < m_iSize; ++ i) { if (NULL != m_pUnit[i]) { m_pUnit[i]->m_iFlag = 0; -- m_pUnitQueue->m_iCount; } } delete [] m_pUnit; } int CRcvBuffer::addData(CUnit* unit, int offset) { int pos = (m_iLastAckPos + offset) % m_iSize; if (offset > m_iMaxPos) m_iMaxPos = offset; if (NULL != m_pUnit[pos]) return -1; m_pUnit[pos] = unit; unit->m_iFlag = 1; ++ m_pUnitQueue->m_iCount; return 0; } int CRcvBuffer::readBuffer(char* data, const int& len) { int p = m_iStartPos; int lastack = m_iLastAckPos; int rs = len; while ((p != lastack) && (rs > 0)) { int unitsize = m_pUnit[p]->m_Packet.getLength() - m_iNotch; if (unitsize > rs) unitsize = rs; memcpy(data, m_pUnit[p]->m_Packet.m_pcData + m_iNotch, unitsize); data += unitsize; if ((rs > unitsize) || (rs == m_pUnit[p]->m_Packet.getLength() - m_iNotch)) { CUnit* tmp = m_pUnit[p]; m_pUnit[p] = NULL; tmp->m_iFlag = 0; -- m_pUnitQueue->m_iCount; if (++ p == m_iSize) p = 0; m_iNotch = 0; } else m_iNotch += rs; rs -= unitsize; } m_iStartPos = p; return len - rs; } int CRcvBuffer::readBufferToFile(fstream& ofs, const int& len) { int p = m_iStartPos; int lastack = m_iLastAckPos; int rs = len; while ((p != lastack) && (rs > 0)) { int unitsize = m_pUnit[p]->m_Packet.getLength() - m_iNotch; if (unitsize > rs) unitsize = rs; ofs.write(m_pUnit[p]->m_Packet.m_pcData + m_iNotch, unitsize); if (ofs.fail()) break; if ((rs > unitsize) || (rs == m_pUnit[p]->m_Packet.getLength() - m_iNotch)) { CUnit* tmp = m_pUnit[p]; m_pUnit[p] = NULL; tmp->m_iFlag = 0; -- m_pUnitQueue->m_iCount; if (++ p == m_iSize) p = 0; m_iNotch = 0; } else m_iNotch += rs; rs -= unitsize; } m_iStartPos = p; return len - rs; } void CRcvBuffer::ackData(const int& len) { m_iLastAckPos = (m_iLastAckPos + len) % m_iSize; m_iMaxPos -= len; if (m_iMaxPos < 0) m_iMaxPos = 0; CTimer::triggerEvent(); } int CRcvBuffer::getAvailBufSize() const { // One slot must be empty in order to tell the difference between "empty buffer" and "full buffer" return m_iSize - getRcvDataSize() - 1; } int CRcvBuffer::getRcvDataSize() const { if (m_iLastAckPos >= m_iStartPos) return m_iLastAckPos - m_iStartPos; return m_iSize + m_iLastAckPos - m_iStartPos; } void CRcvBuffer::dropMsg(const int32_t& msgno) { for (int i = m_iStartPos, n = (m_iLastAckPos + m_iMaxPos) % m_iSize; i != n; i = (i + 1) % m_iSize) if ((NULL != m_pUnit[i]) && (msgno == m_pUnit[i]->m_Packet.m_iMsgNo)) m_pUnit[i]->m_iFlag = 3; } int CRcvBuffer::readMsg(char* data, const int& len) { int p, q; bool passack; if (!scanMsg(p, q, passack)) return 0; int rs = len; while (p != (q + 1) % m_iSize) { int unitsize = m_pUnit[p]->m_Packet.getLength(); if ((rs >= 0) && (unitsize > rs)) unitsize = rs; if (unitsize > 0) { memcpy(data, m_pUnit[p]->m_Packet.m_pcData, unitsize); data += unitsize; rs -= unitsize; } if (!passack) { CUnit* tmp = m_pUnit[p]; m_pUnit[p] = NULL; tmp->m_iFlag = 0; -- m_pUnitQueue->m_iCount; } else m_pUnit[p]->m_iFlag = 2; if (++ p == m_iSize) p = 0; } if (!passack) m_iStartPos = (q + 1) % m_iSize; return len - rs; } int CRcvBuffer::getRcvMsgNum() { int p, q; bool passack; return scanMsg(p, q, passack) ? 1 : 0; } bool CRcvBuffer::scanMsg(int& p, int& q, bool& passack) { // empty buffer if ((m_iStartPos == m_iLastAckPos) && (m_iMaxPos <= 0)) return false; //skip all bad msgs at the beginning while (m_iStartPos != m_iLastAckPos) { if (NULL == m_pUnit[m_iStartPos]) { if (++ m_iStartPos == m_iSize) m_iStartPos = 0; continue; } if ((1 == m_pUnit[m_iStartPos]->m_iFlag) && (m_pUnit[m_iStartPos]->m_Packet.getMsgBoundary() > 1)) { bool good = true; // look ahead for the whole message for (int i = m_iStartPos; i != m_iLastAckPos;) { if ((NULL == m_pUnit[i]) || (1 != m_pUnit[i]->m_iFlag)) { good = false; break; } if ((m_pUnit[i]->m_Packet.getMsgBoundary() == 1) || (m_pUnit[i]->m_Packet.getMsgBoundary() == 3)) break; if (++ i == m_iSize) i = 0; } if (good) break; } CUnit* tmp = m_pUnit[m_iStartPos]; m_pUnit[m_iStartPos] = NULL; tmp->m_iFlag = 0; -- m_pUnitQueue->m_iCount; if (++ m_iStartPos == m_iSize) m_iStartPos = 0; } p = -1; // message head q = m_iStartPos; // message tail passack = m_iStartPos == m_iLastAckPos; bool found = false; // looking for the first message for (int i = 0, n = m_iMaxPos + getRcvDataSize(); i <= n; ++ i) { if ((NULL != m_pUnit[q]) && (1 == m_pUnit[q]->m_iFlag)) { switch (m_pUnit[q]->m_Packet.getMsgBoundary()) { case 3: // 11 p = q; found = true; break; case 2: // 10 p = q; break; case 1: // 01 if (p != -1) found = true; } } else { // a hole in this message, not valid, restart search p = -1; } if (found) { // the msg has to be ack'ed or it is allowed to read out of order, and was not read before if (!passack || !m_pUnit[q]->m_Packet.getMsgOrderFlag()) break; found = false; } if (++ q == m_iSize) q = 0; if (q == m_iLastAckPos) passack = true; } // no msg found if (!found) { // if the message is larger than the receiver buffer, return part of the message if ((p != -1) && ((q + 1) % m_iSize == p)) found = true; } return found; }
[ "aheath@uchicago.edu" ]
aheath@uchicago.edu
3b42cba294e70e7ba9a10330196af4f6f6f7eec5
15e5e7bc5a8626014034d4edcc24dd6dcb143da2
/src/TTWriteADConfigBaF2.cxx
5fb27279895f33bfe66f12b433a22a9b0d2d1910
[]
no_license
A2-Collaboration/TAPSsc
29bb4cc59d0f9888c54d52d91e1d2057ed6011fa
f5dc1af1300b9d98f0bcf6fcec05ca3c377fc4df
refs/heads/master
2020-05-26T00:34:06.093637
2013-12-10T17:40:35
2013-12-10T17:40:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,328
cxx
/************************************************************************* * Author: Thomas Strub, 2013 *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TTWriteADConfigBaF2 // // // // Class to write the AcquDAQ cofiguration files for BaF2 modules from // // a template file and values from the MySQL database. // // // ////////////////////////////////////////////////////////////////////////// #include "TTWriteADConfigBaF2.h" ClassImp(TTWriteADConfigBaF2) //______________________________________________________________________________ Bool_t TTWriteADConfigBaF2::ParseLine() { // Parses the line 'fLineIn' from the template file. // parse key line: 'Hardware-ID' if (TTUtils::IndexOf(fLineIn, "Hardware-ID:") != -1) { Int_t ch = 0; Int_t elem; Double_t tmp; // get map info from data base if (!TTMySQLManager::GetManager()->ReadElements("Map.BaF2.HWID", 1, &ch, fCrate, fModule, &elem)) { Error("ParseLine", "MySQLManager reported an error when trying to get 'Map.BaF2.HWID' values."); return kFALSE; } // get info from data base if (!TTMySQLManager::GetManager()->ReadParameters("Par.BaF2.HWID", 1, &elem, &tmp)) { Error("ParseLine", "MySQLManager reported an error when trying to get 'Par.BaF2.HWID' values."); return kFALSE; } else { // prepare output line sprintf(fLineOut, "Hardware-ID: %04d", (Int_t)tmp); return kTRUE; } } // keys for channel-wise configuration const Int_t keyN = 7; const Char_t* keySt[keyN] = { "Thr-CFD-Raw:", "Thr-LED1:", "Thr-LED2:", "Ped-LG:", "Ped-LGS:", "Ped-SG:", "Ped-SGS:" }; const Char_t* keyID[keyN] = { "Par.BaF2.Thr.CFD", "Par.BaF2.Thr.LED1", "Par.BaF2.Thr.LED2", "Par.BaF2.QAC.LG", "Par.BaF2.QAC.LGS", "Par.BaF2.QAC.SG", "Par.BaF2.QAC.SGS" }; // loop over keys for (Int_t i = 0; i < keyN; i++) { // check for key if (TTUtils::IndexOf(fLineIn, keySt[i]) != -1) { Double_t tmp[fNElements]; // get info from data base if (!TTMySQLManager::GetManager()->ReadParameters(keyID[i], fNElements, fElements, tmp)) { Error("ParseLine", "MySQLManager reported an error when trying to get '%s' values.", keyID[i]); return kFALSE; } else { // prepare output line sprintf(fLineOut, keySt[i]); for (Int_t j = 0; j < fNElements; j++) sprintf(fLineOut, "%s %.f", fLineOut, tmp[j]); return kTRUE; } } } // no key to be overwritten found -> copy input to output line sprintf(fLineOut,"%s", fLineIn); return kTRUE; }
[ "dominik.werthmueller@unibas.ch" ]
dominik.werthmueller@unibas.ch
f4b175c85010bf085d43b7de1999c9ed06cbd6c8
f7c80f2997f7b19da4c5d4588cb59d97d2b51c36
/qrenderdoc/Code/pyrenderdoc/ext_refcounts.h
214384307f040d32bdd46e43605209cae353afb2
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
ylyking/renderdoc
cee1a763aee13476fc29596ec3fe781bd4752b8f
8cc414a8f66ca886baa8ba38f5ee0dd36d4f1a46
refs/heads/v1.x
2021-01-20T17:35:39.089306
2020-10-16T15:08:47
2020-10-16T15:13:30
305,359,596
0
0
MIT
2020-10-19T11:53:56
2020-10-19T11:21:16
null
UTF-8
C++
false
false
2,947
h
/****************************************************************************** * The MIT License (MIT) * * Copyright (c) 2019-2020 Baldur Karlsson * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ******************************************************************************/ #pragma once /////////////////////////////////////////////////////////////////////////// // Helper template used to implement tp_init for a refcounted type, handles // constructing a new object from a PyObject *argsTuple template <typename refcountedType> inline refcountedType *MakeFromArgsTuple(PyObject *args); template <> inline SDChunk *MakeFromArgsTuple<SDChunk>(PyObject *args) { int res = 0; PyObject *name_obj = NULL; SDChunk *result = NULL; rdcstr name; if(!SWIG_Python_UnpackTuple(args, "new_SDChunk", 1, 1, &name_obj)) SWIG_fail; res = ConvertFromPy(name_obj, name); if(!SWIG_IsOK(res)) SWIG_exception_fail(SWIG_ArgError(res), "invalid name used to create SDChunk, expected string"); result = new SDChunk(name.c_str()); return result; fail: return NULL; } template <> inline SDObject *MakeFromArgsTuple<SDObject>(PyObject *args) { int res = 0; PyObject *params[2] = {NULL}; SDObject *result = NULL; rdcstr name, typeName; if(!SWIG_Python_UnpackTuple(args, "new_SDObject", 2, 2, params)) SWIG_fail; res = ConvertFromPy(params[0], name); if(!SWIG_IsOK(res)) SWIG_exception_fail(SWIG_ArgError(res), "invalid name used to create SDObject, expected string"); res = ConvertFromPy(params[1], typeName); if(!SWIG_IsOK(res)) SWIG_exception_fail(SWIG_ArgError(res), "invalid type name used to create SDObject, expected string"); result = new SDObject(name.c_str(), typeName); return result; fail: return NULL; } template <> inline SDFile *MakeFromArgsTuple<SDFile>(PyObject *args) { return new SDFile(); }
[ "baldurk@baldurk.org" ]
baldurk@baldurk.org
a6836c6af2b85297f12f3bb2e4bf08094fd2d3a2
3bc10dca7b8d7383ddc121e864f22f0006e34603
/Client/LoginPage.h
7227d416f262c0078535ab8f3b9635318aa94cc1
[]
no_license
cloudstlife/AnimEditor
0578d2f6338b9ad18697230bec0300744ba190c4
f5919b2e026d482f1ad75d05eb67d5b238fa3143
refs/heads/master
2016-09-06T00:51:32.147553
2015-07-14T02:54:24
2015-07-14T02:54:24
39,050,108
0
0
null
null
null
null
UTF-8
C++
false
false
579
h
#ifndef LOGINPAGE_H #define LOGINPAGE_H #include "IBaseUI.h" namespace Ogre { class LoginPage: public IBaseUI { public: LoginPage(); ~LoginPage(); virtual void Initialize(IUiElement* ui, UIState* state); virtual void injectAppMsg( uint uMsg, int wParam, int lParam ); virtual void update( float timeLapse ); bool CheckLogin(const Message::Base& msg); bool LoginPageCompelete(const Message::Base& msg); void OpenLoginTips(); void SetLoginPageFocusControl(); void ResetLoginPageMiMa(); private: IUiElement* m_pUi; UIState* m_pCurState; }; } #endif
[ "cloudstlife@163.com" ]
cloudstlife@163.com
53c42fe8ef4b849c2bc626b4edf85729a109cba7
cba90bb32332408d01eda8bd42517d2427315e86
/libcef_dll/ctocpp/print_handler_ctocpp.h
a0574f66b3ce61f72fd9cd2bad4ba3aca60704f9
[]
no_license
desura/desura-cef1
1a5f8cf1ad7abdb000dd153ae161929fb911b6f7
54106e0abdbbb362b4d547af3095faeb467500d3
refs/heads/master
2021-01-22T07:39:08.505156
2014-03-28T22:19:31
2014-03-28T22:19:31
17,005,715
1
1
null
null
null
null
UTF-8
C++
false
false
1,732
h
// Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights // reserved. Use of this source code is governed by a BSD-style license that // can be found in the LICENSE file. // // ------------------------------------------------------------------------- // // This file was generated by the CEF translator tool and should not edited // by hand. See the translator.README.txt file in the tools directory for // more information. // #ifndef _PRINTHANDLER_CTOCPP_H #define _PRINTHANDLER_CTOCPP_H #ifndef BUILDING_CEF_SHARED #pragma message("Warning: "__FILE__" may be accessed DLL-side only") #else // BUILDING_CEF_SHARED #include "include/cef.h" #include "include/cef_capi.h" #include "libcef_dll/ctocpp/ctocpp.h" // Wrap a C structure with a C++ class. // This class may be instantiated and accessed DLL-side only. class CefPrintHandlerCToCpp : public CefCToCpp<CefPrintHandlerCToCpp, CefPrintHandler, cef_print_handler_t> { public: CefPrintHandlerCToCpp(cef_print_handler_t* str) : CefCToCpp<CefPrintHandlerCToCpp, CefPrintHandler, cef_print_handler_t>( str) {} virtual ~CefPrintHandlerCToCpp() {} // CefPrintHandler methods virtual bool GetPrintOptions(CefRefPtr<CefBrowser> browser, CefPrintOptions& printOptions) OVERRIDE; virtual bool GetPrintHeaderFooter(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, const CefPrintInfo& printInfo, const CefString& url, const CefString& title, int currentPage, int maxPages, CefString& topLeft, CefString& topCenter, CefString& topRight, CefString& bottomLeft, CefString& bottomCenter, CefString& bottomRight) OVERRIDE; }; #endif // BUILDING_CEF_SHARED #endif // _PRINTHANDLER_CTOCPP_H
[ "mark@moddb.com" ]
mark@moddb.com
e1a0a98bf210c7fb0f2625a9fc88f735ce902703
4689b060a261e6eca568ac9a8fefe4453b7115d9
/tests/tests.cpp
d93a2f42c94b04733c12f7c41c8466c4510417bd
[]
no_license
nevyn/spotcache
1c96e16b2a63469da4ab42d75312f57d38862996
7d05cac392d9f1144d750e806c59af49194febe2
refs/heads/master
2021-01-18T13:58:20.122788
2009-07-24T11:54:22
2009-07-24T11:54:22
467,529
1
0
null
null
null
null
UTF-8
C++
false
false
10,027
cpp
/* Generated file, do not edit */ #ifndef CXXTEST_RUNNING #define CXXTEST_RUNNING #endif #define _CXXTEST_HAVE_STD #define _CXXTEST_HAVE_EH #include <cxxtest/TestListener.h> #include <cxxtest/TestTracker.h> #include <cxxtest/TestRunner.h> #include <cxxtest/RealDescriptions.h> #include <cxxtest/ErrorPrinter.h> int main() { return CxxTest::ErrorPrinter().run(); } #include "tests/SqliteDbSuite.h" static CreateDbSuite suite_CreateDbSuite; static CxxTest::List Tests_CreateDbSuite = { 0, 0 }; CxxTest::StaticSuiteDescription suiteDescription_CreateDbSuite( "tests/SqliteDbSuite.h", 13, "CreateDbSuite", suite_CreateDbSuite, Tests_CreateDbSuite ); static class TestDescription_CreateDbSuite_testCreateTable : public CxxTest::RealTestDescription { public: TestDescription_CreateDbSuite_testCreateTable() : CxxTest::RealTestDescription( Tests_CreateDbSuite, suiteDescription_CreateDbSuite, 28, "testCreateTable" ) {} void runTest() { suite_CreateDbSuite.testCreateTable(); } } testDescription_CreateDbSuite_testCreateTable; #include "tests/SqliteTableSuite.h" static CreateTableSuite suite_CreateTableSuite; static CxxTest::List Tests_CreateTableSuite = { 0, 0 }; CxxTest::StaticSuiteDescription suiteDescription_CreateTableSuite( "tests/SqliteTableSuite.h", 11, "CreateTableSuite", suite_CreateTableSuite, Tests_CreateTableSuite ); static class TestDescription_CreateTableSuite_testInsert : public CxxTest::RealTestDescription { public: TestDescription_CreateTableSuite_testInsert() : CxxTest::RealTestDescription( Tests_CreateTableSuite, suiteDescription_CreateTableSuite, 28, "testInsert" ) {} void runTest() { suite_CreateTableSuite.testInsert(); } } testDescription_CreateTableSuite_testInsert; static class TestDescription_CreateTableSuite_testBlob : public CxxTest::RealTestDescription { public: TestDescription_CreateTableSuite_testBlob() : CxxTest::RealTestDescription( Tests_CreateTableSuite, suiteDescription_CreateTableSuite, 64, "testBlob" ) {} void runTest() { suite_CreateTableSuite.testBlob(); } } testDescription_CreateTableSuite_testBlob; #include "tests/SqliteCacheSuite.h" static SqliteCacheSuite *suite_SqliteCacheSuite = 0; static CxxTest::List Tests_SqliteCacheSuite = { 0, 0 }; CxxTest::DynamicSuiteDescription<SqliteCacheSuite> suiteDescription_SqliteCacheSuite( "tests/SqliteCacheSuite.h", 27, "SqliteCacheSuite", Tests_SqliteCacheSuite, suite_SqliteCacheSuite, 41, 42 ); static class TestDescription_SqliteCacheSuite_testAvailabilityOfNonExistingObject : public CxxTest::RealTestDescription { public: TestDescription_SqliteCacheSuite_testAvailabilityOfNonExistingObject() : CxxTest::RealTestDescription( Tests_SqliteCacheSuite, suiteDescription_SqliteCacheSuite, 47, "testAvailabilityOfNonExistingObject" ) {} void runTest() { if ( suite_SqliteCacheSuite ) suite_SqliteCacheSuite->testAvailabilityOfNonExistingObject(); } } testDescription_SqliteCacheSuite_testAvailabilityOfNonExistingObject; static class TestDescription_SqliteCacheSuite_testHasObjectOfNonExistingObject : public CxxTest::RealTestDescription { public: TestDescription_SqliteCacheSuite_testHasObjectOfNonExistingObject() : CxxTest::RealTestDescription( Tests_SqliteCacheSuite, suiteDescription_SqliteCacheSuite, 52, "testHasObjectOfNonExistingObject" ) {} void runTest() { if ( suite_SqliteCacheSuite ) suite_SqliteCacheSuite->testHasObjectOfNonExistingObject(); } } testDescription_SqliteCacheSuite_testHasObjectOfNonExistingObject; static class TestDescription_SqliteCacheSuite_testReadingNonExistingObject : public CxxTest::RealTestDescription { public: TestDescription_SqliteCacheSuite_testReadingNonExistingObject() : CxxTest::RealTestDescription( Tests_SqliteCacheSuite, suiteDescription_SqliteCacheSuite, 56, "testReadingNonExistingObject" ) {} void runTest() { if ( suite_SqliteCacheSuite ) suite_SqliteCacheSuite->testReadingNonExistingObject(); } } testDescription_SqliteCacheSuite_testReadingNonExistingObject; static class TestDescription_SqliteCacheSuite_testWritePartial : public CxxTest::RealTestDescription { public: TestDescription_SqliteCacheSuite_testWritePartial() : CxxTest::RealTestDescription( Tests_SqliteCacheSuite, suiteDescription_SqliteCacheSuite, 64, "testWritePartial" ) {} void runTest() { if ( suite_SqliteCacheSuite ) suite_SqliteCacheSuite->testWritePartial(); } } testDescription_SqliteCacheSuite_testWritePartial; static class TestDescription_SqliteCacheSuite_testPartialAvailability : public CxxTest::RealTestDescription { public: TestDescription_SqliteCacheSuite_testPartialAvailability() : CxxTest::RealTestDescription( Tests_SqliteCacheSuite, suiteDescription_SqliteCacheSuite, 69, "testPartialAvailability" ) {} void runTest() { if ( suite_SqliteCacheSuite ) suite_SqliteCacheSuite->testPartialAvailability(); } } testDescription_SqliteCacheSuite_testPartialAvailability; static class TestDescription_SqliteCacheSuite_testHasObjectOfPartialObject : public CxxTest::RealTestDescription { public: TestDescription_SqliteCacheSuite_testHasObjectOfPartialObject() : CxxTest::RealTestDescription( Tests_SqliteCacheSuite, suiteDescription_SqliteCacheSuite, 74, "testHasObjectOfPartialObject" ) {} void runTest() { if ( suite_SqliteCacheSuite ) suite_SqliteCacheSuite->testHasObjectOfPartialObject(); } } testDescription_SqliteCacheSuite_testHasObjectOfPartialObject; static class TestDescription_SqliteCacheSuite_testReadingPartial : public CxxTest::RealTestDescription { public: TestDescription_SqliteCacheSuite_testReadingPartial() : CxxTest::RealTestDescription( Tests_SqliteCacheSuite, suiteDescription_SqliteCacheSuite, 78, "testReadingPartial" ) {} void runTest() { if ( suite_SqliteCacheSuite ) suite_SqliteCacheSuite->testReadingPartial(); } } testDescription_SqliteCacheSuite_testReadingPartial; static class TestDescription_SqliteCacheSuite_testTwoPartialsOneObject : public CxxTest::RealTestDescription { public: TestDescription_SqliteCacheSuite_testTwoPartialsOneObject() : CxxTest::RealTestDescription( Tests_SqliteCacheSuite, suiteDescription_SqliteCacheSuite, 93, "testTwoPartialsOneObject" ) {} void runTest() { if ( suite_SqliteCacheSuite ) suite_SqliteCacheSuite->testTwoPartialsOneObject(); } } testDescription_SqliteCacheSuite_testTwoPartialsOneObject; static class TestDescription_SqliteCacheSuite_testFinalizingPartial : public CxxTest::RealTestDescription { public: TestDescription_SqliteCacheSuite_testFinalizingPartial() : CxxTest::RealTestDescription( Tests_SqliteCacheSuite, suiteDescription_SqliteCacheSuite, 98, "testFinalizingPartial" ) {} void runTest() { if ( suite_SqliteCacheSuite ) suite_SqliteCacheSuite->testFinalizingPartial(); } } testDescription_SqliteCacheSuite_testFinalizingPartial; static class TestDescription_SqliteCacheSuite_testCompleteAvailability : public CxxTest::RealTestDescription { public: TestDescription_SqliteCacheSuite_testCompleteAvailability() : CxxTest::RealTestDescription( Tests_SqliteCacheSuite, suiteDescription_SqliteCacheSuite, 113, "testCompleteAvailability" ) {} void runTest() { if ( suite_SqliteCacheSuite ) suite_SqliteCacheSuite->testCompleteAvailability(); } } testDescription_SqliteCacheSuite_testCompleteAvailability; static class TestDescription_SqliteCacheSuite_testHasObjectOfCompleteObject : public CxxTest::RealTestDescription { public: TestDescription_SqliteCacheSuite_testHasObjectOfCompleteObject() : CxxTest::RealTestDescription( Tests_SqliteCacheSuite, suiteDescription_SqliteCacheSuite, 119, "testHasObjectOfCompleteObject" ) {} void runTest() { if ( suite_SqliteCacheSuite ) suite_SqliteCacheSuite->testHasObjectOfCompleteObject(); } } testDescription_SqliteCacheSuite_testHasObjectOfCompleteObject; static class TestDescription_SqliteCacheSuite_testTurningExistingObjectIntoPartial : public CxxTest::RealTestDescription { public: TestDescription_SqliteCacheSuite_testTurningExistingObjectIntoPartial() : CxxTest::RealTestDescription( Tests_SqliteCacheSuite, suiteDescription_SqliteCacheSuite, 123, "testTurningExistingObjectIntoPartial" ) {} void runTest() { if ( suite_SqliteCacheSuite ) suite_SqliteCacheSuite->testTurningExistingObjectIntoPartial(); } } testDescription_SqliteCacheSuite_testTurningExistingObjectIntoPartial; static class TestDescription_SqliteCacheSuite_testGettingSize : public CxxTest::RealTestDescription { public: TestDescription_SqliteCacheSuite_testGettingSize() : CxxTest::RealTestDescription( Tests_SqliteCacheSuite, suiteDescription_SqliteCacheSuite, 136, "testGettingSize" ) {} void runTest() { if ( suite_SqliteCacheSuite ) suite_SqliteCacheSuite->testGettingSize(); } } testDescription_SqliteCacheSuite_testGettingSize; static class TestDescription_SqliteCacheSuite_testOversteppingCacheSize : public CxxTest::RealTestDescription { public: TestDescription_SqliteCacheSuite_testOversteppingCacheSize() : CxxTest::RealTestDescription( Tests_SqliteCacheSuite, suiteDescription_SqliteCacheSuite, 141, "testOversteppingCacheSize" ) {} void runTest() { if ( suite_SqliteCacheSuite ) suite_SqliteCacheSuite->testOversteppingCacheSize(); } } testDescription_SqliteCacheSuite_testOversteppingCacheSize; static class TestDescription_SqliteCacheSuite_testCorruptingStore : public CxxTest::RealTestDescription { public: TestDescription_SqliteCacheSuite_testCorruptingStore() : CxxTest::RealTestDescription( Tests_SqliteCacheSuite, suiteDescription_SqliteCacheSuite, 172, "testCorruptingStore" ) {} void runTest() { if ( suite_SqliteCacheSuite ) suite_SqliteCacheSuite->testCorruptingStore(); } } testDescription_SqliteCacheSuite_testCorruptingStore; static class TestDescription_SqliteCacheSuite_testPersistsMaxSize : public CxxTest::RealTestDescription { public: TestDescription_SqliteCacheSuite_testPersistsMaxSize() : CxxTest::RealTestDescription( Tests_SqliteCacheSuite, suiteDescription_SqliteCacheSuite, 195, "testPersistsMaxSize" ) {} void runTest() { if ( suite_SqliteCacheSuite ) suite_SqliteCacheSuite->testPersistsMaxSize(); } } testDescription_SqliteCacheSuite_testPersistsMaxSize; #include <cxxtest/Root.cpp>
[ "joachimb@gmail.com" ]
joachimb@gmail.com
baed285aa9a9cecda45efbf589d9389bdc72dc3c
5a86421f61da5c7faf7443defb06423f18565332
/storage/src/vespa/storage/common/hostreporter/networkreporter.h
17ecdb4517b1b5190808ed1d06e7ddf9f34f62fa
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
t1707/vespa
1d62116f4345dbc5020dbfcab1fc2934e82e5d68
9f4859e9996ac9913ce80ed9b209f683507fe157
refs/heads/master
2021-04-03T06:24:10.556834
2018-03-08T17:02:09
2018-03-08T17:02:09
124,473,863
0
0
Apache-2.0
2018-03-15T06:06:27
2018-03-09T02:07:53
Java
UTF-8
C++
false
false
593
h
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #ifndef STORAGE_SRC_CPP_STORAGE_COMMON_HOSTREPORTER_NETWORKREPORTER_H_ #define STORAGE_SRC_CPP_STORAGE_COMMON_HOSTREPORTER_NETWORKREPORTER_H_ #include "hostreporter.h" namespace storage { class NetworkReporter: public HostReporter { public: NetworkReporter() {}; ~NetworkReporter() override {}; void report(vespalib::JsonStream& jsonreport) override; }; } /* namespace storage */ #endif /* STORAGE_SRC_CPP_STORAGE_COMMON_HOSTREPORTER_NETWORKREPORTER_H_ */
[ "bratseth@yahoo-inc.com" ]
bratseth@yahoo-inc.com
372eb0ad6d6b6b9163e4212dc8fd056da358abe7
a8450d0cd05feb167efd1b653033881a5cc19c62
/deps/rocksdb-6.7.3/utilities/blob_db/blob_compaction_filter.cc
7b37e2e1ebdc4181b4bc2eccf38a187bddb43704
[ "GPL-2.0-only", "Apache-2.0", "BSD-3-Clause", "MIT" ]
permissive
davidtavarez/GrinPlusPlus
9a563e0b72c8c1503db065928ee175b4420733a6
26ae2019f0e7a0d40dd9b3e12c287415cab67404
refs/heads/master
2020-08-23T16:10:31.103016
2020-04-12T12:08:51
2020-04-12T12:08:51
216,659,169
0
0
MIT
2020-03-12T18:21:36
2019-10-21T20:27:32
C++
UTF-8
C++
false
false
8,761
cc
// Copyright (c) 2011-present, Facebook, Inc. All rights reserved. // This source code is licensed under both the GPLv2 (found in the // COPYING file in the root directory) and Apache 2.0 License // (found in the LICENSE.Apache file in the root directory). #ifndef ROCKSDB_LITE #include "utilities/blob_db/blob_compaction_filter.h" #include "db/dbformat.h" namespace rocksdb { namespace blob_db { CompactionFilter::Decision BlobIndexCompactionFilterBase::FilterV2( int /*level*/, const Slice& key, ValueType value_type, const Slice& value, std::string* /*new_value*/, std::string* /*skip_until*/) const { if (value_type != kBlobIndex) { return Decision::kKeep; } BlobIndex blob_index; Status s = blob_index.DecodeFrom(value); if (!s.ok()) { // Unable to decode blob index. Keeping the value. return Decision::kKeep; } if (blob_index.HasTTL() && blob_index.expiration() <= current_time_) { // Expired expired_count_++; expired_size_ += key.size() + value.size(); return Decision::kRemove; } if (!blob_index.IsInlined() && blob_index.file_number() < context_.next_file_number && context_.current_blob_files.count(blob_index.file_number()) == 0) { // Corresponding blob file gone (most likely, evicted by FIFO eviction). evicted_count_++; evicted_size_ += key.size() + value.size(); return Decision::kRemove; } if (context_.fifo_eviction_seq > 0 && blob_index.HasTTL() && blob_index.expiration() < context_.evict_expiration_up_to) { // Hack: Internal key is passed to BlobIndexCompactionFilter for it to // get sequence number. ParsedInternalKey ikey; bool ok = ParseInternalKey(key, &ikey); // Remove keys that could have been remove by last FIFO eviction. // If get error while parsing key, ignore and continue. if (ok && ikey.sequence < context_.fifo_eviction_seq) { evicted_count_++; evicted_size_ += key.size() + value.size(); return Decision::kRemove; } } return Decision::kKeep; } CompactionFilter::BlobDecision BlobIndexCompactionFilterGC::PrepareBlobOutput( const Slice& key, const Slice& existing_value, std::string* new_value) const { assert(new_value); const BlobDBImpl* const blob_db_impl = context_gc_.blob_db_impl; (void)blob_db_impl; assert(blob_db_impl); assert(blob_db_impl->bdb_options_.enable_garbage_collection); BlobIndex blob_index; const Status s = blob_index.DecodeFrom(existing_value); if (!s.ok()) { return BlobDecision::kCorruption; } if (blob_index.IsInlined()) { return BlobDecision::kKeep; } if (blob_index.HasTTL()) { return BlobDecision::kKeep; } if (blob_index.file_number() >= context_gc_.cutoff_file_number) { return BlobDecision::kKeep; } // Note: each compaction generates its own blob files, which, depending on the // workload, might result in many small blob files. The total number of files // is bounded though (determined by the number of compactions and the blob // file size option). if (!OpenNewBlobFileIfNeeded()) { return BlobDecision::kIOError; } PinnableSlice blob; CompressionType compression_type = kNoCompression; if (!ReadBlobFromOldFile(key, blob_index, &blob, &compression_type)) { return BlobDecision::kIOError; } uint64_t new_blob_file_number = 0; uint64_t new_blob_offset = 0; if (!WriteBlobToNewFile(key, blob, &new_blob_file_number, &new_blob_offset)) { return BlobDecision::kIOError; } if (!CloseAndRegisterNewBlobFileIfNeeded()) { return BlobDecision::kIOError; } BlobIndex::EncodeBlob(new_value, new_blob_file_number, new_blob_offset, blob.size(), compression_type); return BlobDecision::kChangeValue; } bool BlobIndexCompactionFilterGC::OpenNewBlobFileIfNeeded() const { if (blob_file_) { assert(writer_); return true; } BlobDBImpl* const blob_db_impl = context_gc_.blob_db_impl; assert(blob_db_impl); const Status s = blob_db_impl->CreateBlobFileAndWriter( /* has_ttl */ false, ExpirationRange(), "GC", &blob_file_, &writer_); if (!s.ok()) { ROCKS_LOG_ERROR(blob_db_impl->db_options_.info_log, "Error opening new blob file during GC, status: %s", s.ToString().c_str()); return false; } assert(blob_file_); assert(writer_); return true; } bool BlobIndexCompactionFilterGC::ReadBlobFromOldFile( const Slice& key, const BlobIndex& blob_index, PinnableSlice* blob, CompressionType* compression_type) const { BlobDBImpl* const blob_db_impl = context_gc_.blob_db_impl; assert(blob_db_impl); const Status s = blob_db_impl->GetRawBlobFromFile( key, blob_index.file_number(), blob_index.offset(), blob_index.size(), blob, compression_type); if (!s.ok()) { ROCKS_LOG_ERROR(blob_db_impl->db_options_.info_log, "Error reading blob during GC, key: %s (%s), status: %s", key.ToString(/* output_hex */ true).c_str(), blob_index.DebugString(/* output_hex */ true).c_str(), s.ToString().c_str()); return false; } return true; } bool BlobIndexCompactionFilterGC::WriteBlobToNewFile( const Slice& key, const Slice& blob, uint64_t* new_blob_file_number, uint64_t* new_blob_offset) const { assert(new_blob_file_number); assert(new_blob_offset); assert(blob_file_); *new_blob_file_number = blob_file_->BlobFileNumber(); assert(writer_); uint64_t new_key_offset = 0; const Status s = writer_->AddRecord(key, blob, kNoExpiration, &new_key_offset, new_blob_offset); if (!s.ok()) { const BlobDBImpl* const blob_db_impl = context_gc_.blob_db_impl; assert(blob_db_impl); ROCKS_LOG_ERROR( blob_db_impl->db_options_.info_log, "Error writing blob to new file %s during GC, key: %s, status: %s", blob_file_->PathName().c_str(), key.ToString(/* output_hex */ true).c_str(), s.ToString().c_str()); return false; } const uint64_t new_size = BlobLogRecord::kHeaderSize + key.size() + blob.size(); blob_file_->BlobRecordAdded(new_size); BlobDBImpl* const blob_db_impl = context_gc_.blob_db_impl; assert(blob_db_impl); blob_db_impl->total_blob_size_ += new_size; return true; } bool BlobIndexCompactionFilterGC::CloseAndRegisterNewBlobFileIfNeeded() const { const BlobDBImpl* const blob_db_impl = context_gc_.blob_db_impl; assert(blob_db_impl); assert(blob_file_); if (blob_file_->GetFileSize() < blob_db_impl->bdb_options_.blob_file_size) { return true; } return CloseAndRegisterNewBlobFile(); } bool BlobIndexCompactionFilterGC::CloseAndRegisterNewBlobFile() const { BlobDBImpl* const blob_db_impl = context_gc_.blob_db_impl; assert(blob_db_impl); assert(blob_file_); Status s; { WriteLock wl(&blob_db_impl->mutex_); s = blob_db_impl->CloseBlobFile(blob_file_); // Note: we delay registering the new blob file until it's closed to // prevent FIFO eviction from processing it during the GC run. blob_db_impl->RegisterBlobFile(blob_file_); } assert(blob_file_->Immutable()); blob_file_.reset(); if (!s.ok()) { ROCKS_LOG_ERROR(blob_db_impl->db_options_.info_log, "Error closing new blob file %s during GC, status: %s", blob_file_->PathName().c_str(), s.ToString().c_str()); return false; } return true; } std::unique_ptr<CompactionFilter> BlobIndexCompactionFilterFactory::CreateCompactionFilter( const CompactionFilter::Context& /*context*/) { assert(env()); int64_t current_time = 0; Status s = env()->GetCurrentTime(&current_time); if (!s.ok()) { return nullptr; } assert(current_time >= 0); assert(blob_db_impl()); BlobCompactionContext context; blob_db_impl()->GetCompactionContext(&context); return std::unique_ptr<CompactionFilter>(new BlobIndexCompactionFilter( std::move(context), current_time, statistics())); } std::unique_ptr<CompactionFilter> BlobIndexCompactionFilterFactoryGC::CreateCompactionFilter( const CompactionFilter::Context& /*context*/) { assert(env()); int64_t current_time = 0; Status s = env()->GetCurrentTime(&current_time); if (!s.ok()) { return nullptr; } assert(current_time >= 0); assert(blob_db_impl()); BlobCompactionContext context; BlobCompactionContextGC context_gc; blob_db_impl()->GetCompactionContext(&context, &context_gc); return std::unique_ptr<CompactionFilter>(new BlobIndexCompactionFilterGC( std::move(context), std::move(context_gc), current_time, statistics())); } } // namespace blob_db } // namespace rocksdb #endif // ROCKSDB_LITE
[ "davidburkett38@gmail.com" ]
davidburkett38@gmail.com
b1de589191b9e470f56d3b0023f4c9d6ed7ee8b5
0a7bea704c97290adc59f447fe8b7248e7d59e9c
/无锡二院/CrowdAnalyz/SBGLDlg.h
3af1241bdfaa3658b090920a44b571b4aa13a429
[]
no_license
15831944/GitRepository
5251c3735f01c394780adf945c7f233314662321
4d0a6d590447b42749742735b6f3121fdd0fdd36
refs/heads/master
2022-01-22T13:49:31.478598
2018-01-03T07:36:51
2018-01-03T07:36:51
null
0
0
null
null
null
null
GB18030
C++
false
false
1,830
h
#pragma once // CSBGLDlg 对话框 class CSBGLDlg : public CDialogEx { DECLARE_DYNAMIC(CSBGLDlg) public: CSBGLDlg(CWnd* pParent = NULL); // 标准构造函数 virtual ~CSBGLDlg(); // 对话框数据 enum { IDD = IDD_DIALOG_SBGL }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 DECLARE_MESSAGE_MAP() public: afx_msg void OnDestroy(); afx_msg void OnPaint(); virtual BOOL OnInitDialog(); BOOL PreTranslateMessage(MSG* pMsg); //动态分析库统计 struct DATA_LIST { CRect rXQ; CRect rSC; CRect rBJ; CRect rIP; CString csIP;//ip CRect rPos;//位置 CString strPos; CRect rState;//状态 CString csState; CString csFaceDbs; } m_DataList[21]; int m_iDisTongjiCount; //界面 COLORREF m_colorEditText; // edit控件的字体颜色 COLORREF m_colorEditBK; // edit控件的背景颜色 CBrush* m_pEditBkBrush; CDC *pMemDC; CBitmap *pBitmap; CRect m_rClient;//对话框总界面 CRect m_rTable;// CRect m_rData;// CRect m_rFuwuqi;// CRect m_rXiangji;// CRect m_rBaocun;// CRect m_rQuxiao;// CRect m_rTianjia;// CRect m_rShebei;// CRect m_rIp;// CRect m_rPos;// CRect m_rUp;// CRect m_rNext;// CRect m_rPaga;// int m_nPagaNum; int m_nPagasMax; int m_nRedact; int m_nSelectIndex; void InitRet(); BOOL GetDeviceInfo(int nIndex); BOOL SetDeviceInfo(int nIndex); BOOL SetCameraInfo(int nIndex); BOOL GetCameraInfo(int nIndex); BOOL SetShanchu(int nIndex); BOOL SetBianji(int nIndex); BOOL SetBaocun(); BOOL SetQuxiao(); BOOL SetTianjia(); BOOL GetMaxPaga(); void SetUp(); void SetNext(); afx_msg void OnLButtonDown(UINT nFlags, CPoint point); CString m_csIp; CString m_csIpOld; CString m_csPos; CString m_csFaceDbs; afx_msg HBRUSH OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor); CString m_csPage; };
[ "125385615@qq.com" ]
125385615@qq.com
48c292f82ab617f96b2c76fcf9301f7b28f0782d
4045b44189b8c3cb08b205eb3bfc1c8d38394f06
/includes/utils/BlockingQueue.hpp
9cfca8defcc6bc4abba440597d91b7cc4fd7dfaf
[]
no_license
Yeti-Media/anakin-daemons
65173b1ebcf9725a1184df87a48925bf453098d8
e74b5aac51a8201e1fb66dea238ed786deeba0cc
refs/heads/master
2020-04-11T14:42:37.661550
2015-02-20T20:47:06
2015-02-20T20:47:06
11,772,851
2
0
null
null
null
null
UTF-8
C++
false
false
1,508
hpp
/* * BlockingQueue.hpp * * Created on: 29/05/2014 * Author: Franco Pellegrini */ #ifndef BLOCKINGQUEUE_H_ #define BLOCKINGQUEUE_H_ #include <sys/types.h> #include <condition_variable> #include <deque> #include <mutex> using namespace std; namespace Anakin { template<typename T> class BlockingQueue { public: BlockingQueue(); virtual ~BlockingQueue(); void push(T const& value); T pop(); bool empty(); uint size(); /** * get the internal representation to clean it up before deletion. * DO NOT USE THIS FOR ANOTHER PURPOSES. */ deque<T> getQueue(); private: mutex d_mutex; condition_variable d_condition; deque<T> d_queue; }; template<typename T> BlockingQueue<T>::BlockingQueue() { } template<typename T> BlockingQueue<T>::~BlockingQueue() { } template<typename T> void BlockingQueue<T>::push(T const& value) { unique_lock<mutex> lock(this->d_mutex); d_queue.push_front(value); this->d_condition.notify_one(); } template<typename T> T BlockingQueue<T>::pop() { unique_lock<mutex> lock(this->d_mutex); this->d_condition.wait(lock, [=] {return !this->d_queue.empty();}); T rc(move(this->d_queue.back())); this->d_queue.pop_back(); return rc; } template<typename T> bool BlockingQueue<T>::empty() { return this->d_queue.empty(); } template<typename T> uint BlockingQueue<T>::size() { return this->d_queue.size(); } template<typename T> deque<T> BlockingQueue<T>::getQueue() { return this->d_queue; } } /* namespace Anakin */ #endif /* BLOCKINGQUEUE_H_ */
[ "francogpellegrini@gmail.com" ]
francogpellegrini@gmail.com
582e668d2f9bdd90a69968b3c13fc6aabd00be3b
3c33c2e82289cc43e9e354aa0de6cf0f0151721a
/Practical_5_Pacman/Scene.cpp
492b1ae13a2490ab354b64ec1e418dab2d51e5a1
[ "MIT" ]
permissive
CarlosMiraGarcia/Games-Gaming_Engineering_Practices
7452d360cf2d112b995b7ca45d0d638868d2c069
ba26587fb2b538b9c3cceec98f1026112b2c6413
refs/heads/main
2023-03-21T06:57:51.801685
2021-03-10T17:08:27
2021-03-10T17:08:27
335,118,163
0
0
null
null
null
null
UTF-8
C++
false
false
103
cpp
#include "Scene.h" void Scene::update(double dt) {} void Scene::render() {} void Scene::respawn() {}
[ "carlosgarciamira@gmail.com" ]
carlosgarciamira@gmail.com
bf758d7a2e56d6f9f118e04b20f4abb384af0402
dc126b3e0482fbe4b77e00cf2781c12e3c698c4c
/src/server/managment/MainFlow.h
73d6e8744d342cbf63a144838d7721bde67d0e4b
[]
no_license
nevow/ex6AP
38a6f002bbef1bd769e5761a1f8c0302f7a9c439
d278a6cc797e7b916c9831214bb8d05edc0c606d
refs/heads/master
2021-01-11T18:54:35.659288
2017-01-28T21:57:34
2017-01-28T21:57:34
79,654,500
0
0
null
null
null
null
UTF-8
C++
false
false
979
h
// // MainFlow. // #ifndef EX1_MAINFLOW_H #define EX1_MAINFLOW_H #include <list> #include <map> #include "SystemOperations.h" #include "../enum/ColorFactory.h" #include "../enum/CarManufactureFactory.h" #include "../taxi/LuxuryCab.h" #include "../taxi/Cab.h" #include "../taxi/LuxuryCab.h" #include "../sockets/Tcp.h" #include "../../parsers/Parser.h" class MainFlow { private: SystemOperations *so; Socket *sock; list<Connection *> *connections; pthread_t connection_thread; map<int, Connection *> *conMap; int *choice; Parser parser; public: MainFlow(int port); ~MainFlow() { delete so; delete conMap; while (!(connections->empty())) { delete connections->front(); connections->pop_front(); } delete connections; delete sock; delete choice; pthread_mutex_destroy(&global_validator_locker); } void input(); }; #endif //EX1_MAINFLOW_H
[ "nevo12345@gmail.com" ]
nevo12345@gmail.com
d47ccae29ced376e2e9786835ff81ef54e2487f2
b7f7edf9d8b75a7e0c6310cd077527c8d98fe1a7
/misalignment/amplitudesCalculator.cpp
a27a00d715b19bc0978dad0d3a9e673c1b5e847b
[]
no_license
sowuy/Simulation
32688b68cda80ca835fe41334a5ae85864b2aca5
e045e2175259a775196738ad412a87b3d3faf248
refs/heads/master
2021-04-28T14:15:23.095657
2019-06-11T14:08:04
2019-06-11T14:08:04
121,960,585
0
0
null
null
null
null
UTF-8
C++
false
false
9,653
cpp
#include <iostream> #include <fstream> #include <unistd.h> #include <string> #include <cstdlib> #include <vector> #include <cmath> #include <iomanip> #include <sstream> #include <random> using namespace std; //pi Definition const double PI = 4*atan(1); //Shorthand notation to make the code more understadable and to allow for //drop-in replacement by another C++11 random number generator. typedef mt19937 Generator; //A fonction that generate a random position within a certain rectangle double getRandom(Generator& generator){ return generate_canonical<double, 32>(generator); } double getRandomInRange(Generator& generator, double x0, double length){ return length*getRandom(generator) + x0; } /**************************************************************************************/ vector <double> misalignment (double delta, vector <double> aligned, int detectorPlan){ vector <double> outputVector; for(unsigned int i=0;i<aligned.size();i++){ aligned[i] = aligned[i] + delta; outputVector.push_back(aligned[i]); } return outputVector; } /****************************************************************************************/ pair<vector <double>, vector<double> > generalCase(vector <double> x1, vector <double> y2, vector <double> x3, vector <double> y4, double w, double delta1, double delta2, double delta3, double delta4){ if(x1.size() == 0 || x1.size() != y2.size() || x1.size() != x3.size() || x1.size()!= y4.size()){ cerr << "Error with data." << endl; cerr << "The files must contain the same number(>0) of values." << endl; cerr << "Data01 : " << x1.size() << " read values" << endl; cerr << "Data02 : " << y2.size() << " read values" << endl; cerr << "Data03 : " << x3.size() << " read values" << endl; cerr << "Data04 : " << y4.size() << " read values" << endl; exit(EXIT_FAILURE); } double x, y,z,r; vector<double> rho(x1.size()), theta(x1.size()); vector<double> rhoInDeg(x1.size()), thetaInDeg(x1.size()); vector<double> x1Mis = misalignment(delta1,x1,1); vector<double> y2Mis = misalignment(delta2,y2,2); vector<double> x3Mis = misalignment(delta3,x3,3); vector<double> y4Mis = misalignment(delta4,y4,4); ; for(unsigned int i=0; i< x1.size(); i++){ x = x3Mis[i] - x1Mis[i]; y = y4Mis[i] - y2Mis[i]; z = w + 7.4; r = sqrt(x * x + y * y + z * z); rho[i] = x == 0.0 ? 0.0 : atan(y / x); theta[i] = acos(z / r); rhoInDeg[i]= rho[i]*180/PI; thetaInDeg[i]= theta[i]*180/PI; } return make_pair(rhoInDeg, thetaInDeg); } /*****************************************************************************************/ void writeFile(string filename, vector<double> v){ ofstream outFile(filename.c_str()); if(!outFile.is_open()){ std::cerr << "Error while writing the file \'" << filename << "\'" << endl; return; } for(unsigned int i=0; i< v.size(); i++) outFile << v[i] << endl; outFile.close(); } /******************************************************************************************/ vector<vector <double> > readFile(string filename){ vector<double> line; vector<vector<double> > matrix; double value; ifstream myFile(filename.c_str()); if(!myFile.is_open()){ cerr << "Error while opening the file \'" << filename << "\'." << endl; exit(EXIT_FAILURE); } if(!myFile.good()){ cerr << "Error with the file \'" << filename << "\'."<< endl; cerr << "Reading cancelled." << endl; exit(EXIT_FAILURE); } while(!myFile.eof()){ myFile >> value; line.push_back(value); if(myFile.peek() == '\n'){ matrix.push_back(line); line.clear(); } } myFile.close(); return matrix; } /****************************************************************************************/ string getHelpPage(char* scriptName){ string name(scriptName); string out = "Usage: " + name + " -w w file \n"; out += "\t-w w\t Gap between detectors\n"; out += "\tfile\t file containing data\n"; out += "The program applies the following formulas :\n"; out += "All rho will be printed in the outfile \'rho_X\' and all theta\n"; out += "in the outfile \'theta_X\' (where X is the initial outfile name).\n"; return out; } /*************************************************************************************/ /*vector<double> conversion(vector<double> stripNumber){ vector<double> position; double stripWidth=0.9; double interstrip = 0.15; double firstStrip = 0.45; double strip=stripNumber[0]; double value=0; double lengthVector = stripNumber.size(); for(int i=0;i<lengthVector;i++){ value = firstStrip + (stripNumber[i]-1)*(stripWidth+interstrip); position.push_back(value); } return position; }*/ /*****************************************************************************************/ double conversion(double stripNumber){ double position; double stripWidth=0.9; double interstrip = 0.15; double firstStrip = 0.45; position = firstStrip + (stripNumber-1)*(stripWidth+interstrip); return position; } /*************************************************************************************************************************************************************************************************************************************************************************************/ int main(int argc, char** argv){ // Start with random seed random_device rd; Generator generator(rd()); // Get the thing started generator.discard(100); int opt; char* endptr; string outfileName1 = "alignedAmplitudes.txt"; string outfileName2 = "misalignedAmplitudes.txt"; string outfileName3 = "misalignEffect.txt"; vector < vector <double> > dataIn; double w = -1; double init = -1*pow(10,-3); double width = abs(2*init); const double delta1 = getRandomInRange(generator,init,width); const double delta2 = getRandomInRange(generator,init,width); const double delta3 = getRandomInRange(generator,init,width); const double delta4 = getRandomInRange(generator,init,width); cout << "delta1 = " << delta1 << endl; cout << "delta2 = " << delta2 << endl; cout << "delta3 = " << delta3 << endl; cout << "delta4 = " << delta4 << endl; string filename; vector<double> data01, data02, data03, data04, outputS; double data1, data2, data3, data4; pair<vector<double>, vector<double> > outputAligned; pair<vector<double>, vector<double> > outputMisaligned; pair<vector<double>, vector<double> > outputDifference; while((opt = getopt(argc, argv, "w:h")) != -1){ switch(opt){ case 'w': endptr = optarg; w = strtof(optarg,&endptr); if(optarg == endptr || w<0){ cerr << "invalid value for option -w" << endl; return EXIT_FAILURE; } break; case 'h': cout << getHelpPage(argv[0]); return EXIT_SUCCESS; default: cerr << getHelpPage(argv[0]); return EXIT_FAILURE; } } if(argc < 2){ cerr << "Some arguments (or options) are missing" << endl; cerr << "\n" << getHelpPage(argv[0]); return EXIT_FAILURE; } if( w == -1){ cerr << "The options -w must be set !" << endl; cerr << "\n" << getHelpPage(argv[0]); return EXIT_FAILURE; } filename = argv[optind]; cout << "Reading file..." << endl; dataIn = readFile(filename); // Aligned detectors configuration for(int i=0; i<dataIn.size();i++){ if(dataIn[i].size()!=4){ cerr<<"Data n° "<< (i+1)<< " do not have 4 values. \nData ignored."<<endl; } else{ data1 = conversion(dataIn[i][0]); data2 = conversion(dataIn[i][1]); data3 = conversion(dataIn[i][2]); data4 = conversion(dataIn[i][3]); data01.push_back(data1); data02.push_back(data2); data03.push_back(data3); data04.push_back(data4); } } //cout << "Calculating the amplitudes in aligned case.." << endl; outputAligned = generalCase(data01, data02, data03, data04,w,0,0,0,0); //cout << "Writing the results (1/2)..." << endl; //writeFile("rho_"+outfileName1, outputAligned.first); //cout << "Writing the results (2/2)..." << endl; //writeFile("theta_"+outfileName1, outputAligned.second); // Misaligned detectors configuration with random delta in x and y for(int i=0; i<dataIn.size();i++){ if(dataIn[i].size()!=4){ cerr<<"Data n° "<< (i+1)<< " do not have 4 values. \nData ignored."<<endl; } else{ data1 = conversion(dataIn[i][0]); data2 = conversion(dataIn[i][1]); data3 = conversion(dataIn[i][2]); data4 = conversion(dataIn[i][3]); data01[i]=data1; data02[i]=data2; data03[i]=data3; data04[i]=data4; } } //cout << "Calculating the amplitudes in misaligned case..." << endl; outputMisaligned = generalCase(data01, data02, data03, data04,w,delta1,delta2,delta3,delta4); cout << "length data01 : " << data01.size() << endl; //cout << "Writing the results (1/2)..." << endl; //writeFile("rho_"+outfileName2, outputMisaligned.first); //cout << "Writing the results (2/2)..." << endl; //writeFile("theta_"+outfileName2, outputMisaligned.second); outputDifference.first = vector<double>(outputMisaligned.first.size()); outputDifference.second = vector<double>(outputMisaligned.first.size()); for(unsigned int k = 0; k < outputAligned.first.size();k++){ outputDifference.first[k] = outputMisaligned.first[k] - outputAligned.first[k]; outputDifference.second[k] = outputMisaligned.second[k] - outputAligned.second[k]; } //cout << "Writing the results (1/2)..." << endl; writeFile("rho_"+outfileName3, outputDifference.first); //cout << "Writing the results (2/2)..." << endl; writeFile("theta_"+outfileName3, outputDifference.second); return EXIT_SUCCESS; }
[ "sophie.wuyckens@gmail.com" ]
sophie.wuyckens@gmail.com
9cb2c493519f0963460ca1317c8a68e56b8eaeea
540bf26df5570f7dfe9f3dca52769bdc594dbaa5
/src/game/server/gameinterface.cpp
4c0d55eaec3116414097b1d81aad80adb986c874
[]
no_license
InfoSmart/InSource-Singleplayer
c7a8e0de648c4fafcebc4d7ec78e46ad8afd742c
55e6fb30252d5ff4d19fb7c9d146bfec56055ad4
refs/heads/master
2021-01-17T05:46:39.867026
2013-07-07T06:13:41
2013-07-07T06:13:41
7,018,102
2
0
null
null
null
null
UTF-8
C++
false
false
93,901
cpp
//===== Copyright © 1996-2005, Valve Corporation, All rights reserved. ======// // // Purpose: encapsulates and implements all the accessing of the game dll from external // sources (only the engine at the time of writing) // This files ONLY contains functions and data necessary to build an interface // to external modules //===========================================================================// #include "cbase.h" #include "gamestringpool.h" #include "mapentities_shared.h" #include "game.h" #include "entityapi.h" #include "client.h" #include "saverestore.h" #include "entitylist.h" #include "gamerules.h" #include "soundent.h" #include "player.h" #include "server_class.h" #include "ai_node.h" #include "ai_link.h" #include "ai_saverestore.h" #include "ai_networkmanager.h" #include "ndebugoverlay.h" #include "ivoiceserver.h" #include <stdarg.h> #include "movehelper_server.h" #include "networkstringtable_gamedll.h" #include "filesystem.h" #include "func_areaportalwindow.h" #include "igamesystem.h" #include "init_factory.h" #include "vstdlib/random.h" #include "env_wind_shared.h" #include "engine/IEngineSound.h" #include "ispatialpartition.h" #include "textstatsmgr.h" #include "bitbuf.h" #include "saverestoretypes.h" #include "physics_saverestore.h" #include "achievement_saverestore.h" #include "tier0/vprof.h" #include "effect_dispatch_data.h" #include "engine/IStaticPropMgr.h" #include "TemplateEntities.h" #include "ai_speech.h" #include "soundenvelope.h" #include "usermessages.h" #include "physics.h" #include "igameevents.h" #include "EventLog.h" #include "datacache/idatacache.h" #include "engine/ivdebugoverlay.h" #include "shareddefs.h" #include "props.h" #include "timedeventmgr.h" #include "gameinterface.h" #include "eventqueue.h" #include "hltvdirector.h" #include "SoundEmitterSystem/isoundemittersystembase.h" #include "nav_mesh.h" #include "AI_ResponseSystem.h" #include "saverestore_stringtable.h" #include "util.h" #include "tier0/icommandline.h" #include "datacache/imdlcache.h" #include "engine/iserverplugin.h" #ifdef _WIN32 #include "ienginevgui.h" #endif #include "ragdoll_shared.h" #include "toolframework/iserverenginetools.h" #include "sceneentity.h" #include "appframework/IAppSystemGroup.h" #include "scenefilecache/ISceneFileCache.h" #include "tier2/tier2.h" #include "particles/particles.h" #include "GameStats.h" #include "ixboxsystem.h" #include "engine/imatchmaking.h" #include "hl2orange.spa.h" #include "particle_parse.h" #include "steam/steam_api.h" #include "tier3/tier3.h" #include "serverbenchmark_base.h" #ifdef CSTRIKE_DLL // BOTPORT: TODO: move these ifdefs out #include "bot/bot.h" #endif #ifdef PORTAL #include "prop_portal_shared.h" #include "portal_player.h" #endif #if defined ( SDK_DLL ) #include "sdk_gamerules.h" #endif extern IToolFrameworkServer *g_pToolFrameworkServer; extern IParticleSystemQuery *g_pParticleSystemQuery; extern ConVar commentary; static CSteamAPIContext g_SteamAPIContext; CSteamAPIContext *steamapicontext = &g_SteamAPIContext; IUploadGameStats *gamestatsuploader = NULL; // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" CTimedEventMgr g_NetworkPropertyEventMgr; ISaveRestoreBlockHandler *GetEventQueueSaveRestoreBlockHandler(); ISaveRestoreBlockHandler *GetCommentarySaveRestoreBlockHandler(); CUtlLinkedList<CMapEntityRef, unsigned short> g_MapEntityRefs; // Engine interfaces. IVEngineServer *engine = NULL; IVoiceServer *g_pVoiceServer = NULL; #if !defined(_STATIC_LINKED) IFileSystem *filesystem = NULL; #else extern IFileSystem *filesystem; #endif INetworkStringTableContainer *networkstringtable = NULL; IStaticPropMgrServer *staticpropmgr = NULL; IUniformRandomStream *random = NULL; IEngineSound *enginesound = NULL; ISpatialPartition *partition = NULL; IVModelInfo *modelinfo = NULL; IEngineTrace *enginetrace = NULL; IGameEventManager2 *gameeventmanager = NULL; IDataCache *datacache = NULL; IVDebugOverlay * debugoverlay = NULL; ISoundEmitterSystemBase *soundemitterbase = NULL; IServerPluginHelpers *serverpluginhelpers = NULL; IServerEngineTools *serverenginetools = NULL; ISceneFileCache *scenefilecache = NULL; IXboxSystem *xboxsystem = NULL; // Xbox 360 only IMatchmaking *matchmaking = NULL; // Xbox 360 only IGameSystem *SoundEmitterSystem(); bool ModelSoundsCacheInit(); void ModelSoundsCacheShutdown(); void SceneManager_ClientActive( CBasePlayer *player ); class IMaterialSystem; class IStudioRender; #ifdef _DEBUG static ConVar s_UseNetworkVars( "UseNetworkVars", "1", FCVAR_CHEAT, "For profiling, toggle network vars." ); #endif extern ConVar sv_noclipduringpause; ConVar sv_massreport( "sv_massreport", "0" ); ConVar sv_force_transmit_ents( "sv_force_transmit_ents", "0", FCVAR_CHEAT | FCVAR_DEVELOPMENTONLY, "Will transmit all entities to client, regardless of PVS conditions (will still skip based on transmit flags, however)." ); ConVar sv_autosave( "sv_autosave", "1", 0, "Set to 1 to autosave game on level transition. Does not affect autosave triggers." ); ConVar *sv_maxreplay = NULL; static ConVar *g_pcv_commentary = NULL; static ConVar *g_pcv_ThreadMode = NULL; // String tables INetworkStringTable *g_pStringTableParticleEffectNames = NULL; INetworkStringTable *g_pStringTableEffectDispatch = NULL; INetworkStringTable *g_pStringTableVguiScreen = NULL; INetworkStringTable *g_pStringTableMaterials = NULL; INetworkStringTable *g_pStringTableInfoPanel = NULL; INetworkStringTable *g_pStringTableClientSideChoreoScenes = NULL; CStringTableSaveRestoreOps g_VguiScreenStringOps; // Holds global variables shared between engine and game. CGlobalVars *gpGlobals; edict_t *g_pDebugEdictBase = 0; static int g_nCommandClientIndex = 0; // The chapter number of the current static int g_nCurrentChapterIndex = -1; static ConVar sv_showhitboxes( "sv_showhitboxes", "-1", FCVAR_CHEAT, "Send server-side hitboxes for specified entity to client (NOTE: this uses lots of bandwidth, use on listen server only)." ); void PrecachePointTemplates(); static ClientPutInServerOverrideFn g_pClientPutInServerOverride = NULL; static void UpdateChapterRestrictions( const char *mapname ); static void UpdateRichPresence ( void ); #if !defined( _XBOX ) // Don't doubly define this symbol. CSharedEdictChangeInfo *g_pSharedChangeInfo = NULL; #endif IChangeInfoAccessor *CBaseEdict::GetChangeAccessor() { return engine->GetChangeAccessor( (const edict_t *)this ); } const IChangeInfoAccessor *CBaseEdict::GetChangeAccessor() const { return engine->GetChangeAccessor( (const edict_t *)this ); } const char *GetHintTypeDescription( CAI_Hint *pHint ); void ClientPutInServerOverride( ClientPutInServerOverrideFn fn ) { g_pClientPutInServerOverride = fn; } ConVar ai_post_frame_navigation( "ai_post_frame_navigation", "0" ); class CPostFrameNavigationHook; extern CPostFrameNavigationHook *PostFrameNavigationSystem( void ); //----------------------------------------------------------------------------- // Purpose: // Output : int //----------------------------------------------------------------------------- int UTIL_GetCommandClientIndex( void ) { // -1 == unknown,dedicated server console // 0 == player 1 // Convert to 1 based offset return (g_nCommandClientIndex+1); } //----------------------------------------------------------------------------- // Purpose: // Output : CBasePlayer //----------------------------------------------------------------------------- CBasePlayer *UTIL_GetCommandClient( void ) { int idx = UTIL_GetCommandClientIndex(); if ( idx > 0 ) { return UTIL_PlayerByIndex( idx ); } // HLDS console issued command return NULL; } //----------------------------------------------------------------------------- // Purpose: Retrieves the MOD directory for the active game (ie. "hl2") //----------------------------------------------------------------------------- bool UTIL_GetModDir( char *lpszTextOut, unsigned int nSize ) { // Must pass in a buffer at least large enough to hold the desired string const char *pGameDir = CommandLine()->ParmValue( "-game", "hl2" ); Assert( strlen(pGameDir) <= nSize ); if ( strlen(pGameDir) > nSize ) return false; Q_strncpy( lpszTextOut, pGameDir, nSize ); if ( Q_strnchr( lpszTextOut, '/', nSize ) || Q_strnchr( lpszTextOut, '\\', nSize ) ) { // Strip the last directory off (which will be our game dir) Q_StripLastDir( lpszTextOut, nSize ); // Find the difference in string lengths and take that difference from the original string as the mod dir int dirlen = Q_strlen( lpszTextOut ); Q_strncpy( lpszTextOut, pGameDir + dirlen, Q_strlen( pGameDir ) - dirlen + 1 ); } return true; } extern void InitializeCvars( void ); CBaseEntity* FindPickerEntity( CBasePlayer* pPlayer ); CAI_Node* FindPickerAINode( CBasePlayer* pPlayer, NodeType_e nNodeType ); CAI_Link* FindPickerAILink( CBasePlayer* pPlayer ); float GetFloorZ(const Vector &origin); void UpdateAllClientData( void ); void DrawMessageEntities(); #include "ai_network.h" // For now just using one big AI network extern ConVar think_limit; #if 0 //----------------------------------------------------------------------------- // Purpose: Draw output overlays for any measure sections // Input : //----------------------------------------------------------------------------- void DrawMeasuredSections(void) { int row = 1; float rowheight = 0.025; CMeasureSection *p = CMeasureSection::GetList(); while ( p ) { char str[256]; Q_snprintf(str,sizeof(str),"%s",p->GetName()); NDebugOverlay::ScreenText( 0.01,0.51+(row*rowheight),str, 255,255,255,255, 0.0 ); Q_snprintf(str,sizeof(str),"%5.2f\n",p->GetTime().GetMillisecondsF()); //Q_snprintf(str,sizeof(str),"%3.3f\n",p->GetTime().GetSeconds() * 100.0 / engine->Time()); NDebugOverlay::ScreenText( 0.28,0.51+(row*rowheight),str, 255,255,255,255, 0.0 ); Q_snprintf(str,sizeof(str),"%5.2f\n",p->GetMaxTime().GetMillisecondsF()); //Q_snprintf(str,sizeof(str),"%3.3f\n",p->GetTime().GetSeconds() * 100.0 / engine->Time()); NDebugOverlay::ScreenText( 0.34,0.51+(row*rowheight),str, 255,255,255,255, 0.0 ); row++; p = p->GetNext(); } bool sort_reset = false; // Time to redo sort? if ( measure_resort.GetFloat() > 0.0 && engine->Time() >= CMeasureSection::m_dNextResort ) { // Redo it CMeasureSection::SortSections(); // Set next time CMeasureSection::m_dNextResort = engine->Time() + measure_resort.GetFloat(); // Flag to reset sort accumulator, too sort_reset = true; } // Iterate through the sections now p = CMeasureSection::GetList(); while ( p ) { // Update max p->UpdateMax(); // Reset regular accum. p->Reset(); // Reset sort accum less often if ( sort_reset ) { p->SortReset(); } p = p->GetNext(); } } #endif //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void DrawAllDebugOverlays( void ) { // If in debug select mode print the selection entities name or classname if (CBaseEntity::m_bInDebugSelect) { CBasePlayer* pPlayer = UTIL_PlayerByIndex( CBaseEntity::m_nDebugPlayer ); if (pPlayer) { // First try to trace a hull to an entity CBaseEntity *pEntity = FindPickerEntity( pPlayer ); if ( pEntity ) { pEntity->DrawDebugTextOverlays(); pEntity->DrawBBoxOverlay(); pEntity->SendDebugPivotOverlay(); } } } // -------------------------------------------------------- // Draw debug overlay lines // -------------------------------------------------------- UTIL_DrawOverlayLines(); // ------------------------------------------------------------------------ // If in wc_edit mode draw a box to highlight which node I'm looking at // ------------------------------------------------------------------------ if (engine->IsInEditMode()) { CBasePlayer* pPlayer = UTIL_PlayerByIndex( CBaseEntity::m_nDebugPlayer ); if (pPlayer) { if (g_pAINetworkManager->GetEditOps()->m_bLinkEditMode) { CAI_Link* pAILink = FindPickerAILink(pPlayer); if (pAILink) { // For now just using one big AI network Vector startPos = g_pBigAINet->GetNode(pAILink->m_iSrcID)->GetPosition(g_pAINetworkManager->GetEditOps()->m_iHullDrawNum); Vector endPos = g_pBigAINet->GetNode(pAILink->m_iDestID)->GetPosition(g_pAINetworkManager->GetEditOps()->m_iHullDrawNum); Vector linkDir = startPos-endPos; float linkLen = VectorNormalize( linkDir ); // Draw in green if link that's been turned off if (pAILink->m_LinkInfo & bits_LINK_OFF) { NDebugOverlay::BoxDirection(startPos, Vector(-4,-4,-4), Vector(-linkLen,4,4), linkDir, 0,255,0,40,0); } else { NDebugOverlay::BoxDirection(startPos, Vector(-4,-4,-4), Vector(-linkLen,4,4), linkDir, 255,0,0,40,0); } } } else { CAI_Node* pAINode; if (g_pAINetworkManager->GetEditOps()->m_bAirEditMode) { pAINode = FindPickerAINode(pPlayer,NODE_AIR); } else { pAINode = FindPickerAINode(pPlayer,NODE_GROUND); } if (pAINode) { Vector vecPos = pAINode->GetPosition(g_pAINetworkManager->GetEditOps()->m_iHullDrawNum); NDebugOverlay::Box( vecPos, Vector(-8,-8,-8), Vector(8,8,8), 255,0,0,40,0); if ( pAINode->GetHint() ) { CBaseEntity *pEnt = (CBaseEntity *)pAINode->GetHint(); if ( pEnt->GetEntityName() != NULL_STRING ) { NDebugOverlay::Text( vecPos + Vector(0,0,6), STRING(pEnt->GetEntityName()), false, 0 ); } NDebugOverlay::Text( vecPos, GetHintTypeDescription( pAINode->GetHint() ), false, 0 ); } } } // ------------------------------------ // If in air edit mode draw guide line // ------------------------------------ if (g_pAINetworkManager->GetEditOps()->m_bAirEditMode) { UTIL_DrawPositioningOverlay(g_pAINetworkManager->GetEditOps()->m_flAirEditDistance); } else { NDebugOverlay::DrawGroundCrossHairOverlay(); } } } // For not just using one big AI Network if ( g_pAINetworkManager ) { g_pAINetworkManager->GetEditOps()->DrawAINetworkOverlay(); } // PERFORMANCE: only do this in developer mode if ( g_pDeveloper->GetInt() ) { // iterate through all objects for debug overlays const CEntInfo *pInfo = gEntList.FirstEntInfo(); for ( ;pInfo; pInfo = pInfo->m_pNext ) { CBaseEntity *ent = (CBaseEntity *)pInfo->m_pEntity; // HACKHACK: to flag off these calls if ( ent->m_debugOverlays || ent->m_pTimedOverlay ) { MDLCACHE_CRITICAL_SECTION(); ent->DrawDebugGeometryOverlays(); } } } if ( sv_massreport.GetInt() ) { // iterate through all objects for debug overlays const CEntInfo *pInfo = gEntList.FirstEntInfo(); for ( ;pInfo; pInfo = pInfo->m_pNext ) { CBaseEntity *ent = (CBaseEntity *)pInfo->m_pEntity; if (!ent->VPhysicsGetObject()) continue; char tempstr[512]; Q_snprintf(tempstr, sizeof(tempstr),"%s: Mass: %.2f kg / %.2f lb (%s)", ent->GetModelName(), ent->VPhysicsGetObject()->GetMass(), kg2lbs(ent->VPhysicsGetObject()->GetMass()), GetMassEquivalent(ent->VPhysicsGetObject()->GetMass())); ent->EntityText(0, tempstr, 0); } } // A hack to draw point_message entities w/o developer required DrawMessageEntities(); } CServerGameDLL g_ServerGameDLL; EXPOSE_SINGLE_INTERFACE_GLOBALVAR(CServerGameDLL, IServerGameDLL, INTERFACEVERSION_SERVERGAMEDLL, g_ServerGameDLL); //Tony; added to fetch the gameinfo file and mount additional content. static void MountAdditionalContent() { KeyValues *pMainFile = new KeyValues( "gameinfo.txt" ); #ifndef _WINDOWS // case sensitivity pMainFile->LoadFromFile( filesystem, "GameInfo.txt", "MOD" ); if (!pMainFile) #endif pMainFile->LoadFromFile( filesystem, "gameinfo.txt", "MOD" ); if (pMainFile) { KeyValues* pFileSystemInfo = pMainFile->FindKey( "FileSystem" ); if (pFileSystemInfo) for ( KeyValues *pKey = pFileSystemInfo->GetFirstSubKey(); pKey; pKey = pKey->GetNextKey() ) { if ( strcmp(pKey->GetName(),"AdditionalContentId") == 0 ) { int appid = abs(pKey->GetInt()); if (appid) if( filesystem->MountSteamContent(-appid) != FILESYSTEM_MOUNT_OK ) Warning("Unable to mount extra content with appId: %i\n", appid); } } } pMainFile->deleteThis(); } bool CServerGameDLL::DLLInit( CreateInterfaceFn appSystemFactory, CreateInterfaceFn physicsFactory, CreateInterfaceFn fileSystemFactory, CGlobalVars *pGlobals) { ConnectTier1Libraries( &appSystemFactory, 1 ); ConnectTier2Libraries( &appSystemFactory, 1 ); ConnectTier3Libraries( &appSystemFactory, 1 ); // Connected in ConnectTier1Libraries if ( cvar == NULL ) return false; #ifndef _X360 g_SteamAPIContext.Init(); #endif // init each (seperated for ease of debugging) if ( (engine = (IVEngineServer*)appSystemFactory(INTERFACEVERSION_VENGINESERVER, NULL)) == NULL ) return false; if ( (g_pVoiceServer = (IVoiceServer*)appSystemFactory(INTERFACEVERSION_VOICESERVER, NULL)) == NULL ) return false; if ( (networkstringtable = (INetworkStringTableContainer *)appSystemFactory(INTERFACENAME_NETWORKSTRINGTABLESERVER,NULL)) == NULL ) return false; if ( (staticpropmgr = (IStaticPropMgrServer *)appSystemFactory(INTERFACEVERSION_STATICPROPMGR_SERVER,NULL)) == NULL ) return false; if ( (random = (IUniformRandomStream *)appSystemFactory(VENGINE_SERVER_RANDOM_INTERFACE_VERSION, NULL)) == NULL ) return false; if ( (enginesound = (IEngineSound *)appSystemFactory(IENGINESOUND_SERVER_INTERFACE_VERSION, NULL)) == NULL ) return false; if ( (partition = (ISpatialPartition *)appSystemFactory(INTERFACEVERSION_SPATIALPARTITION, NULL)) == NULL ) return false; if ( (modelinfo = (IVModelInfo *)appSystemFactory(VMODELINFO_SERVER_INTERFACE_VERSION, NULL)) == NULL ) return false; if ( (enginetrace = (IEngineTrace *)appSystemFactory(INTERFACEVERSION_ENGINETRACE_SERVER,NULL)) == NULL ) return false; if ( (filesystem = (IFileSystem *)fileSystemFactory(FILESYSTEM_INTERFACE_VERSION,NULL)) == NULL ) return false; if ( (gameeventmanager = (IGameEventManager2 *)appSystemFactory(INTERFACEVERSION_GAMEEVENTSMANAGER2,NULL)) == NULL ) return false; if ( (datacache = (IDataCache*)appSystemFactory(DATACACHE_INTERFACE_VERSION, NULL )) == NULL ) return false; if ( (soundemitterbase = (ISoundEmitterSystemBase *)appSystemFactory(SOUNDEMITTERSYSTEM_INTERFACE_VERSION, NULL)) == NULL ) return false; #ifndef _XBOX if ( (gamestatsuploader = (IUploadGameStats *)appSystemFactory( INTERFACEVERSION_UPLOADGAMESTATS, NULL )) == NULL ) return false; #endif if ( !mdlcache ) return false; if ( (serverpluginhelpers = (IServerPluginHelpers *)appSystemFactory(INTERFACEVERSION_ISERVERPLUGINHELPERS, NULL)) == NULL ) return false; if ( (scenefilecache = (ISceneFileCache *)appSystemFactory( SCENE_FILE_CACHE_INTERFACE_VERSION, NULL )) == NULL ) return false; if ( IsX360() && (xboxsystem = (IXboxSystem *)appSystemFactory( XBOXSYSTEM_INTERFACE_VERSION, NULL )) == NULL ) return false; if ( IsX360() && (matchmaking = (IMatchmaking *)appSystemFactory( VENGINE_MATCHMAKING_VERSION, NULL )) == NULL ) return false; // If not running dedicated, grab the engine vgui interface if ( !engine->IsDedicatedServer() ) { #ifdef _WIN32 // This interface is optional, and is only valid when running with -tools serverenginetools = ( IServerEngineTools * )appSystemFactory( VSERVERENGINETOOLS_INTERFACE_VERSION, NULL ); #endif } // Yes, both the client and game .dlls will try to Connect, the soundemittersystem.dll will handle this gracefully if ( !soundemitterbase->Connect( appSystemFactory ) ) return false; //Tony; mount an extra appId if it exists. MountAdditionalContent(); // cache the globals gpGlobals = pGlobals; g_pSharedChangeInfo = engine->GetSharedEdictChangeInfo(); MathLib_Init( 2.2f, 2.2f, 0.0f, 2.0f ); // save these in case other system inits need them factorylist_t factories; factories.engineFactory = appSystemFactory; factories.fileSystemFactory = fileSystemFactory; factories.physicsFactory = physicsFactory; FactoryList_Store( factories ); // load used game events gameeventmanager->LoadEventsFromFile("resource/gameevents.res"); // init the cvar list first in case inits want to reference them InitializeCvars(); // Initialize the particle system if ( !g_pParticleSystemMgr->Init( g_pParticleSystemQuery ) ) { return false; } sv_cheats = g_pCVar->FindVar( "sv_cheats" ); if ( !sv_cheats ) return false; g_pcv_commentary = g_pCVar->FindVar( "commentary" ); g_pcv_ThreadMode = g_pCVar->FindVar( "host_thread_mode" ); sv_maxreplay = g_pCVar->FindVar( "sv_maxreplay" ); g_pGameSaveRestoreBlockSet->AddBlockHandler( GetEntitySaveRestoreBlockHandler() ); g_pGameSaveRestoreBlockSet->AddBlockHandler( GetPhysSaveRestoreBlockHandler() ); g_pGameSaveRestoreBlockSet->AddBlockHandler( GetAISaveRestoreBlockHandler() ); g_pGameSaveRestoreBlockSet->AddBlockHandler( GetTemplateSaveRestoreBlockHandler() ); g_pGameSaveRestoreBlockSet->AddBlockHandler( GetDefaultResponseSystemSaveRestoreBlockHandler() ); g_pGameSaveRestoreBlockSet->AddBlockHandler( GetCommentarySaveRestoreBlockHandler() ); g_pGameSaveRestoreBlockSet->AddBlockHandler( GetEventQueueSaveRestoreBlockHandler() ); g_pGameSaveRestoreBlockSet->AddBlockHandler( GetAchievementSaveRestoreBlockHandler() ); // The string system must init first + shutdown last IGameSystem::Add( GameStringSystem() ); // Physics must occur before the sound envelope manager IGameSystem::Add( PhysicsGameSystem() ); // Used to service deferred navigation queries for NPCs IGameSystem::Add( (IGameSystem *) PostFrameNavigationSystem() ); // Add game log system IGameSystem::Add( GameLogSystem() ); #ifndef _XBOX // Add HLTV director IGameSystem::Add( HLTVDirectorSystem() ); #endif // Add sound emitter IGameSystem::Add( SoundEmitterSystem() ); // load Mod specific game events ( MUST be before InitAllSystems() so it can pickup the mod specific events) gameeventmanager->LoadEventsFromFile("resource/ModEvents.res"); #ifdef CSTRIKE_DLL // BOTPORT: TODO: move these ifdefs out InstallBotControl(); #endif if ( !IGameSystem::InitAllSystems() ) return false; // Due to dependencies, these are not autogamesystems if ( !ModelSoundsCacheInit() ) { return false; } // Parse the particle manifest file & register the effects within it ParseParticleEffects( false ); // try to get debug overlay, may be NULL if on HLDS debugoverlay = (IVDebugOverlay *)appSystemFactory( VDEBUG_OVERLAY_INTERFACE_VERSION, NULL ); #ifndef _XBOX // create the Navigation Mesh interface TheNavMesh = new CNavMesh; // init the gamestatsupload connection gamestatsuploader->InitConnection(); #endif return true; } void CServerGameDLL::PostInit() { IGameSystem::PostInitAllSystems(); } void CServerGameDLL::DLLShutdown( void ) { // Due to dependencies, these are not autogamesystems ModelSoundsCacheShutdown(); g_pGameSaveRestoreBlockSet->RemoveBlockHandler( GetAchievementSaveRestoreBlockHandler() ); g_pGameSaveRestoreBlockSet->RemoveBlockHandler( GetCommentarySaveRestoreBlockHandler() ); g_pGameSaveRestoreBlockSet->RemoveBlockHandler( GetEventQueueSaveRestoreBlockHandler() ); g_pGameSaveRestoreBlockSet->RemoveBlockHandler( GetDefaultResponseSystemSaveRestoreBlockHandler() ); g_pGameSaveRestoreBlockSet->RemoveBlockHandler( GetTemplateSaveRestoreBlockHandler() ); g_pGameSaveRestoreBlockSet->RemoveBlockHandler( GetAISaveRestoreBlockHandler() ); g_pGameSaveRestoreBlockSet->RemoveBlockHandler( GetPhysSaveRestoreBlockHandler() ); g_pGameSaveRestoreBlockSet->RemoveBlockHandler( GetEntitySaveRestoreBlockHandler() ); char *pFilename = g_TextStatsMgr.GetStatsFilename(); if ( !pFilename || !pFilename[0] ) { g_TextStatsMgr.SetStatsFilename( "stats.txt" ); } g_TextStatsMgr.WriteFile( filesystem ); IGameSystem::ShutdownAllSystems(); #ifdef CSTRIKE_DLL // BOTPORT: TODO: move these ifdefs out RemoveBotControl(); #endif #ifndef _XBOX // destroy the Navigation Mesh interface if (TheNavMesh) { delete TheNavMesh; TheNavMesh = NULL; } #endif DisconnectTier3Libraries(); DisconnectTier2Libraries(); ConVar_Unregister(); DisconnectTier1Libraries(); } //----------------------------------------------------------------------------- // Purpose: See shareddefs.h for redefining this. Don't even think about it, though, for HL2. Or you will pay. ywb 9/22/03 // Output : float //----------------------------------------------------------------------------- float CServerGameDLL::GetTickInterval( void ) const { float tickinterval = DEFAULT_TICK_INTERVAL; #if defined( CSTRIKE_DLL ) // in CS reduce tickrate/sec by defualt tickinterval *= 2; #endif // Ignoring this for now, server ops are abusing it #if !defined( TF_DLL ) // override if tick rate specified in command line if ( CommandLine()->CheckParm( "-tickrate" ) ) { float tickrate = CommandLine()->ParmValue( "-tickrate", 0 ); if ( tickrate > 10 ) tickinterval = 1.0f / tickrate; } #endif return tickinterval; } // This is called when a new game is started. (restart, map) bool CServerGameDLL::GameInit( void ) { ResetGlobalState(); engine->ServerCommand( "exec game.cfg\n" ); engine->ServerExecute( ); CBaseEntity::sm_bAccurateTriggerBboxChecks = true; IGameEvent *event = gameeventmanager->CreateEvent( "game_init" ); if ( event ) { gameeventmanager->FireEvent( event ); } return true; } // This is called when a game ends (server disconnect, death, restart, load) // NOT on level transitions within a game void CServerGameDLL::GameShutdown( void ) { ResetGlobalState(); } static bool g_OneWayTransition = false; void Game_SetOneWayTransition( void ) { g_OneWayTransition = true; } static CUtlVector<EHANDLE> g_RestoredEntities; // just for debugging, assert that this is the only time this function is called static bool g_InRestore = false; void AddRestoredEntity( CBaseEntity *pEntity ) { Assert(g_InRestore); if ( !pEntity ) return; g_RestoredEntities.AddToTail( EHANDLE(pEntity) ); } void EndRestoreEntities() { if ( !g_InRestore ) return; // The entire hierarchy is restored, so we can call GetAbsOrigin again. //CBaseEntity::SetAbsQueriesValid( true ); // Call all entities' OnRestore handlers for ( int i = g_RestoredEntities.Count()-1; i >=0; --i ) { CBaseEntity *pEntity = g_RestoredEntities[i].Get(); if ( pEntity && !pEntity->IsDormant() ) { MDLCACHE_CRITICAL_SECTION(); pEntity->OnRestore(); } } g_RestoredEntities.Purge(); IGameSystem::OnRestoreAllSystems(); g_InRestore = false; gEntList.CleanupDeleteList(); // HACKHACK: UNDONE: We need to redesign the main loop with respect to save/load/server activate g_ServerGameDLL.ServerActivate( NULL, 0, 0 ); CBaseEntity::SetAllowPrecache( false ); } void BeginRestoreEntities() { if ( g_InRestore ) { DevMsg( "BeginRestoreEntities without previous EndRestoreEntities.\n" ); gEntList.CleanupDeleteList(); } g_RestoredEntities.Purge(); g_InRestore = true; CBaseEntity::SetAllowPrecache( true ); // No calls to GetAbsOrigin until the entire hierarchy is restored! //CBaseEntity::SetAbsQueriesValid( false ); } //----------------------------------------------------------------------------- // Purpose: This prevents sv.tickcount/gpGlobals->tickcount from advancing during restore which // would cause a lot of the NPCs to fast forward their think times to the same // tick due to some ticks being elapsed during restore where there was no simulation going on //----------------------------------------------------------------------------- bool CServerGameDLL::IsRestoring() { return g_InRestore; } // Called any time a new level is started (after GameInit() also on level transitions within a game) bool CServerGameDLL::LevelInit( const char *pMapName, char const *pMapEntities, char const *pOldLevel, char const *pLandmarkName, bool loadGame, bool background ) { VPROF("CServerGameDLL::LevelInit"); ResetWindspeed(); UpdateChapterRestrictions( pMapName ); if ( IsX360() && !background && (gpGlobals->maxClients == 1) && (g_nCurrentChapterIndex >= 0) ) { // Single player games tell xbox live what game & chapter the user is playing UpdateRichPresence(); } //Tony; parse custom manifest if exists! ParseParticleEffectsMap( pMapName, false ); // IGameSystem::LevelInitPreEntityAllSystems() is called when the world is precached // That happens either in LoadGameState() or in MapEntity_ParseAllEntities() if ( loadGame ) { if ( pOldLevel ) { gpGlobals->eLoadType = MapLoad_Transition; } else { gpGlobals->eLoadType = MapLoad_LoadGame; } BeginRestoreEntities(); if ( !engine->LoadGameState( pMapName, 1 ) ) { if ( pOldLevel ) { MapEntity_ParseAllEntities( pMapEntities ); } else { // Regular save load case return false; } } if ( pOldLevel ) { engine->LoadAdjacentEnts( pOldLevel, pLandmarkName ); } if ( g_OneWayTransition ) { engine->ClearSaveDirAfterClientLoad(); } if ( pOldLevel && sv_autosave.GetBool() == true ) { // This is a single-player style level transition. // Queue up an autosave one second into the level CBaseEntity *pAutosave = CBaseEntity::Create( "logic_autosave", vec3_origin, vec3_angle, NULL ); if ( pAutosave ) { g_EventQueue.AddEvent( pAutosave, "Save", 1.0, NULL, NULL ); g_EventQueue.AddEvent( pAutosave, "Kill", 1.1, NULL, NULL ); } } } else { if ( background ) { gpGlobals->eLoadType = MapLoad_Background; } else { gpGlobals->eLoadType = MapLoad_NewGame; } // Clear out entity references, and parse the entities into it. g_MapEntityRefs.Purge(); CMapLoadEntityFilter filter; MapEntity_ParseAllEntities( pMapEntities, &filter ); g_pServerBenchmark->StartBenchmark(); // Now call the mod specific parse LevelInit_ParseAllEntities( pMapEntities ); } // Check low violence settings for this map g_RagdollLVManager.SetLowViolence( pMapName ); // Now that all of the active entities have been loaded in, precache any entities who need point_template parameters // to be parsed (the above code has loaded all point_template entities) PrecachePointTemplates(); // load MOTD from file into stringtable LoadMessageOfTheDay(); // Sometimes an ent will Remove() itself during its precache, so RemoveImmediate won't happen. // This makes sure those ents get cleaned up. gEntList.CleanupDeleteList(); g_AIFriendliesTalkSemaphore.Release(); g_AIFoesTalkSemaphore.Release(); g_OneWayTransition = false; // clear any pending autosavedangerous m_fAutoSaveDangerousTime = 0.0f; m_fAutoSaveDangerousMinHealthToCommit = 0.0f; return true; } //----------------------------------------------------------------------------- // Purpose: called after every level change and load game, iterates through all the // active entities and gives them a chance to fix up their state //----------------------------------------------------------------------------- #ifdef DEBUG bool g_bReceivedChainedActivate; bool g_bCheckForChainedActivate; #define BeginCheckChainedActivate() if (0) ; else { g_bCheckForChainedActivate = true; g_bReceivedChainedActivate = false; } #define EndCheckChainedActivate( bCheck ) \ if (0) ; else \ { \ if ( bCheck ) \ { \ char msg[ 1024 ]; \ Q_snprintf( msg, sizeof( msg ), "Entity (%i/%s/%s) failed to call base class Activate()\n", pClass->entindex(), pClass->GetClassname(), STRING( pClass->GetEntityName() ) ); \ AssertMsg( g_bReceivedChainedActivate == true, msg ); \ } \ g_bCheckForChainedActivate = false; \ } #else #define BeginCheckChainedActivate() ((void)0) #define EndCheckChainedActivate( bCheck ) ((void)0) #endif void CServerGameDLL::ServerActivate( edict_t *pEdictList, int edictCount, int clientMax ) { // HACKHACK: UNDONE: We need to redesign the main loop with respect to save/load/server activate if ( g_InRestore ) return; if ( gEntList.ResetDeleteList() != 0 ) { Msg( "ERROR: Entity delete queue not empty on level start!\n" ); } for ( CBaseEntity *pClass = gEntList.FirstEnt(); pClass != NULL; pClass = gEntList.NextEnt(pClass) ) { if ( pClass && !pClass->IsDormant() ) { MDLCACHE_CRITICAL_SECTION(); BeginCheckChainedActivate(); pClass->Activate(); // We don't care if it finished activating if it decided to remove itself. EndCheckChainedActivate( !( pClass->GetEFlags() & EFL_KILLME ) ); } } IGameSystem::LevelInitPostEntityAllSystems(); // No more precaching after PostEntityAllSystems!!! CBaseEntity::SetAllowPrecache( false ); // only display the think limit when the game is run with "developer" mode set if ( !g_pDeveloper->GetInt() ) { think_limit.SetValue( 0 ); } #ifndef _XBOX // load the Navigation Mesh for this map TheNavMesh->Load(); #endif #ifdef CSTRIKE_DLL // BOTPORT: TODO: move these ifdefs out TheBots->ServerActivate(); #endif //Tony; call activate on the gamerules #if defined ( SDK_DLL ) SDKGameRules()->ServerActivate(); #endif } //----------------------------------------------------------------------------- // Purpose: Called at the start of every game frame //----------------------------------------------------------------------------- ConVar trace_report( "trace_report", "0" ); void CServerGameDLL::GameFrame( bool simulating ) { VPROF( "CServerGameDLL::GameFrame" ); // Don't run frames until fully restored if ( g_InRestore ) return; if ( CBaseEntity::IsSimulatingOnAlternateTicks() ) { // only run simulation on even numbered ticks if ( gpGlobals->tickcount & 1 ) { UpdateAllClientData(); return; } // If we're skipping frames, then the frametime is 2x the normal tick gpGlobals->frametime *= 2.0f; } float oldframetime = gpGlobals->frametime; #ifdef _DEBUG // For profiling.. let them enable/disable the networkvar manual mode stuff. g_bUseNetworkVars = s_UseNetworkVars.GetBool(); #endif extern void GameStartFrame( void ); extern void ServiceEventQueue( void ); extern void Physics_RunThinkFunctions( bool simulating ); // Delete anything that was marked for deletion // outside of server frameloop (e.g., in response to concommand) gEntList.CleanupDeleteList(); IGameSystem::FrameUpdatePreEntityThinkAllSystems(); GameStartFrame(); #ifndef _XBOX TheNavMesh->Update(); gamestatsuploader->UpdateConnection(); #endif g_pServerBenchmark->UpdateBenchmark(); Physics_RunThinkFunctions( simulating ); IGameSystem::FrameUpdatePostEntityThinkAllSystems(); // UNDONE: Make these systems IGameSystems and move these calls into FrameUpdatePostEntityThink() // service event queue, firing off any actions whos time has come ServiceEventQueue(); // free all ents marked in think functions gEntList.CleanupDeleteList(); // FIXME: Should this only occur on the final tick? UpdateAllClientData(); if ( g_pGameRules ) { g_pGameRules->EndGameFrame(); } if ( trace_report.GetBool() ) { int total = 0, totals[3]; for ( int i = 0; i < 3; i++ ) { totals[i] = enginetrace->GetStatByIndex( i, true ); if ( totals[i] > 0 ) { total += totals[i]; } } if ( total ) { Msg("Trace: %d, contents %d, enumerate %d\n", totals[0], totals[1], totals[2] ); } } // Any entities that detect network state changes on a timer do it here. g_NetworkPropertyEventMgr.FireEvents(); gpGlobals->frametime = oldframetime; } //----------------------------------------------------------------------------- // Purpose: Called every frame even if not ticking // Input : simulating - //----------------------------------------------------------------------------- void CServerGameDLL::PreClientUpdate( bool simulating ) { if ( !simulating ) return; /* if (game_speeds.GetInt()) { DrawMeasuredSections(); } */ //#ifdef _DEBUG - allow this in release for now DrawAllDebugOverlays(); //#endif IGameSystem::PreClientUpdateAllSystems(); if ( sv_showhitboxes.GetInt() == -1 ) return; if ( sv_showhitboxes.GetInt() == 0 ) { // assume it's text CBaseEntity *pEntity = NULL; while (1) { pEntity = gEntList.FindEntityByName( pEntity, sv_showhitboxes.GetString() ); if ( !pEntity ) break; CBaseAnimating *anim = dynamic_cast< CBaseAnimating * >( pEntity ); if (anim) { anim->DrawServerHitboxes(); } } return; } CBaseAnimating *anim = dynamic_cast< CBaseAnimating * >( CBaseEntity::Instance( engine->PEntityOfEntIndex( sv_showhitboxes.GetInt() ) ) ); if ( !anim ) return; anim->DrawServerHitboxes(); } void CServerGameDLL::Think( bool finalTick ) { if ( m_fAutoSaveDangerousTime != 0.0f && m_fAutoSaveDangerousTime < gpGlobals->curtime ) { // The safety timer for a dangerous auto save has expired CBasePlayer *pPlayer = UTIL_PlayerByIndex( 1 ); if ( pPlayer && ( pPlayer->GetDeathTime() == 0.0f || pPlayer->GetDeathTime() > gpGlobals->curtime ) && !pPlayer->IsSinglePlayerGameEnding() ) { if( pPlayer->GetHealth() >= m_fAutoSaveDangerousMinHealthToCommit ) { // The player isn't dead, so make the dangerous auto save safe engine->ServerCommand( "autosavedangerousissafe\n" ); } } m_fAutoSaveDangerousTime = 0.0f; m_fAutoSaveDangerousMinHealthToCommit = 0.0f; } } void CServerGameDLL::OnQueryCvarValueFinished( QueryCvarCookie_t iCookie, edict_t *pPlayerEntity, EQueryCvarValueStatus eStatus, const char *pCvarName, const char *pCvarValue ) { } // Called when a level is shutdown (including changing levels) void CServerGameDLL::LevelShutdown( void ) { MDLCACHE_CRITICAL_SECTION(); IGameSystem::LevelShutdownPreEntityAllSystems(); // YWB: // This entity pointer is going away now and is corrupting memory on level transitions/restarts CSoundEnt::ShutdownSoundEnt(); gEntList.Clear(); IGameSystem::LevelShutdownPostEntityAllSystems(); // In case we quit out during initial load CBaseEntity::SetAllowPrecache( false ); g_nCurrentChapterIndex = -1; } //----------------------------------------------------------------------------- // Purpose: // Input : // Output : ServerClass* //----------------------------------------------------------------------------- ServerClass* CServerGameDLL::GetAllServerClasses() { return g_pServerClassHead; } const char *CServerGameDLL::GetGameDescription( void ) { return ::GetGameDescription(); } void CServerGameDLL::CreateNetworkStringTables( void ) { // Create any shared string tables here (and only here!) // E.g.: xxx = networkstringtable->CreateStringTable( "SceneStrings", 512 ); g_pStringTableParticleEffectNames = networkstringtable->CreateStringTable( "ParticleEffectNames", MAX_PARTICLESYSTEMS_STRINGS ); g_pStringTableEffectDispatch = networkstringtable->CreateStringTable( "EffectDispatch", MAX_EFFECT_DISPATCH_STRINGS ); g_pStringTableVguiScreen = networkstringtable->CreateStringTable( "VguiScreen", MAX_VGUI_SCREEN_STRINGS ); g_pStringTableMaterials = networkstringtable->CreateStringTable( "Materials", MAX_MATERIAL_STRINGS ); g_pStringTableInfoPanel = networkstringtable->CreateStringTable( "InfoPanel", MAX_INFOPANEL_STRINGS ); g_pStringTableClientSideChoreoScenes = networkstringtable->CreateStringTable( "Scenes", MAX_CHOREO_SCENES_STRINGS ); Assert( g_pStringTableParticleEffectNames && g_pStringTableEffectDispatch && g_pStringTableVguiScreen && g_pStringTableMaterials && g_pStringTableInfoPanel && g_pStringTableClientSideChoreoScenes ); // Need this so we have the error material always handy PrecacheMaterial( "debug/debugempty" ); Assert( GetMaterialIndex( "debug/debugempty" ) == 0 ); PrecacheParticleSystem( "error" ); // ensure error particle system is handy Assert( GetParticleSystemIndex( "error" ) == 0 ); CreateNetworkStringTables_GameRules(); // Set up save/load utilities for string tables g_VguiScreenStringOps.Init( g_pStringTableVguiScreen ); } CSaveRestoreData *CServerGameDLL::SaveInit( int size ) { return ::SaveInit(size); } //----------------------------------------------------------------------------- // Purpose: Saves data from a struct into a saverestore object, to be saved to disk // Input : *pSaveData - the saverestore object // char *pname - the name of the data to write // *pBaseData - the struct into which the data is to be read // *pFields - pointer to an array of data field descriptions // fieldCount - the size of the array (number of field descriptions) //----------------------------------------------------------------------------- void CServerGameDLL::SaveWriteFields( CSaveRestoreData *pSaveData, const char *pname, void *pBaseData, datamap_t *pMap, typedescription_t *pFields, int fieldCount ) { CSave saveHelper( pSaveData ); saveHelper.WriteFields( pname, pBaseData, pMap, pFields, fieldCount ); } //----------------------------------------------------------------------------- // Purpose: Reads data from a save/restore block into a structure // Input : *pSaveData - the saverestore object // char *pname - the name of the data to extract from // *pBaseData - the struct into which the data is to be restored // *pFields - pointer to an array of data field descriptions // fieldCount - the size of the array (number of field descriptions) //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CServerGameDLL::SaveReadFields( CSaveRestoreData *pSaveData, const char *pname, void *pBaseData, datamap_t *pMap, typedescription_t *pFields, int fieldCount ) { CRestore restoreHelper( pSaveData ); restoreHelper.ReadFields( pname, pBaseData, pMap, pFields, fieldCount ); } //----------------------------------------------------------------------------- void CServerGameDLL::SaveGlobalState( CSaveRestoreData *s ) { ::SaveGlobalState(s); } void CServerGameDLL::RestoreGlobalState(CSaveRestoreData *s) { ::RestoreGlobalState(s); } void CServerGameDLL::Save( CSaveRestoreData *s ) { CSave saveHelper( s ); g_pGameSaveRestoreBlockSet->Save( &saveHelper ); } void CServerGameDLL::Restore( CSaveRestoreData *s, bool b) { CRestore restore(s); g_pGameSaveRestoreBlockSet->Restore( &restore, b ); g_pGameSaveRestoreBlockSet->PostRestore(); } //----------------------------------------------------------------------------- // Purpose: // Input : msg_type - // *name - // size - // Output : Returns true on success, false on failure. //----------------------------------------------------------------------------- bool CServerGameDLL::GetUserMessageInfo( int msg_type, char *name, int maxnamelength, int& size ) { if ( !usermessages->IsValidIndex( msg_type ) ) return false; Q_strncpy( name, usermessages->GetUserMessageName( msg_type ), maxnamelength ); size = usermessages->GetUserMessageSize( msg_type ); return true; } CStandardSendProxies* CServerGameDLL::GetStandardSendProxies() { return &g_StandardSendProxies; } int CServerGameDLL::CreateEntityTransitionList( CSaveRestoreData *s, int a) { CRestore restoreHelper( s ); // save off file base int base = restoreHelper.GetReadPos(); int movedCount = ::CreateEntityTransitionList(s, a); if ( movedCount ) { g_pGameSaveRestoreBlockSet->CallBlockHandlerRestore( GetPhysSaveRestoreBlockHandler(), base, &restoreHelper, false ); g_pGameSaveRestoreBlockSet->CallBlockHandlerRestore( GetAISaveRestoreBlockHandler(), base, &restoreHelper, false ); } GetPhysSaveRestoreBlockHandler()->PostRestore(); GetAISaveRestoreBlockHandler()->PostRestore(); return movedCount; } void CServerGameDLL::PreSave( CSaveRestoreData *s ) { g_pGameSaveRestoreBlockSet->PreSave( s ); } #include "client_textmessage.h" // This little hack lets me marry BSP names to messages in titles.txt typedef struct { char *pBSPName; char *pTitleName; } TITLECOMMENT; // this list gets searched for the first partial match, so some are out of order static TITLECOMMENT gTitleComments[] = { #ifdef HL1_DLL { "t0a0", "#T0A0TITLE" }, { "c0a0", "#HL1_Chapter1_Title" }, { "c1a0", "#HL1_Chapter2_Title" }, { "c1a1", "#HL1_Chapter3_Title" }, { "c1a2", "#HL1_Chapter4_Title" }, { "c1a3", "#HL1_Chapter5_Title" }, { "c1a4", "#HL1_Chapter6_Title" }, { "c2a1", "#HL1_Chapter7_Title" }, { "c2a2", "#HL1_Chapter8_Title" }, { "c2a3", "#HL1_Chapter9_Title" }, { "c2a4d", "#HL1_Chapter11_Title" }, // These must appear before "C2A4" so all other map names starting with C2A4 get that title { "c2a4e", "#HL1_Chapter11_Title" }, { "c2a4f", "#HL1_Chapter11_Title" }, { "c2a4g", "#HL1_Chapter11_Title" }, { "c2a4", "#HL1_Chapter10_Title" }, { "c2a5", "#HL1_Chapter12_Title" }, { "c3a1", "#HL1_Chapter13_Title" }, { "c3a2", "#HL1_Chapter14_Title" }, { "c4a1a", "#HL1_Chapter17_Title" }, // Order is important, see above { "c4a1b", "#HL1_Chapter17_Title" }, { "c4a1c", "#HL1_Chapter17_Title" }, { "c4a1d", "#HL1_Chapter17_Title" }, { "c4a1e", "#HL1_Chapter17_Title" }, { "c4a1", "#HL1_Chapter15_Title" }, { "c4a2", "#HL1_Chapter16_Title" }, { "c4a3", "#HL1_Chapter18_Title" }, { "c5a1", "#HL1_Chapter19_Title" }, #elif defined PORTAL { "testchmb_a_00", "#Portal_Chapter1_Title" }, { "testchmb_a_01", "#Portal_Chapter1_Title" }, { "testchmb_a_02", "#Portal_Chapter2_Title" }, { "testchmb_a_03", "#Portal_Chapter2_Title" }, { "testchmb_a_04", "#Portal_Chapter3_Title" }, { "testchmb_a_05", "#Portal_Chapter3_Title" }, { "testchmb_a_06", "#Portal_Chapter4_Title" }, { "testchmb_a_07", "#Portal_Chapter4_Title" }, { "testchmb_a_08_advanced", "#Portal_Chapter5_Title" }, { "testchmb_a_08", "#Portal_Chapter5_Title" }, { "testchmb_a_09_advanced", "#Portal_Chapter6_Title" }, { "testchmb_a_09", "#Portal_Chapter6_Title" }, { "testchmb_a_10_advanced", "#Portal_Chapter7_Title" }, { "testchmb_a_10", "#Portal_Chapter7_Title" }, { "testchmb_a_11_advanced", "#Portal_Chapter8_Title" }, { "testchmb_a_11", "#Portal_Chapter8_Title" }, { "testchmb_a_13_advanced", "#Portal_Chapter9_Title" }, { "testchmb_a_13", "#Portal_Chapter9_Title" }, { "testchmb_a_14_advanced", "#Portal_Chapter10_Title" }, { "testchmb_a_14", "#Portal_Chapter10_Title" }, { "testchmb_a_15", "#Portal_Chapter11_Title" }, { "escape_", "#Portal_Chapter11_Title" }, { "background2", "#Portal_Chapter12_Title" }, #else { "intro", "#HL2_Chapter1_Title" }, { "d1_trainstation_05", "#HL2_Chapter2_Title" }, { "d1_trainstation_06", "#HL2_Chapter2_Title" }, { "d1_trainstation_", "#HL2_Chapter1_Title" }, { "d1_canals_06", "#HL2_Chapter4_Title" }, { "d1_canals_07", "#HL2_Chapter4_Title" }, { "d1_canals_08", "#HL2_Chapter4_Title" }, { "d1_canals_09", "#HL2_Chapter4_Title" }, { "d1_canals_1", "#HL2_Chapter4_Title" }, { "d1_canals_0", "#HL2_Chapter3_Title" }, { "d1_eli_", "#HL2_Chapter5_Title" }, { "d1_town_", "#HL2_Chapter6_Title" }, { "d2_coast_09", "#HL2_Chapter8_Title" }, { "d2_coast_1", "#HL2_Chapter8_Title" }, { "d2_prison_01", "#HL2_Chapter8_Title" }, { "d2_coast_", "#HL2_Chapter7_Title" }, { "d2_prison_06", "#HL2_Chapter9a_Title" }, { "d2_prison_07", "#HL2_Chapter9a_Title" }, { "d2_prison_08", "#HL2_Chapter9a_Title" }, { "d2_prison_", "#HL2_Chapter9_Title" }, { "d3_c17_01", "#HL2_Chapter9a_Title" }, { "d3_c17_09", "#HL2_Chapter11_Title" }, { "d3_c17_1", "#HL2_Chapter11_Title" }, { "d3_c17_", "#HL2_Chapter10_Title" }, { "d3_citadel_", "#HL2_Chapter12_Title" }, { "d3_breen_", "#HL2_Chapter13_Title" }, { "credits", "#HL2_Chapter14_Title" }, { "ep1_citadel_00", "#episodic_Chapter1_Title" }, { "ep1_citadel_01", "#episodic_Chapter1_Title" }, { "ep1_citadel_02b", "#episodic_Chapter1_Title" }, { "ep1_citadel_02", "#episodic_Chapter1_Title" }, { "ep1_citadel_03", "#episodic_Chapter2_Title" }, { "ep1_citadel_04", "#episodic_Chapter2_Title" }, { "ep1_c17_00a", "#episodic_Chapter3_Title" }, { "ep1_c17_00", "#episodic_Chapter3_Title" }, { "ep1_c17_01", "#episodic_Chapter4_Title" }, { "ep1_c17_02b", "#episodic_Chapter4_Title" }, { "ep1_c17_02", "#episodic_Chapter4_Title" }, { "ep1_c17_05", "#episodic_Chapter5_Title" }, { "ep1_c17_06", "#episodic_Chapter5_Title" }, { "ep2_outland_01a", "#ep2_Chapter1_Title" }, { "ep2_outland_01", "#ep2_Chapter1_Title" }, { "ep2_outland_02", "#ep2_Chapter2_Title" }, { "ep2_outland_03", "#ep2_Chapter2_Title" }, { "ep2_outland_04", "#ep2_Chapter2_Title" }, { "ep2_outland_05", "#ep2_Chapter3_Title" }, { "ep2_outland_06a", "#ep2_Chapter4_Title" }, { "ep2_outland_06", "#ep2_Chapter3_Title" }, { "ep2_outland_07", "#ep2_Chapter4_Title" }, { "ep2_outland_08", "#ep2_Chapter4_Title" }, { "ep2_outland_09", "#ep2_Chapter5_Title" }, { "ep2_outland_10a", "#ep2_Chapter5_Title" }, { "ep2_outland_10", "#ep2_Chapter5_Title" }, { "ep2_outland_11a", "#ep2_Chapter6_Title" }, { "ep2_outland_11", "#ep2_Chapter6_Title" }, { "ep2_outland_12a", "#ep2_Chapter7_Title" }, { "ep2_outland_12", "#ep2_Chapter6_Title" }, #endif }; #ifdef _XBOX void CServerGameDLL::GetTitleName( const char *pMapName, char* pTitleBuff, int titleBuffSize ) { // Try to find a matching title comment for this mapname for ( int i = 0; i < ARRAYSIZE(gTitleComments); i++ ) { if ( !Q_strnicmp( pMapName, gTitleComments[i].pBSPName, strlen(gTitleComments[i].pBSPName) ) ) { Q_strncpy( pTitleBuff, gTitleComments[i].pTitleName, titleBuffSize ); return; } } Q_strncpy( pTitleBuff, pMapName, titleBuffSize ); } #endif void CServerGameDLL::GetSaveComment( char *text, int maxlength, float flMinutes, float flSeconds, bool bNoTime ) { char comment[64]; const char *pName; int i; char const *mapname = STRING( gpGlobals->mapname ); pName = NULL; // Try to find a matching title comment for this mapname for ( i = 0; i < ARRAYSIZE(gTitleComments) && !pName; i++ ) { if ( !Q_strnicmp( mapname, gTitleComments[i].pBSPName, strlen(gTitleComments[i].pBSPName) ) ) { // found one int j; // Got a message, post-process it to be save name friendly Q_strncpy( comment, gTitleComments[i].pTitleName, sizeof( comment ) ); pName = comment; j = 0; // Strip out CRs while ( j < 64 && comment[j] ) { if ( comment[j] == '\n' || comment[j] == '\r' ) comment[j] = 0; else j++; } break; } } // If we didn't get one, use the designer's map name, or the BSP name itself if ( !pName ) { pName = mapname; } if ( bNoTime ) { Q_snprintf( text, maxlength, "%-64.64s", pName ); } else { int minutes = flMinutes; int seconds = flSeconds; // Wow, this guy/gal must suck...! if ( minutes >= 1000 ) { minutes = 999; seconds = 59; } int minutesAdd = ( seconds / 60 ); seconds %= 60; // add the elapsed time at the end of the comment, for the ui to parse out Q_snprintf( text, maxlength, "%-64.64s %03d:%02d", pName, (minutes + minutesAdd), seconds ); } } void CServerGameDLL::WriteSaveHeaders( CSaveRestoreData *s ) { CSave saveHelper( s ); g_pGameSaveRestoreBlockSet->WriteSaveHeaders( &saveHelper ); g_pGameSaveRestoreBlockSet->PostSave(); } void CServerGameDLL::ReadRestoreHeaders( CSaveRestoreData *s ) { CRestore restoreHelper( s ); g_pGameSaveRestoreBlockSet->PreRestore(); g_pGameSaveRestoreBlockSet->ReadRestoreHeaders( &restoreHelper ); } void CServerGameDLL::PreSaveGameLoaded( char const *pSaveName, bool bInGame ) { gamestats->Event_PreSaveGameLoaded( pSaveName, bInGame ); } //----------------------------------------------------------------------------- // Purpose: Returns true if the game DLL wants the server not to be made public. // Used by commentary system to hide multiplayer commentary servers from the master. //----------------------------------------------------------------------------- bool CServerGameDLL::ShouldHideServer( void ) { if ( g_pcv_commentary && g_pcv_commentary->GetBool() ) return true; if ( gpGlobals->eLoadType == MapLoad_Background ) return true; return false; } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- void CServerGameDLL::InvalidateMdlCache() { CBaseAnimating *pAnimating; for ( CBaseEntity *pEntity = gEntList.FirstEnt(); pEntity != NULL; pEntity = gEntList.NextEnt(pEntity) ) { pAnimating = dynamic_cast<CBaseAnimating *>(pEntity); if ( pAnimating ) { pAnimating->InvalidateMdlCache(); } } } //----------------------------------------------------------------------------- // Purpose: Called during a transition, to build a map adjacency list //----------------------------------------------------------------------------- void CServerGameDLL::BuildAdjacentMapList( void ) { // retrieve the pointer to the save data CSaveRestoreData *pSaveData = gpGlobals->pSaveData; if ( pSaveData ) pSaveData->levelInfo.connectionCount = BuildChangeList( pSaveData->levelInfo.levelList, MAX_LEVEL_CONNECTIONS ); } //----------------------------------------------------------------------------- // Purpose: Sanity-check to verify that a path is a relative path inside the game dir // Taken From: engine/cmd.cpp //----------------------------------------------------------------------------- static bool IsValidPath( const char *pszFilename ) { if ( !pszFilename ) { return false; } if ( Q_strlen( pszFilename ) <= 0 || Q_IsAbsolutePath( pszFilename ) || // to protect absolute paths Q_strstr( pszFilename, ".." ) ) // to protect relative paths { return false; } return true; } static void ValidateMOTDFilename( IConVar *pConVar, const char *oldValue, float flOldValue ) { ConVarRef var( pConVar ); if ( !IsValidPath( var.GetString() ) ) { var.SetValue( var.GetDefault() ); } } static ConVar motdfile( "motdfile", "motd.txt", 0, "The MOTD file to load.", ValidateMOTDFilename ); void CServerGameDLL::LoadMessageOfTheDay() { #ifndef _XBOX char data[2048]; int length = filesystem->Size( motdfile.GetString(), "GAME" ); if ( length <= 0 || length >= (sizeof(data)-1) ) { DevMsg("Invalid file size for %s\n", motdfile.GetString() ); return; } FileHandle_t hFile = filesystem->Open( motdfile.GetString(), "rb", "GAME" ); if ( hFile == FILESYSTEM_INVALID_HANDLE ) return; filesystem->Read( data, length, hFile ); filesystem->Close( hFile ); data[length] = 0; g_pStringTableInfoPanel->AddString( CBaseEntity::IsServer(), "motd", length+1, data ); #endif } // keeps track of which chapters the user has unlocked ConVar sv_unlockedchapters( "sv_unlockedchapters", "1", FCVAR_ARCHIVE | FCVAR_ARCHIVE_XBOX ); //----------------------------------------------------------------------------- // Purpose: Updates which chapters are unlocked //----------------------------------------------------------------------------- void UpdateChapterRestrictions( const char *mapname ) { // look at the chapter for this map char chapterTitle[64]; chapterTitle[0] = 0; for ( int i = 0; i < ARRAYSIZE(gTitleComments); i++ ) { if ( !Q_strnicmp( mapname, gTitleComments[i].pBSPName, strlen(gTitleComments[i].pBSPName) ) ) { // found Q_strncpy( chapterTitle, gTitleComments[i].pTitleName, sizeof( chapterTitle ) ); int j = 0; while ( j < 64 && chapterTitle[j] ) { if ( chapterTitle[j] == '\n' || chapterTitle[j] == '\r' ) chapterTitle[j] = 0; else j++; } break; } } if ( !chapterTitle[0] ) return; // make sure the specified chapter title is unlocked strlwr( chapterTitle ); // Get our active mod directory name char modDir[MAX_PATH]; if ( UTIL_GetModDir( modDir, sizeof(modDir) ) == false ) return; char chapterNumberPrefix[64]; Q_snprintf(chapterNumberPrefix, sizeof(chapterNumberPrefix), "#%s_chapter", modDir); const char *newChapterNumber = strstr( chapterTitle, chapterNumberPrefix ); if ( newChapterNumber ) { // cut off the front newChapterNumber += strlen( chapterNumberPrefix ); char newChapter[32]; Q_strncpy( newChapter, newChapterNumber, sizeof(newChapter) ); // cut off the end char *end = strstr( newChapter, "_title" ); if ( end ) { *end = 0; } int nNewChapter = atoi( newChapter ); // HACK: HL2 added a zany chapter "9a" which wreaks // havoc in this stupid atoi-based chapter code. if ( !Q_stricmp( modDir, "hl2" ) ) { if ( !Q_stricmp( newChapter, "9a" ) ) { nNewChapter = 10; } else if ( nNewChapter > 9 ) { nNewChapter++; } } // ok we have the string, see if it's newer const char *unlockedChapter = sv_unlockedchapters.GetString(); int nUnlockedChapter = atoi( unlockedChapter ); if ( nUnlockedChapter < nNewChapter ) { // ok we're at a higher chapter, unlock sv_unlockedchapters.SetValue( nNewChapter ); // HACK: Call up through a better function than this? 7/23/07 - jdw if ( IsX360() ) { engine->ServerCommand( "host_writeconfig\n" ); } } g_nCurrentChapterIndex = nNewChapter; } } //----------------------------------------------------------------------------- // Purpose: Update xbox live data for the user's presence //----------------------------------------------------------------------------- void UpdateRichPresence ( void ) { // This assumes we're playing a single player game Assert ( gpGlobals->maxClients == 1 ); // Shouldn't get here unless we're playing a map and we've updated sv_unlockedchapters Assert ( g_nCurrentChapterIndex >= 0 ); // Get our active mod directory name char modDir[MAX_PATH]; if ( UTIL_GetModDir( modDir, sizeof(modDir) ) == false ) return; // Get presence data based on the game we're playing uint iGameID, iChapterIndex, iChapterID, iGamePresenceID; iGameID = iChapterIndex = iChapterID = iGamePresenceID = 0; if ( Q_stristr( modDir, "hl2" ) ) { iGameID = CONTEXT_GAME_GAME_HALF_LIFE_2; iChapterID = CONTEXT_CHAPTER_HL2; iChapterIndex = g_nCurrentChapterIndex - 1; iGamePresenceID = CONTEXT_PRESENCE_HL2_INGAME; } else if ( Q_stristr( modDir, "episodic" ) ) { iGameID = CONTEXT_GAME_GAME_EPISODE_ONE; iChapterID = CONTEXT_CHAPTER_EP1; iChapterIndex = g_nCurrentChapterIndex - 1; iGamePresenceID = CONTEXT_PRESENCE_EP1_INGAME; } else if ( Q_stristr( modDir, "ep2" ) ) { iGameID = CONTEXT_GAME_GAME_EPISODE_TWO; iChapterID = CONTEXT_CHAPTER_EP2; iChapterIndex = g_nCurrentChapterIndex - 1; iGamePresenceID = CONTEXT_PRESENCE_EP2_INGAME; } else if ( Q_stristr( modDir, "portal" ) ) { iGameID = CONTEXT_GAME_GAME_PORTAL; iChapterID = CONTEXT_CHAPTER_PORTAL; iChapterIndex = g_nCurrentChapterIndex - 1; iGamePresenceID = CONTEXT_PRESENCE_PORTAL_INGAME; } else { Warning( "UpdateRichPresence failed in GameInterface. Didn't recognize -game parameter." ); } if ( iChapterID < 0 ) iChapterID = 0; #if defined( _X360 ) // Set chapter context based on mapname if ( !xboxsystem->UserSetContext( XBX_GetPrimaryUserId(), iChapterID, iChapterIndex, true ) ) { Warning( "GameInterface: UserSetContext failed.\n" ); } if ( commentary.GetBool() ) { // Set presence to show the user is playing developer commentary if ( !xboxsystem->UserSetContext( XBX_GetPrimaryUserId(), X_CONTEXT_PRESENCE, CONTEXT_PRESENCE_COMMENTARY, true ) ) { Warning( "GameInterface: UserSetContext failed.\n" ); } } else { // Set presence to show the user is in-game if ( !xboxsystem->UserSetContext( XBX_GetPrimaryUserId(), X_CONTEXT_PRESENCE, iGamePresenceID, true ) ) { Warning( "GameInterface: UserSetContext failed.\n" ); } } // Set which game the user is playing if ( !xboxsystem->UserSetContext( XBX_GetPrimaryUserId(), CONTEXT_GAME, iGameID, true ) ) { Warning( "GameInterface: UserSetContext failed.\n" ); } if ( !xboxsystem->UserSetContext( XBX_GetPrimaryUserId(), X_CONTEXT_GAME_TYPE, X_CONTEXT_GAME_TYPE_STANDARD, true ) ) { Warning( "GameInterface: UserSetContext failed.\n" ); } if ( !xboxsystem->UserSetContext( XBX_GetPrimaryUserId(), X_CONTEXT_GAME_MODE, CONTEXT_GAME_MODE_SINGLEPLAYER, true ) ) { Warning( "GameInterface: UserSetContext failed.\n" ); } #endif } //----------------------------------------------------------------------------- // Precaches a vgui screen overlay material //----------------------------------------------------------------------------- void PrecacheMaterial( const char *pMaterialName ) { Assert( pMaterialName && pMaterialName[0] ); g_pStringTableMaterials->AddString( CBaseEntity::IsServer(), pMaterialName ); } //----------------------------------------------------------------------------- // Converts a previously precached material into an index //----------------------------------------------------------------------------- int GetMaterialIndex( const char *pMaterialName ) { if (pMaterialName) { int nIndex = g_pStringTableMaterials->FindStringIndex( pMaterialName ); if (nIndex != INVALID_STRING_INDEX ) { return nIndex; } else { DevMsg("Warning! GetMaterialIndex: couldn't find material %s\n ", pMaterialName ); return 0; } } // This is the invalid string index return 0; } //----------------------------------------------------------------------------- // Converts a previously precached material index into a string //----------------------------------------------------------------------------- const char *GetMaterialNameFromIndex( int nMaterialIndex ) { return g_pStringTableMaterials->GetString( nMaterialIndex ); } //----------------------------------------------------------------------------- // Precaches a vgui screen overlay material //----------------------------------------------------------------------------- void PrecacheParticleSystem( const char *pParticleSystemName ) { Assert( pParticleSystemName && pParticleSystemName[0] ); g_pStringTableParticleEffectNames->AddString( CBaseEntity::IsServer(), pParticleSystemName ); } //----------------------------------------------------------------------------- // Converts a previously precached material into an index //----------------------------------------------------------------------------- int GetParticleSystemIndex( const char *pParticleSystemName ) { if ( pParticleSystemName ) { int nIndex = g_pStringTableParticleEffectNames->FindStringIndex( pParticleSystemName ); if (nIndex != INVALID_STRING_INDEX ) return nIndex; DevWarning("Server: Missing precache for particle system \"%s\"!\n", pParticleSystemName ); } // This is the invalid string index return 0; } //----------------------------------------------------------------------------- // Converts a previously precached material index into a string //----------------------------------------------------------------------------- const char *GetParticleSystemNameFromIndex( int nMaterialIndex ) { if ( nMaterialIndex < g_pStringTableParticleEffectNames->GetMaxStrings() ) return g_pStringTableParticleEffectNames->GetString( nMaterialIndex ); return "error"; } //----------------------------------------------------------------------------- // Returns true if host_thread_mode is set to non-zero (and engine is running in threaded mode) //----------------------------------------------------------------------------- bool IsEngineThreaded() { if ( g_pcv_ThreadMode ) { return g_pcv_ThreadMode->GetBool(); } return false; } class CServerGameEnts : public IServerGameEnts { public: virtual void SetDebugEdictBase(edict_t *base); virtual void MarkEntitiesAsTouching( edict_t *e1, edict_t *e2 ); virtual void FreeContainingEntity( edict_t * ); virtual edict_t* BaseEntityToEdict( CBaseEntity *pEnt ); virtual CBaseEntity* EdictToBaseEntity( edict_t *pEdict ); virtual void CheckTransmit( CCheckTransmitInfo *pInfo, const unsigned short *pEdictIndices, int nEdicts ); }; EXPOSE_SINGLE_INTERFACE(CServerGameEnts, IServerGameEnts, INTERFACEVERSION_SERVERGAMEENTS); void CServerGameEnts::SetDebugEdictBase(edict_t *base) { g_pDebugEdictBase = base; } //----------------------------------------------------------------------------- // Purpose: Marks entities as touching // Input : *e1 - // *e2 - //----------------------------------------------------------------------------- void CServerGameEnts::MarkEntitiesAsTouching( edict_t *e1, edict_t *e2 ) { CBaseEntity *entity = GetContainingEntity( e1 ); CBaseEntity *entityTouched = GetContainingEntity( e2 ); if ( entity && entityTouched ) { // HACKHACK: UNDONE: Pass in the trace here??!?!? trace_t tr; UTIL_ClearTrace( tr ); tr.endpos = (entity->GetAbsOrigin() + entityTouched->GetAbsOrigin()) * 0.5; entity->PhysicsMarkEntitiesAsTouching( entityTouched, tr ); } } void CServerGameEnts::FreeContainingEntity( edict_t *e ) { ::FreeContainingEntity(e); } edict_t* CServerGameEnts::BaseEntityToEdict( CBaseEntity *pEnt ) { if ( pEnt ) return pEnt->edict(); else return NULL; } CBaseEntity* CServerGameEnts::EdictToBaseEntity( edict_t *pEdict ) { if ( pEdict ) return CBaseEntity::Instance( pEdict ); else return NULL; } /* Yuck.. ideally this would be in CServerNetworkProperty's header, but it requires CBaseEntity and // inlining it gives a nice speedup. inline void CServerNetworkProperty::CheckTransmit( CCheckTransmitInfo *pInfo ) { // If we have a transmit proxy, let it hook our ShouldTransmit return value. if ( m_pTransmitProxy ) { nShouldTransmit = m_pTransmitProxy->ShouldTransmit( pInfo, nShouldTransmit ); } if ( m_pOuter->ShouldTransmit( pInfo ) ) { m_pOuter->SetTransmit( pInfo ); } } */ void CServerGameEnts::CheckTransmit( CCheckTransmitInfo *pInfo, const unsigned short *pEdictIndices, int nEdicts ) { // NOTE: for speed's sake, this assumes that all networkables are CBaseEntities and that the edict list // is consecutive in memory. If either of these things change, then this routine needs to change, but // ideally we won't be calling any virtual from this routine. This speedy routine was added as an // optimization which would be nice to keep. edict_t *pBaseEdict = engine->PEntityOfEntIndex( 0 ); // get recipient player's skybox: CBaseEntity *pRecipientEntity = CBaseEntity::Instance( pInfo->m_pClientEnt ); Assert( pRecipientEntity && pRecipientEntity->IsPlayer() ); if ( !pRecipientEntity ) return; MDLCACHE_CRITICAL_SECTION(); CBasePlayer *pRecipientPlayer = static_cast<CBasePlayer*>( pRecipientEntity ); const int skyBoxArea = pRecipientPlayer->m_Local.m_skybox3d.area; #ifndef _X360 const bool bIsHLTV = pRecipientPlayer->IsHLTV(); // m_pTransmitAlways must be set if HLTV client Assert( bIsHLTV == ( pInfo->m_pTransmitAlways != NULL) ); #endif for ( int i=0; i < nEdicts; i++ ) { int iEdict = pEdictIndices[i]; edict_t *pEdict = &pBaseEdict[iEdict]; Assert( pEdict == engine->PEntityOfEntIndex( iEdict ) ); int nFlags = pEdict->m_fStateFlags & (FL_EDICT_DONTSEND|FL_EDICT_ALWAYS|FL_EDICT_PVSCHECK|FL_EDICT_FULLCHECK); // entity needs no transmit if ( nFlags & FL_EDICT_DONTSEND ) continue; // entity is already marked for sending if ( pInfo->m_pTransmitEdict->Get( iEdict ) ) continue; if ( nFlags & FL_EDICT_ALWAYS ) { // FIXME: Hey! Shouldn't this be using SetTransmit so as // to also force network down dependent entities? while ( true ) { // mark entity for sending pInfo->m_pTransmitEdict->Set( iEdict ); #ifndef _X360 if ( bIsHLTV ) { pInfo->m_pTransmitAlways->Set( iEdict ); } #endif CServerNetworkProperty *pEnt = static_cast<CServerNetworkProperty*>( pEdict->GetNetworkable() ); if ( !pEnt ) break; CServerNetworkProperty *pParent = pEnt->GetNetworkParent(); if ( !pParent ) break; pEdict = pParent->edict(); iEdict = pParent->entindex(); } continue; } // FIXME: Would like to remove all dependencies CBaseEntity *pEnt = ( CBaseEntity * )pEdict->GetUnknown(); Assert( dynamic_cast< CBaseEntity* >( pEdict->GetUnknown() ) == pEnt ); if ( nFlags == FL_EDICT_FULLCHECK ) { // do a full ShouldTransmit() check, may return FL_EDICT_CHECKPVS nFlags = pEnt->ShouldTransmit( pInfo ); Assert( !(nFlags & FL_EDICT_FULLCHECK) ); if ( nFlags & FL_EDICT_ALWAYS ) { pEnt->SetTransmit( pInfo, true ); continue; } } // don't send this entity if ( !( nFlags & FL_EDICT_PVSCHECK ) ) continue; CServerNetworkProperty *netProp = static_cast<CServerNetworkProperty*>( pEdict->GetNetworkable() ); #ifndef _X360 if ( bIsHLTV ) { // for the HLTV we don't cull against PVS if ( netProp->AreaNum() == skyBoxArea ) { pEnt->SetTransmit( pInfo, true ); } else { pEnt->SetTransmit( pInfo, false ); } continue; } #endif // Always send entities in the player's 3d skybox. // Sidenote: call of AreaNum() ensures that PVS data is up to date for this entity bool bSameAreaAsSky = netProp->AreaNum() == skyBoxArea; if ( bSameAreaAsSky ) { pEnt->SetTransmit( pInfo, true ); continue; } bool bInPVS = netProp->IsInPVS( pInfo ); if ( bInPVS || sv_force_transmit_ents.GetBool() ) { // only send if entity is in PVS pEnt->SetTransmit( pInfo, false ); continue; } // If the entity is marked "check PVS" but it's in hierarchy, walk up the hierarchy looking for the // for any parent which is also in the PVS. If none are found, then we don't need to worry about sending ourself CBaseEntity *orig = pEnt; CServerNetworkProperty *check = netProp->GetNetworkParent(); // BUG BUG: I think it might be better to build up a list of edict indices which "depend" on other answers and then // resolve them in a second pass. Not sure what happens if an entity has two parents who both request PVS check? while ( check ) { int checkIndex = check->entindex(); // Parent already being sent if ( pInfo->m_pTransmitEdict->Get( checkIndex ) ) { orig->SetTransmit( pInfo, true ); break; } edict_t *checkEdict = check->edict(); int checkFlags = checkEdict->m_fStateFlags & (FL_EDICT_DONTSEND|FL_EDICT_ALWAYS|FL_EDICT_PVSCHECK|FL_EDICT_FULLCHECK); if ( checkFlags & FL_EDICT_DONTSEND ) break; if ( checkFlags & FL_EDICT_ALWAYS ) { orig->SetTransmit( pInfo, true ); break; } if ( checkFlags == FL_EDICT_FULLCHECK ) { // do a full ShouldTransmit() check, may return FL_EDICT_CHECKPVS CBaseEntity *pCheckEntity = check->GetBaseEntity(); nFlags = pCheckEntity->ShouldTransmit( pInfo ); Assert( !(nFlags & FL_EDICT_FULLCHECK) ); if ( nFlags & FL_EDICT_ALWAYS ) { pCheckEntity->SetTransmit( pInfo, true ); orig->SetTransmit( pInfo, true ); } break; } if ( checkFlags & FL_EDICT_PVSCHECK ) { // Check pvs check->RecomputePVSInformation(); bool bMoveParentInPVS = check->IsInPVS( pInfo ); if ( bMoveParentInPVS ) { orig->SetTransmit( pInfo, true ); break; } } // Continue up chain just in case the parent itself has a parent that's in the PVS... check = check->GetNetworkParent(); } } // Msg("A:%i, N:%i, F: %i, P: %i\n", always, dontSend, fullCheck, PVS ); } CServerGameClients g_ServerGameClients; EXPOSE_SINGLE_INTERFACE_GLOBALVAR(CServerGameClients, IServerGameClients, INTERFACEVERSION_SERVERGAMECLIENTS, g_ServerGameClients ); //----------------------------------------------------------------------------- // Purpose: called when a player tries to connect to the server // Input : *pEdict - the new player // char *pszName - the players name // char *pszAddress - the IP address of the player // reject - output - fill in with the reason why // maxrejectlen -- sizeof output buffer // the player was not allowed to connect. // Output : Returns TRUE if player is allowed to join, FALSE if connection is denied. //----------------------------------------------------------------------------- bool CServerGameClients::ClientConnect( edict_t *pEdict, const char *pszName, const char *pszAddress, char *reject, int maxrejectlen ) { return g_pGameRules->ClientConnected( pEdict, pszName, pszAddress, reject, maxrejectlen ); } //----------------------------------------------------------------------------- // Purpose: Called when a player is fully active (i.e. ready to receive messages) // Input : *pEntity - the player //----------------------------------------------------------------------------- void CServerGameClients::ClientActive( edict_t *pEdict, bool bLoadGame ) { MDLCACHE_CRITICAL_SECTION(); ::ClientActive( pEdict, bLoadGame ); // If we just loaded from a save file, call OnRestore on valid entities EndRestoreEntities(); if ( gpGlobals->eLoadType != MapLoad_LoadGame ) { // notify all entities that the player is now in the game for ( CBaseEntity *pEntity = gEntList.FirstEnt(); pEntity != NULL; pEntity = gEntList.NextEnt(pEntity) ) { pEntity->PostClientActive(); } } // Tell the sound controller to check looping sounds CBasePlayer *pPlayer = ( CBasePlayer * )CBaseEntity::Instance( pEdict ); CSoundEnvelopeController::GetController().CheckLoopingSoundsForPlayer( pPlayer ); SceneManager_ClientActive( pPlayer ); } //----------------------------------------------------------------------------- // Purpose: called when a player disconnects from a server // Input : *pEdict - the player //----------------------------------------------------------------------------- void CServerGameClients::ClientDisconnect( edict_t *pEdict ) { extern bool g_fGameOver; CBasePlayer *player = ( CBasePlayer * )CBaseEntity::Instance( pEdict ); if ( player ) { if ( !g_fGameOver ) { player->SetMaxSpeed( 0.0f ); CSound *pSound; pSound = CSoundEnt::SoundPointerForIndex( CSoundEnt::ClientSoundIndex( pEdict ) ); { // since this client isn't around to think anymore, reset their sound. if ( pSound ) { pSound->Reset(); } } // since the edict doesn't get deleted, fix it so it doesn't interfere. player->RemoveFlag( FL_AIMTARGET ); // don't attract autoaim player->AddFlag( FL_DONTTOUCH ); // stop it touching anything player->AddFlag( FL_NOTARGET ); // stop NPCs noticing it player->AddSolidFlags( FSOLID_NOT_SOLID ); // nonsolid if ( g_pGameRules ) { g_pGameRules->ClientDisconnected( pEdict ); gamestats->Event_PlayerDisconnected( player ); } } // Make sure all Untouch()'s are called for this client leaving CBaseEntity::PhysicsRemoveTouchedList( player ); CBaseEntity::PhysicsRemoveGroundList( player ); #if !defined( NO_ENTITY_PREDICTION ) // Make sure anything we "own" is simulated by the server from now on player->ClearPlayerSimulationList(); #endif } } void CServerGameClients::ClientPutInServer( edict_t *pEntity, const char *playername ) { if ( g_pClientPutInServerOverride ) g_pClientPutInServerOverride( pEntity, playername ); else ::ClientPutInServer( pEntity, playername ); } void CServerGameClients::ClientCommand( edict_t *pEntity, const CCommand &args ) { CBasePlayer *pPlayer = ToBasePlayer( GetContainingEntity( pEntity ) ); ::ClientCommand( pPlayer, args ); } //----------------------------------------------------------------------------- // Purpose: called after the player changes userinfo - gives dll a chance to modify // it before it gets sent into the rest of the engine-> // Input : *pEdict - the player // *infobuffer - their infobuffer //----------------------------------------------------------------------------- void CServerGameClients::ClientSettingsChanged( edict_t *pEdict ) { // Is the client spawned yet? if ( !pEdict->GetUnknown() ) return; CBasePlayer *player = ( CBasePlayer * )CBaseEntity::Instance( pEdict ); if ( !player ) return; #define QUICKGETCVARVALUE(v) (engine->GetClientConVarValue( player->entindex(), v )) // get network setting for prediction & lag compensation // Unfortunately, we have to duplicate the code in cdll_bounded_cvars.cpp here because the client // doesn't send the virtualized value up (because it has no way to know when the virtualized value // changes). Possible todo: put the responsibility on the bounded cvar to notify the engine when // its virtualized value has changed. player->m_nUpdateRate = Q_atoi( QUICKGETCVARVALUE("cl_updaterate") ); static const ConVar *pMinUpdateRate = g_pCVar->FindVar( "sv_minupdaterate" ); static const ConVar *pMaxUpdateRate = g_pCVar->FindVar( "sv_maxupdaterate" ); if ( pMinUpdateRate && pMaxUpdateRate ) player->m_nUpdateRate = (int)clamp( player->m_nUpdateRate, pMinUpdateRate->GetFloat(), pMaxUpdateRate->GetFloat() ); bool useInterpolation = Q_atoi( QUICKGETCVARVALUE("cl_interpolate") ) != 0; if ( useInterpolation ) { float flLerpRatio = Q_atof( QUICKGETCVARVALUE("cl_interp_ratio") ); if ( flLerpRatio == 0 ) flLerpRatio = 1.0f; float flLerpAmount = Q_atof( QUICKGETCVARVALUE("cl_interp") ); static const ConVar *pMin = g_pCVar->FindVar( "sv_client_min_interp_ratio" ); static const ConVar *pMax = g_pCVar->FindVar( "sv_client_max_interp_ratio" ); if ( pMin && pMax && pMin->GetFloat() != -1 ) { flLerpRatio = clamp( flLerpRatio, pMin->GetFloat(), pMax->GetFloat() ); } else { if ( flLerpRatio == 0 ) flLerpRatio = 1.0f; } // #define FIXME_INTERP_RATIO player->m_fLerpTime = max( flLerpAmount, flLerpRatio / player->m_nUpdateRate ); } else { player->m_fLerpTime = 0.0f; } #if !defined( NO_ENTITY_PREDICTION ) bool usePrediction = Q_atoi( QUICKGETCVARVALUE("cl_predict")) != 0; if ( usePrediction ) { player->m_bPredictWeapons = Q_atoi( QUICKGETCVARVALUE("cl_predictweapons")) != 0; player->m_bLagCompensation = Q_atoi( QUICKGETCVARVALUE("cl_lagcompensation")) != 0; } else #endif { player->m_bPredictWeapons = false; player->m_bLagCompensation = false; } #undef QUICKGETCVARVALUE g_pGameRules->ClientSettingsChanged( player ); } #ifdef PORTAL //----------------------------------------------------------------------------- // Purpose: Runs CFuncAreaPortalBase::UpdateVisibility on each portal // Input : pAreaPortal - The Area portal to test for visibility from portals // Output : int - 1 if any portal needs this area portal open, 0 otherwise. //----------------------------------------------------------------------------- int TestAreaPortalVisibilityThroughPortals ( CFuncAreaPortalBase* pAreaPortal, edict_t *pViewEntity, unsigned char *pvs, int pvssize ) { int iPortalCount = CProp_Portal_Shared::AllPortals.Count(); if( iPortalCount == 0 ) return 0; CProp_Portal **pPortals = CProp_Portal_Shared::AllPortals.Base(); for ( int i = 0; i != iPortalCount; ++i ) { CProp_Portal* pLocalPortal = pPortals[ i ]; if ( pLocalPortal && pLocalPortal->m_bActivated ) { CProp_Portal* pRemotePortal = pLocalPortal->m_hLinkedPortal.Get(); // Make sure this portal's linked portal is in the PVS before we add what it can see if ( pRemotePortal && pRemotePortal->m_bActivated && pRemotePortal->NetworkProp() && pRemotePortal->NetworkProp()->IsInPVS( pViewEntity, pvs, pvssize ) ) { bool bIsOpenOnClient = true; float fovDistanceAdjustFactor = 1.0f; Vector portalOrg = pLocalPortal->GetAbsOrigin(); int iPortalNeedsThisPortalOpen = pAreaPortal->UpdateVisibility( portalOrg, fovDistanceAdjustFactor, bIsOpenOnClient ); // Stop checking on success, this portal needs to be open if ( iPortalNeedsThisPortalOpen ) { return iPortalNeedsThisPortalOpen; } } } } return 0; } #endif //----------------------------------------------------------------------------- // Purpose: A client can have a separate "view entity" indicating that his/her view should depend on the origin of that // view entity. If that's the case, then pViewEntity will be non-NULL and will be used. Otherwise, the current // entity's origin is used. Either is offset by the m_vecViewOffset to get the eye position. // From the eye position, we set up the PAS and PVS to use for filtering network messages to the client. At this point, we could // override the actual PAS or PVS values, or use a different origin. // NOTE: Do not cache the values of pas and pvs, as they depend on reusable memory in the engine, they are only good for this one frame // Input : *pViewEntity - // *pClient - // **pvs - // **pas - //----------------------------------------------------------------------------- void CServerGameClients::ClientSetupVisibility( edict_t *pViewEntity, edict_t *pClient, unsigned char *pvs, int pvssize ) { Vector org; // Reset the PVS!!! engine->ResetPVS( pvs, pvssize ); g_pToolFrameworkServer->PreSetupVisibility(); // Find the client's PVS CBaseEntity *pVE = NULL; if ( pViewEntity ) { pVE = GetContainingEntity( pViewEntity ); // If we have a viewentity, it overrides the player's origin if ( pVE ) { org = pVE->EyePosition(); engine->AddOriginToPVS( org ); } } float fovDistanceAdjustFactor = 1; CBasePlayer *pPlayer = ( CBasePlayer * )GetContainingEntity( pClient ); if ( pPlayer ) { org = pPlayer->EyePosition(); pPlayer->SetupVisibility( pVE, pvs, pvssize ); UTIL_SetClientVisibilityPVS( pClient, pvs, pvssize ); fovDistanceAdjustFactor = pPlayer->GetFOVDistanceAdjustFactorForNetworking(); } unsigned char portalBits[MAX_AREA_PORTAL_STATE_BYTES]; memset( portalBits, 0, sizeof( portalBits ) ); int portalNums[512]; int isOpen[512]; int iOutPortal = 0; for( unsigned short i = g_AreaPortals.Head(); i != g_AreaPortals.InvalidIndex(); i = g_AreaPortals.Next(i) ) { CFuncAreaPortalBase *pCur = g_AreaPortals[i]; bool bIsOpenOnClient = true; // Update our array of which portals are open and flush it if necessary. portalNums[iOutPortal] = pCur->m_portalNumber; isOpen[iOutPortal] = pCur->UpdateVisibility( org, fovDistanceAdjustFactor, bIsOpenOnClient ); #ifdef PORTAL // If the client doesn't need this open, test if portals might need this area portal open if ( isOpen[iOutPortal] == 0 ) { isOpen[iOutPortal] = TestAreaPortalVisibilityThroughPortals( pCur, pViewEntity, pvs, pvssize ); } #endif ++iOutPortal; if ( iOutPortal >= ARRAYSIZE( portalNums ) ) { engine->SetAreaPortalStates( portalNums, isOpen, iOutPortal ); iOutPortal = 0; } // Version 0 portals (ie: shipping Half-Life 2 era) are always treated as open // for purposes of the m_chAreaPortalBits array on the client. if ( pCur->m_iPortalVersion == 0 ) bIsOpenOnClient = true; if ( bIsOpenOnClient ) { if ( pCur->m_portalNumber < 0 ) continue; else if ( pCur->m_portalNumber >= sizeof( portalBits ) * 8 ) Error( "ClientSetupVisibility: portal number (%d) too large", pCur->m_portalNumber ); else portalBits[pCur->m_portalNumber >> 3] |= (1 << (pCur->m_portalNumber & 7)); } } // Flush the remaining areaportal states. engine->SetAreaPortalStates( portalNums, isOpen, iOutPortal ); // Update the area bits that get sent to the client. pPlayer->m_Local.UpdateAreaBits( pPlayer, portalBits ); #ifdef PORTAL // *After* the player's view has updated its area bits, add on any other areas seen by portals CPortal_Player* pPortalPlayer = dynamic_cast<CPortal_Player*>( pPlayer ); if ( pPortalPlayer ) { pPortalPlayer->UpdatePortalViewAreaBits( pvs, pvssize ); } #endif //PORTAL } //----------------------------------------------------------------------------- // Purpose: // Input : *player - // *buf - // numcmds - // totalcmds - // dropped_packets - // ignore - // paused - // Output : float //----------------------------------------------------------------------------- #define CMD_MAXBACKUP 64 float CServerGameClients::ProcessUsercmds( edict_t *player, bf_read *buf, int numcmds, int totalcmds, int dropped_packets, bool ignore, bool paused ) { int i; CUserCmd *from, *to; // We track last three command in case we drop some // packets but get them back. CUserCmd cmds[ CMD_MAXBACKUP ]; CUserCmd cmdNull; // For delta compression Assert( numcmds >= 0 ); Assert( ( totalcmds - numcmds ) >= 0 ); CBasePlayer *pPlayer = NULL; CBaseEntity *pEnt = CBaseEntity::Instance(player); if ( pEnt && pEnt->IsPlayer() ) { pPlayer = static_cast< CBasePlayer * >( pEnt ); } // Too many commands? if ( totalcmds < 0 || totalcmds >= ( CMD_MAXBACKUP - 1 ) ) { const char *name = "unknown"; if ( pPlayer ) { name = pPlayer->GetPlayerName(); } Msg("CBasePlayer::ProcessUsercmds: too many cmds %i sent for player %s\n", totalcmds, name ); // FIXME: Need a way to drop the client from here //SV_DropClient ( host_client, false, "CMD_MAXBACKUP hit" ); buf->SetOverflowFlag(); return 0.0f; } // Initialize for reading delta compressed usercmds cmdNull.Reset(); from = &cmdNull; for ( i = totalcmds - 1; i >= 0; i-- ) { to = &cmds[ i ]; ReadUsercmd( buf, to, from ); from = to; } // Client not fully connected or server has gone inactive or is paused, just ignore if ( ignore || !pPlayer ) { return 0.0f; } MDLCACHE_CRITICAL_SECTION(); pPlayer->ProcessUsercmds( cmds, numcmds, totalcmds, dropped_packets, paused ); return TICK_INTERVAL; } void CServerGameClients::PostClientMessagesSent( void ) { VPROF("CServerGameClients::PostClient"); gEntList.PostClientMessagesSent(); } // Sets the client index for the client who typed the command into his/her console void CServerGameClients::SetCommandClient( int index ) { g_nCommandClientIndex = index; } int CServerGameClients::GetReplayDelay( edict_t *pEdict, int &entity ) { CBasePlayer *pPlayer = ( CBasePlayer * )CBaseEntity::Instance( pEdict ); if ( !pPlayer ) return 0; entity = pPlayer->GetReplayEntity(); return pPlayer->GetDelayTicks(); } //----------------------------------------------------------------------------- // The client's userinfo data lump has changed //----------------------------------------------------------------------------- void CServerGameClients::ClientEarPosition( edict_t *pEdict, Vector *pEarOrigin ) { CBasePlayer *pPlayer = ( CBasePlayer * )CBaseEntity::Instance( pEdict ); if (pPlayer) { *pEarOrigin = pPlayer->EarPosition(); } else { // Shouldn't happen Assert(0); *pEarOrigin = vec3_origin; } } //----------------------------------------------------------------------------- // Purpose: // Input : *player - // Output : CPlayerState //----------------------------------------------------------------------------- CPlayerState *CServerGameClients::GetPlayerState( edict_t *player ) { // Is the client spawned yet? if ( !player || !player->GetUnknown() ) return NULL; CBasePlayer *pBasePlayer = ( CBasePlayer * )CBaseEntity::Instance( player ); if ( !pBasePlayer ) return NULL; return &pBasePlayer->pl; } //----------------------------------------------------------------------------- // Purpose: Anything this game .dll wants to add to the bug reporter text (e.g., the entity/model under the picker crosshair) // can be added here // Input : *buf - // buflen - //----------------------------------------------------------------------------- void CServerGameClients::GetBugReportInfo( char *buf, int buflen ) { recentNPCSpeech_t speech[ SPEECH_LIST_MAX_SOUNDS ]; int num; int i; buf[ 0 ] = 0; if ( gpGlobals->maxClients == 1 ) { CBaseEntity *ent = FindPickerEntity( UTIL_PlayerByIndex(1) ); if ( ent ) { Q_snprintf( buf, buflen, "Picker %i/%s - ent %s model %s\n", ent->entindex(), ent->GetClassname(), STRING( ent->GetEntityName() ), ent->GetModelName() ); } // get any sounds that were spoken by NPCs recently num = GetRecentNPCSpeech( speech ); if ( num > 0 ) { Q_snprintf( buf, buflen, "%sRecent NPC speech:\n", buf ); for( i = 0; i < num; i++ ) { Q_snprintf( buf, buflen, "%s time: %6.3f sound name: %s scene: %s\n", buf, speech[ i ].time, speech[ i ].name, speech[ i ].sceneName ); } Q_snprintf( buf, buflen, "%sCurrent time: %6.3f\n", buf, gpGlobals->curtime ); } } } //----------------------------------------------------------------------------- // Purpose: A user has had their network id setup and validated //----------------------------------------------------------------------------- void CServerGameClients::NetworkIDValidated( const char *pszUserName, const char *pszNetworkID ) { } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- static bf_write *g_pMsgBuffer = NULL; void EntityMessageBegin( CBaseEntity * entity, bool reliable /*= false*/ ) { Assert( !g_pMsgBuffer ); Assert ( entity ); g_pMsgBuffer = engine->EntityMessageBegin( entity->entindex(), entity->GetServerClass(), reliable ); } void UserMessageBegin( IRecipientFilter& filter, const char *messagename ) { Assert( !g_pMsgBuffer ); Assert( messagename ); int msg_type = usermessages->LookupUserMessage( messagename ); if ( msg_type == -1 ) { Error( "UserMessageBegin: Unregistered message '%s'\n", messagename ); } g_pMsgBuffer = engine->UserMessageBegin( &filter, msg_type ); } void MessageEnd( void ) { Assert( g_pMsgBuffer ); engine->MessageEnd(); g_pMsgBuffer = NULL; } void MessageWriteByte( int iValue) { if (!g_pMsgBuffer) Error( "WRITE_BYTE called with no active message\n" ); g_pMsgBuffer->WriteByte( iValue ); } void MessageWriteChar( int iValue) { if (!g_pMsgBuffer) Error( "WRITE_CHAR called with no active message\n" ); g_pMsgBuffer->WriteChar( iValue ); } void MessageWriteShort( int iValue) { if (!g_pMsgBuffer) Error( "WRITE_SHORT called with no active message\n" ); g_pMsgBuffer->WriteShort( iValue ); } void MessageWriteWord( int iValue ) { if (!g_pMsgBuffer) Error( "WRITE_WORD called with no active message\n" ); g_pMsgBuffer->WriteWord( iValue ); } void MessageWriteLong( int iValue) { if (!g_pMsgBuffer) Error( "WriteLong called with no active message\n" ); g_pMsgBuffer->WriteLong( iValue ); } void MessageWriteFloat( float flValue) { if (!g_pMsgBuffer) Error( "WriteFloat called with no active message\n" ); g_pMsgBuffer->WriteFloat( flValue ); } void MessageWriteAngle( float flValue) { if (!g_pMsgBuffer) Error( "WriteAngle called with no active message\n" ); g_pMsgBuffer->WriteBitAngle( flValue, 8 ); } void MessageWriteCoord( float flValue) { if (!g_pMsgBuffer) Error( "WriteCoord called with no active message\n" ); g_pMsgBuffer->WriteBitCoord( flValue ); } void MessageWriteVec3Coord( const Vector& rgflValue) { if (!g_pMsgBuffer) Error( "WriteVec3Coord called with no active message\n" ); g_pMsgBuffer->WriteBitVec3Coord( rgflValue ); } void MessageWriteVec3Normal( const Vector& rgflValue) { if (!g_pMsgBuffer) Error( "WriteVec3Normal called with no active message\n" ); g_pMsgBuffer->WriteBitVec3Normal( rgflValue ); } void MessageWriteAngles( const QAngle& rgflValue) { if (!g_pMsgBuffer) Error( "WriteVec3Normal called with no active message\n" ); g_pMsgBuffer->WriteBitAngles( rgflValue ); } void MessageWriteString( const char *sz ) { if (!g_pMsgBuffer) Error( "WriteString called with no active message\n" ); g_pMsgBuffer->WriteString( sz ); } void MessageWriteEntity( int iValue) { if (!g_pMsgBuffer) Error( "WriteEntity called with no active message\n" ); g_pMsgBuffer->WriteShort( iValue ); } void MessageWriteEHandle( CBaseEntity *pEntity ) { if (!g_pMsgBuffer) Error( "WriteEHandle called with no active message\n" ); long iEncodedEHandle; if( pEntity ) { EHANDLE hEnt = pEntity; int iSerialNum = hEnt.GetSerialNumber() & (1 << NUM_NETWORKED_EHANDLE_SERIAL_NUMBER_BITS) - 1; iEncodedEHandle = hEnt.GetEntryIndex() | (iSerialNum << MAX_EDICT_BITS); } else { iEncodedEHandle = INVALID_NETWORKED_EHANDLE_VALUE; } g_pMsgBuffer->WriteLong( iEncodedEHandle ); } // bitwise void MessageWriteBool( bool bValue ) { if (!g_pMsgBuffer) Error( "WriteBool called with no active message\n" ); g_pMsgBuffer->WriteOneBit( bValue ? 1 : 0 ); } void MessageWriteUBitLong( unsigned int data, int numbits ) { if (!g_pMsgBuffer) Error( "WriteUBitLong called with no active message\n" ); g_pMsgBuffer->WriteUBitLong( data, numbits ); } void MessageWriteSBitLong( int data, int numbits ) { if (!g_pMsgBuffer) Error( "WriteSBitLong called with no active message\n" ); g_pMsgBuffer->WriteSBitLong( data, numbits ); } void MessageWriteBits( const void *pIn, int nBits ) { if (!g_pMsgBuffer) Error( "WriteBits called with no active message\n" ); g_pMsgBuffer->WriteBits( pIn, nBits ); } class CServerDLLSharedAppSystems : public IServerDLLSharedAppSystems { public: CServerDLLSharedAppSystems() { AddAppSystem( "soundemittersystem", SOUNDEMITTERSYSTEM_INTERFACE_VERSION ); AddAppSystem( "scenefilecache", SCENE_FILE_CACHE_INTERFACE_VERSION ); } virtual int Count() { return m_Systems.Count(); } virtual char const *GetDllName( int idx ) { return m_Systems[ idx ].m_pModuleName; } virtual char const *GetInterfaceName( int idx ) { return m_Systems[ idx ].m_pInterfaceName; } private: void AddAppSystem( char const *moduleName, char const *interfaceName ) { AppSystemInfo_t sys; sys.m_pModuleName = moduleName; sys.m_pInterfaceName = interfaceName; m_Systems.AddToTail( sys ); } CUtlVector< AppSystemInfo_t > m_Systems; }; EXPOSE_SINGLE_INTERFACE( CServerDLLSharedAppSystems, IServerDLLSharedAppSystems, SERVER_DLL_SHARED_APPSYSTEMS ); //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- void CServerGameTags::GetTaggedConVarList( KeyValues *pCvarTagList ) { if ( pCvarTagList && g_pGameRules ) { g_pGameRules->GetTaggedConVarList( pCvarTagList ); } }
[ "webmaster@infosmart.mx" ]
webmaster@infosmart.mx
e866e27a30029be9c0a49dbbbdcb33e5fa41d554
fb5ee81d79bc7b76eddde2302b6d60354be2020c
/src/gpu/gpu_utils_filter.h
cb75bfdb1340bc70be98c624a3720dba8b9fcd39
[ "MIT" ]
permissive
kygx-legend/vsgm
6a343c80ea8be7777299498c575edace55fbbeeb
be624ce904a5c69f0c818b454451febb365db87f
refs/heads/main
2023-04-13T15:25:53.921203
2022-07-27T03:04:07
2022-07-27T03:04:07
495,288,698
12
1
null
null
null
null
UTF-8
C++
false
false
562
h
#pragma once #include <cassert> #include <cub/cub.cuh> #include "common/meta.h" namespace GpuUtils { namespace Filter { template <typename uintV> DEVICE bool CheckVertexCondition(uintV first_vertex_id, uintV second_vertex_id, CondOperator op) { switch (op) { case LESS_THAN: return first_vertex_id < second_vertex_id; case LARGER_THAN: return first_vertex_id > second_vertex_id; case NON_EQUAL: return first_vertex_id != second_vertex_id; default: return true; } } } // namespace Filter } // namespace GpuUtils
[ "kygx.legend@gmail.com" ]
kygx.legend@gmail.com
5eb5ba7462b43afaecd99a2549369bcce205c3b9
9ba19c1a3e01fe3d82ce89de232d53c048f52409
/src/build-PolygenPainter-Desktop_Qt_5_5_0_MinGW_32bit-Debug/debug/moc_paintwidget.cpp
543b599ab6b426a0e2c1c4356682570ddbbc20d2
[]
no_license
yangyanzhe/GeometryManipulation
2ded5236c70e22fd7f9d2575f18634892acea865
3d1cb4e7c3f7049db26bc564d160c4a70241480b
refs/heads/master
2021-01-10T01:22:21.056241
2015-10-17T05:48:00
2015-10-17T05:48:00
43,731,212
0
0
null
null
null
null
UTF-8
C++
false
false
9,538
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'paintwidget.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.5.0) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../../PolygenPainter/paintwidget.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'paintwidget.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.5.0. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE struct qt_meta_stringdata_PaintWidget_t { QByteArrayData data[20]; char stringdata0[221]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_PaintWidget_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_PaintWidget_t qt_meta_stringdata_PaintWidget = { { QT_MOC_LITERAL(0, 0, 11), // "PaintWidget" QT_MOC_LITERAL(1, 12, 12), // "rightPressed" QT_MOC_LITERAL(2, 25, 0), // "" QT_MOC_LITERAL(3, 26, 1), // "x" QT_MOC_LITERAL(4, 28, 1), // "y" QT_MOC_LITERAL(5, 30, 11), // "leftPressed" QT_MOC_LITERAL(6, 42, 13), // "rightReleased" QT_MOC_LITERAL(7, 56, 12), // "leftReleased" QT_MOC_LITERAL(8, 69, 5), // "moved" QT_MOC_LITERAL(9, 75, 13), // "doubleClicked" QT_MOC_LITERAL(10, 89, 15), // "mousePressEvent" QT_MOC_LITERAL(11, 105, 12), // "QMouseEvent*" QT_MOC_LITERAL(12, 118, 1), // "e" QT_MOC_LITERAL(13, 120, 17), // "mouseReleaseEvent" QT_MOC_LITERAL(14, 138, 14), // "mouseMoveEvent" QT_MOC_LITERAL(15, 153, 21), // "mouseDoubleClickEvent" QT_MOC_LITERAL(16, 175, 13), // "focusOutEvent" QT_MOC_LITERAL(17, 189, 12), // "QFocusEvent*" QT_MOC_LITERAL(18, 202, 5), // "event" QT_MOC_LITERAL(19, 208, 12) // "focusInEvent" }, "PaintWidget\0rightPressed\0\0x\0y\0leftPressed\0" "rightReleased\0leftReleased\0moved\0" "doubleClicked\0mousePressEvent\0" "QMouseEvent*\0e\0mouseReleaseEvent\0" "mouseMoveEvent\0mouseDoubleClickEvent\0" "focusOutEvent\0QFocusEvent*\0event\0" "focusInEvent" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_PaintWidget[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 12, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 6, // signalCount // signals: name, argc, parameters, tag, flags 1, 2, 74, 2, 0x06 /* Public */, 5, 2, 79, 2, 0x06 /* Public */, 6, 2, 84, 2, 0x06 /* Public */, 7, 2, 89, 2, 0x06 /* Public */, 8, 2, 94, 2, 0x06 /* Public */, 9, 0, 99, 2, 0x06 /* Public */, // slots: name, argc, parameters, tag, flags 10, 1, 100, 2, 0x08 /* Private */, 13, 1, 103, 2, 0x08 /* Private */, 14, 1, 106, 2, 0x08 /* Private */, 15, 1, 109, 2, 0x08 /* Private */, 16, 1, 112, 2, 0x08 /* Private */, 19, 1, 115, 2, 0x08 /* Private */, // signals: parameters QMetaType::Void, QMetaType::Int, QMetaType::Int, 3, 4, QMetaType::Void, QMetaType::Int, QMetaType::Int, 3, 4, QMetaType::Void, QMetaType::Int, QMetaType::Int, 3, 4, QMetaType::Void, QMetaType::Int, QMetaType::Int, 3, 4, QMetaType::Void, QMetaType::Int, QMetaType::Int, 3, 4, QMetaType::Void, // slots: parameters QMetaType::Void, 0x80000000 | 11, 12, QMetaType::Void, 0x80000000 | 11, 12, QMetaType::Void, 0x80000000 | 11, 12, QMetaType::Void, 0x80000000 | 11, 12, QMetaType::Void, 0x80000000 | 17, 18, QMetaType::Void, 0x80000000 | 17, 18, 0 // eod }; void PaintWidget::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { PaintWidget *_t = static_cast<PaintWidget *>(_o); Q_UNUSED(_t) switch (_id) { case 0: _t->rightPressed((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2]))); break; case 1: _t->leftPressed((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2]))); break; case 2: _t->rightReleased((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2]))); break; case 3: _t->leftReleased((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2]))); break; case 4: _t->moved((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2]))); break; case 5: _t->doubleClicked(); break; case 6: _t->mousePressEvent((*reinterpret_cast< QMouseEvent*(*)>(_a[1]))); break; case 7: _t->mouseReleaseEvent((*reinterpret_cast< QMouseEvent*(*)>(_a[1]))); break; case 8: _t->mouseMoveEvent((*reinterpret_cast< QMouseEvent*(*)>(_a[1]))); break; case 9: _t->mouseDoubleClickEvent((*reinterpret_cast< QMouseEvent*(*)>(_a[1]))); break; case 10: _t->focusOutEvent((*reinterpret_cast< QFocusEvent*(*)>(_a[1]))); break; case 11: _t->focusInEvent((*reinterpret_cast< QFocusEvent*(*)>(_a[1]))); break; default: ; } } else if (_c == QMetaObject::IndexOfMethod) { int *result = reinterpret_cast<int *>(_a[0]); void **func = reinterpret_cast<void **>(_a[1]); { typedef void (PaintWidget::*_t)(int , int ); if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&PaintWidget::rightPressed)) { *result = 0; } } { typedef void (PaintWidget::*_t)(int , int ); if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&PaintWidget::leftPressed)) { *result = 1; } } { typedef void (PaintWidget::*_t)(int , int ); if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&PaintWidget::rightReleased)) { *result = 2; } } { typedef void (PaintWidget::*_t)(int , int ); if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&PaintWidget::leftReleased)) { *result = 3; } } { typedef void (PaintWidget::*_t)(int , int ); if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&PaintWidget::moved)) { *result = 4; } } { typedef void (PaintWidget::*_t)(); if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&PaintWidget::doubleClicked)) { *result = 5; } } } } const QMetaObject PaintWidget::staticMetaObject = { { &QWidget::staticMetaObject, qt_meta_stringdata_PaintWidget.data, qt_meta_data_PaintWidget, qt_static_metacall, Q_NULLPTR, Q_NULLPTR} }; const QMetaObject *PaintWidget::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *PaintWidget::qt_metacast(const char *_clname) { if (!_clname) return Q_NULLPTR; if (!strcmp(_clname, qt_meta_stringdata_PaintWidget.stringdata0)) return static_cast<void*>(const_cast< PaintWidget*>(this)); return QWidget::qt_metacast(_clname); } int PaintWidget::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QWidget::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 12) qt_static_metacall(this, _c, _id, _a); _id -= 12; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 12) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 12; } return _id; } // SIGNAL 0 void PaintWidget::rightPressed(int _t1, int _t2) { void *_a[] = { Q_NULLPTR, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)) }; QMetaObject::activate(this, &staticMetaObject, 0, _a); } // SIGNAL 1 void PaintWidget::leftPressed(int _t1, int _t2) { void *_a[] = { Q_NULLPTR, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)) }; QMetaObject::activate(this, &staticMetaObject, 1, _a); } // SIGNAL 2 void PaintWidget::rightReleased(int _t1, int _t2) { void *_a[] = { Q_NULLPTR, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)) }; QMetaObject::activate(this, &staticMetaObject, 2, _a); } // SIGNAL 3 void PaintWidget::leftReleased(int _t1, int _t2) { void *_a[] = { Q_NULLPTR, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)) }; QMetaObject::activate(this, &staticMetaObject, 3, _a); } // SIGNAL 4 void PaintWidget::moved(int _t1, int _t2) { void *_a[] = { Q_NULLPTR, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)) }; QMetaObject::activate(this, &staticMetaObject, 4, _a); } // SIGNAL 5 void PaintWidget::doubleClicked() { QMetaObject::activate(this, &staticMetaObject, 5, Q_NULLPTR); } QT_END_MOC_NAMESPACE
[ "yangyanzhe@126.com" ]
yangyanzhe@126.com
65b11de9afaffae3aa497cf92a370ce84297e464
b0bf0bbf72c66ba31ebb0fbad4fc22a19c41563e
/src/Subsystems/LeanBack.h
e5b03f371e5518d8bcb56d4b62f9cb9d3e20fc8b
[ "MIT" ]
permissive
frc3197/Recycle-Rush
8874b29fb20aa95022c0f8e28ac091bb0146e4ab
f9953db5c7c6608928bab6916e9d4604d467bb76
refs/heads/master
2021-08-02T09:18:12.349167
2019-04-28T20:04:35
2019-04-28T20:04:35
183,952,835
0
1
null
null
null
null
UTF-8
C++
false
false
411
h
#ifndef LEAN_BACK_H #define LEAN_BACK_H #include "Commands/Subsystem.h" #include "WPILib.h" class LeanBack: public Subsystem { private: DigitalInput frontSwitch; DigitalInput backSwitch; Victor tiltMotor; Gyro gyro; public: LeanBack(); void InitDefaultCommand(); bool GetFrontSwitch(); bool GetBackSwitch(); void SetMotorSpeed(float victorSpeed); float getGyroAngle(); void resetGyro(); }; #endif
[ "23708360+spencrr@users.noreply.github.com" ]
23708360+spencrr@users.noreply.github.com
5a82443e2c65e61cdc6a53d56de7ccb1c85771e3
4f52a4da323feb3bfaa3c67d141999f46cfd3d9e
/BOJ_11656/BOJ_11656/BOJ_11656.cpp
fa5d50f0445c36345993beb0eb5807a680de949b
[]
no_license
LHI0915/StudyBackjoon
407b4c7c3fbbec60e6cc719714303570ddf34a1f
e649de567abea81e49ea8d95249ad735a2bc0a37
refs/heads/master
2021-07-22T22:12:26.399750
2021-07-13T17:35:53
2021-07-13T17:35:53
141,692,612
0
0
null
null
null
null
UTF-8
C++
false
false
328
cpp
#include <string> #include <iostream> #include <algorithm> #include <vector> using namespace std; int main(void){ vector<string> save; string s; cin >> s; for(int i=0;i<s.size();i++){ save.push_back(s.substr(i,s.size())); } sort(save.begin(),save.end()); for(int i=0;i<s.size();i++){ cout << save[i] << endl; } }
[ "gowns1998@gmail.com" ]
gowns1998@gmail.com
d116c0f051cfdc46c0f652df872e0306add1e8d2
e39c93f2ee23b82f3e62668c6f417bd6a65eeed3
/filesys/filehdr.cc
20926893cf2ddb22e60ecf03160db2aaf99c8cf1
[]
no_license
aminfallahi/Nachos-Filesystem
f710c132315ade04b6e01dd670b66e38ae3cb8c4
1e4a835d940b819a8f797d54bd373dac26981d72
refs/heads/master
2022-03-21T23:15:34.364778
2019-12-05T04:31:54
2019-12-05T04:31:54
221,956,286
0
0
null
null
null
null
UTF-8
C++
false
false
5,527
cc
// filehdr.cc // Routines for managing the disk file header (in UNIX, this // would be called the i-node). // // The file header is used to locate where on disk the // file's data is stored. We implement this as a fixed size // table of pointers -- each entry in the table points to the // disk sector containing that portion of the file data // (in other words, there are no indirect or doubly indirect // blocks). The table size is chosen so that the file header // will be just big enough to fit in one disk sector, // // Unlike in a real system, we do not keep track of file permissions, // ownership, last modification date, etc., in the file header. // // A file header can be initialized in two ways: // for a new file, by modifying the in-memory data structure // to point to the newly allocated data blocks // for a file already on disk, by reading the file header from disk // // Copyright (c) 1992-1993 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. #include "copyright.h" #include "filehdr.h" #include "debug.h" #include "synchdisk.h" #include "main.h" //---------------------------------------------------------------------- // FileHeader::Allocate // Initialize a fresh file header for a newly created file. // Allocate data blocks for the file out of the map of free disk blocks. // Return FALSE if there are not enough free blocks to accomodate // the new file. // // "freeMap" is the bit map of free disk sectors // "fileSize" is the bit map of free disk sectors //---------------------------------------------------------------------- bool FileHeader::Allocate(PersistentBitmap *freeMap, int fileSize) { numBytes = fileSize; numSectors = divRoundUp(fileSize, SectorSize); if (freeMap->NumClear() < numSectors) return FALSE; // not enough space for (int i = 0; i < numSectors; i++) { dataSectors[i] = freeMap->FindAndSet(); // since we checked that there was enough free space, // we expect this to succeed ASSERT(dataSectors[i] >= 0); } return TRUE; } //---------------------------------------------------------------------- // FileHeader::Deallocate // De-allocate all the space allocated for data blocks for this file. // // "freeMap" is the bit map of free disk sectors //---------------------------------------------------------------------- void FileHeader::Deallocate(PersistentBitmap *freeMap) { for (int i = 0; i < numSectors; i++) { ASSERT(freeMap->Test((int) dataSectors[i])); // ought to be marked! freeMap->Clear((int) dataSectors[i]); } } //---------------------------------------------------------------------- // FileHeader::FetchFrom // Fetch contents of file header from disk. // // "sector" is the disk sector containing the file header //---------------------------------------------------------------------- void FileHeader::FetchFrom(int sector) { kernel->synchDisk->ReadSector(sector, (char *) this); } //---------------------------------------------------------------------- // FileHeader::WriteBack // Write the modified contents of the file header back to disk. // // "sector" is the disk sector to contain the file header //---------------------------------------------------------------------- void FileHeader::WriteBack(int sector) { kernel->synchDisk->WriteSector(sector, (char *) this); } //---------------------------------------------------------------------- // FileHeader::ByteToSector // Return which disk sector is storing a particular byte within the file. // This is essentially a translation from a virtual address (the // offset in the file) to a physical address (the sector where the // data at the offset is stored). // // "offset" is the location within the file of the byte in question //---------------------------------------------------------------------- int FileHeader::ByteToSector(int offset) { return (dataSectors[offset / SectorSize]); } //---------------------------------------------------------------------- // FileHeader::FileLength // Return the number of bytes in the file. //---------------------------------------------------------------------- int FileHeader::FileLength() { return numBytes; } //---------------------------------------------------------------------- // FileHeader::Print // Print the contents of the file header, and the contents of all // the data blocks pointed to by the file header. //---------------------------------------------------------------------- void FileHeader::Print() { int i, j, k; char *data = new char[SectorSize]; printf("FileHeader contents. File size: %d. File blocks:\n", numBytes); for (i = 0; i < numSectors; i++) printf("%d ", dataSectors[i]); printf("\nFile contents:\n"); for (i = k = 0; i < numSectors; i++) { kernel->synchDisk->ReadSector(dataSectors[i], data); for (j = 0; (j < SectorSize) && (k < numBytes); j++, k++) { if ('\040' <= data[j] && data[j] <= '\176') // isprint(data[j]) printf("%c", data[j]); else printf("\\%x", (unsigned char) data[j]); } printf("\n"); } delete [] data; } void FileHeader::chmod(int protection) { r = protection / 100 == 0 ? false : true; w = protection / 10 % 10 == 0 ? false : true; x = protection % 10 == 0 ? false : true; }
[ "amin.fallahi@gmail.com" ]
amin.fallahi@gmail.com
51c5119d3673814b4dc904bb8dbbdcf567dd41e1
fbe1f9222c6172893be5ce59252d0389589238a1
/main.cpp
22df60110892db654b91cc6eba092d62f7eeb86e
[]
no_license
S1lash/DinnerPhilosophers
2a1c1f198ac76c20259b56b258e5636e1695de4c
0e678546a1870f05aaebda9472c0ac4db7720814
refs/heads/master
2021-01-24T19:12:38.435023
2016-05-17T19:22:20
2016-05-17T19:22:20
59,051,732
1
0
null
null
null
null
UTF-8
C++
false
false
405
cpp
#include <QCoreApplication> #include <forks.h> #include <phy.h> #include <oficient.h> #include <iostream> using namespace std; int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); int num = 5; Oficient oficient(num); oficient.OpenRestaurant(); PrintResult print(oficient.phy); oficient.ClosedRestaurant(); return a.exec(); }
[ "mg20118@gmail.com" ]
mg20118@gmail.com
cca9c006b521475f6cafd9ebedbad6fb7a24cdb9
697a3746c91d073a16fdaf5c9ec8c563db404278
/Search-Insert-Position.cpp
ac308610227ef2b174f9dc4bbd849ca2d8fedf0f
[]
no_license
chihyu14/LeetCode-1
662b10e231d95fda765f2ee169bbac1d4fd9e959
15492820e568448dc7dba9817bcba20ff328bd9b
refs/heads/master
2021-01-21T01:27:19.179578
2014-08-19T02:43:29
2014-08-19T02:43:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,036
cpp
class Solution { public: int searchInsert(int A[], int n, int target) { //lo: the low index of A[] //hi: the high index of A[] //mi: middle of lo and hi int lo, hi, mi; //init lo and hi lo = 0; hi = n-1; while(lo < hi) { //calculates mi mi = (lo + hi)>>1; //if A[mi] == target, return the answer if(A[mi] == target) return mi; //if A[mi] is less than target, then, updates lo if(A[mi] < target) lo = mi+1; //updates hi, hi may be less than 0!!!! else hi = mi-1; } //if all the elements in A[] is less than target //such as {{1}, 2} if(A[hi] < target) ++hi; //if hi is less than 0 //hi will be less than 0 if (lo=0 && hi=1 && A[mi]>=target) if(hi<0) hi = 0; return hi; } };
[ "qcx978132955@gmail.com" ]
qcx978132955@gmail.com
9c76d17835c04b2723d88f515e32f358b3b0d01f
ceb18dbff900d48d7df6b744d1cd167c7c9eb5c5
/thirdparty/uilib/DM/3rdParty/lua/wrapper/DMLua.cpp
caf3ab4787017ab9b9d062eba1592d5119c6bfe3
[]
no_license
15831944/sourcecode
6bb5f74aac5cf1f496eced1b31a0fd4cf3271740
412f0ba73dd7fb179a92d2d0635ddbf025bfe6d4
refs/heads/master
2021-12-27T20:07:32.598613
2018-01-15T14:38:35
2018-01-15T14:38:35
null
0
0
null
null
null
null
GB18030
C++
false
false
19,746
cpp
extern "C" { #include "lua.h" #include "lualib.h" #include "lauxlib.h" } #include "DMLua.h" namespace DMLUA { // 辅助函数 static int tostring_s64(lua_State *L) { char temp[64]; sprintf_s(temp, 64, "%I64d", *(long long*)lua_topointer(L, 1)); lua_pushstring(L, temp); return 1; } static int tostring_u64(lua_State *L) { char temp[64]; sprintf_s(temp, 64, "%I64u", *(unsigned long long*)lua_topointer(L, 1)); lua_pushstring(L, temp); return 1; } static int eq_s64(lua_State *L) { lua_pushboolean(L, memcmp(lua_topointer(L, 1), lua_topointer(L, 2), sizeof(long long)) == 0); return 1; } static int eq_u64(lua_State *L) { lua_pushboolean(L, memcmp(lua_topointer(L, 1), lua_topointer(L, 2), sizeof(unsigned long long)) == 0); return 1; } static int lt_s64(lua_State *L) { lua_pushboolean(L, memcmp(lua_topointer(L, 1), lua_topointer(L, 2), sizeof(long long)) < 0); return 1; } static int lt_u64(lua_State *L) { lua_pushboolean(L, memcmp(lua_topointer(L, 1), lua_topointer(L, 2), sizeof(unsigned long long)) < 0); return 1; } static int le_s64(lua_State *L) { lua_pushboolean(L, memcmp(lua_topointer(L, 1), lua_topointer(L, 2), sizeof(long long)) <= 0); return 1; } static int le_u64(lua_State *L) { lua_pushboolean(L, memcmp(lua_topointer(L, 1), lua_topointer(L, 2), sizeof(unsigned long long)) <= 0); return 1; } static void call_stack(lua_State* L, int n) { lua_Debug ar; if (lua_getstack(L, n, &ar) == 1) { lua_getinfo(L, "nSlu", &ar); const char* indent; if (n == 0) { indent = "->\t"; print_error(L, "\t<call stack>"); } else { indent = "\t"; } if (ar.name) { print_error(L, "%s%s() : line %d [%s : line %d]", indent, ar.name, ar.currentline, ar.source, ar.linedefined); } else { print_error(L, "%sunknown : line %d [%s : line %d]", indent, ar.currentline, ar.source, ar.linedefined); } call_stack(L, n+1); } } //------------------------------------------ void init(lua_State *L) { init_s64(L); init_u64(L); } void init_s64(lua_State *L) { const char* name = "__s64"; lua_newtable(L); lua_pushstring(L, "__name"); lua_pushstring(L, name); lua_rawset(L, -3); lua_pushstring(L, "__tostring"); lua_pushcclosure(L, tostring_s64, 0); lua_rawset(L, -3); lua_pushstring(L, "__eq"); lua_pushcclosure(L, eq_s64, 0); lua_rawset(L, -3); lua_pushstring(L, "__lt"); lua_pushcclosure(L, lt_s64, 0); lua_rawset(L, -3); lua_pushstring(L, "__le"); lua_pushcclosure(L, le_s64, 0); lua_rawset(L, -3); lua_setglobal(L, name); } void init_u64(lua_State *L) { const char* name = "__u64"; lua_newtable(L); lua_pushstring(L, "__name"); lua_pushstring(L, name); lua_rawset(L, -3); lua_pushstring(L, "__tostring"); lua_pushcclosure(L, tostring_u64, 0); lua_rawset(L, -3); // 比较只会两边元表都是相同的元素才会进入比较 lua_pushstring(L, "__eq"); lua_pushcclosure(L, eq_u64, 0); lua_rawset(L, -3); lua_pushstring(L, "__lt"); lua_pushcclosure(L, lt_u64, 0); lua_rawset(L, -3); lua_pushstring(L, "__le"); lua_pushcclosure(L, le_u64, 0); lua_rawset(L, -3); lua_setglobal(L, name); } lua_State* open() { lua_State *L = luaL_newstate(); return L; } void close(lua_State *L) { //销毁指定 Lua 状态机中的所有对象(如果有垃圾收集相关的元方法的话,会调用它们),并且释放状态机中使用的所有动态内存 lua_close(L); } void open_base(lua_State *L) { luaL_requiref(L, LUA_STRLIBNAME, luaopen_base, 1); } void open_string(lua_State *L) { luaL_requiref(L, LUA_STRLIBNAME, luaopen_string, 1); } void open_math(lua_State *L) { luaL_requiref(L, LUA_MATHLIBNAME, luaopen_math, 1); } void open_coroutine(lua_State *L) { luaL_requiref(L, LUA_COLIBNAME, luaopen_coroutine, 1); } void open_os(lua_State *L) { luaL_requiref(L, LUA_OSLIBNAME, luaopen_os, 1); } void dostring(lua_State *L, const char* buff) { dobuffer(L, buff, strlen(buff)); } void dofile(lua_State *L, const char *filename) { lua_pushcclosure(L, on_error, 0); int errfunc = lua_gettop(L); if (0 == luaL_loadfile(L, filename)) { if (0 != lua_pcall(L, 0, 0, errfunc)) { lua_pop(L, 1); } } else { print_error(L, "%s", lua_tostring(L, -1)); lua_pop(L, 1); } lua_pop(L, 1); } void dobuffer(lua_State *L, const char* buff, size_t len) { lua_pushcclosure(L, on_error, 0); int errfunc = lua_gettop(L); if (0 == luaL_loadbuffer(L, buff, len, "DMLUA::dobuffer()")) { if (0 != lua_pcall(L, 0, 0, errfunc)) { lua_pop(L, 1); } } else { print_error(L, "%s", lua_tostring(L, -1)); lua_pop(L, 1); } lua_pop(L, 1); } int on_error(lua_State *L) { print_error(L, "%s", lua_tostring(L, -1)); call_stack(L, 0); return 0; } void enum_stack(lua_State *L) { int top = lua_gettop(L); print_error(L, "Type:%d", top); for(int i=1; i<=lua_gettop(L); ++i) { switch(lua_type(L, i)) { case LUA_TNIL: print_error(L, "\t%s", lua_typename(L, lua_type(L, i))); break; case LUA_TBOOLEAN: print_error(L, "\t%s %s", lua_typename(L, lua_type(L, i)), lua_toboolean(L, i)?"true":"false"); break; case LUA_TLIGHTUSERDATA: print_error(L, "\t%s 0x%08p", lua_typename(L, lua_type(L, i)), lua_topointer(L, i)); break; case LUA_TNUMBER: print_error(L, "\t%s %f", lua_typename(L, lua_type(L, i)), lua_tonumber(L, i)); break; case LUA_TSTRING: print_error(L, "\t%s %s", lua_typename(L, lua_type(L, i)), lua_tostring(L, i)); break; case LUA_TTABLE: print_error(L, "\t%s 0x%08p", lua_typename(L, lua_type(L, i)), lua_topointer(L, i)); break; case LUA_TFUNCTION: print_error(L, "\t%s() 0x%08p", lua_typename(L, lua_type(L, i)), lua_topointer(L, i)); break; case LUA_TUSERDATA: print_error(L, "\t%s 0x%08p", lua_typename(L, lua_type(L, i)), lua_topointer(L, i)); break; case LUA_TTHREAD: print_error(L, "\t%s", lua_typename(L, lua_type(L, i))); break; } } } void print_error(lua_State *L, const char* fmt, ...) { char text[4096] = {0}; va_list args; va_start(args, fmt); vsprintf_s(text, 4096, fmt, args); va_end(args); lua_getglobal(L, "_ALERT"); if(lua_isfunction(L, -1)) { lua_pushstring(L, text); lua_call(L, 1, 0); } else { printf("%s\n", text); lua_pop(L, 1); } OutputDebugStringA("\n"); OutputDebugStringA(text); printf(text); } // read----------------------------------------------- template<> char* read(lua_State *L, int index) { return (char*)lua_tostring(L, index); } template<> const char* read(lua_State *L, int index) { return (const char*)lua_tostring(L, index); } template<> char read(lua_State *L, int index) { return (char)lua_tonumber(L, index); } template<> unsigned char read(lua_State *L, int index) { return (unsigned char)lua_tonumber(L, index); } template<> short read(lua_State *L, int index) { return (short)lua_tonumber(L, index); } template<> unsigned short read(lua_State *L, int index) { return (unsigned short)lua_tonumber(L, index); } // long is different between i386 and X86_64 architecture #if defined(__X86_64__) || defined(__X86_64) || defined(__amd_64) || defined(__amd_64__) template<> long read(lua_State *L, int index) { if(lua_isnumber(L,index)) return (long)lua_tonumber(L, index); else return *(long*)lua_touserdata(L, index); } template<> unsigned long read(lua_State *L, int index) { if(lua_isnumber(L,index)) return (unsigned long)lua_tonumber(L, index); else return *(unsigned long*)lua_touserdata(L, index); } #else //__i386__ //32bit template<> long read(lua_State *L, int index) { return (long)lua_tonumber(L, index); } template<> unsigned long read(lua_State *L, int index) { return (unsigned long)lua_tonumber(L, index); } #endif template<> int read(lua_State *L, int index) { return (int)lua_tonumber(L, index); } template<> unsigned int read(lua_State *L, int index) { return (unsigned int)lua_tonumber(L, index); } template<> float read(lua_State *L, int index) { return (float)lua_tonumber(L, index); } template<> double read(lua_State *L, int index) { return (double)lua_tonumber(L, index); } template<> bool read(lua_State *L, int index) { if(lua_isboolean(L, index)) return lua_toboolean(L, index) != 0; else return lua_tonumber(L, index) != 0; } template<> void read(lua_State *L, int index) { (void)L; (void)index; return; } template<> long long read(lua_State *L, int index) { if(lua_isnumber(L,index)) return (long long)lua_tonumber(L, index); else return *(long long*)lua_touserdata(L, index); } template<> unsigned long long read(lua_State *L, int index) { if(lua_isnumber(L,index)) return (unsigned long long)lua_tonumber(L, index); else return *(unsigned long long*)lua_touserdata(L, index); } template<> table read(lua_State *L, int index) { return table(L, index); } template<> HWND read(lua_State *L, int index) { if(lua_isnumber(L,index)) return (HWND)(UINT)lua_tonumber(L, index); else return *(HWND*)lua_touserdata(L, index); } template<> HDC read(lua_State *L, int index) { if(lua_isnumber(L,index)) return (HDC)(UINT)lua_tonumber(L, index); else return *(HDC*)lua_touserdata(L, index); } template<> HICON read(lua_State *L, int index) { if(lua_isnumber(L,index)) return (HICON)(UINT)lua_tonumber(L, index); else return *(HICON*)lua_touserdata(L, index); } template<> HBITMAP read(lua_State *L, int index) { if(lua_isnumber(L,index)) return (HBITMAP)(UINT)lua_tonumber(L, index); else return *(HBITMAP*)lua_touserdata(L, index); } template<> HINSTANCE read(lua_State *L, int index) { if(lua_isnumber(L,index)) return (HINSTANCE)(UINT)lua_tonumber(L, index); else return *(HINSTANCE*)lua_touserdata(L, index); } // push----------------------------------------------- template<> void push(lua_State *L, char ret) { lua_pushnumber(L, ret); } template<> void push(lua_State *L, unsigned char ret) { lua_pushnumber(L, ret); } template<> void push(lua_State *L, short ret) { lua_pushnumber(L, ret); } template<> void push(lua_State *L, unsigned short ret) { lua_pushnumber(L, ret); } #if defined(__X86_64__) || defined(__X86_64) || defined(__amd_64) || defined(__amd_64__) template<> void lua_tinker::push(lua_State *L, long ret) { *(long*)lua_newuserdata(L, sizeof(long)) = ret; lua_getglobal(L, "__s64"); lua_setmetatable(L, -2); } template<> void lua_tinker::push(lua_State *L, unsigned long ret) { *(unsigned long*)lua_newuserdata(L, sizeof(unsigned long)) = ret; lua_getglobal(L, "__u64"); lua_setmetatable(L, -2); } #else //__i386__ template<> void push(lua_State *L, long ret) { lua_pushnumber(L, ret); } template<> void push(lua_State *L, unsigned long ret) { lua_pushnumber(L, ret); } #endif template<> void push(lua_State *L, int ret) { lua_pushnumber(L, ret); } template<> void push(lua_State *L, unsigned int ret) { lua_pushnumber(L, ret); } template<> void push(lua_State *L, float ret) { lua_pushnumber(L, ret); } template<> void push(lua_State *L, double ret) { lua_pushnumber(L, ret); } template<> void push(lua_State *L, char* ret) { lua_pushstring(L, ret); } template<> void push(lua_State *L, const char* ret) { lua_pushstring(L, ret); } template<> void push(lua_State *L, bool ret) { lua_pushboolean(L, ret); } template<> void push(lua_State *L, lua_value* ret) { if(ret) ret->to_lua(L); else lua_pushnil(L); } template<> void push(lua_State *L, long long ret) { *(long long*)lua_newuserdata(L, sizeof(long long)) = ret; lua_getglobal(L, "__s64"); lua_setmetatable(L, -2); } template<> void push(lua_State *L, unsigned long long ret) { *(unsigned long long*)lua_newuserdata(L, sizeof(unsigned long long)) = ret; lua_getglobal(L, "__u64"); lua_setmetatable(L, -2); } template<> void push(lua_State *L, table ret) { lua_pushvalue(L, ret.m_obj->m_index); } template<> void push(lua_State *L, HWND ret) { *(HWND*)lua_newuserdata(L, sizeof(HWND)) = ret; lua_getglobal(L,"__hwnd"); lua_setmetatable(L, -2); } template<> void push(lua_State *L, HDC ret) { *(HDC*)lua_newuserdata(L, sizeof(HDC)) = ret; lua_getglobal(L,"__hdc"); lua_setmetatable(L, -2); } template<> void push(lua_State *L, HICON ret) { *(HICON*)lua_newuserdata(L, sizeof(HICON)) = ret; lua_getglobal(L,"__hicon"); lua_setmetatable(L, -2); } template<> void push(lua_State *L, HBITMAP ret) { *(HBITMAP*)lua_newuserdata(L, sizeof(HBITMAP)) = ret; lua_getglobal(L,"__hbmp"); lua_setmetatable(L, -2); } template<> void push(lua_State *L, HINSTANCE ret) { *(HINSTANCE*)lua_newuserdata(L, sizeof(HINSTANCE)) = ret; lua_getglobal(L,"__hinst"); lua_setmetatable(L, -2); } // pop----------------------------------------------- template<> void pop(lua_State *L) { lua_pop(L, 1); } template<> table pop(lua_State *L) { return table(L, lua_gettop(L)); } // Tinker Class Helper ---------------------------------- static void invoke_parent(lua_State *L) { lua_pushstring(L, "__parent"); lua_rawget(L, -2); if(lua_istable(L,-1)) { lua_pushvalue(L,2); lua_rawget(L, -2); if(!lua_isnil(L,-1)) { lua_remove(L,-2); } else { lua_remove(L, -1); invoke_parent(L); lua_remove(L,-2); } } } // -------------------------------------------------------- int meta_get(lua_State *L) { // 传入表 和 索引参数 // stack: 1.类(userdata) 2.变量(string) lua_getmetatable(L,1); // stack: 1.类(userdata) 2.变量(string) 3.meta(table) lua_pushvalue(L,2); // stack: 1.类(userdata) 2.变量(string) 3.meta(table) 4.变量(string) lua_rawget(L,-2); // stack: 1.类(userdata) 2.变量(string) 3.meta(table) 4.meta[变量]value值(userdata) // 如果存在userdata 存在该变量 if(lua_isuserdata(L,-1)) { user2type<var_base*>::invoke(L,-1)->get(L); // stack: 1.类(userdata) 2.变量(string) 3.meta(table) 4.meta[变量]value值(userdata) 5.实际值 lua_remove(L, -2); // stack: 1.类(userdata) 2.变量(string) 3.meta(table) 4.实际值 } else if(lua_isnil(L,-1)) { // stack: 1.类(userdata) 2.变量(string) 3.meta(table) 4.nil lua_remove(L,-1); // stack: 1.类(userdata) 2.变量(string) 3.meta(table) invoke_parent(L); // fix bug by fergus // 调用父类也需调用get if(lua_isuserdata(L,-1)) { // stack: 1.类(userdata) 2.变量(string) 3.meta(table) 4.父类中的变量(userdata) user2type<var_base*>::invoke(L,-1)->get(L); // stack: 1.类(userdata) 2.变量(string) 3.meta(table) 4.父类中的变量(userdata) 5.实际值 lua_remove(L, -2); // stack: 1.类(userdata) 2.变量(string) 3.meta(table) 4.实际值 } else if(lua_isnil(L,-1)) { // stack: 1.类(userdata) 2.变量(string) 3.meta(table) 4.nil lua_pushfstring(L, "can't find '%s' class variable. (forgot registering class variable ?)", lua_tostring(L, 2)); lua_error(L); } } lua_remove(L,-2); // stack: 1.类(userdata) 2.变量(string) 3.实际值 return 1; } int meta_set(lua_State *L) { // stack: 1.类(userdata) 2.变量(string) 3.要赋的值 lua_getmetatable(L,1); // stack: 1.类(userdata) 2.变量(string) 3.要赋的值 4.类meta(table) lua_pushvalue(L,2); // stack: 1.类(userdata) 2.变量(string) 3.要赋的值 4.类meta(table) 5.变量(string) lua_rawget(L,-2); // stack: 1.类(userdata) 2.变量(string) 3.要赋的值 4.类meta(table) 5.meta[变量](userdata mem_var指针) if(lua_isuserdata(L,-1)) { user2type<var_base*>::invoke(L,-1)->set(L); // stack: 1.类(userdata) 2.变量(string) 3.要赋的值 4.类meta(table) 5.meta[变量](userdata mem_var指针) } else if(lua_isnil(L, -1)) { // stack: 1.类(userdata) 2.变量(string) 3.要赋的值 4.类meta(table) 5.nil lua_remove(L,-1); // stack: 1.类(userdata) 2.变量(string) 3.要赋的值 4.类meta(table) lua_pushvalue(L,2); // stack: 1.类(userdata) 2.变量(string) 3.要赋的值 4.类meta(table) 5.变量(string) lua_pushvalue(L,4); // stack: 1.类(userdata) 2.变量(string) 3.要赋的值 4.类meta(table) 5.变量(string) 6.类meta(table) invoke_parent(L); // stack: 1.类(userdata) 2.变量(string) 3.要赋的值 4.类meta(table) 5.变量(string) 6.类meta(table) 7.获取到父类的变量(userdata mem_var指针) if(lua_isuserdata(L,-1)) { user2type<var_base*>::invoke(L,-1)->set(L); } else if(lua_isnil(L,-1)) { // stack: 1.类(userdata) 2.变量(string) 3.要赋的值 4.类meta(table) 5.变量(string) 6.类meta(table) 7.nil lua_pushfstring(L, "can't find '%s' class variable. (forgot registering class variable ?)", lua_tostring(L, 2)); lua_error(L); } } lua_settop(L, 3); // stack: 1.类(userdata) 2.变量(string) 3.要赋的值 return 0; } void push_meta(lua_State *L, const char* name) { lua_getglobal(L, name); } // table object on stack --------------------------------------- table_obj::table_obj(lua_State* L, int index) :m_L(L) ,m_index(index) ,m_ref(0) { if(lua_isnil(m_L, m_index)) { m_pointer = NULL; lua_remove(m_L, m_index); } else { m_pointer = lua_topointer(m_L, m_index); } } table_obj::~table_obj() { if(validate()) { lua_remove(m_L, m_index); } } void table_obj::inc_ref() { ++m_ref; } void table_obj::dec_ref() { if(--m_ref == 0) delete this; } bool table_obj::validate() { if(m_pointer != NULL) { if(m_pointer == lua_topointer(m_L, m_index)) { return true; } else { int top = lua_gettop(m_L); for(int i=1; i<=top; ++i) { if(m_pointer == lua_topointer(m_L, i)) { m_index = i; return true; } } m_pointer = NULL; return false; } } else { return false; } } // Table Object Holder --------------------------------------- table::table(lua_State* L) { lua_newtable(L); m_obj = new table_obj(L, lua_gettop(L)); m_obj->inc_ref(); } table::table(lua_State* L, const char* name) { lua_getglobal(L, name); if(lua_istable(L, -1) == 0) { lua_pop(L, 1); lua_newtable(L); lua_setglobal(L, name); lua_getglobal(L, name); } m_obj = new table_obj(L, lua_gettop(L)); m_obj->inc_ref();//dm } table::table(lua_State* L, int index) { if(index < 0) { index = lua_gettop(L) + index + 1; } m_obj = new table_obj(L, index); m_obj->inc_ref(); } table::table(const table& input) { m_obj = input.m_obj; m_obj->inc_ref(); } table::~table() { m_obj->dec_ref(); } }//namespace DMLUA
[ "mushilanxin@163.com" ]
mushilanxin@163.com
b708fd12cdc4bccd76943dc1e9bc230327589ea0
4503b4ec29e9a30d26c433bac376f2bddaefd9e5
/PCL 1.7.2_vs2013/x86/3rdParty/VTK/include/vtk-6.2/vtkmetaio/metaOutput.h
0f0ec4d43b555d6d84dbb54f8a3fab0c4f6ec338
[]
no_license
SwunZH/ecocommlibs
0a872e0bbecbb843a0584fb787cf0c5e8a2a270b
4cff09ff1e479f5f519f207262a61ee85f543b3a
refs/heads/master
2021-01-25T12:02:39.067444
2018-02-23T07:04:43
2018-02-23T07:04:43
123,447,012
1
0
null
2018-03-01T14:37:53
2018-03-01T14:37:53
null
UTF-8
C++
false
false
5,079
h
/*============================================================================ MetaIO Copyright 2000-2010 Insight Software Consortium Distributed under the OSI-approved BSD License (the "License"); see accompanying file Copyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the License for more information. ============================================================================*/ #include "metaTypes.h" #ifndef __MetaOutput_H_ #define __MetaOutput_H_ #ifdef _MSC_VER #pragma warning ( disable : 4786 ) #pragma warning ( disable: 4251 ) #pragma warning ( disable: 4511 ) // copy constructor not found #pragma warning ( disable: 4512 ) // assignment operator not found #endif #include "metaCommand.h" #include <stdio.h> #include <string> #if (METAIO_USE_NAMESPACE) namespace METAIO_NAMESPACE { #endif class MetaOutputStream { public: MetaOutputStream(); virtual ~MetaOutputStream() {}; void SetName(const char* name); METAIO_STL::string GetName() const; void Enable(); bool IsEnable() const; void Disable(); void SetStdStream(METAIO_STREAM::ostream * stream); bool IsStdStream(); METAIO_STREAM::ostream * GetStdStream(); virtual bool Open(); virtual bool Close(); virtual bool Write(const char* buffer); void SetMetaOutput(void* metaOutput); protected: METAIO_STREAM::ostream * m_StdStream; bool m_IsStdStream; bool m_Enable; bool m_IsOpen; METAIO_STL::string m_Name; void* m_MetaOutput; }; class MetaFileOutputStream : public MetaOutputStream { public: MetaFileOutputStream(const char* name); virtual ~MetaFileOutputStream() {}; bool Open(); bool Close(); METAIO_STL::string GetFileName(); private: METAIO_STL::string m_FileName; METAIO_STREAM::ofstream m_FileStream; }; class METAIO_EXPORT MetaOutput { public: typedef enum {INT,FLOAT,CHAR,STRING,LIST,FLAG,BOOL} TypeEnumType; struct Field{ METAIO_STL::string name; METAIO_STL::string description; METAIO_STL::vector<METAIO_STL::string> value; TypeEnumType type; METAIO_STL::string rangeMin; METAIO_STL::string rangeMax; }; typedef METAIO_STL::vector<Field> FieldVector; typedef METAIO_STL::vector<MetaOutputStream*> StreamVector; typedef METAIO_STL::list< METAIO_STL::string > ListType; MetaOutput(); ~MetaOutput(); /** Add a field */ bool AddField(METAIO_STL::string name, METAIO_STL::string description, TypeEnumType type, METAIO_STL::string value, METAIO_STL::string rangeMin = "", METAIO_STL::string rangeMax = "" ); bool AddFloatField(METAIO_STL::string name, METAIO_STL::string description, float value, METAIO_STL::string rangeMin = "", METAIO_STL::string rangeMax = "" ); bool AddIntField(METAIO_STL::string name, METAIO_STL::string description, int value, METAIO_STL::string rangeMin = "", METAIO_STL::string rangeMax = "" ); bool AddListField(METAIO_STL::string name, METAIO_STL::string description, ListType list); /** Set the metaCommand for parsing */ void SetMetaCommand(MetaCommand* metaCommand); /** Write the output to the connected streams */ void Write(); /** Add a standard stream */ void AddStream(const char* name,METAIO_STREAM::ostream & stream); void AddStream(const char* name,MetaOutputStream * stream); /** Add a stream file. Helper function */ void AddStreamFile(const char* name, const char* filename); /** Enable or Disable a stream */ void EnableStream(const char* name); void DisableStream(const char* name); METAIO_STL::string GetHostname(void); METAIO_STL::string GetHostip(void); private: METAIO_STL::string TypeToString(TypeEnumType type); /** Private function to fill in the buffer */ METAIO_STL::string GenerateXML(const char* filename=NULL); METAIO_STL::string GetUsername(void); FieldVector m_FieldVector; MetaCommand* m_MetaCommand; StreamVector m_StreamVector; METAIO_STL::string m_CurrentVersion; }; // end of class #if (METAIO_USE_NAMESPACE) }; #endif #endif
[ "hnk0313@3e9e098e-e079-49b3-9d2b-ee27db7392fb" ]
hnk0313@3e9e098e-e079-49b3-9d2b-ee27db7392fb