blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
listlengths
1
1
author
stringlengths
0
119
b70e1e3a0b8ce44dbeb7ffc34e30a3837ca9b3a9
2cb84ecc228318cb440f197d457616e98ed49c33
/src/cachemap.h
0707730942db8527799c7b59720e56f5b5fe6f4b
[ "MIT" ]
permissive
SMScoin/smscoin
ad1d8625cdecb80bb0ba8b4cf126ad82e0833f16
6235292465ccfbcd8b40369dcc634661ac8dbe2e
refs/heads/master
2020-03-20T21:48:19.658882
2018-06-19T06:45:21
2018-06-19T06:45:21
137,374,261
0
0
null
null
null
null
UTF-8
C++
false
false
4,257
h
// Copyright (c) 2014-2018 The SMScoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef CACHEMAP_H_ #define CACHEMAP_H_ #include <map> #include <list> #include <cstddef> #include "serialize.h" /** * Serializable structure for key/value items */ template<typename K, typename V> struct CacheItem { CacheItem() {} CacheItem(const K& keyIn, const V& valueIn) : key(keyIn), value(valueIn) {} K key; V value; ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { READWRITE(key); READWRITE(value); } }; /** * Map like container that keeps the N most recently added items */ template<typename K, typename V, typename Size = uint32_t> class CacheMap { public: typedef Size size_type; typedef CacheItem<K,V> item_t; typedef std::list<item_t> list_t; typedef typename list_t::iterator list_it; typedef typename list_t::const_iterator list_cit; typedef std::map<K, list_it> map_t; typedef typename map_t::iterator map_it; typedef typename map_t::const_iterator map_cit; private: size_type nMaxSize; size_type nCurrentSize; list_t listItems; map_t mapIndex; public: CacheMap(size_type nMaxSizeIn = 0) : nMaxSize(nMaxSizeIn), nCurrentSize(0), listItems(), mapIndex() {} CacheMap(const CacheMap<K,V>& other) : nMaxSize(other.nMaxSize), nCurrentSize(other.nCurrentSize), listItems(other.listItems), mapIndex() { RebuildIndex(); } void Clear() { mapIndex.clear(); listItems.clear(); nCurrentSize = 0; } void SetMaxSize(size_type nMaxSizeIn) { nMaxSize = nMaxSizeIn; } size_type GetMaxSize() const { return nMaxSize; } size_type GetSize() const { return nCurrentSize; } void Insert(const K& key, const V& value) { map_it it = mapIndex.find(key); if(it != mapIndex.end()) { item_t& item = *(it->second); item.value = value; return; } if(nCurrentSize == nMaxSize) { PruneLast(); } listItems.push_front(item_t(key, value)); mapIndex[key] = listItems.begin(); ++nCurrentSize; } bool HasKey(const K& key) const { map_cit it = mapIndex.find(key); return (it != mapIndex.end()); } bool Get(const K& key, V& value) const { map_cit it = mapIndex.find(key); if(it == mapIndex.end()) { return false; } item_t& item = *(it->second); value = item.value; return true; } void Erase(const K& key) { map_it it = mapIndex.find(key); if(it == mapIndex.end()) { return; } listItems.erase(it->second); mapIndex.erase(it); --nCurrentSize; } const list_t& GetItemList() const { return listItems; } CacheMap<K,V>& operator=(const CacheMap<K,V>& other) { nMaxSize = other.nMaxSize; nCurrentSize = other.nCurrentSize; listItems = other.listItems; RebuildIndex(); return *this; } ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { READWRITE(nMaxSize); READWRITE(nCurrentSize); READWRITE(listItems); if(ser_action.ForRead()) { RebuildIndex(); } } private: void PruneLast() { if(nCurrentSize < 1) { return; } item_t& item = listItems.back(); mapIndex.erase(item.key); listItems.pop_back(); --nCurrentSize; } void RebuildIndex() { mapIndex.clear(); for(list_it it = listItems.begin(); it != listItems.end(); ++it) { mapIndex[it->key] = it; } } }; #endif /* CACHEMAP_H_ */
[ "wijnand_schouten@hotmail.com" ]
wijnand_schouten@hotmail.com
c17e0664367ade313b64ebac3043c7b45c5d4855
1a1dab692cd7bb699c200b46366dd927a492f195
/abhi_q1.cpp
4bfeb729a5b58e928104f0a0df3e111e9b1478c0
[]
no_license
sainisajal147/Problem_solving
a33679102f041bdaeedc3e67c091f76655ec2f67
93ed4ee477a37d450be9c0679e6eabc84845c6c6
refs/heads/main
2023-06-26T16:58:27.023984
2021-07-27T17:17:54
2021-07-27T17:17:54
370,247,351
0
0
null
null
null
null
UTF-8
C++
false
false
1,536
cpp
/* AUTHOR : SAJAL SAINI */ #include <stdio.h> #include <cmath> #include <map> #include <math.h> #include <cstdio> #include <vector> #include <string> #include <iostream> #include <algorithm> #include <stack> #include <queue> #include <bits/stdc++.h> #include <math.h> #include <set> using namespace std; typedef long long int ll; template <class t> void disp(vector<vector<t>> v) { for(int i=0;i<v.size();i++) { for(int j=0;j<v[i].size();j++) { cout<<v[i][j]<<" "; } cout<<endl; } } template <class t> void disp(vector<t> v) { for(int i=0;i<v.size();i++) { cout<<v[i]<<" "; } cout<<endl; } int solve1(vector<int> a, vector<int> b, int k) { int n=a.size(),score=0; for(int i=0;i<k;i++) { int index=-1,temp=INT_MIN,temp_val=INT_MIN; for(int j=0;j<n;j++) { if(a[j]>temp_val) { temp_val=a[j]; index=j; temp=a[j]/b[i]; } } score+=a[index]; a[index]=a[index]/b[index]; } return score; } int solve2(vector<vector<int>> v,int n,vector<int> a,int k) { int ans=INT_MIN; for(int i=0;i<k;i++) { for(int j=0;j<n;j++) { if(v[i][j]) a[i]=max(a[i],a[i]^a[j]); } } disp(v); disp(a); ans=accumulate(a.begin(), a.end(),0); return ans; } int main(void) { //vector<int> a={12,4,2,3},b={5,1,2,2}; //cout<<solve1(a,b,3); int n=3; vector<vector<int>> v(n,vector<int> (n,0)); vector<int> a(n,0); v[0][1]=1,v[0][2]=1; a[0]=1,a[1]=1,a[2]=3; cout<<solve2(v,n,a,3); return 0; }
[ "sainisajal147@gmail.com" ]
sainisajal147@gmail.com
31376d9cb08cad7f0e0c65e98c387ce9ab19998c
26e2291166af8d8a3c3ff1016d6a19f6b7fe7304
/src/Model/AVLTree.h
f9f3f8eff686e73fb608a1824a8474cb1571a09f
[]
no_license
JohnathanFlint/Mondo
4e56d6dc09395d5bb8bd659d666e9b3b623bb73a
feb96f8fb56767f9e90749b8dbc2f9b25e48abf7
refs/heads/master
2021-01-22T03:13:15.265143
2017-06-05T11:19:15
2017-06-05T11:19:15
81,104,472
0
0
null
null
null
null
UTF-8
C++
false
false
4,200
h
/* * AVLTree.h * * Created on: Apr 19, 2017 * Author: nwhi5696 */ #ifndef MODEL_AVLTREE_H_ #define MODEL_AVLTREE_H_ #include "BinarySearchTreeNode.h" #include "BinarySearchTree.h" template<class Type> class AVLTree : public BinarySearchTree<Type> { private: BinarySearchTreeNode<Type> * leftRotation(BinarySearchTreeNode<Type> * parent); BinarySearchTreeNode<Type> * rightRotation(BinarySearchTreeNode<Type> * parent); BinarySearchTreeNode<Type> * leftRightRotation(BinarySearchTreeNode<Type> * parent); BinarySearchTreeNode<Type> * rightLeftRotation(BinarySearchTreeNode<Type> * parent); BinarySearchTreeNode<Type> * balanceSubTree(BinarySearchTreeNode<Type> * parent); BinarySearchTreeNode<Type> * insertedNode(BinarySearchTreeNode<Type> * parent, Type value); BinarySearchTreeNode<Type> * removenode(BinarySearchTreeNode<Type> * parent, Type value); int heightDifference(BinarySearchTreeNode<Type> * parent); public: AVLTree(); ~AVLTree(); void insert(Type toInsert); void remove(Type value); }; // A negative value means the right is greater than the left template <class Type> int AVLTree<Type> :: heightDifference(BinarySearchTreeNode<Type> * node) { int balance; int leftHeight = calculateHeight(node->getLeftChild()); int rightHeight = calculateHeight(node->getRightChild()); balance = leftHeight - rightHeight; return balance; } template <class Type> BinarySearchTreeNode<Type> * AVLTree<Type> :: leftRotation(BinarySearchTreeNode<Type> * parent) { BinarySearchTreeNode<Type> * changedNode; changedNode = parent->getLeftChild(); parent->setLeftChild(changedNode->getRightChild()); changedNode->setRightChild(parent); return changedNode; } template <class Type> BinarySearchTreeNode<Type> * AVLTree<Type> :: rightRotation(BinarySearchTreeNode<Type> * parent) { BinarySearchTreeNode<Type> * changedNode;; changedNode = parent->getRightChild(); parent->setRightChild(changedNode->getLeftChild()); changedNode->setLeftChild(parent); return changedNode; } template <class Type> BinarySearchTreeNode<Type> * AVLTree<Type> :: rightLeftRotation(BinarySearchTreeNode<Type> * parent) { BinarySearchTreeNode<Type> * changedNode; changedNode = parent->getRightChild(); parent->setRightChild(leftRotation(changedNode)); return rightRotation(parent); } template <class Type> BinarySearchTreeNode<Type> * AVLTree<Type> :: leftRightRotation(BinarySearchTreeNode<Type> * parent) { BinarySearchTreeNode<Type> * changedNode; changedNode = parent->getLeftChild(); parent->setLeftChild(rightRotation(changedNode)); return leftRotation(parent); } template <class Type> BinarySearchTreeNode<Type> * AVLTree<Type> :: balanceSubTree(BinarySearchTreeNode<Type> * parent) { int balanceFactor = heightDifference(parent); if(balanceFactor > 1) { if(heightDifference(parent->getLeftChild()) > 0) { parent = leftRotation(parent); } else { parent = leftRightRotation(parent); } } else if(balanceFactor < -1) { if(heightDifference(parent->getRightChild()) > 0) { parent rightLeftRotation(parent); } else { parent = rightRotation(parent); } } return parent; } template <class Type> AVLTree<Type> :: AVLTree() : BinarySearchTree<Type>() { this->root = nullptr; } template <class Type> AVLTree<Type> :: ~AVLTree() : BinarySearchTree<Type>() { delete this->getRoot(); } template <class Type> BinarySearchTreeNode<Type> * AVLTree<Type> :: removeNode(BinarySearchTreeNode<Type> * parent, Type inserted) { } template <class Type> BinarySearchTreeNode<Type> * AVLTree<Type> :: insertNode(BinarySearchTreeNode<Type> * parent, Type inserted) { if(parent == nullptr) { parent = new BnarySearchTreeNode<Type>(inserted); return parent; } else if(inserted < parent->getNodeData()) { parent->setLeftChild(insertedNode(parent->getLeftChild(), inserted)); parent = balanceSubtree(parent); } else if(inserted > parent->getNodeData()) { parent->setRightChild(insertedNode(parent->getRightChild(), inserted)); parent = balanceSubTree(parent); } return parent; } template <class Type> void AVLTree<Type> :: insert(Type item) { insertNode(this->getRoot(), item); } #endif /* MODEL_AVLTREE_H_ */
[ "nicholas.white142@gmail.com" ]
nicholas.white142@gmail.com
21de7f03a219fff44f1393a8fc3e5b726f4ab244
4a1ef66e84febdd996ccccb1d7cdf0002ba9e411
/framework/LuaKigsBind/libs/bintoc.cpp
3337825df803ddc67878cb6af099b7970a31e419
[ "MIT" ]
permissive
grtwall/kigs
dc782b517626ab792048a3f74e670ba39ae17aaa
2ada0068c8618935ed029db442ecf58f6bf96126
refs/heads/master
2023-06-06T12:11:44.054106
2021-06-28T11:31:43
2021-06-28T11:35:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,523
cpp
/* * bin2c: A Program to convert binary data into C source code * Copyright 2004 by Adrian Prantl <adrian@f4z.org> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * */ #include <stdio.h> #include <stdlib.h> char* self = 0; void usage() { printf("Usage:\n%s input.bin output.h name\n\n", self); } void bail_out(const char* s1, const char* s2) { fprintf(stderr, "%s: FATAL ERROR:\n%s%s\n", self, s1, s2); exit(1); } int main(int argc, char** argv) { FILE *fi, *fo; int c, i; self = argv[0]; if (argc != 4) { usage(); return 0; } if ((fi = fopen(argv[1], "rb")) == 0) bail_out("Cannot open input file ", argv[1]); if ((fo = fopen(argv[2], "w")) == 0) bail_out("Cannot open output file ", argv[2]); if ((c = fgetc(fi)) != EOF) { fprintf(fo, "#ifndef %s_H\n", argv[3]); fprintf(fo, "#define %s_H\n\n", argv[3]); fprintf(fo, "const unsigned char %s[] = {\n", argv[3]); fprintf(fo, c < 16 ? " 0x%02x" : " 0x%02x", (unsigned char)c); } i = 1; while ((c = fgetc(fi)) != EOF) { if (i < 12) fprintf(fo, c < 16 ? ", 0x%02x" : ", 0x%02x", (unsigned char)c); else { fprintf(fo, c < 16 ? ",\n 0x%02x" : ",\n 0x%02x", (unsigned char)c); i = 0; } i++; } fprintf(fo, ", 0x00\n};\n\n"); fprintf(fo, "#endif\n"); printf("converted %s\n", argv[1]); return 0; }
[ "antoine.fresse@assoria.com" ]
antoine.fresse@assoria.com
351ed07efca1515464ba886ed383a9bed8297e72
dc2ba43ea63e9548a45528c5869579f18f267fc2
/include/contact_enums.h
3458be923e2b6a6ef644d4514f087ea0a0820111
[ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
Chunting/contact_control
7dcc185dfd8e25452c4e78653b1ccb6fe027fbf5
d6607b50a16589a3cec987dcca5a682080ff5c6b
refs/heads/master
2020-05-24T06:36:47.544641
2017-03-02T22:06:29
2017-03-02T22:06:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,921
h
#ifndef CONTACT_ENUMS_H_ #define CONTACT_ENUMS_H_ /** * Enums and constants for the Contact Control library */ namespace Contact { /** * Dimension enum. * The Dimension enum is used to determine the dimension that is being * controlled or requested. */ enum Dimension {DIM_X = 0, /**< The X dimension. */ DIM_Y = 1, /**< The Y dimension. */ DIM_Z = 2, /**< The Z dimension. */ DIM_RX = 3, /**< The rotational X dimension. */ DIM_RY = 4, /**< The rotational Y dimension. */ DIM_RZ = 5, /**< The rotational Z dimension. */ NUM_DIMS = 6}; /**< The number of dimensions. */ /** * Perspective enum. * The Perspective enum is used to differentiate between translational dimensions * and rotational dimensions. */ enum Perspective {TRANSLATION = 0, /**< The translational perspective or forces. */ ROTATION = 1, /**< The rotational persepective or torques. */ NUM_PERSPECTIVES = 2}; /**< The number of perspectives. */ /** * Movement enum. * The movement enum differentiates between the different control laws that are * available. When new control laws are added the the framework, this enum should * be updated accordingly. */ enum Movement {DIRECTION = 0, /**< The directional control law. */ SPRING = 1, /**< The static spring based control law. */ FOLLOWER = 2, /**< The follower control law. */ NUM_LAWS = 3}; /**< The number of laws. */ /** * End condition enum. * The end condtion enum tells why the move was ended. As new end conditions are added * to the framework, this enum should be updated accordingly. */ enum EndCondition {NO_CONDITION = 0, /**< A move is being executed and there is not yet an end condition. */ NO_LAWS = 1, /**< No dimensions were initialized with a control law to follow. */ FT_VIOLATION = 2, /**< Force or torque was read as maximum allowed. */ MAX_TRAVEL = 3, /**< Maximum allowed travel was reached. */ EXTERNAL = 4, /**< Stop move function was called. */ DIFF_VIOLATION = 5, /**< Force torque differential max was reached */ NO_FT_DATA = 6, /**< Netft is not reading force data */ IN_MOTION = 7, /**< Another move is executing */ INVALID_PARAMS = 8, /**< Invalid parameters passed to method */ NOT_INITIALIZED = 9, /**< Invalid parameters passed to method */ NUM_CONDITIONS = 10}; /**< The number of end conditions. */ } #endif /* CONTACT_ENUMS_H_ */
[ "alexvs@utexas.edu" ]
alexvs@utexas.edu
8bb85328b6eac11c2c6ad95d228cbc9fb757d202
4029b175ef91afb448ef1cd9eec43678680aea54
/item.cpp
fcc654e2a0e9ee0c177720134d1389163a95bab6
[]
no_license
pilgarlicx/Wow-3D-viewer
92ad7402d10e90379e9aae77d627e76cbe068c6d
64f7d4bd56f617843915ea4407f14b9c1b7b5f4d
refs/heads/master
2020-03-08T20:12:55.399990
2013-11-30T11:23:09
2013-11-30T11:23:09
null
0
0
null
null
null
null
GB18030
C++
false
false
3,552
cpp
#include "mpq.h" #include "Item.h" #include "texture.h" #include "DB.h" extern ItemDisplayDB itemdisplaydb; extern TextureManager texturemanager; void ItemModel::InitBodyTexture(MPQFile& f,MPQFile& g) { } void ItemModel::InitHairTexture(MPQFile& f,MPQFile& g) { } wxString sFilterDir; bool filterDir(wxString fn) { wxString tmp = fn.Lower(); return (tmp.StartsWith(sFilterDir) && tmp.EndsWith(wxT("blp"))); } void ItemModel::InitCapeTexture(MPQFile& f,MPQFile& g) { //CharacterModel::InitCapeTexture(f,g); //这里应该根据Item的Id 去加载相应的纹理 //代码参考于 AnimControl.cpp 中的 UpdateItemModel wxString fn = model_name_; // change M2 to mdx fn = fn.BeforeLast(wxT('.')) + wxT(".mdx"); // Check to see if its a helmet model, if so cut off the race // and gender specific part of the filename off if (fn.Find(wxT("\\head\\")) > wxNOT_FOUND || fn.Find(wxT("\\Head\\")) > wxNOT_FOUND) { fn = fn.BeforeLast('_') + wxT(".mdx"); } // just get the file name, exclude the path. fn = fn.AfterLast(wxT('\\')); TextureSet skins; for (ItemDisplayDB::Iterator it=itemdisplaydb.begin(); it!=itemdisplaydb.end(); ++it) { if (fn.IsSameAs(it->getString(ItemDisplayDB::Model), false)) { TextureGroup grp; grp.base = TEXTURE_ITEM; grp.count = 1; wxString skin = it->getString(ItemDisplayDB::Skin); grp.tex[0] = skin; if (grp.tex[0].length() > 0) skins.insert(grp); } //if (!strcmp(it->getString(ItemDisplayDB::Model2), fn.c_str())) { if (fn.IsSameAs(it->getString(ItemDisplayDB::Model2), false)) { TextureGroup grp; grp.base = TEXTURE_ITEM; grp.count = 1; wxString skin = it->getString(ItemDisplayDB::Skin2); grp.tex[0] = skin; if (grp.tex[0].length() > 0) skins.insert(grp); } } // Search the same directory for BLPs std::set<FileTreeItem> filelist; sFilterDir = model_name_.BeforeLast(wxT('.')).Lower(); getFileLists(filelist, filterDir); if (filelist.begin() != filelist.end()) { TextureGroup grp; grp.base = TEXTURE_ITEM; grp.count = 1; for (std::set<FileTreeItem>::iterator it = filelist.begin(); it != filelist.end(); ++it) { grp.tex[0] = (*it).displayName.BeforeLast(wxT('.')).AfterLast(wxT('\\')); skins.insert(grp); } } bool ret = false; if (!skins.empty()) { //这里我们主要打印一些信息 然后 选择最后一个Skin作为物品的纹理 printf("We have found %d skins for the Item\n",skins.size() ); for(TextureSet::iterator it = skins.begin(); it != skins.end(); ++it){ printf("Skin name is %s\n",it->tex[0]); } //ret = FillSkinSelector(skins); //int mySkin = 0; for(TextureSet::iterator it = skins.begin(); it != skins.end(); ++it){ wxString name_ = model_name_.BeforeLast(wxT('\\')) + wxT('\\') + it->tex[0] + wxT(".blp"); for (ssize_t j=0; j<TEXTURE_MAX; j++) { if (it->base == specialTextures[j]) { TextureList[j] = name_; replaceTextures[it->base] = texturemanager.add(name_); printf("We use texture %s as special id %d\n",name_,it->base); return; } } } } } void ItemModel::calcBones(ssize_t anim, size_t time) { for (size_t i=0; i<model_header_.nBones; i++) { bones[i].calc = false; } size_t a, t; a = anim; t = time; for (size_t i=0; i<model_header_.nBones; i++) { bones[i].calcMatrix(bones, anim, time); } } void ItemModel::Draw() { //这里暂时和CharacterModel一样 CharacterModel::Draw(); }
[ "wubaolin@wubaolin-virtual-machine.(none)" ]
wubaolin@wubaolin-virtual-machine.(none)
e7aefe6a52862266ecc628391645087f939bb9e9
46fe6148b7aafb7671a4e711584a5c52289ef585
/libraries/ArduinoBLE/src/local/BLELocalDevice.cpp
91cc86950aa7a84db1e3bdf391435783b0cafa01
[ "LGPL-2.1-or-later", "LGPL-2.1-only", "MIT" ]
permissive
matteobaccan/PassiveCooker
845d93c69b689b51cfd066f6cfe0878bbd33b9e6
a84a909311806af5048e5903781ecd37c5001e51
refs/heads/main
2023-05-31T05:00:21.428527
2022-11-20T20:39:38
2022-11-20T20:39:38
555,814,343
1
0
MIT
2023-09-04T15:45:50
2022-10-22T11:50:17
C++
UTF-8
C++
false
false
10,909
cpp
/* This file is part of the ArduinoBLE library. Copyright (c) 2018 Arduino SA. All rights reserved. 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; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 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 Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "utility/ATT.h" #include "utility/HCI.h" #include "utility/GAP.h" #include "utility/GATT.h" #include "utility/L2CAPSignaling.h" #include "BLELocalDevice.h" #if defined(ARDUINO_PORTENTA_H7_M4) || defined(ARDUINO_PORTENTA_H7_M7) #ifndef BT_REG_ON #define BT_REG_ON PJ_12 #endif #elif defined(ARDUINO_NICLA_VISION) #ifndef BT_REG_ON #define BT_REG_ON PF_14 #endif #endif BLELocalDevice::BLELocalDevice() { _advertisingData.setFlags(BLEFlagsGeneralDiscoverable | BLEFlagsBREDRNotSupported); } BLELocalDevice::~BLELocalDevice() { } int BLELocalDevice::begin() { #if defined(ARDUINO_SAMD_MKRWIFI1010) || defined(ARDUINO_AVR_UNO_WIFI_REV2) || defined(ARDUINO_SAMD_NANO_33_IOT) || defined(ARDUINO_NANO_RP2040_CONNECT) // reset the NINA in BLE mode pinMode(SPIWIFI_SS, OUTPUT); pinMode(NINA_RESETN, OUTPUT); digitalWrite(SPIWIFI_SS, LOW); #endif #if defined(ARDUINO_SAMD_MKRWIFI1010) || defined(ARDUINO_AVR_UNO_WIFI_REV2) digitalWrite(NINA_RESETN, HIGH); delay(100); digitalWrite(NINA_RESETN, LOW); delay(750); #elif defined(ARDUINO_SAMD_NANO_33_IOT) || defined(ARDUINO_NANO_RP2040_CONNECT) // inverted reset digitalWrite(NINA_RESETN, LOW); delay(100); digitalWrite(NINA_RESETN, HIGH); delay(750); #elif defined(ARDUINO_PORTENTA_H7_M4) || defined(ARDUINO_PORTENTA_H7_M7) || defined(ARDUINO_NICLA_VISION) // BT_REG_ON -> HIGH pinMode(BT_REG_ON, OUTPUT); digitalWrite(BT_REG_ON, HIGH); #endif #ifdef ARDUINO_AVR_UNO_WIFI_REV2 // set SS HIGH digitalWrite(SPIWIFI_SS, HIGH); // set RTS HIGH pinMode(NINA_RTS, OUTPUT); digitalWrite(NINA_RTS, HIGH); // set CTS as input pinMode(NINA_CTS, INPUT); #endif if (!HCI.begin()) { end(); return 0; } delay(100); if (HCI.reset() != 0) { end(); return 0; } uint8_t hciVer; uint16_t hciRev; uint8_t lmpVer; uint16_t manufacturer; uint16_t lmpSubVer; if (HCI.readLocalVersion(hciVer, hciRev, lmpVer, manufacturer, lmpSubVer) != 0) { end(); return 0; } if (HCI.setEventMask(0x3FFFFFFFFFFFFFFF) != 0) { end(); return 0; } if (HCI.setLeEventMask(0x00000000000003FF) != 0) { end(); return 0; } uint16_t pktLen; uint8_t maxPkt; if (HCI.readLeBufferSize(pktLen, maxPkt) != 0) { end(); return 0; } /// The HCI should allow automatic address resolution. // // If we have callbacks to remember bonded devices: // if(HCI._getIRKs!=0){ // uint8_t nIRKs = 0; // uint8_t** BADDR_Type = new uint8_t*; // uint8_t*** BADDRs = new uint8_t**; // uint8_t*** IRKs = new uint8_t**; // uint8_t* memcheck; // if(!HCI._getIRKs(&nIRKs, BADDR_Type, BADDRs, IRKs)){ // Serial.println("error"); // } // for(int i=0; i<nIRKs; i++){ // Serial.print("Baddr type: "); // Serial.println((*BADDR_Type)[i]); // Serial.print("BADDR:"); // for(int k=0; k<6; k++){ // Serial.print(", 0x"); // Serial.print((*BADDRs)[i][k],HEX); // } // Serial.println(); // Serial.print("IRK:"); // for(int k=0; k<16; k++){ // Serial.print(", 0x"); // Serial.print((*IRKs)[i][k],HEX); // } // Serial.println(); // // save this // uint8_t zeros[16]; // for(int k=0; k<16; k++) zeros[15-k] = 0; // // HCI.leAddResolvingAddress((*BADDR_Type)[i],(*BADDRs)[i],(*IRKs)[i], zeros); // delete[] (*BADDRs)[i]; // delete[] (*IRKs)[i]; // } // delete[] (*BADDR_Type); // delete BADDR_Type; // delete[] (*BADDRs); // delete BADDRs; // delete[] (*IRKs); // delete IRKs; // memcheck = new uint8_t[1]; // Serial.print("nIRK location: 0x"); // Serial.println((int)memcheck,HEX); // delete[] memcheck; // } GATT.begin(); return 1; } void BLELocalDevice::end() { GATT.end(); HCI.end(); #if defined(ARDUINO_SAMD_MKRWIFI1010) || defined(ARDUINO_AVR_UNO_WIFI_REV2) // disable the NINA digitalWrite(NINA_RESETN, HIGH); #elif defined(ARDUINO_SAMD_NANO_33_IOT) || defined(ARDUINO_NANO_RP2040_CONNECT) // disable the NINA digitalWrite(NINA_RESETN, LOW); #elif defined(ARDUINO_PORTENTA_H7_M4) || defined(ARDUINO_PORTENTA_H7_M7) || defined(ARDUINO_NICLA_VISION) digitalWrite(BT_REG_ON, LOW); #endif } void BLELocalDevice::poll() { HCI.poll(); } void BLELocalDevice::poll(unsigned long timeout) { HCI.poll(timeout); } bool BLELocalDevice::connected() const { HCI.poll(); return ATT.connected(); } /* * Whether there is at least one paired device */ bool BLELocalDevice::paired() { HCI.poll(); return ATT.paired(); } bool BLELocalDevice::disconnect() { return ATT.disconnect(); } String BLELocalDevice::address() const { uint8_t addr[6] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; HCI.readBdAddr(addr); char result[18]; sprintf(result, "%02x:%02x:%02x:%02x:%02x:%02x", addr[5], addr[4], addr[3], addr[2], addr[1], addr[0]); return result; } int BLELocalDevice::rssi() { BLEDevice central = ATT.central(); if (central) { return central.rssi(); } return 127; } bool BLELocalDevice::setAdvertisedServiceUuid(const char* advertisedServiceUuid) { return _advertisingData.setAdvertisedServiceUuid(advertisedServiceUuid); } bool BLELocalDevice::setAdvertisedService(const BLEService& service) { return setAdvertisedServiceUuid(service.uuid()); } bool BLELocalDevice::setAdvertisedServiceData(uint16_t uuid, const uint8_t data[], int length) { return _advertisingData.setAdvertisedServiceData(uuid, data, length); } bool BLELocalDevice::setManufacturerData(const uint8_t manufacturerData[], int manufacturerDataLength) { return _advertisingData.setManufacturerData(manufacturerData, manufacturerDataLength); } bool BLELocalDevice::setManufacturerData(const uint16_t companyId, const uint8_t manufacturerData[], int manufacturerDataLength) { return _advertisingData.setManufacturerData(companyId, manufacturerData, manufacturerDataLength); } bool BLELocalDevice::setLocalName(const char *localName) { return _scanResponseData.setLocalName(localName); } void BLELocalDevice::setAdvertisingData(BLEAdvertisingData& advertisingData) { _advertisingData = advertisingData; if (!_advertisingData.hasFlags()) { _advertisingData.setFlags(BLEFlagsGeneralDiscoverable | BLEFlagsBREDRNotSupported); } } void BLELocalDevice::setScanResponseData(BLEAdvertisingData& scanResponseData) { _scanResponseData = scanResponseData; } BLEAdvertisingData& BLELocalDevice::getAdvertisingData() { return _advertisingData; } BLEAdvertisingData& BLELocalDevice::getScanResponseData() { return _scanResponseData; } void BLELocalDevice::setDeviceName(const char* deviceName) { GATT.setDeviceName(deviceName); } void BLELocalDevice::setAppearance(uint16_t appearance) { GATT.setAppearance(appearance); } void BLELocalDevice::addService(BLEService& service) { GATT.addService(service); } int BLELocalDevice::advertise() { _advertisingData.updateData(); _scanResponseData.updateData(); return GAP.advertise( _advertisingData.data(), _advertisingData.dataLength(), _scanResponseData.data(), _scanResponseData.dataLength()); } void BLELocalDevice::stopAdvertise() { GAP.stopAdvertise(); } int BLELocalDevice::scan(bool withDuplicates) { return GAP.scan(withDuplicates); } int BLELocalDevice::scanForName(String name, bool withDuplicates) { return GAP.scanForName(name, withDuplicates); } int BLELocalDevice::scanForUuid(String uuid, bool withDuplicates) { return GAP.scanForUuid(uuid, withDuplicates); } int BLELocalDevice::scanForAddress(String address, bool withDuplicates) { return GAP.scanForAddress(address, withDuplicates); } void BLELocalDevice::stopScan() { GAP.stopScan(); } BLEDevice BLELocalDevice::central() { HCI.poll(); return ATT.central(); } BLEDevice BLELocalDevice::available() { HCI.poll(); return GAP.available(); } void BLELocalDevice::setEventHandler(BLEDeviceEvent event, BLEDeviceEventHandler eventHandler) { if (event == BLEDiscovered) { GAP.setEventHandler(event, eventHandler); } else { ATT.setEventHandler(event, eventHandler); } } void BLELocalDevice::setAdvertisingInterval(uint16_t advertisingInterval) { GAP.setAdvertisingInterval(advertisingInterval); } void BLELocalDevice::setConnectionInterval(uint16_t minimumConnectionInterval, uint16_t maximumConnectionInterval) { L2CAPSignaling.setConnectionInterval(minimumConnectionInterval, maximumConnectionInterval); } void BLELocalDevice::setSupervisionTimeout(uint16_t supervisionTimeout) { L2CAPSignaling.setSupervisionTimeout(supervisionTimeout); } void BLELocalDevice::setConnectable(bool connectable) { GAP.setConnectable(connectable); } void BLELocalDevice::setTimeout(unsigned long timeout) { ATT.setTimeout(timeout); } /* * Control whether pairing is allowed or rejected * Use true/false or the Pairable enum */ void BLELocalDevice::setPairable(uint8_t pairable) { L2CAPSignaling.setPairingEnabled(pairable); } /* * Whether pairing is currently allowed */ bool BLELocalDevice::pairable() { return L2CAPSignaling.isPairingEnabled(); } void BLELocalDevice::setGetIRKs(int (*getIRKs)(uint8_t* nIRKs, uint8_t** BADDR_type, uint8_t*** BADDRs, uint8_t*** IRKs)){ HCI._getIRKs = getIRKs; } void BLELocalDevice::setGetLTK(int (*getLTK)(uint8_t* BADDR, uint8_t* LTK)){ HCI._getLTK = getLTK; } void BLELocalDevice::setStoreLTK(int (*storeLTK)(uint8_t*, uint8_t*)){ HCI._storeLTK = storeLTK; } void BLELocalDevice::setStoreIRK(int (*storeIRK)(uint8_t*, uint8_t*)){ HCI._storeIRK = storeIRK; } void BLELocalDevice::setDisplayCode(void (*displayCode)(uint32_t confirmationCode)){ HCI._displayCode = displayCode; } void BLELocalDevice::setBinaryConfirmPairing(bool (*binaryConfirmPairing)()){ HCI._binaryConfirmPairing = binaryConfirmPairing; } void BLELocalDevice::debug(Stream& stream) { HCI.debug(stream); } void BLELocalDevice::noDebug() { HCI.noDebug(); } #if !defined(FAKE_BLELOCALDEVICE) BLELocalDevice BLEObj; BLELocalDevice& BLE = BLEObj; #endif
[ "matteo.baccan@gmail.com" ]
matteo.baccan@gmail.com
930b335d86e48222b9c69fc3966c6790d2b5d0be
5e1cd5cc05e6dd1ff20c6b9f5dbf608834c04491
/ONScripter/onscripter_main.mm
27a8aea64bc15a45ae966af638a467707d99d09f
[]
no_license
houweifeng/Onscripter-cn-iOS-V2
2f8590e70ddb83a3a3b4b47269e81980e30b4aa2
725ae7cd4570c5dea1e9e69f93d0d9b4a82f6209
refs/heads/master
2020-12-11T16:52:28.968623
2013-02-15T07:32:21
2013-02-15T07:32:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,591
mm
/* -*- C++ -*- * * onscripter_main.cpp -- main function of ONScripter * * Copyright (c) 2001-2012 Ogapee. All rights reserved. * * ogapee@aqua.dti2.ne.jp * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "ONScripter.h" #include "version.h" ONScripter ons; #if defined(IOS) #import <Foundation/NSArray.h> #import <UIKit/UIKit.h> #import "DataDownloader.h" #endif #if defined(PSP) #include <pspkernel.h> #include <psputility.h> #include <psppower.h> #include <ctype.h> PSP_HEAP_SIZE_KB(-1); int psp_power_resume_number = 0; int exit_callback(int arg1, int arg2, void *common) { ons.endCommand(); sceKernelExitGame(); return 0; } int power_callback(int unknown, int pwrflags, void *common) { if (pwrflags & PSP_POWER_CB_RESUMING) psp_power_resume_number++; return 0; } int CallbackThread(SceSize args, void *argp) { int cbid; cbid = sceKernelCreateCallback("Exit Callback", exit_callback, NULL); sceKernelRegisterExitCallback(cbid); cbid = sceKernelCreateCallback("Power Callback", power_callback, NULL); scePowerRegisterCallback(0, cbid); sceKernelSleepThreadCB(); return 0; } int SetupCallbacks(void) { int thid = sceKernelCreateThread("update_thread", CallbackThread, 0x11, 0xFA0, 0, 0); if (thid >= 0) sceKernelStartThread(thid, 0, 0); return thid; } #endif void optionHelp() { printf( "Usage: onscripter [option ...]\n" ); printf( " --cdaudio\t\tuse CD audio if available\n"); printf( " --cdnumber no\tspecify CD-ROM drive number\n"); printf( " -f, --font file\tspecify a TTF font file\n"); printf( " --registry file\tspecify a registry file\n"); printf( " --dll file\tspecify a dll file\n"); printf( " -r, --root path\tspecify the root path to the archives\n"); printf( " --fullscreen\tstart in fullscreen mode\n"); printf( " --window\t\tstart in windowed mode\n"); printf( " --force-button-shortcut\tignore useescspc and getenter command\n"); printf( " --enable-wheeldown-advance\tadvance the text on mouse wheel down\n"); printf( " --disable-rescale\tdo not rescale the images in the archives\n"); printf( " --edit\t\tenable online modification of the volume and variables when 'z' is pressed\n"); printf( " --key-exe file\tspecify a file (*.EXE) that includes a key table\n"); printf( " -h, --help\t\tshow this help and exit\n"); printf( " -v, --version\t\tshow the version number and exit\n"); exit(0); } void optionVersion() { printf("Written by Ogapee <ogapee@aqua.dti2.ne.jp>\n\n"); printf("Copyright (c) 2001-2012 Ogapee.\n"); printf("This is free software; see the source for copying conditions.\n"); exit(0); } #ifdef ANDROID extern "C" { #include <jni.h> #ifndef SDL_JAVA_PACKAGE_PATH #error You have to define SDL_JAVA_PACKAGE_PATH to your package path with dots replaced with underscores, for example "com_example_SanAngeles" #endif #define JAVA_EXPORT_NAME2(name,package) Java_##package##_##name #define JAVA_EXPORT_NAME1(name,package) JAVA_EXPORT_NAME2(name,package) #define JAVA_EXPORT_NAME(name) JAVA_EXPORT_NAME1(name,SDL_JAVA_PACKAGE_PATH) JNIEXPORT jint JNICALL JAVA_EXPORT_NAME(ONScripter_nativeGetWidth) ( JNIEnv* env, jobject thiz ) { return ons.getWidth(); } JNIEXPORT jint JNICALL JAVA_EXPORT_NAME(ONScripter_nativeGetHeight) ( JNIEnv* env, jobject thiz ) { return ons.getHeight(); } } #endif #if defined(QWS) || defined(ANDROID) int SDL_main( int argc, char **argv ) #elif defined(PSP) extern "C" int main( int argc, char **argv ) #else int main( int argc, char **argv ) #endif { printf("ONScripter version %s(%d.%02d)\n", ONS_VERSION, NSC_VERSION/100, NSC_VERSION%100 ); #if defined(PSP) ons.disableRescale(); ons.enableButtonShortCut(); SetupCallbacks(); #elif defined(WINCE) char currentDir[256]; strcpy(currentDir, argv[0]); char* cptr = currentDir; int i, len = strlen(currentDir); for(i=len-1; i>0; i--){ if(cptr[i] == '\\' || cptr[i] == '/') break; } cptr[i] = '\0'; ons.setArchivePath(currentDir); ons.disableRescale(); ons.enableButtonShortCut(); #elif defined(ANDROID) ons.enableButtonShortCut(); #endif #if defined(IOS) NSArray* paths; NSString* path; paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); path = [paths objectAtIndex:0]; char filename[256]; strcpy(filename, [path UTF8String]); ons.setArchivePath(filename); #if defined(ZIP_URL) if ([[[DataDownloader alloc] init] download]) exit(-1); #endif #endif // ---------------------------------------- // Parse options argv++; while( argc > 1 ){ if ( argv[0][0] == '-' ){ if ( !strcmp( argv[0]+1, "h" ) || !strcmp( argv[0]+1, "-help" ) ){ optionHelp(); } else if ( !strcmp( argv[0]+1, "v" ) || !strcmp( argv[0]+1, "-version" ) ){ optionVersion(); } else if ( !strcmp( argv[0]+1, "-cdaudio" ) ){ ons.enableCDAudio(); } else if ( !strcmp( argv[0]+1, "-cdnumber" ) ){ argc--; argv++; ons.setCDNumber(atoi(argv[0])); } else if ( !strcmp( argv[0]+1, "f" ) || !strcmp( argv[0]+1, "-font" ) ){ argc--; argv++; ons.setFontFile(argv[0]); } else if ( !strcmp( argv[0]+1, "-registry" ) ){ argc--; argv++; ons.setRegistryFile(argv[0]); } else if ( !strcmp( argv[0]+1, "-dll" ) ){ argc--; argv++; ons.setDLLFile(argv[0]); } else if ( !strcmp( argv[0]+1, "r" ) || !strcmp( argv[0]+1, "-root" ) ){ argc--; argv++; ons.setArchivePath(argv[0]); } else if ( !strcmp( argv[0]+1, "-fullscreen" ) ){ ons.setFullscreenMode(); } else if ( !strcmp( argv[0]+1, "-window" ) ){ ons.setWindowMode(); } else if ( !strcmp( argv[0]+1, "-force-button-shortcut" ) ){ ons.enableButtonShortCut(); } else if ( !strcmp( argv[0]+1, "-enable-wheeldown-advance" ) ){ ons.enableWheelDownAdvance(); } else if ( !strcmp( argv[0]+1, "-render-font-outline")){ ons.renderFontOutline(); } else if ( !strcmp( argv[0]+1, "-disable-rescale" ) ){ ons.disableRescale(); } else if ( !strcmp( argv[0]+1, "-edit" ) ){ ons.enableEdit(); } else if ( !strcmp( argv[0]+1, "-key-exe" ) ){ argc--; argv++; ons.setKeyEXE(argv[0]); } else if ( !strcmp( argv[0]+1, "-wide") ){ ons.setWideMode(); } else if ( !strcmp(argv[0]+1, "-full")){ ons.setFullMode(); } #if defined(ANDROID) else if ( !strcmp( argv[0]+1, "-open-only" ) ){ argc--; argv++; if (ons.openScript()) exit(-1); return 0; } #endif else{ printf(" unknown option %s\n", argv[0] ); } } else{ optionHelp(); } argc--; argv++; } // ---------------------------------------- // Run ONScripter if (ons.openScript()) exit(-1); if (ons.init()) exit(-1); ons.executeLabel(); exit(0); }
[ "287935387@qq.com" ]
287935387@qq.com
4f442e301a676c0cf1942c4e83933d5d9945d42b
e9a4346e9dddf2b6f9e5d8c76af5fd4be7e693dc
/net/quic/crypto/aead_base_decrypter.h
2217ec95b6352ea5d43107e9936fcbb70e6d0598
[ "BSD-3-Clause" ]
permissive
lauer3912/chromium.src
6999d382122f65bf09244fd733d1892d29833301
969c559f5e43b329295b68c49ae9bf46a833395c
refs/heads/nw
2022-07-20T00:57:09.588885
2014-06-20T04:30:37
2014-06-20T04:30:37
21,058,952
0
0
BSD-3-Clause
2022-07-06T21:18:27
2014-06-21T03:06:32
C++
UTF-8
C++
false
false
3,576
h
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef NET_QUIC_CRYPTO_AEAD_BASE_DECRYPTER_H_ #define NET_QUIC_CRYPTO_AEAD_BASE_DECRYPTER_H_ #include "base/compiler_specific.h" #include "net/quic/crypto/quic_decrypter.h" #if defined(USE_OPENSSL) #include "net/quic/crypto/scoped_evp_aead_ctx.h" #else #include <pkcs11t.h> #include <seccomon.h> typedef struct PK11SymKeyStr PK11SymKey; typedef SECStatus (*PK11_DecryptFunction)( PK11SymKey* symKey, CK_MECHANISM_TYPE mechanism, SECItem* param, unsigned char* out, unsigned int* outLen, unsigned int maxLen, const unsigned char* enc, unsigned encLen); #endif namespace net { // AeadBaseDecrypter is the base class of AEAD QuicDecrypter subclasses. class NET_EXPORT_PRIVATE AeadBaseDecrypter : public QuicDecrypter { public: #if defined(USE_OPENSSL) AeadBaseDecrypter(const EVP_AEAD* aead_alg, size_t key_size, size_t auth_tag_size, size_t nonce_prefix_size); #else AeadBaseDecrypter(CK_MECHANISM_TYPE aead_mechanism, PK11_DecryptFunction pk11_decrypt, size_t key_size, size_t auth_tag_size, size_t nonce_prefix_size); #endif virtual ~AeadBaseDecrypter(); // QuicDecrypter implementation virtual bool SetKey(base::StringPiece key) OVERRIDE; virtual bool SetNoncePrefix(base::StringPiece nonce_prefix) OVERRIDE; virtual bool Decrypt(base::StringPiece nonce, base::StringPiece associated_data, base::StringPiece ciphertext, unsigned char* output, size_t* output_length) OVERRIDE; virtual QuicData* DecryptPacket(QuicPacketSequenceNumber sequence_number, base::StringPiece associated_data, base::StringPiece ciphertext) OVERRIDE; virtual base::StringPiece GetKey() const OVERRIDE; virtual base::StringPiece GetNoncePrefix() const OVERRIDE; protected: // Make these constants available to the subclasses so that the subclasses // can assert at compile time their key_size_ and nonce_prefix_size_ do not // exceed the maximum. static const size_t kMaxKeySize = 32; static const size_t kMaxNoncePrefixSize = 4; #if !defined(USE_OPENSSL) struct AeadParams { unsigned int len; union { CK_GCM_PARAMS gcm_params; #if !defined(USE_NSS) // USE_NSS means we are using system NSS rather than our copy of NSS. // The system NSS <pkcs11n.h> header doesn't define this type yet. CK_NSS_AEAD_PARAMS nss_aead_params; #endif } data; }; virtual void FillAeadParams(base::StringPiece nonce, base::StringPiece associated_data, size_t auth_tag_size, AeadParams* aead_params) const = 0; #endif // !defined(USE_OPENSSL) private: #if defined(USE_OPENSSL) const EVP_AEAD* const aead_alg_; #else const CK_MECHANISM_TYPE aead_mechanism_; const PK11_DecryptFunction pk11_decrypt_; #endif const size_t key_size_; const size_t auth_tag_size_; const size_t nonce_prefix_size_; // The key. unsigned char key_[kMaxKeySize]; // The nonce prefix. unsigned char nonce_prefix_[kMaxNoncePrefixSize]; #if defined(USE_OPENSSL) ScopedEVPAEADCtx ctx_; #endif }; } // namespace net #endif // NET_QUIC_CRYPTO_AEAD_BASE_DECRYPTER_H_
[ "wtc@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98" ]
wtc@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98
cb87a8979f4fa79f74287a34153abc749cbdb9cd
91e43f2585c05f30d406c1c524bbf49f9b8634e7
/src/sta.h
fa8e1423179ea3a5754da7188b9fc5c4f67c6b66
[]
no_license
hb4837/cpphdl
f757dd7cbbf7ec712027e8b8ecbdb3ed5848c4bc
c0e0f9cb152cb0af132868d9e16a1f5a2baf2cd4
refs/heads/master
2021-01-18T18:29:45.198844
2016-06-20T19:31:05
2016-06-20T19:31:05
61,569,476
0
0
null
null
null
null
UTF-8
C++
false
false
1,064
h
#ifndef STA_H #define STA_H #include <list> #include <map> #include <algorithm> #include "sim.h" #include "model.h" #include "equation.h" #include "node.h" #include "quantity.h" #include "matrix.h" using namespace std; class op { public: static int monitor; class newton { public: static int itlim; static double abstol; static double reltol; static double vntol; }; // class ramp { // public: // class src { // public: // static int itlim; // static double step; // }; // }; }; class sta : public sim { private: map<string, node *> nodes; map<string, quantity_ *> currents; double t; int numNodes; int numUnknowns; matrix *g; bool conv; public: sta(); // sta(const sta& orig); virtual ~sta(); double time() const; void op(); void print() const; private: void init(); void load(); int iterate(const int& , const int&); void solve(); bool convergence(); void printSolution(); }; #endif /* STA_H */
[ "berndabel@hotmail.com" ]
berndabel@hotmail.com
2f95136ed21fcd3e3cae5ccbbec789f26c82f62f
7891fdfbbf23acff3ce75a2b0f776645e3e2d5f8
/Tree/SkipedTable.cpp
984204fdc67618c2c41be5e52908145d7c04ed41
[]
no_license
qwb492859377/interview_problemset
378bd76c1d415e007f3a709f4321a5b51a65e3ed
9592c6225904220a3eb556c019cb81503fd55479
refs/heads/master
2021-01-01T20:40:31.322707
2017-08-29T05:44:06
2017-08-29T05:44:06
98,911,736
2
0
null
null
null
null
UTF-8
C++
false
false
3,184
cpp
#include <ctime> #include <cstdio> #include <cstdlib> #include <climits> #include <cstring> #include <cassert> #include <algorithm> using namespace std; // 感觉我的跳跃表慢的出翔。。 class SkipedTable { private: static const int MAX_HEIGHT = 30; const int INF = INT_MAX; const double P = 0.25; struct Node { int val; Node *up, *down; Node *left, *right; Node(int _val) { val = _val; up = down = NULL; left = right = NULL; } }; Node *head[MAX_HEIGHT]; int min(int a, int b) { return a < b ? a : b; } int get_random_height() { int ret = 1; while(true) { double p = 1.0 * rand() / RAND_MAX; if(p <= P) ret++; else break; } return min(ret, MAX_HEIGHT - 1); } public: int height; SkipedTable() { // srand(time(NULL)); for(int i = 1; i < MAX_HEIGHT; i++) { head[i] = NULL; } height = 1; Node *a = new Node(-INF), *b = new Node(INF); a->right = b; b->left = a; head[height] = a; } void insert(int x) { Node *now = head[height]; for(int i = height; i >= 1; i--) { while(now->right->val < x) { now = now->right; } if (i != 1) { now = now->down; } } Node *end_inf = head[height]; while(end_inf->right != NULL) { end_inf = end_inf->right; } int h = get_random_height(); for(int i = height + 1; i <= h; i++) { Node *a = new Node(-INF), *b = new Node(INF); a->right = b; b->left = a; head[i] = a; a->down = head[i - 1]; head[i - 1]->up = a; b->down = end_inf; end_inf->up = b; end_inf = b; } Node *last = NULL; height = max(height, h); for(int i = 1; i <= height; i++) { Node *temp = new Node(x); if(last != NULL) { temp->down = last; last->up = temp; } last = temp; temp->right = now->right; now->right->left = temp; temp->left = now; now->right = temp; if(i != height) { while(now->up == NULL) { now = now->left; } now = now->up; } } } bool exists(int x) { Node *now = head[height]; now = head[height]; for(int i = height; i >= 1; i--) { while(now->right->val < x) { now = now->right; } if(now->right->val == x) { return true; } if(i != 1) { now = now->down; } } return false; } }; const int MX = 2e4; int A[MX]; int main() { SkipedTable set; for(int i = 0; i < MX; i++) { A[i] = i; } random_shuffle(A, A + MX); for(int i = 0; i < MX; i++) { set.insert(A[i]); } printf("%d\n", set.height); return 0; }
[ "qwb@csustacm.com" ]
qwb@csustacm.com
f8a2baa808fe0e9be8a9feb065464fb03592f76a
61f39de0bcb8f0dc6e0d51437af4bd6216eb074b
/Thread_Pool/Thread_Pool/Thread.h
b24bfd92a135d1fa5f6fc2059e5b3cd837a8ac94
[]
no_license
MarySoroka/OSASP-2
93a76d08cd14d66f1f4c9edbf19601d163f51743
70c997b0f58a3a2886654fc97feaf82572038c95
refs/heads/main
2023-01-22T23:42:17.680293
2020-11-23T18:11:08
2020-11-23T18:11:08
306,828,842
0
0
null
null
null
null
UTF-8
C++
false
false
208
h
#pragma once #include <windows.h> #include "Task.h" class Thread { public: Thread(); ~Thread(); CRITICAL_SECTION crSection; CONDITION_VARIABLE cnVariable; Task* taskForExecution; BOOL alive; };
[ "m.soroka.01.06.01@gmail.com" ]
m.soroka.01.06.01@gmail.com
ee8aac83d3f62072469d444187d137676d29a44b
c42be4f643faf558061bfa04cf11b46cf47a45d9
/cv018_ChromaKeyProcessing/cv018_ChromaKeyProcessing/cv018_ChromaKeyProcessing.cpp
e8ec25231c0d3a935f9fd250d8c5decc0e1df76f
[]
no_license
freeman-as/OpenCV_study
c617949fe194dc72e92714c557cc95d8033daa5e
23c73652b53b3af2ef602d103d826ae7f4cc8e75
refs/heads/master
2020-04-13T04:48:55.321738
2019-02-03T14:19:17
2019-02-03T14:19:17
162,972,046
0
0
null
null
null
null
UTF-8
C++
false
false
2,027
cpp
#include "pch.h" #include <opencv2/opencv.hpp> #pragma comment(lib, "opencv_world343d.lib") using namespace std; using namespace cv; static const string DATA_PATH = "../../data/"; int main() { Mat src1, src2, mask, dst, hsv; VideoCapture cap1(DATA_PATH + "video.avi"), cap2(DATA_PATH + "duck_greenback.avi"); //cap2(DATA_PATH + "color_chart.jpg"); vector<Mat> ch(3); // 色相範囲ウィンドウと色相環の生成 Mat imgHue1(Size(300, 300), CV_8UC3, Scalar::all(0)), imgHue2; for (int h = 0; h < 180; h++) { ellipse(imgHue1, Point(150, 150), Size(120, 120), -90, 2 * h - 1, 2 * h + 1, Scalar(h, 255, 255), -1); } cvtColor(imgHue1, imgHue1, COLOR_HSV2BGR); imshow("色相範囲", imgHue1); // 色相範囲初期値 int minTrack = 30, maxTrack = 110; createTrackbar("最小値", "色相範囲", &minTrack, 180); createTrackbar("最大値", "色相範囲", &maxTrack, 180); while (1) { cap1 >> src1; if (src1.empty()) break; cap2 >> src2; if (src2.empty()) break; // src2をsrc1のサイズにあわせる resize(src2, src2, src1.size()); // BGR > HSV変換合成 cvtColor(src2, hsv, COLOR_BGR2HSV); split(hsv, ch); // HSVのHからマスク画像生成 int maxH = max(maxTrack, minTrack); int minH = min(maxTrack, minTrack); // 上限 threshold(ch[0], mask, maxH, 255, THRESH_TOZERO_INV); // 下限 threshold(mask, mask, minH, 255, THRESH_BINARY); // ノイズ除去 morphologyEx(mask, mask, MORPH_OPEN, noArray(), Point(-1, -1), 2); // 合成 // アヒル映像を全部コピー src2.copyTo(dst); // 入力映像をマスク src1.copyTo(dst, mask); // 色相環と範囲の描画 imgHue1.copyTo(imgHue2); ellipse(imgHue2, Point(150, 150), Size(130, 130), -90, 2 * minH - 1, 2 * maxH + 1, Scalar::all(255), 16); imshow("マスク映像", mask); imshow("合成映像", dst); imshow("色相範囲", imgHue2); if (waitKey(20) == 27) break; } return 0; }
[ "freeman.by2018@gmail.com" ]
freeman.by2018@gmail.com
5b6521f270a8ce2ec4ea16f9d38282a901a07de2
e1fd1f93a6e322e6650023ae7824db172d9ce2f4
/mdprl/include/mc_example/vehicle_physics.hpp
d310e91fed399deb5d03a874cf94d9a62c8774f9
[]
no_license
yukonhenry/mdprl
9153505b3eac77d553e12a9c6459951f7270e831
14247aa8e0875eb4b56a359b5743070bf359efb2
refs/heads/master
2020-04-15T03:47:40.551705
2019-02-15T18:24:06
2019-02-15T18:24:06
164,360,374
0
0
null
null
null
null
UTF-8
C++
false
false
565
hpp
// // vehicle_physics.hpp // mdprl // // Created by Henry Tominaga on 11/4/18. // Copyright © 2018 Henry Tominaga. All rights reserved. // #ifndef vehicle_physics_hpp #define vehicle_physics_hpp #include <iostream> #include "racetrack_vehicle.hpp" const int kMinimumVelocity = 0; const int kMaximumVelocity = 5; Position VehicleMove(const Position&, const Velocity&); Velocity VehicleAccel(const Velocity&, const Accel&); Position VehicleMoveWithAccel(const Position&, const Velocity&, const Accel&); int BoundVelocity(int); #endif /* vehicle_physics_hpp */
[ "htominaga@grubhub.com" ]
htominaga@grubhub.com
8bfa48f949602c0f405bd5d688889cbd0e43b25a
5456502f97627278cbd6e16d002d50f1de3da7bb
/base/threading/thread_perftest.cc
87c47b01d504d88647d40559adb8284892821bca
[ "BSD-3-Clause" ]
permissive
TrellixVulnTeam/Chromium_7C66
72d108a413909eb3bd36c73a6c2f98de1573b6e5
c8649ab2a0f5a747369ed50351209a42f59672ee
refs/heads/master
2023-03-16T12:51:40.231959
2017-12-20T10:38:26
2017-12-20T10:38:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,519
cc
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <stddef.h> #include "base/base_switches.h" #include "base/bind.h" #include "base/command_line.h" #include "base/location.h" #include "base/memory/scoped_vector.h" #include "base/single_thread_task_runner.h" #include "base/strings/stringprintf.h" #include "base/synchronization/condition_variable.h" #include "base/synchronization/lock.h" #include "base/synchronization/waitable_event.h" #include "base/threading/thread.h" #include "base/time/time.h" #include "build/build_config.h" #include "testing/gtest/include/gtest/gtest.h" #include "testing/perf/perf_test.h" #if defined(OS_POSIX) #include <pthread.h> #endif namespace base { namespace { const int kNumRuns = 100000; // Base class for a threading perf-test. This sets up some threads for the // test and measures the clock-time in addition to time spent on each thread. class ThreadPerfTest : public testing::Test { public: ThreadPerfTest() : done_(WaitableEvent::ResetPolicy::AUTOMATIC, WaitableEvent::InitialState::NOT_SIGNALED) { // Disable the task profiler as it adds significant cost! CommandLine::Init(0, NULL); CommandLine::ForCurrentProcess()->AppendSwitchASCII( switches::kProfilerTiming, switches::kProfilerTimingDisabledValue); } // To be implemented by each test. Subclass must uses threads_ such that // their cpu-time can be measured. Test must return from PingPong() _and_ // call FinishMeasurement from any thread to complete the test. virtual void Init() { if (ThreadTicks::IsSupported()) ThreadTicks::WaitUntilInitialized(); } virtual void PingPong(int hops) = 0; virtual void Reset() {} void TimeOnThread(base::ThreadTicks* ticks, base::WaitableEvent* done) { *ticks = base::ThreadTicks::Now(); done->Signal(); } base::ThreadTicks ThreadNow(base::Thread* thread) { base::WaitableEvent done(WaitableEvent::ResetPolicy::AUTOMATIC, WaitableEvent::InitialState::NOT_SIGNALED); base::ThreadTicks ticks; thread->task_runner()->PostTask( FROM_HERE, base::Bind(&ThreadPerfTest::TimeOnThread, base::Unretained(this), &ticks, &done)); done.Wait(); return ticks; } void RunPingPongTest(const std::string& name, unsigned num_threads) { // Create threads and collect starting cpu-time for each thread. std::vector<base::ThreadTicks> thread_starts; while (threads_.size() < num_threads) { threads_.push_back(new base::Thread("PingPonger")); threads_.back()->Start(); if (base::ThreadTicks::IsSupported()) thread_starts.push_back(ThreadNow(threads_.back())); } Init(); base::TimeTicks start = base::TimeTicks::Now(); PingPong(kNumRuns); done_.Wait(); base::TimeTicks end = base::TimeTicks::Now(); // Gather the cpu-time spent on each thread. This does one extra tasks, // but that should be in the noise given enough runs. base::TimeDelta thread_time; while (threads_.size()) { if (base::ThreadTicks::IsSupported()) { thread_time += ThreadNow(threads_.back()) - thread_starts.back(); thread_starts.pop_back(); } threads_.pop_back(); } Reset(); double num_runs = static_cast<double>(kNumRuns); double us_per_task_clock = (end - start).InMicroseconds() / num_runs; double us_per_task_cpu = thread_time.InMicroseconds() / num_runs; // Clock time per task. perf_test::PrintResult( "task", "", name + "_time ", us_per_task_clock, "us/hop", true); // Total utilization across threads if available (likely higher). if (base::ThreadTicks::IsSupported()) { perf_test::PrintResult( "task", "", name + "_cpu ", us_per_task_cpu, "us/hop", true); } } protected: void FinishMeasurement() { done_.Signal(); } ScopedVector<base::Thread> threads_; private: base::WaitableEvent done_; }; // Class to test task performance by posting empty tasks back and forth. class TaskPerfTest : public ThreadPerfTest { base::Thread* NextThread(int count) { return threads_[count % threads_.size()]; } void PingPong(int hops) override { if (!hops) { FinishMeasurement(); return; } NextThread(hops)->task_runner()->PostTask( FROM_HERE, base::Bind(&ThreadPerfTest::PingPong, base::Unretained(this), hops - 1)); } }; // This tries to test the 'best-case' as well as the 'worst-case' task posting // performance. The best-case keeps one thread alive such that it never yeilds, // while the worse-case forces a context switch for every task. Four threads are // used to ensure the threads do yeild (with just two it might be possible for // both threads to stay awake if they can signal each other fast enough). TEST_F(TaskPerfTest, TaskPingPong) { RunPingPongTest("1_Task_Threads", 1); RunPingPongTest("4_Task_Threads", 4); } // Same as above, but add observers to test their perf impact. class MessageLoopObserver : public base::MessageLoop::TaskObserver { public: void WillProcessTask(const base::PendingTask& pending_task) override {} void DidProcessTask(const base::PendingTask& pending_task) override {} }; MessageLoopObserver message_loop_observer; class TaskObserverPerfTest : public TaskPerfTest { public: void Init() override { TaskPerfTest::Init(); for (size_t i = 0; i < threads_.size(); i++) { threads_[i]->message_loop()->AddTaskObserver(&message_loop_observer); } } }; TEST_F(TaskObserverPerfTest, TaskPingPong) { RunPingPongTest("1_Task_Threads_With_Observer", 1); RunPingPongTest("4_Task_Threads_With_Observer", 4); } // Class to test our WaitableEvent performance by signaling back and fort. // WaitableEvent is templated so we can also compare with other versions. template <typename WaitableEventType> class EventPerfTest : public ThreadPerfTest { public: void Init() override { for (size_t i = 0; i < threads_.size(); i++) { events_.push_back( new WaitableEventType(WaitableEvent::ResetPolicy::AUTOMATIC, WaitableEvent::InitialState::NOT_SIGNALED)); } } void Reset() override { events_.clear(); } void WaitAndSignalOnThread(size_t event) { size_t next_event = (event + 1) % events_.size(); int my_hops = 0; do { events_[event]->Wait(); my_hops = --remaining_hops_; // We own 'hops' between Wait and Signal. events_[next_event]->Signal(); } while (my_hops > 0); // Once we are done, all threads will signal as hops passes zero. // We only signal completion once, on the thread that reaches zero. if (!my_hops) FinishMeasurement(); } void PingPong(int hops) override { remaining_hops_ = hops; for (size_t i = 0; i < threads_.size(); i++) { threads_[i]->task_runner()->PostTask( FROM_HERE, base::Bind(&EventPerfTest::WaitAndSignalOnThread, base::Unretained(this), i)); } // Kick off the Signal ping-ponging. events_.front()->Signal(); } int remaining_hops_; ScopedVector<WaitableEventType> events_; }; // Similar to the task posting test, this just tests similar functionality // using WaitableEvents. We only test four threads (worst-case), but we // might want to craft a way to test the best-case (where the thread doesn't // end up blocking because the event is already signalled). typedef EventPerfTest<base::WaitableEvent> WaitableEventPerfTest; TEST_F(WaitableEventPerfTest, EventPingPong) { RunPingPongTest("4_WaitableEvent_Threads", 4); } // Build a minimal event using ConditionVariable. class ConditionVariableEvent { public: ConditionVariableEvent(WaitableEvent::ResetPolicy reset_policy, WaitableEvent::InitialState initial_state) : cond_(&lock_), signaled_(false) { DCHECK_EQ(WaitableEvent::ResetPolicy::AUTOMATIC, reset_policy); DCHECK_EQ(WaitableEvent::InitialState::NOT_SIGNALED, initial_state); } void Signal() { { base::AutoLock scoped_lock(lock_); signaled_ = true; } cond_.Signal(); } void Wait() { base::AutoLock scoped_lock(lock_); while (!signaled_) cond_.Wait(); signaled_ = false; } private: base::Lock lock_; base::ConditionVariable cond_; bool signaled_; }; // This is meant to test the absolute minimal context switching time // using our own base synchronization code. typedef EventPerfTest<ConditionVariableEvent> ConditionVariablePerfTest; TEST_F(ConditionVariablePerfTest, EventPingPong) { RunPingPongTest("4_ConditionVariable_Threads", 4); } #if defined(OS_POSIX) // Absolutely 100% minimal posix waitable event. If there is a better/faster // way to force a context switch, we should use that instead. class PthreadEvent { public: PthreadEvent(WaitableEvent::ResetPolicy reset_policy, WaitableEvent::InitialState initial_state) { DCHECK_EQ(WaitableEvent::ResetPolicy::AUTOMATIC, reset_policy); DCHECK_EQ(WaitableEvent::InitialState::NOT_SIGNALED, initial_state); pthread_mutex_init(&mutex_, 0); pthread_cond_init(&cond_, 0); signaled_ = false; } ~PthreadEvent() { pthread_cond_destroy(&cond_); pthread_mutex_destroy(&mutex_); } void Signal() { pthread_mutex_lock(&mutex_); signaled_ = true; pthread_mutex_unlock(&mutex_); pthread_cond_signal(&cond_); } void Wait() { pthread_mutex_lock(&mutex_); while (!signaled_) pthread_cond_wait(&cond_, &mutex_); signaled_ = false; pthread_mutex_unlock(&mutex_); } private: bool signaled_; pthread_mutex_t mutex_; pthread_cond_t cond_; }; // This is meant to test the absolute minimal context switching time. // If there is any faster way to do this we should substitute it in. typedef EventPerfTest<PthreadEvent> PthreadEventPerfTest; TEST_F(PthreadEventPerfTest, EventPingPong) { RunPingPongTest("4_PthreadCondVar_Threads", 4); } #endif } // namespace } // namespace base
[ "lixiaodonglove7@aliyun.com" ]
lixiaodonglove7@aliyun.com
bee98f63ca1598584d5ea1840f5a562b05b60cca
25a1c0926700b4daee3c8afae055e74b02f7227a
/app/src/main/cpp/jni_bridge.cpp
59213ad46740c083f9d6c2986bd75dbf93ba12db
[]
no_license
freeDevelope/FaceDetectAndroid2
ea00d80908193d9331fb8214dd821d49f2d90003
a7a19c35d2c0cb60c620350ad2891b00c81a3487
refs/heads/master
2020-03-19T02:46:57.933805
2018-06-01T03:07:30
2018-06-01T03:07:30
135,660,146
0
0
null
null
null
null
UTF-8
C++
false
false
6,518
cpp
#define LOG_TAG "jni_bridge" #include "jni_bridge.h" #include <assert.h> #define info(...) __android_log_print(ANDROID_LOG_INFO, "MaiPai", __VA_ARGS__) // **************** Java to C++ **************** // uint32_t getNativeColor(jint _color) { // @see http://stackoverflow.com/questions/1751346/interpret-signed-as-unsigned // Should one use static_cast or reinterpret_cast between signed and unsigned integers? uint32_t color = static_cast<uint32_t>(_color); // Android/Java #Color use #AARRGGBB, namely BGRA in memory layout, while native // layer use #AABBGGRR, namely RGBA memory layout, need a swap(R, B) here. uint8_t* bytes = reinterpret_cast<uint8_t*>(&color); uint8_t tmp = bytes[0]; bytes[0] = bytes[2]; bytes[2] = tmp; return color; } std::string getNativeString(JNIEnv *env, jstring _str) { const char *str = env->GetStringUTFChars(_str, nullptr); std::string result(str); env->ReleaseStringUTFChars(_str, str); // DON'T forget to release strings return result; } cv::Mat* getNativeMat(JNIEnv *env, jobject _mat) { jclass class_Mat = env->FindClass("org/opencv/core/Mat"); jmethodID method_getNativeObjAddr = env->GetMethodID(class_Mat, "getNativeObjAddr", "()J"); assert(class_Mat != nullptr && method_getNativeObjAddr != nullptr); jlong pointer = env->CallLongMethod(_mat, method_getNativeObjAddr); return reinterpret_cast<cv::Mat*>(pointer); } /** * @author yuyuankun * @Description 获取C++对象的人脸矩形框 * @param _rect java对象的人脸矩形框 * @return C++对象的人脸矩形框 */ cv::Rect getNativeRect(JNIEnv *env, jobject _rect) { jclass class_Rect = env->FindClass("org/opencv/core/Rect");//获取class对象 jfieldID field_x = env->GetFieldID(class_Rect, "x", "I"); jfieldID field_y = env->GetFieldID(class_Rect, "y", "I"); jfieldID field_width = env->GetFieldID(class_Rect, "width", "I"); jfieldID field_height = env->GetFieldID(class_Rect, "height", "I"); assert(class_Rect != nullptr); assert(field_x != nullptr && field_y != nullptr && field_width != nullptr && field_height != nullptr); jfloat x = env->GetIntField(_rect, field_x); jfloat y = env->GetIntField(_rect, field_y); jfloat width = env->GetIntField(_rect, field_width); jfloat height = env->GetIntField(_rect, field_height); return cv::Rect(x, y, width, height); } // This is the Point that reside in android.graphic.Point, not org.opencv.core.Point cv::Point2f getNativePoint(JNIEnv *env, jobject _point) { jclass class_PointF = env->FindClass("android/graphics/PointF"); jfieldID field_x = env->GetFieldID(class_PointF, "x", "F"); jfieldID field_y = env->GetFieldID(class_PointF, "y", "F"); assert(class_PointF != nullptr); assert(field_x != nullptr && field_y != nullptr); jfloat x = env->GetFloatField(_point, field_x); jfloat y = env->GetFloatField(_point, field_y); return cv::Point2f(x, y); } std::vector<cv::Point2f> getNativePointArray(JNIEnv *env, jobjectArray _points) { jclass class_PointF = env->FindClass("android/graphics/PointF"); jfieldID field_x = env->GetFieldID(class_PointF, "x", "F"); jfieldID field_y = env->GetFieldID(class_PointF, "y", "F"); assert(class_PointF != nullptr); assert(field_x != nullptr && field_y != nullptr); // Get<Primitive>ArrayRegion, no GetObjectArrayRegion method, fetch element one by one. jsize feature_point_count = env->GetArrayLength(_points); std::vector<cv::Point2f> points(feature_point_count); for(jsize i = 0; i < feature_point_count; ++i) { jobject element = env->GetObjectArrayElement(_points, i); float x = env->GetFloatField(element, field_x); float y = env->GetFloatField(element, field_y); points[i] = cv::Point2f(x, y); env->DeleteLocalRef(element); } return points; } #ifdef ANDROID uint32_t* lockJavaBitmap(JNIEnv* env, jobject bitmap, AndroidBitmapInfo& info) { // https://developer.android.com/ndk/reference/group___bitmap.html int ret = AndroidBitmap_getInfo(env, bitmap, &info); if(ret < 0) { LOGE("AndroidBitmap_getInfo() failed ! error = %d", ret); return nullptr; } // LOGD("width:%d height:%d stride:%d", info.width, info.height, info.stride); uint32_t* pixels; ret = AndroidBitmap_lockPixels(env, bitmap, reinterpret_cast<void**>(&pixels)); if(ret < 0) { LOGE("AndroidBitmap_lockPixels() failed ! error = %d", ret); return nullptr; } return pixels; } void unlockJavaBitmap(JNIEnv* env, jobject bitmap) { AndroidBitmap_unlockPixels(env, bitmap); } #endif // ANDROID // **************** C++ to Java **************** // jobject getJavaMat(JNIEnv *env, const cv::Mat& mat) { jclass class_Mat = env->FindClass("org/opencv/core/Mat"); jmethodID method_Mat = env->GetMethodID(class_Mat, "<init>", "()V"); assert(class_Mat != nullptr && method_Mat != nullptr); jobject Mat_result = env->NewObject(class_Mat, method_Mat); jmethodID method_getNativeObjAddr = env->GetMethodID(class_Mat, "getNativeObjAddr", "()J"); cv::Mat* ptr_result = reinterpret_cast<cv::Mat*>(env->CallLongMethod(Mat_result, method_getNativeObjAddr)); assert(method_getNativeObjAddr != nullptr && ptr_result != nullptr); *ptr_result = mat; return Mat_result; } jobject getJavaPoint(JNIEnv *env, const cv::Point2f& point) { jclass class_PointF = env->FindClass("android/graphics/PointF"); jmethodID method_PointF = env->GetMethodID(class_PointF, "<init>", "(FF)V"); assert(class_PointF != nullptr && method_PointF != nullptr); return env->NewObject(class_PointF, method_PointF, point.x, point.y); } void setJavaPoint(JNIEnv *env, jobject _point, const cv::Point2f& point) { jclass class_PointF = env->FindClass("android/graphics/PointF"); jfieldID field_x = env->GetFieldID(class_PointF, "x", "F"); jfieldID field_y = env->GetFieldID(class_PointF, "y", "F"); assert(class_PointF != nullptr); assert(field_x != nullptr && field_y != nullptr); env->SetFloatField(_point, field_x, point.x); env->SetFloatField(_point, field_y, point.y); } void setJavaPointArray(JNIEnv *env, jobjectArray _array, const std::vector<cv::Point2f>& points) { jclass class_PointF = env->FindClass("android/graphics/PointF"); jmethodID method_PointF = env->GetMethodID(class_PointF, "<init>", "(FF)V"); assert(class_PointF != nullptr && method_PointF != nullptr); const size_t count = points.size(); for(size_t i = 0; i < count; ++i) { const cv::Point2f& point = points[i]; jobject object_point = env->NewObject(class_PointF, method_PointF, point.x, point.y); env->SetObjectArrayElement(_array, i, object_point); } }
[ "wph_Xidian@outlook.com" ]
wph_Xidian@outlook.com
473a93bc40b8342795c4d765b0fca5da1f216083
00d8eef608f063874a0f7f4377244c28338f3b75
/LBE/3_object_And_Classes/myExample.cpp
16d5689884344a7005f686e7e3bf27079ef26a08
[]
no_license
kornava/CppSamples
6afc1e2ec8d9b933ab60363a53f592bd11354de3
98de55bf0670f039c9e606037432684341487444
refs/heads/master
2021-09-05T00:58:58.329939
2018-01-23T07:17:01
2018-01-23T07:17:01
105,474,661
0
0
null
null
null
null
UTF-8
C++
false
false
372
cpp
#include <iostream> using namespace std; class Vehicle{ int id; public: Vehicle(int x):id(x){ //return 5; } Vehicle(Vehicle &v):id(v.id){ } int getID(){ return id; } }; int main(){ std::cout<<"Hello world"<<std::endl; Vehicle v(4),B(13); cout<<"v = "<<v.getID()<<"B = "<<B.getID()<<endl; B=v; cout<<"v = "<<v.getID()<<"B = "<<B.getID()<<endl; return 0; }
[ "awainia@gmail.com" ]
awainia@gmail.com
042a0d4846d4da736a2081810b78074dce23fe0e
754e5bf82c9511bd5c1719e945689ee52523fd3a
/src/av_windows.cpp
4c4f6c245c8da1754433cc06716f56fbd87223a1
[]
no_license
dseeni/gct633
404273704fdc2120582f268f00c837a1e79ae56c
e93381309d4f93b4c1f75b3a5d8a1e4e8c5f0921
refs/heads/master
2023-07-01T03:42:12.433428
2013-12-17T06:27:44
2013-12-17T06:27:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,323
cpp
#include <stdlib.h> #include <stdio.h> #include <string.h> #include "av.hpp" // http://bobobobo.wordpress.com/2008/02/11/opengl-in-a-proper-windows-app-no-glut/ // http://msdn2.microsoft.com/en-us/library/ms673957%28VS.85%29.aspx // http://msdn2.microsoft.com/en-us/library/ms970745.aspx #include <windows.h> #include <math.h> #include <gl/gl.h> #include <gl/glu.h> #pragma comment(lib, "opengl32.lib") #pragma comment(lib, "glu32.lib") HINSTANCE ghInstance; // window app instance HWND ghwnd; // handle for the window HDC ghdc; // handle to device context HGLRC ghglrc; // handle to OpenGL rendering context int width = 800; int height = 600; LRESULT CALLBACK WndProc( HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam ); void draw(); // drawing function containing OpenGL function calls // entry point for a C++ Windows app: int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR szCmdLine, int iCmdShow) { ghInstance = hInstance; // add a console: AllocConsole() ; AttachConsole( GetCurrentProcessId() ) ; // http://lua-users.org/lists/lua-l/1999-08/msg00001.html //HANDLE Console = CreateConsoleScreenBuffer(GENERIC_READ|GENERIC_WRITE,0,0,CONSOLE_TEXTMODE_BUFFER,0); //SetConsoleActiveScreenBuffer(Console); //SetConsoleCtrlHandler((PHANDLER_ROUTINE)CtrlHandler, TRUE); SetConsoleTitle("av console"); //As for repositioning the window, you can do a FindWindow on the caption "av //console" and then a SetWindowPos on the HWND you get back. Not the most //elegant solution, but I doubt there's a better one. freopen("CON", "w", stdout) ; freopen("CON", "wt", stderr); freopen("CON", "rt", stdin); // create a window: WNDCLASS wc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hbrBackground = (HBRUSH)GetStockObject( BLACK_BRUSH ); wc.hCursor = LoadCursor( NULL, IDC_ARROW ); wc.hIcon = LoadIcon( NULL, IDI_APPLICATION ); wc.hInstance = hInstance; wc.lpfnWndProc = WndProc; wc.lpszClassName = TEXT("av"); wc.lpszMenuName = 0; wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; // register with Windows: RegisterClass(&wc); // adjust window client area: RECT rect; SetRect( &rect, 50, // left 50, // top width + 50, // right height + 50 ); // bottom AdjustWindowRect( &rect, WS_OVERLAPPEDWINDOW, false ); // create window: ghwnd = CreateWindow(TEXT("av"), TEXT("av"), WS_OVERLAPPEDWINDOW, rect.left, rect.top, // adjusted x, y positions rect.right - rect.left, rect.bottom - rect.top, // adjusted width and height NULL, NULL, hInstance, NULL); if( ghwnd == NULL ) { FatalAppExit( NULL, TEXT("CreateWindow() failed!") ); } ShowWindow( ghwnd, iCmdShow ); // get device context: ghdc = GetDC( ghwnd ); // set pixel format of window: // http://msdn2.microsoft.com/en-us/library/ms537556(VS.85).aspx PIXELFORMATDESCRIPTOR pfd = { 0 }; pfd.nSize = sizeof( PIXELFORMATDESCRIPTOR ); // just its size pfd.nVersion = 1; // always 1 pfd.dwFlags = PFD_SUPPORT_OPENGL | // OpenGL support - not DirectDraw PFD_DOUBLEBUFFER | // double buffering support PFD_DRAW_TO_WINDOW; // draw to the app window, not to a bitmap image pfd.iPixelType = PFD_TYPE_RGBA ; // red, green, blue, alpha for each pixel pfd.cColorBits = 24; // 24 bit == 8 bits for red, 8 for green, 8 for blue. pfd.cDepthBits = 32; // 32 bits to measure pixel depth // get best approximation of it: int chosenPixelFormat = ChoosePixelFormat( g.hdc, &pfd ); if( chosenPixelFormat == 0 ) { FatalAppExit( NULL, TEXT("ChoosePixelFormat() failed!") ); } // apply it: int result = SetPixelFormat( g.hdc, chosenPixelFormat, &pfd ); if (result == NULL) { FatalAppExit( NULL, TEXT("SetPixelFormat() failed!") ); } // create rendering context: ghglrc = wglCreateContext( ghdc ); // connect with device: wglMakeCurrent( ghdc, ghglrc ); //////////////////////////////////////////////////////////////////////////// // event loop: MSG msg; while( 1 ) { if( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) ) { if( msg.message == WM_QUIT ) { break; } TranslateMessage( &msg ); DispatchMessage( &msg ); } else { // check for async keyboard input here glViewport(0, 0, width, height); //6. DRAW USING OPENGL. // This region right here is the // heart of our application. THE MOST // execution time is spent just repeating // this draw() function. //draw(); SwapBuffers(ghdc); // SLEEP() } } // cleanup: wglMakeCurrent( NULL, NULL ); wglDeleteContext( ghglrc ); ReleaseDC( ghwnd, ghdc ); //CloseHandle(Console); FreeConsole(); // cheesy fadeout AnimateWindow( ghwnd, 200, AW_HIDE | AW_BLEND ); return msg.wParam; } LRESULT CALLBACK WndProc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam) { switch( message ) { case WM_CREATE: return 0; break; case WM_PAINT: { HDC hdc; PAINTSTRUCT ps; hdc = BeginPaint( hwnd, &ps ); // don't draw here. would be waaay too slow. // draw in the draw() function instead. EndPaint( hwnd, &ps ); } return 0; break; case WM_KEYDOWN: /* switch( wparam ) { case VK_ESCAPE: PostQuitMessage( 0 ); break; default: break; } */ return 0; break; case WM_DESTROY: PostQuitMessage( 0 ) ; return 0; break; } return DefWindowProc( hwnd, message, wparam, lparam ); }
[ "grrrwaaa@gmail.com" ]
grrrwaaa@gmail.com
b9be226996bf3d5a9073e2e5f35ca625d1dd16ea
e35939ddddd8302fe4e07aa4e1b3885f869ddda5
/Library/Wavelet-Matrix.cpp
c8074d7ab01ee46302b5bb3d20e558e2ecf95a97
[]
no_license
Pumpkin1e18/Library
16be5bbfb941e16fdc07888c887d6e7b7b49905d
045a0ee8a2ce4b83c156d7600bb8c74fd72ad37c
refs/heads/master
2020-03-27T21:44:21.686340
2018-09-15T19:59:20
2018-09-15T19:59:20
147,164,000
0
0
null
null
null
null
UTF-8
C++
false
false
6,601
cpp
//Wavelet-Matrix template<int N> class FID { static const int bucket = 512, block = 16; static char popcount[]; int n, B[N/bucket+10]; unsigned short bs[N/block+10], b[N/block+10]; public: FID(){} FID(int n, bool s[]) : n(n) { if(!popcount[1]) for (int i = 0; i < (1<<block); i++) popcount[i] = __builtin_popcount(i); bs[0] = B[0] = b[0] = 0; for (int i = 0; i < n; i++) { if(i%block == 0) { bs[i/block+1] = 0; if(i%bucket == 0) { B[i/bucket+1] = B[i/bucket]; b[i/block+1] = b[i/block] = 0; } else b[i/block+1] = b[i/block]; } bs[i/block] |= short(s[i])<<(i%block); b[i/block+1] += s[i]; B[i/bucket+1] += s[i]; } if(n%bucket == 0) b[n/block] = 0; } // number of val in [0,r), O(1) int count(bool val, int r) { return val? B[r/bucket]+b[r/block]+popcount[bs[r/block]&((1<<(r%block))-1)]: r-count(1,r); } // number of val in [l,r), O(1) int count(bool val, int l, int r) { return count(val,r)-count(val,l); } // position of ith in val, 0-indexed, O(log n) int select(bool val, int i) { if(i < 0 or count(val,n) <= i) return -1; i++; int lb = 0, ub = n, md; while(ub-lb>1) { md = (lb+ub)>>1; if(count(val,md) >= i) ub = md; else lb = md; } return ub-1; } int select(bool val, int i, int l) { return select(val,i+count(val,l)); } bool operator[](int i) { return bs[i/block]>>(i%block)&1; } }; template<int N> char FID<N>::popcount[1<<FID<N>::block]; template<class T, int N, int D> class wavelet { int n, zs[D]; FID<N> dat[D]; void max_dfs(int d, int l, int r, int &k, T val, vector<T> &vs) { if(l >= r or !k) return; if(d == D) { while(l++ < r and k > 0) vs.push_back(val), k--; return; } int lc = dat[d].count(1,l), rc = dat[d].count(1,r); // if min, change this order max_dfs(d+1, lc+zs[d], rc+zs[d], k, 1ULL<<(D-d-1)|val,vs); max_dfs(d+1, l-lc, r-rc, k, val, vs); } T max_dfs(int d, int l, int r, T val, T a, T b) { if(r-l <= 0 or val >= b) return -1; if(d == D) return val>=a? val: -1; int lc = dat[d].count(1,l), rc = dat[d].count(1,r); T ret = max_dfs(d+1, lc+zs[d], rc+zs[d], 1ULL<<(D-d-1)|val, a, b); if(~ret) return ret; return max_dfs(d+1, l-lc, r-rc, val, a, b); } int freq_dfs(int d, int l, int r, T val, T a, T b) { if(l == r) return 0; if(d == D) return (a <= val and val < b)? r-l: 0; T nv = 1ULL<<(D-d-1)|val, nnv = ((1ULL<<(D-d-1))-1)|nv; if(nnv < a or b <= val) return 0; if(a <= val and nnv < b) return r-l; int lc = dat[d].count(1,l), rc = dat[d].count(1,r); return freq_dfs(d+1,l-lc,r-rc,val,a,b)+ freq_dfs(d+1,lc+zs[d],rc+zs[d],nv,a,b); } void list_dfs(int d, int l, int r, T val, T a, T b, vector<pair<T,int>> &vs) { if(val >= b or r-l <= 0) return; if(d == D) { if(a <= val) vs.push_back(make_pair(val,r-l)); return; } T nv = val|(1LL<<(D-d-1)), nnv = nv|(((1LL<<(D-d-1))-1)); if(nnv < a) return; int lc = dat[d].count(1,l), rc = dat[d].count(1,r); list_dfs(d+1,l-lc,r-rc,val,a,b,vs); list_dfs(d+1,lc+zs[d],rc+zs[d],nv,a,b,vs); } public: wavelet(int n, T seq[]) : n(n) { T f[N], l[N], r[N]; bool b[N]; memcpy(f, seq, sizeof(T)*n); for (int d = 0; d < D; d++) { int lh = 0, rh = 0; for (int i = 0; i < n; i++) { bool k = (f[i]>>(D-d-1))&1; if(k) r[rh++] = f[i]; else l[lh++] = f[i]; b[i] = k; } dat[d] = FID<N>(n,b); zs[d] = lh; swap(l,f); memcpy(f+lh, r, rh*sizeof(T)); } } T get(int i) { T ret = 0; bool b; for (int d = 0; d < D; d++) { ret <<= 1; b = dat[d][i]; ret |= b; i = dat[d].count(b,i)+b*zs[d]; } return ret; } T operator[](int i) { return get(i); } int count(T val, int l, int r) { for (int d = 0; d < D; d++) { bool b = (val>>(D-d-1))&1; l = dat[d].count(b,l)+b*zs[d]; r = dat[d].count(b,r)+b*zs[d]; } return r-l; } int count(T val, int r) { return count(val,0,r); } int select(T val, int k) { int ls[D], rs[D], l = 0, r = n; for (int d = 0; d < D; d++) { ls[d] = l; rs[d] = r; bool b = val>>(D-d-1)&1; l = dat[d].count(b,l)+b*zs[d]; r = dat[d].count(b,r)+b*zs[d]; } for (int d = D-1; d >= 0; d--) { bool b = val>>(D-d-1)&1; k = dat[d].select(b,k,ls[d]); if(k >= rs[d] or k < 0) return -1; k -= ls[d]; } return k; } int select(T val, int k, int l) { return select(val,k+count(val,l)); } vector<T> maximum(int l, int r, int k) { if (r-l < k) k = r-l; if(k < 0) return {}; vector<T> ret; max_dfs(0,l,r,k,0,ret); return ret; } T maximum(int l, int r, T a, T b) { return max_dfs(0,l,r,0,a,b); } // k is 0-indexed T kth_number(int l, int r, int k) { if(r-l <= k or k < 0) return -1; T ret = 0; for (int d = 0; d < D; d++) { int lc = dat[d].count(1,l), rc = dat[d].count(1,r); if(rc-lc > k) { l = lc+zs[d]; r = rc+zs[d]; ret |= 1ULL<<(D-d-1); } else { k -= rc-lc; l -= lc; r -= rc; } } return ret; } vector<pair<T,int>> freq_list(int l, int r, T a, T b) { vector<pair<T,int>> ret; list_dfs(0,l,r,0,a,b,ret); return ret; } vector<pair<int,T>> get_rect(int l, int r, T a, T b) { vector<pair<T,int>> res = freq_list(l,r,a,b); vector<pair<int,T>> ret; for(auto &e: res) for (int i = 0; i < e.second; i++) ret.push_back(make_pair(select(e.first,i,l), e.first)); return ret; } // number of elements in [l,r) in [a,b), O(D) int freq(int l, int r, T a, T b) { return freq_dfs(0,l,r,0,a,b); } };
[ "pumpkin1e18@gmail.com" ]
pumpkin1e18@gmail.com
6b90df5f73f47ccf8a4671be979641ea38b77153
c2f9cc97cde70f98352c5400031c4d6636266ab3
/Recognize_Target/Recognize_Target/src/Pre_Get_Frame.cpp
bb9d1608b3235571b1426d9eca7e61e8f4697ec0
[ "MIT" ]
permissive
YanHuiGUO/UAV-Automatically-Landing-Based-on-Machine-Vision
7327193f70cdc7c748b9e43b9ee96cb3369b17c5
3f53ea55c95fe60f3ebaf2cde5f4845f8a8af688
refs/heads/master
2020-05-03T13:54:58.139093
2019-03-31T09:59:49
2019-03-31T09:59:49
178,664,161
2
0
null
null
null
null
GB18030
C++
false
false
2,864
cpp
#include <Pre_Get_Frame.h> #include <Deal_Frame.h> #include <math.h> #include <Serial.h> //保留小数位的函数 string do_fraction(double value, int decplaces = 16) { ostringstream out; out.precision(decplaces);//覆盖默认精度 out << setiosflags(ios::fixed) << value; return out.str(); } //读取摄像头 bool Pre_Frame::get_Camera(void){ camera.open(0); if (!camera.isOpened()) { cout << "摄像头打开失败" << endl; return false; } return true; } //获取原始帧信号 Mat Pre_Frame::getFrame(void){ time_now = (double)getTickCount(); camera >> frame; frame = Camera_Deal_frame.calibration_camera(frame); time_one_frame = (time_now - time_last) / getTickFrequency(); fps = 1.0 / time_one_frame; string str = do_fraction(fps,2); fpsString = "FPS:"; fpsString += str; // 在"FPS:"后加入帧率数值字符串 //// 将帧率信息写在输出帧上 //putText(frame, // 图像矩阵 // fpsString, // string型文字内容 // cv::Point(5, 20), // 文字坐标,以左下角为原点 // cv::FONT_HERSHEY_SIMPLEX, // 字体类型 // 0.5, // 字体大小 // cv::Scalar(0, 0, 0)); // 字体颜色 //imshow("Camera FPS", frame); time_last = time_now; return frame; } //剪切需要的区域 bool Pre_Frame::Cut_need_area(RotatedRect rect, Mat Src_Img, Mat &Dir_Img) { Rect orig = Rect(0, 0, Src_Img.size().width, Src_Img.size().height); Rect roRect = rect.boundingRect(); //返回包含旋转矩形的最小矩形 Point seed; Rect region = roRect & orig; double Angle = 0; if (rect.size.area() > 0) { Dir_Img = Src_Img(region); } else return false; return true; } //保存视频的线程 DWORD WINAPI start_save_vedio(LPVOID lpParam){ static unsigned long time_cnt = 0; static int vedio_cnt = 1; Pre_Frame* p = (Pre_Frame*)lpParam; while (1){ if (true == p->Deal_Complete) { //发送串口数据 //20ms左右进来一次,所以这里是录制83分钟视频 if ((int)(time_cnt += 1) <= (int)(5000.0f/0.02f)){ if (time_cnt % (int)(100.0f / 0.02f) == 0) { vedio_cnt++; p->writer.release(); p->writer; p->videoPath = "D:\\quater\\Recognize_Target\\vedio\\Video" + to_string(vedio_cnt) + ".avi"; p->writer.open(p->videoPath, CV_FOURCC('X', 'V', 'I', 'D'), 25, Size(IMG_Col, IMG_Row), 1); } p->writer << p->save_img; } p->Deal_Complete = false; } } return 0; } bool Pre_Frame::start_save_pic(string path, Mat img, int cnt){ string Image_name; #ifdef Write_Posive_Frame Image_name = path + "\\target_pos" + to_string(cnt) + ".jpg"; #endif #ifdef Write_Negotive_Frame Image_name = path + "\\target_neg" + to_string(cnt) + ".jpg"; #endif if (imwrite(Image_name, img)) //保存一帧图片 return true; else return false; }
[ "346155263@qq.com" ]
346155263@qq.com
3cd6d8bee572a2be3c3f6721d84bb6960fe6a2e3
0e88491050f5543deeeca0b6e0b0b45880ca09ce
/restoration/Plugins/SOURCE/MT_Masktools/common/params/params.h
bb7ea4988e63c05f5c80685e4e2c8bddc0cf72e5
[]
no_license
furmuzsev/avsScripts
47f9a00ecee1c94c7b270badd51965ae13805dce
8b96ec97d56f6b270b375ff4400d2e6beb11d846
refs/heads/master
2021-01-21T00:47:55.934741
2011-09-19T15:44:24
2011-09-19T15:44:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,560
h
#ifndef __Common_Params_H__ #define __Common_Params_H__ #include "../clip/clip.h" #include "../constraints/constraints.h" namespace Filtering { typedef enum { TYPE_INT, TYPE_FLOAT, TYPE_STRING, TYPE_BOOL, TYPE_CLIP, TYPE_UNDEFINED, } Type; /* generic """polymorphic""" class, whose value can be defined or not */ class Value { Type type; bool defined; PClip val_clip; int val_int; String val_string; bool val_bool; double val_float; public: Value() : type(TYPE_UNDEFINED), defined(false) { }; Value(int n) : type(TYPE_INT), defined(true), val_int(n) { } Value(double d) : type(TYPE_FLOAT), defined(true), val_float(d) { } Value(float d) : type(TYPE_FLOAT), defined(true), val_float(d) { } Value(const String &s) : type(TYPE_STRING), defined(true), val_string(s) { } Value(bool b) : type(TYPE_BOOL), defined(true), val_bool(b) { } Value(const PClip& c) : type(TYPE_CLIP), defined(true), val_clip(c) { } Value(Type t) : type(t), defined(false) { } Value(const Value &v) : type(v.type), val_clip(v.val_clip), val_int(v.val_int), val_float(v.val_float), val_string(v.val_string), val_bool(v.val_bool), defined(v.defined) { } operator int() const { return val_int; } operator double() const { return val_float; } operator float() const { return float(val_float); } operator bool() const { return val_bool; } operator String() const { return val_string; } operator PClip() const { return val_clip; } operator Type() const { return type; } int toInt() const { return val_int; } double toFloat() const { return val_float; } bool toBool() const { return val_bool; } String toString() const { return val_string; } PClip toClip() const { return val_clip; } bool is_defined() const { return defined; } void set_defined(bool d) { defined = d; } }; /* parameter will be used to defined a filter signature, but also to contain the actual value of a parameter once the filter has been called */ class Parameter { Value value; String name; public: Parameter() : value(), name("") { } Parameter(Type type) : value(type), name("") { } Parameter(const Value &value) : value(value), name("") { } Parameter(const Value &value, const String &name) : value(value), name(name) { } void set_defined(bool d) { value.set_defined( d ); } operator String() const { return name; } operator Value() const { return value; } operator Type() const { return value; } }; /* list of parameters */ class Parameters : public std::vector<Parameter> { public: /* handy accessor */ Value operator[](const String &name) const { for ( const_iterator it = begin(); it != end(); it++ ) if ( name == String(*it) ) return *it; return Value(); } Value operator[](int n) const { return std::vector<Parameter>::operator [](n); } }; /* signature of the filter */ class Signature { Parameters parameters; String name; public: Signature(const String &name) : name(name) { } void add(const Parameter &parameter) { parameters.push_back(parameter); } String toString() const { return name; } operator String() const { return name; } Value operator[](const String &name) const { return parameters[name]; } Parameter operator[](int index) const { return parameters.at(index); } int count() const { return int(parameters.size()); } }; } // namespace Filtering #endif
[ "alexei@chaptermedia.com" ]
alexei@chaptermedia.com
09375ac08fe47b004b88db3da9a230fa4cc885a6
53941c898b8c3e8c5592f84760bbeb21262ce980
/LogicLayer/CasualGame/SFRoom.cpp
bb7fe1e1b2a6425b3284a55fa3288a5296b887a3
[]
no_license
mehome/CGSF
bb2218b7098cabee3b35ea3f2f49e43237822bb9
88296aa402f660a69f67c04dbd0dec2bbb84fed3
refs/heads/master
2022-02-28T06:05:50.472200
2019-10-12T06:08:19
2019-10-12T06:08:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,840
cpp
#include "StdAfx.h" #include "SFRoom.h" #include "SFRoomFSM.h" #include "SFObserver.h" #include "SFTeam.h" #include "SFPlayer.h" #include "SFRoomManager.h" #include "SFSendPacket.h" SFRoom::SFRoom(int RoomIndex) : m_RoomIndex(RoomIndex) { m_pRoomFSM = new SFRoomFSM(this, ROOM_STATE_NONE); for(int i = 0; i < TEAM_TYPE_MAX; i++) { m_Team[i].SetTeamType(i); } } SFRoom::~SFRoom(void) { } int SFRoom::GetRoomState() { return m_pRoomFSM->GetRoomState(); } BOOL SFRoom::ProcessUserRequest( SFPlayer* pPlayer, BasePacket* pPacket ) { return m_pRoomFSM->ProcessUserRequest(pPlayer, pPacket); } BOOL SFRoom::ProcessUserRequest( SFPlayer* pPlayer, int Msg ) { return m_pRoomFSM->ProcessUserRequest(pPlayer, Msg); } BOOL SFRoom::ChangeState( eRoomState State ) { return m_pRoomFSM->ChangeState(State); } BOOL SFRoom::Open( SFPlayer* pPlayer ) { AddObserver((SFObserver*)pPlayer); SetRoomChief(pPlayer); AddTeamMember(pPlayer); m_RoomMemberMap.insert(make_pair(pPlayer->GetSerial(), pPlayer)); return TRUE; } BOOL SFRoom::AddTeamMember( SFPlayer* pPlayer) { SFTeam* pTeam = SelectMyTeam(pPlayer); pPlayer->SetMyTeam(pTeam->GetTeamType()); pTeam->AddMember(pPlayer); //SendTeamInfo(pPlayer, pTeam); return TRUE; } BOOL SFRoom::ChangePlayerFSM( ePlayerState State ) { for(int i = 0; i < TEAM_TYPE_MAX; i++) { TeamMemberMap& MemberMap = m_Team[i].GetMemberMap(); TeamMemberMap::iterator iter = MemberMap.begin(); for(iter; iter != MemberMap.end(); iter++) { SFPlayer* pPlayer = iter->second; pPlayer->ChangeState(State); } } return TRUE; } BOOL SFRoom::Update(int timerId) { return m_pRoomFSM->Update(timerId); } BOOL SFRoom::OnEnter( SFPlayer* pPlayer ) { if (MAX_ROOM_MEMBER <= GetObserverCount()) return FALSE; if(FALSE == AddObserver(pPlayer)) return FALSE; AddTeamMember(pPlayer); pPlayer->SetRoomIndex(GetRoomIndex()); SFMessage Message; Message.Initialize(CGSF::EnterTeamMember); Message << pPlayer->GetSerial(); Message << (char*)pPlayer->GetPlayerName().c_str(); PropagateMessage(&Message); m_RoomMemberMap.insert(make_pair(pPlayer->GetSerial(), pPlayer)); return TRUE; } BOOL SFRoom::OnLeave( SFPlayer* pPlayer ) { m_RoomMemberMap.erase(pPlayer->GetSerial()); DelObserver(pPlayer); SFMessage Message; Message.Initialize(CGSF::LeaveTeamMember); Message << pPlayer->GetSerial(); Message << (char*)pPlayer->GetPlayerName().c_str(); PropagateMessage(&Message); DelTeamMember(pPlayer); if(0 == GetObserverCount()) { SFRoomManager* pManager = SFLogicEntry::GetLogicEntry()->GetRoomManager(); pManager->RecallRoom(this); } else { if(GetRoomChief() == pPlayer) { RoomMemberMap::iterator iter = m_RoomMemberMap.begin(); if(iter == m_RoomMemberMap.end()) { SFASSERT(0); return FALSE; } SetRoomChief(iter->second); } } return TRUE; } BOOL SFRoom::ChangeTeam( SFPlayer* pPlayer ) { eTeamType TeamType = pPlayer->GetMyTeam(); DelTeamMember(pPlayer); TeamType = (eTeamType)(TeamType + 1); if(TeamType >= TEAM_TYPE_MAX) TeamType = TEAM_RED; AddTeamMember(pPlayer, TeamType); return TRUE; } BOOL SFRoom::CheckPlayerState( ePlayerState State ) { for(int i = 0; i < TEAM_TYPE_MAX; i++) { TeamMemberMap& MemberMap = m_Team[i].GetMemberMap(); TeamMemberMap::iterator iter = MemberMap.begin(); for(iter; iter != MemberMap.end(); iter++) { SFPlayer* pPlayer = iter->second; if(pPlayer->GetPlayerState() != State) return FALSE; } } return TRUE; } BOOL SFRoom::DelTeamMember( SFPlayer* pPlayer ) { m_Team[pPlayer->GetMyTeam()].DelMember(pPlayer); return TRUE; } SFTeam* SFRoom::SelectMyTeam(SFPlayer* pPlayer) { if(m_Team[TEAM_RED].GetMemberCount() > m_Team[TEAM_BLUE].GetMemberCount()) { return &m_Team[TEAM_BLUE]; } return &m_Team[TEAM_RED]; } BOOL SFRoom::AddTeamMember( SFPlayer* pPlayer, eTeamType TeamType ) { pPlayer->SetMyTeam(TeamType); m_Team[TeamType].AddMember((pPlayer)); //SendTeamInfo(pPlayer, &m_Team[TEAM_RED]); //SendTeamInfo(pPlayer, &m_Team[TEAM_blue]); return TRUE; } BOOL SFRoom::CheckLoadingComplete() { for(int i = 0; i < TEAM_TYPE_MAX; i++) { TeamMemberMap& MemberMap = m_Team[i].GetMemberMap(); TeamMemberMap::iterator iter = MemberMap.begin(); for(iter; iter != MemberMap.end(); iter++) { SFPlayer* pPlayer = iter->second; if(pPlayer->GetLoadingComplete() != TRUE) return FALSE; } } return TRUE; } BOOL SFRoom::CanEnter( SFPlayer* pPlayer ) { return FALSE; } BOOL SFRoom::BroadCast( BasePacket* pPacket ) { for(int i = 0; i < TEAM_TYPE_MAX; i++) { TeamMemberMap& MemberMap = m_Team[i].GetMemberMap(); TeamMemberMap::iterator iter = MemberMap.begin(); for(iter; iter != MemberMap.end(); iter++) { SFPlayer* pPlayer = iter->second; SendToClient(pPlayer, pPacket); } } return TRUE; }
[ "juhang3@daum.net" ]
juhang3@daum.net
47e5b25be068dd55101610d1d1b7a5974291637d
c764fb0ff4193f97e29b3178d776b8ae7e9fd677
/project/vs c++项目/坦克大战/Game/Input.cpp
f3c43d8b78dbd4a93b07bbc4fb8f42b4fbc3a6c0
[]
no_license
ooshell/qtCode
0ea0293c6c7daccfb2d43378431c8f20b2c6e940
738056da71c5e8601337a911ed9e3064db5433d4
refs/heads/master
2020-09-04T23:36:25.411840
2019-11-06T06:15:09
2019-11-06T06:15:09
219,923,818
0
0
null
2019-11-06T06:05:47
2019-11-06T06:05:47
null
UTF-8
C++
false
false
5,081
cpp
// Input.cpp: implementation of the CDirectInput class. // ////////////////////////////////////////////////////////////////////// #include "Input.h" #define SAFE_RELEASE(x) if(x) { x->Release(); x = NULL; } ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CDirectInput::CDirectInput() { m_pDI = NULL; m_pdevKeyboard = NULL; m_pdevJoystick = NULL; } CDirectInput::~CDirectInput() { Destroy(); } BOOL CDirectInput::Create( HINSTANCE hInst, HWND hWnd ) { HRESULT hr; // Create DirectInput object hr = DirectInputCreate( hInst, DIRECTINPUT_VERSION, &m_pDI, NULL ); if( FAILED(hr) ) return FALSE; // Initialize keyboard... hr = m_pDI->CreateDevice( GUID_SysKeyboard, &m_pdevKeyboard, NULL ); if( FAILED(hr) ) { Destroy(); return FALSE; } m_pdevKeyboard->SetDataFormat( &c_dfDIKeyboard ); m_pdevKeyboard->SetCooperativeLevel( hWnd, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE ); // acquire keyboard m_pdevKeyboard->Acquire(); // enum joystick devices m_pDI->EnumDevices( DIDEVTYPE_JOYSTICK, EnumJoystickCB, (LPVOID)this, DIEDFL_ATTACHEDONLY ); if( m_pdevJoystick ) { m_pdevJoystick->SetDataFormat( &c_dfDIJoystick ); m_pdevJoystick->SetCooperativeLevel( hWnd, DISCL_FOREGROUND | DISCL_EXCLUSIVE ); // Set the range of the joystick axes tp [-1000,+1000] DIPROPRANGE diprg; diprg.diph.dwSize = sizeof(DIPROPRANGE); diprg.diph.dwHeaderSize = sizeof(DIPROPHEADER); diprg.diph.dwHow = DIPH_BYOFFSET; diprg.lMin = -10; diprg.lMax = +10; diprg.diph.dwObj = DIJOFS_X; // Set the x-axis range m_pdevJoystick->SetProperty( DIPROP_RANGE, &diprg.diph ); diprg.diph.dwObj = DIJOFS_Y; // Set the y-axis range m_pdevJoystick->SetProperty( DIPROP_RANGE, &diprg.diph ); // Set the dead zone for the joystick axes (because many joysticks // aren't perfectly calibrated to be zero when centered). DIPROPDWORD dipdw; ZeroMemory( &dipdw, sizeof(dipdw) ); dipdw.diph.dwSize = sizeof(DIPROPDWORD); dipdw.diph.dwHeaderSize = sizeof(DIPROPHEADER); dipdw.diph.dwHow = DIPH_DEVICE; dipdw.dwData = 9000; dipdw.diph.dwObj = DIJOFS_X; // Set the x-axis deadzone m_pdevJoystick->SetProperty( DIPROP_DEADZONE, &dipdw.diph ); dipdw.diph.dwObj = DIJOFS_Y; // Set the y-axis deadzone m_pdevJoystick->SetProperty( DIPROP_DEADZONE, &dipdw.diph ); // acquire joystick m_pdevJoystick->Acquire(); } return TRUE; } void CDirectInput::Destroy() { if( m_pdevKeyboard ) m_pdevKeyboard->Unacquire(); if( m_pdevJoystick ) m_pdevJoystick->Unacquire(); SAFE_RELEASE( m_pdevKeyboard ); SAFE_RELEASE( m_pdevJoystick ); SAFE_RELEASE( m_pDI ); } BOOL CDirectInput::Acquire() { if( !m_pdevKeyboard || FAILED(m_pdevKeyboard->Acquire()) ) return FALSE; if( m_pdevJoystick ) m_pdevJoystick->Acquire(); return TRUE; } BOOL CDirectInput::GetKey( WORD& input1, WORD& input2 ) { #define KEYDOWN(key) (buffer[key] & 0x80) // Read keyboard data... HRESULT hr; char buffer[256]; // We have not read any data yet input1 = input2 = 0; hr = m_pdevKeyboard->GetDeviceState( sizeof(buffer), &buffer ); if( FAILED(hr) ) { if( hr == DIERR_INPUTLOST ) hr = Acquire(); return FALSE; } if( KEYDOWN( DIK_UP ) ) input1 |= KEY_UP; else if( KEYDOWN( DIK_DOWN ) ) input1 |= KEY_DOWN; else if( KEYDOWN( DIK_LEFT ) ) input1 |= KEY_LEFT; else if( KEYDOWN( DIK_RIGHT ) ) input1 |= KEY_RIGHT; if( KEYDOWN( DIK_NUMPAD0 ) ) input1 |= KEY_FIRE; if( KEYDOWN( DIK_E ) ) input2 |= KEY_UP; else if( KEYDOWN( DIK_D ) ) input2 |= KEY_DOWN; else if( KEYDOWN( DIK_S ) ) input2 |= KEY_LEFT; else if( KEYDOWN( DIK_F ) ) input2 |= KEY_RIGHT; if( KEYDOWN( DIK_SPACE ) ) input2 |= KEY_FIRE; if( m_pdevJoystick ) { DIJOYSTATE js; // poll the joystick to read the current state m_pdevJoystick->Poll(); // get data from the joystick hr = m_pdevJoystick->GetDeviceState( sizeof(js), &js ); if( FAILED(hr) ) { // did the read fail because we lost input for some reason? // if so, then attempt to reacquire. If the second acquire // fails, then the error from GetDeviceData will be // DIERR_NOTACQUIRED, so we won't get stuck an infinite loop. if( hr = DIERR_INPUTLOST ) hr = Acquire(); return FALSE; } if( js.lX < 0 ) input1 |= KEY_LEFT; else if( js.lX > 0 ) input1 |= KEY_RIGHT; else if( js.lY < 0 ) input1 |= KEY_UP; else if( js.lY > 0 ) input1 |= KEY_DOWN; if( js.rgbButtons[0] & 0x80 ) input1 |= KEY_FIRE; } return TRUE; } BOOL CALLBACK EnumJoystickCB( LPCDIDEVICEINSTANCE pdinst, LPVOID pvRef ) { CDirectInput* p = (CDirectInput*)pvRef; LPDIRECTINPUTDEVICE pdev; if( FAILED(p->m_pDI->CreateDevice( pdinst->guidInstance, &pdev, NULL)) ) return DIENUM_CONTINUE; pdev->QueryInterface( IID_IDirectInputDevice2, (LPVOID *)&p->m_pdevJoystick ); return DIENUM_STOP; }
[ "523090538@qq.com" ]
523090538@qq.com
16243575c8d1374a61bac6b1d5e88cbd6b85ab07
87f82a52aa160db6e7a762a27b2fad87e07eb49a
/sparseTable.cpp
a46723fc5ffa34855314594af4894b508f990bb1
[ "CC0-1.0" ]
permissive
Vidit24/cp-black_box
cfe4d0ab1b7144dba8ec78032d13fd6c26285515
50c22d3d6cbb9674c106152c8392ba087ae51937
refs/heads/main
2023-08-15T12:57:57.867969
2021-10-16T11:56:47
2021-10-16T11:56:47
398,625,380
0
1
CC0-1.0
2021-10-16T11:06:16
2021-08-21T18:02:25
HTML
UTF-8
C++
false
false
455
cpp
int sparseTable[200005][25]; void preprocess(vector<int>&a){ int n = a.size(); FOR(i,0,n){ sparseTable[i][0] = a[i]; } FOR(i,1,25){ for(int j = 0 ; j + (1<<i) -1 < n ; j++){ sparseTable[j][i] = min(sparseTable[j][i-1],sparseTable[j+(1<<(i-1))][i-1]); } } } int query(int L,int R){ int length = R-L+1; int tp = log2(length); return min(sparseTable[L][tp],sparseTable[R-(1<<tp)+1][tp]); }
[ "noreply@github.com" ]
noreply@github.com
80e8a36e42c094a1aeebd56cdd09c987b7af6400
829a3d7e48afc93f0607bdf22de626a0f5aa9767
/vector.cpp
5ca4208ef6abc8519cbf9107eac2e5080fb30a74
[]
no_license
tulinkry/metric
53cd3f20426c584d26c7fdceaaeb524538295e36
6f425ba1ce3c08cd91e2c4d52e5ca4b147c23262
refs/heads/master
2016-09-15T23:16:06.222689
2014-04-28T18:32:43
2014-04-28T18:32:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,088
cpp
#include "vector.h" using namespace std; /* -------------------------------------------------------------------------------------- */ /* PROTECTED FUNCTIONS */ /* -------------------------------------------------------------------------------------- */ void vector::resize ( int size ) { m_MaxSize = size; double * newpole = new double [ size ]; for ( int i = 0; i < ( m_Size > size ? size : m_Size ); i ++ ) newpole [ i ] = m_Vector [ i ]; m_Size = m_Size > size ? size : m_Size; delete [] m_Vector; m_Vector = newpole; } /* -------------------------------------------------------------------------------------- */ /* CONSTRUCTORS */ /* -------------------------------------------------------------------------------------- */ vector::vector ( int size ) : m_MaxSize ( size ), m_Size ( 0 ) { m_Vector = new double [ m_MaxSize ]; for ( int i = 0; i < m_MaxSize; i ++ ) m_Vector [ i ] = 0.0; } vector::vector ( int size, double number ) : m_MaxSize ( size ), m_Size ( size ) { m_Vector = new double [ m_MaxSize ]; for ( int i = 0; i < m_MaxSize; i ++ ) m_Vector [ i ] = number; } vector::vector ( const vector & x ) : m_MaxSize ( x . m_MaxSize ), m_Size ( x . m_Size ) { m_Vector = new double [ m_MaxSize ]; for ( int i = 0; i < m_MaxSize; i ++ ) m_Vector [ i ] = x . m_Vector [ i ]; } vector::~vector ( void ) { delete [] m_Vector; } /* -------------------------------------------------------------------------------------- */ /* FUNCTIONS */ /* -------------------------------------------------------------------------------------- */ vector & vector::operator = ( const vector & x ) { if ( &x == this ) return *this; delete [] m_Vector; m_MaxSize = x . m_MaxSize; m_Size = x . m_Size; m_Vector = new double [ m_MaxSize ]; for ( int i = 0; i < m_MaxSize; i ++ ) m_Vector [ i ] = x . m_Vector [ i ]; return *this; } double & vector::operator [] ( int index ) { if ( index > m_MaxSize - 1 || index < 0 ) throw new InvalidIndexException ( "Index is out of range" ); m_Size = index + 1; return m_Vector [ index ]; } const double & vector::operator [] ( int index ) const { if ( index > m_MaxSize - 1 || index < 0 ) throw new InvalidIndexException ( "Index is out of range" ); return m_Vector [ index ]; } int vector::size ( void ) const { return m_Size; } /* -------------------------------------------------------------------------------------- */ /* PRINT FUNCTIONS */ /* -------------------------------------------------------------------------------------- */ void vector::print ( ostream & os ) const { os << "[ "; for ( int i = 0; i < m_Size; i ++ ) { os << m_Vector [ i ]; if ( i != m_Size - 1 ) os << ", "; } os << " ]"; } ostream & operator << ( ostream & os, const vector & x ) { x . print ( os ); return os; }
[ "krystof@PC-HOME.(none)" ]
krystof@PC-HOME.(none)
f988514dce7a273b322181976ea91dccf48780d8
733b1e5d06b0ad1044138208a9ad6f7390051e77
/pattern pg3.cpp
098bcaca7b99c92914e5e924268cb426c3a30e6b
[]
no_license
Sudhanshuo8/Pattern-01
6eb72b6510445df20b2fcece30916bda653b21dd
69459fd60160ab75b0c06d94aee0a4df0769aace
refs/heads/master
2022-03-05T07:20:31.707679
2020-03-12T16:47:08
2020-03-12T16:47:08
246,884,432
0
0
null
null
null
null
UTF-8
C++
false
false
157
cpp
#include<iostream> using namespace std; int main() { for(int i=5;i>=1;i--) { for(int j=5;j>=1;j--) { cout<<j; } cout<<endl; } }
[ "noreply@github.com" ]
noreply@github.com
508eff45f234c4ab54b06e6e2bc2af4c1c1167e1
5c40398112739a481ae0ddbee71832523da6d032
/libs/image/include/image/ImageSampler.h
7fc2f5251da2995f43ef0b508c0467dea3a08439
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
molysgaard/filament
972f1445c115e52d1b6b615ced74f6c38c984343
81b7b1ac6f430071bfb453261831dc3ed8afe241
refs/heads/master
2020-03-26T14:07:59.763106
2018-08-16T16:09:37
2018-08-16T16:09:37
144,973,614
0
0
Apache-2.0
2018-08-16T10:33:17
2018-08-16T10:33:16
null
UTF-8
C++
false
false
5,049
h
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef IMAGE_IMAGESAMPLER_H #define IMAGE_IMAGESAMPLER_H #include <image/LinearImage.h> namespace image { /** * Value of a single point sample, allocated according to the number of image channels. */ struct SingleSample { float& operator[](int index) { return *(data + index); } float* data = nullptr; ~SingleSample(); }; /** * Controls the weighted average used across a window of source samples. */ enum class Filter { DEFAULT, // Selects MITCHELL or LANCZOS dynamically. BOX, // Computes the un-weighted average over the filter radius. NEAREST, // Copies the source sample nearest to the center of the filter. HERMITE, // Also known as "smoothstep", has some nice properties. GAUSSIAN_SCALARS, // Standard Gaussian filter with sigma = 0.5 GAUSSIAN_NORMALS, // Same as GAUSSIAN_SCALARS, but interpolates unitized vectors. MITCHELL, // Cubic resampling per Mitchell-Netravali, default for magnification. LANCZOS, // Popular sinc-based filter, default for minification. MINIMUM // Takes a min val rather than avg, perhaps useful for depth maps and SDF's. }; /** * Defines a viewport inside the texture such that (0,0) is at the top-left corner of the top-left * pixel, and (1,1) is at the bottom-right corner of the bottom-corner pixel. */ struct Region { float left; float top; float right; float bottom; }; /** * Transforms the texel fetching operation when sampling from adjacent images. */ enum class Orientation { STANDARD = 0, FLIP_X = 1 << 0, FLIP_Y = 1 << 1, FLIP_XY = FLIP_X | FLIP_Y }; /** * Specifies how to generate samples that lie outside the boundaries of the source region. */ struct Boundary { enum { EXCLUDE, // Ignore the samples and renormalize the filter. This is probably what you want. REGION, // Keep samples that are outside sourceRegion if they are still within the image. CLAMP, // Pretend the edge pixel is repeated forever. Gives edge pixels more weight. REPEAT, // Resample from the region, wrapping back to the front of the row or column. MIRROR, // Resample from the region but assume that it has been flipped. COLOR, // Use the specified constant color. NEIGHBOR // Sample from an adjacent image. } mode = EXCLUDE; SingleSample color; // Used only if mode = COLOR LinearImage* neighbor = nullptr; // Used only if mode = NEIGHBOR Orientation orientation; // Used only if mode = NEIGHBOR }; /** * Configuration for the resampleImage function. Provides reasonable defaults. */ struct ImageSampler { Filter horizontalFilter = Filter::DEFAULT; Filter verticalFilter = Filter::DEFAULT; Region sourceRegion = {0, 0, 1, 1}; float filterRadiusMultiplier = 1; Boundary east; Boundary north; Boundary west; Boundary south; }; /** * Resizes or blurs the given linear image, producing a new linear image with the given dimensions. */ LinearImage resampleImage(const LinearImage& source, uint32_t width, uint32_t height, const ImageSampler& sampler); /** * Resizes the given linear image using a simplified API that takes target dimensions and filter. */ LinearImage resampleImage(const LinearImage& source, uint32_t width, uint32_t height, Filter filter = Filter::DEFAULT); /** * Computes a single sample for the given texture coordinate and writes the resulting color * components into the given output holder. * * For decent performance, do not call this across the entire image, instead call resampleImage. * On the first call, pass in a default SingleSample to allocate the result holder. For example: * * SingleSample result; * computeSingleSample(img, 0.5f, 0.5f, &result); * printf("r g b = %f %f %f\n", result[0], result[1], result[2]); * computeSingleSample(img, 0.9f, 0.1f, &result); * printf("r g b = %f %f %f\n", result[0], result[1], result[2]); * * The x y coordinates live in "texture space" such that (0.0f, 0.0f) is the upper-left boundary of * the top-left pixel and (+1.0f, +1.0f) is the lower-right boundary of the bottom-right pixel. */ void computeSingleSample(const LinearImage& source, float x, float y, SingleSample* result, Filter filter = Filter::BOX); } // namespace image #endif /* IMAGE_IMAGESAMPLER_H */
[ "noreply@github.com" ]
noreply@github.com
45079bf7ea18fa918eb12299f8813ceb25f5c8e5
48b84468b1c18a139ccd0def5812617a0a4f6cd2
/Tank/solidblock.h
5ec3612ed1b71f4b6f92514c40560d537fdc61e1
[]
no_license
jk7724/Tank_game
c22d468b323d8c60e47a75083574ff35f1bb84fd
d4d75e6f1b360f6663e0d0904463afeda57986fa
refs/heads/master
2022-11-17T20:13:29.967341
2020-07-20T16:01:38
2020-07-20T16:01:38
279,912,849
0
0
null
null
null
null
UTF-8
C++
false
false
262
h
#ifndef SOLIDBLOCK_H #define SOLIDBLOCK_H #include "baseblock.h" class SolidBlock: public BaseBlock { Q_OBJECT public: SolidBlock(); virtual void createBlock(QPointF pos);//create new block, set position and add to scene }; #endif // SOLIDBLOCK_H
[ "ad8422@protonmail.com" ]
ad8422@protonmail.com
7ee1d267d6b8fdb14602a867415156fdf1b2c2e9
684890a1bdb0c5c98c85f6564f52ea4dd162c0b1
/Day-127/Harshitha.cpp
af6617567a863f8509bbc94cae612e462c5b6fae
[]
no_license
Job-Colab/Coding-Preparation
eb39dc6f064a76c9ef3a0318f3612e96d6cc6459
a0273cb0d38afbbda7b6a1f008ab812b93f09d74
refs/heads/main
2023-04-28T21:50:38.218873
2021-05-13T03:11:48
2021-05-13T03:11:48
301,300,545
10
2
null
null
null
null
UTF-8
C++
false
false
369
cpp
long long int count(long long int n) { long long int table[n+1],i; memset(table, 0, sizeof(table)); table[0]=1; // If 0 sum is required number of ways is 1. for(int i = 3; i <= n ; ++i) table[i]+= table[i-3]; for(int i = 5; i <= n ; ++i) table[i]+= table[i-5]; for(int i = 10; i <= n ; ++i) table[i]+= table[i-10]; return table[n]; }
[ "noreply@github.com" ]
noreply@github.com
c05314986c83829be5b7fe8022b8b11d46780c00
72b661db3cfb46523c39bab6ff18bf3898ace824
/PsyLib/c_rectanglespattern.cpp
563e43db74641d5f6d2c51c0281ba707985fe613
[]
no_license
Firsto/matcharea
6843fc9964188a125a92dfe36f2e6b174426d34c
ed6cd553757b9c58472d0d56648f16b7f5f11bdd
refs/heads/master
2021-01-18T10:29:48.277490
2015-12-22T22:38:22
2015-12-22T22:38:22
51,526,676
1
0
null
2016-02-11T16:05:16
2016-02-11T16:05:15
null
UTF-8
C++
false
false
4,095
cpp
#include <QtDebug> #include "c_rectanglespattern.h" CRectanglesPattern::CRectanglesPattern() { difiniOrtangulojKvanto(3); m_width = 10; m_height = 10; } void CRectanglesPattern::difiniOrtangulojKvanto(int kvanto) { if (kvanto > 0) { ortanguloj.clear(); ortanguloj.fill(QRectF(), kvanto); } } QRectF CRectanglesPattern::ortangulo(int indico) { if (indico >= 0 && indico < ortanguloj.count()) { return ortanguloj.at(indico); } return QRectF(); } bool CRectanglesPattern::isEqual(CAbstractPattern *other) { CRectanglesPattern *pattern = dynamic_cast <CRectanglesPattern *> (other); if (pattern) { if (ortangulojKvanto() != pattern->ortangulojKvanto()) return false; for (int i = 0; i < ortangulojKvanto(); ++i) { if (ortanguloj.at(i) != pattern->ortangulo(i)) return false; } return true; } return false; } bool CRectanglesPattern::isSimilar(CAbstractPattern *other) { CRectanglesPattern *pattern = dynamic_cast <CRectanglesPattern *> (other); if (pattern) { if (ortangulojKvanto() != pattern->ortangulojKvanto()) return false; qreal spaco = 0.05; for (int i = 0; i < ortangulojKvanto(); ++i) { QRectF ekstera = ortanguloj[i].adjusted(-spaco, -spaco, spaco, spaco); QRectF interna = ortanguloj[i].adjusted(spaco, spaco, -spaco, -spaco); for (int j = 0; j < ortangulojKvanto(); ++j) { if (ekstera.contains(pattern->ortangulo(j)) && pattern->ortangulo(j).contains(interna)) { return true; } } } } return false; } void CRectanglesPattern::drawTo(QPainter *painter, const QRect & drawRect, const QColor & color) { int wMarg = qRound(0.08 * m_width); int hMarg = qRound(0.08 * m_height); QRect bildRekt = drawRect.adjusted(wMarg, hMarg, -wMarg, -hMarg); bildRekt.moveTo(drawRect.left() + (drawRect.width() - bildRekt.width())/2, drawRect.top() + (drawRect.height() - bildRekt.height())/2); painter->setPen(QPen(color, kalibro)); painter->setBrush(Qt::NoBrush); int xSkalo = bildRekt.width(); int ySkalo = bildRekt.height(); for (int i = 0; i < ortangulojKvanto(); ++i) { painter->drawRect(ortanguloj[i].left()*xSkalo + bildRekt.left(), ortanguloj[i].top()*ySkalo + bildRekt.top(), ortanguloj[i].width()*xSkalo, ortanguloj[i].height()*ySkalo); } } bool chuOrtangulojSimila(const QRectF r1, const QRectF r2) { //qreal spaco = 0.05; return false; } void CRectanglesPattern::genRandom() { for (int i = 0; i < ortangulojKvanto(); ++i) { QRectF kandidato; bool bona = false; while (!bona) { int w = qrand()%80 + 20; int h = qrand()%80 + 20; int x = qrand()%(100 - w); int y = qrand()%(100 - h); kandidato = QRectF(x/100.0, y/100.0, w/100.0, h/100.0); bona = true; qreal spaco = (qrand()%20 + 10)/100.0; for (int j = 0; j < i; ++j) { if (qAbs(ortanguloj[j].left() - kandidato.left()) <= spaco || qAbs(ortanguloj[j].right() - kandidato.right()) <= spaco || qAbs(ortanguloj[j].top() - kandidato.top()) <= spaco || qAbs(ortanguloj[j].bottom() - kandidato.bottom()) <= spaco) { bona = false; break; } } } ortanguloj[i] = kandidato; } } void CRectanglesPattern::updateSize(int w, int h) { m_width = w; m_height = h; qreal d = h; if (w > h) d = w; kalibro = qBound(3.0, d/50.0, 7.0); if (d < 50) kalibro = 2.0; } CAbstractPattern *CRectanglesPattern::clone() { CRectanglesPattern *result = new CRectanglesPattern; *result = *this; return result; }
[ "drafterleo@gmail.com" ]
drafterleo@gmail.com
d193a711f2e63d60b79cdeb795cdea68f7ca0e66
4ba129e0121fda723e7fb292495ad1da1fd7a640
/Ozcan_vs_Nebulus_and_the_Towergoround/code/Camera/CameraTransform.h
6d0d186efbae6040e48905c43fb260810b1ffb83
[]
no_license
nickben99/Ozcan
64f13069fa61f1bb790ec7e0093d19f7a71e3ed0
07ecc94e8587600ed9f0b5d6d2803741ca52c7fa
refs/heads/master
2020-05-21T16:42:27.590241
2018-01-11T04:59:49
2018-01-11T04:59:49
61,513,500
0
0
null
null
null
null
UTF-8
C++
false
false
1,061
h
//CameraTransform.h - header for the camera class //system includes------------ //--------------------------- #ifndef _CameraTransform_h_ #define _CameraTransform_h_ //header files--------- #include "Math/CQuaternion.h" #include "Math/CVector.h" //--------------------- //defines-------------- //--------------------- //forward declerations---- //------------------------ class CameraTransform { public: CameraTransform(); void Init(); void SetLookAt(const CVector& lookAt); CVector GetLookAt() const; void SetOrientation(const CQuaternion& orientation); CQuaternion GetOrientation() const; void SetDistanceFromLookAt(float distanceFromLookAt); float GetDistanceFromLookAt() const; CVector CalculatePosition() const; static CameraTransform Lerp(const CameraTransform& from, const CameraTransform& to, float interp); #ifdef DETERMINISTIC_REPLAY_DEBUG void ReplayCheck() const; #endif private: CVector mLookAt; CQuaternion mOrientation; float mDistanceFromLookAt; }; // end class CameraTransform #endif // ifndef _CameraTransform_h_
[ "nickbenson99@gmail.com" ]
nickbenson99@gmail.com
f273273932108ca00bd7272a2a8f6ae986c81fbe
b77349e25b6154dae08820d92ac01601d4e761ee
/GDI/membmtst/membmtst2.h
eab11e90c5ecedb6c2ad633ddf4a56587ab1c2a3
[]
no_license
ShiverZm/MFC
e084c3460fe78f820ff1fec46fe1fc575c3e3538
3d05380d2e02b67269d2f0eb136a3ac3de0dbbab
refs/heads/master
2023-02-21T08:57:39.316634
2021-01-26T10:18:38
2021-01-26T10:18:38
332,725,087
0
0
null
2021-01-25T11:35:20
2021-01-25T11:29:59
null
UTF-8
C++
false
false
1,278
h
// membmtst2.h : main header file for the MEMBMTST2 application // #if !defined(AFX_MEMBMTST2_H__2F4B85CB_3229_4A42_919A_84FA9FF07D92__INCLUDED_) #define AFX_MEMBMTST2_H__2F4B85CB_3229_4A42_919A_84FA9FF07D92__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #ifndef __AFXWIN_H__ #error include 'stdafx.h' before including this file for PCH #endif #include "resource.h" // main symbols ///////////////////////////////////////////////////////////////////////////// // CTstApp: // See membmtst2.cpp for the implementation of this class // class CTstApp : public CWinApp { public: CTstApp(); // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CTstApp) public: virtual BOOL InitInstance(); //}}AFX_VIRTUAL // Implementation //{{AFX_MSG(CTstApp) // NOTE - the ClassWizard will add and remove member functions here. // DO NOT EDIT what you see in these blocks of generated code ! //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_MEMBMTST2_H__2F4B85CB_3229_4A42_919A_84FA9FF07D92__INCLUDED_)
[ "w.z.y2006@163.com" ]
w.z.y2006@163.com
0c8a2e9a30cbae2c5a92a59b759ea61a3c5a27b5
93f4134844fed34b7ddc550ed056072ce6f55c27
/zstringmaphelper.h
99db2352096ff3d0e75816b9198cd2fc492cb5a1
[]
no_license
horvathzoltan/retek2
79533e0b2cf9fdc3a63769720c86cd4ef0cc66c3
626358e783c2bd2c04848eca3ac2f43493e87ae3
refs/heads/master
2021-06-05T12:29:40.339077
2020-02-13T20:45:50
2020-02-13T20:45:50
104,221,991
0
0
null
null
null
null
UTF-8
C++
false
false
486
h
#ifndef ZSTRINGMAPHELPER_H #define ZSTRINGMAPHELPER_H #include <QString> #include <QMap> class zStringMapHelper { public: zStringMapHelper(); static void StringMapFeltolt(const QString& fn, QMap<QString, QString> *map); static void StringMapSave(const QString&, QMap<QString, QString> *map); static bool contains(QMap<QString, QString> *map, const QString& k); static QString getKey(QMap<QString, QString> *map, const QString& k); }; #endif // ZSTRINGMAPHELPER_H
[ "horvaath.zoltaan.debrecen@gmail.com" ]
horvaath.zoltaan.debrecen@gmail.com
90ee11d86efee66531dd51ada23b953fbd138e6a
a3d6556180e74af7b555f8d47d3fea55b94bcbda
/chromeos/ash/services/recording/lzw_pixel_color_indices_writer_test.cc
cc5735788f20275fa3be409bda04090130eed36d
[ "BSD-3-Clause" ]
permissive
chromium/chromium
aaa9eda10115b50b0616d2f1aed5ef35d1d779d6
a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c
refs/heads/main
2023-08-24T00:35:12.585945
2023-08-23T22:01:11
2023-08-23T22:01:11
120,360,765
17,408
7,102
BSD-3-Clause
2023-09-10T23:44:27
2018-02-05T20:55:32
null
UTF-8
C++
false
false
3,253
cc
// Copyright 2023 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <cstdint> #include <string> #include <vector> #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/files/scoped_temp_dir.h" #include "chromeos/ash/services/recording/gif_file_writer.h" #include "chromeos/ash/services/recording/lzw_pixel_color_indices_writer.h" #include "chromeos/ash/services/recording/public/mojom/recording_service.mojom.h" #include "chromeos/ash/services/recording/recording_file_io_helper.h" #include "mojo/public/cpp/bindings/pending_remote.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/abseil-cpp/absl/types/optional.h" namespace recording { class FakeDelegate : public RecordingFileIoHelper::Delegate { public: FakeDelegate() = default; FakeDelegate(const FakeDelegate&) = delete; FakeDelegate& operator=(const FakeDelegate&) = delete; ~FakeDelegate() override = default; // RecordingFileIoHelper::Delegate: void NotifyFailure(mojom::RecordingStatus status) override {} }; class LzwTest : public testing::Test { public: LzwTest() { const bool dir_created = temp_dir_.CreateUniqueTempDir(); DCHECK(dir_created); } LzwTest(const LzwTest&) = delete; LzwTest& operator=(const LzwTest&) = delete; ~LzwTest() override = default; // Returns a path for the given `file_name` under the temp dir created by this // fixture. base::FilePath GetPathInTempDir(const std::string& file_name) { return temp_dir_.GetPath().Append(file_name); } private: base::ScopedTempDir temp_dir_; }; TEST_F(LzwTest, VerifyOutputStream) { const auto gif_path = GetPathInTempDir("test.gif"); FakeDelegate delegate; GifFileWriter gif_file_writer( mojo::PendingRemote<mojom::DriveFsQuotaDelegate>(), gif_path, &delegate); LzwPixelColorIndicesWriter lzw_encoder(&gif_file_writer); // Let's assume we have the following image with only 3 colors; red, green, // and blue. // // +---+---+---+ // | R | R | R | // +---+---+---+ // | G | G | G | // +---+---+---+ // | B | B | B | // +---+---+---+ // // This means we only have 3 color indices; R => 0, G => 1, B => 2. The bit // depth in this case is 2. Let's feed this pixel color indices to the LZW // encoder. const ColorIndices color_indices{0, 0, 0, 1, 1, 1, 2, 2, 2}; lzw_encoder.EncodeAndWrite(color_indices, /*color_bit_depth=*/2); // Verify that the contents of the file are the expected output of the // encoder. absl::optional<std::vector<uint8_t>> actual_file_contents = base::ReadFileToBytes(gif_path); ASSERT_TRUE(actual_file_contents.has_value()); EXPECT_THAT( *actual_file_contents, testing::ElementsAre(0x02, // LZW minimum code size. 0x04, // Number of bytes in the data sub-block. 0x84, // -+ 0x83, // +-- LZW-compressed indices. 0xA2, // -+ 0x54, // Clear code + EoI code. 0x00)); // Block terminator. } } // namespace recording
[ "chromium-scoped@luci-project-accounts.iam.gserviceaccount.com" ]
chromium-scoped@luci-project-accounts.iam.gserviceaccount.com
309382c94322db1ee2d11a354c2f505a64b54e3e
8b0a8f9b84ba2556e71ef4135ac9b9306ac2c54d
/LaboratoryHomework/analogRGBControl.ino
41494e9bc3e884ea1d3bde43b09b4d5b54a96d9d
[]
no_license
Alecsandu/IntroductionToRobotics
2065d1f78f7bef3e2b355875cf322892ded01770
e71716765d4aa5dcdf0f44c0c467a88bd21a9140
refs/heads/master
2022-02-15T13:30:28.533999
2022-02-01T13:34:54
2022-02-01T13:34:54
219,337,825
4
0
null
null
null
null
UTF-8
C++
false
false
1,211
ino
const int redIn = A0; const int greenIn = A1; const int blueIn = A2; const int redPin = 11; const int greenPin = 10; const int bluePin = 9; int redValue = 0; int greenValue = 0; int blueValue = 0; /* In setup it is configured each pin to behave either as an input or an output */ void setup() { pinMode(redIn, INPUT); pinMode(greenIn, INPUT); pinMode(blueIn, INPUT); pinMode(redPin, OUTPUT); pinMode(greenPin, OUTPUT); pinMode(bluePin, OUTPUT); } void loop() { redValue = analogRead(redIn); greenValue = analogRead(greenIn); blueValue = analogRead(blueIn); /* After we read the values from the 3 potentiometers, the map function is used because stored values are between 0-1023 and the written values must be between 0-255 */ redValue = map(redValue, 0, 1023, 0, 255); greenValue = map(greenValue, 0, 1023, 0, 255); blueValue = map(blueValue, 0, 1023, 0, 255); setColor(redValue, greenValue, blueValue); } /* This function is used to control each color channel of the RGB LED */ void setColor(int red, int green, int blue) { analogWrite(redPin, red); analogWrite(greenPin, green); analogWrite(bluePin, blue); }
[ "noreply@github.com" ]
noreply@github.com
f4cef9d4c7219bd937ee96d11e229be0b219cf9f
03253c43569f47cd74b773f12c8eb2a09ff111be
/ScoreBoard.cpp
76e6b9dff34f67aa593143bbf7303d908299f8f9
[ "MIT" ]
permissive
AbdullahNaveed/Centipede-Game
d4da7cb7efc076e37837dd696dea5ceccc4691b4
7e4ff514633ebb479be83c35bc77be2efb56e3af
refs/heads/master
2021-06-21T23:58:53.271034
2021-05-22T14:28:43
2021-05-22T14:28:43
225,152,409
2
0
null
null
null
null
UTF-8
C++
false
false
2,770
cpp
// Abdullah Naveed // ROLL # 18I-0654 (A) // OOP_Project #include "ScoreBoard.h" ScoreBoard :: ScoreBoard(): GameObject(0,0) , NumberOfLives(2) , Score(0) , highScore(0) , scoreCheck(10000) , level(1) { } ScoreBoard :: ScoreBoard(int x,int y,int nol,int score): GameObject(x,y) , NumberOfLives(nol) , Score(score) , highScore(0) , scoreCheck(10000), level(1) { } ScoreBoard :: ScoreBoard(const ScoreBoard& rhs): GameObject(rhs.getX(),rhs.getY()) { this->NumberOfLives = rhs.getNumberOfLives(); this->Score = rhs.getScore(); this->highScore = rhs.getHighScore(); this->scoreCheck = 10000; this->level = 1; } void ScoreBoard :: retrieveHighScore() { ////for restoring value of high score back in game//// ifstream InputFile; if(InputFile) { InputFile.open("HighScore.txt", ios::in); InputFile>>this->highScore; InputFile.close(); } else cout<<"File not Opened\n"; /////////////////////////////////////////////////////// } void ScoreBoard :: saveHighScore() { /////////////////////SAVING HIGH SCORE//// if(this->Score >= this->highScore) { this->highScore = this->Score; } ofstream OutputFile; if(OutputFile) { OutputFile.open("HighScore.txt", ios::out); OutputFile<<this->highScore; OutputFile.close(); } else cout<<"File not Opened\n"; ////////////////////////////////////////// } void ScoreBoard :: draw() { DrawLine(10, 610, 1010, 610, 3, colors[45]); //line below DrawString( 40, 615, "Score : ", colors[45]); DrawString( 150, 615 , to_string(this->Score), colors[45]); DrawString( 300, 615, "HighScore : ", colors[45]); DrawString( 450, 615 , to_string(this->highScore), colors[45]); DrawString( 900, 615 , "Lives : ", colors[45]); DrawString( 970, 615, to_string(this->NumberOfLives), colors[45]); DrawString( 600, 615 , "Level : ", colors[45]); DrawString( 670, 615, to_string(this->level), colors[45]); if(this->Score >= (this->scoreCheck) ) { if(this->NumberOfLives<6) { this->NumberOfLives++; this->scoreCheck += 10000; } } if(this->Score >= 999999) { this->Score = 999999; } } int ScoreBoard::getNumberOfLives() const { return NumberOfLives; } void ScoreBoard::setNumberOfLives(int numberOfLives) { NumberOfLives = numberOfLives; } int ScoreBoard::getScore() const { return Score; } int ScoreBoard::getHighScore() const { return highScore; } int ScoreBoard::getScoreCheck() const { return scoreCheck; } int ScoreBoard::getLevel() const { return level; } void ScoreBoard::setLevel(int level) { this->level = level; } void ScoreBoard::setScoreCheck(int scoreCheck) { this->scoreCheck = scoreCheck; } void ScoreBoard::setHighScore(int highScore) { this->highScore = highScore; } void ScoreBoard::setScore(int score) { Score = score; } ScoreBoard :: ~ScoreBoard() { }
[ "noreply@github.com" ]
noreply@github.com
8886ccdf3468eeb245031a78ffed08725226495b
3d6deb89702e3ea9edbb987484afa24be5a25ca8
/Diablo2/Motor2D/j1FileSystem.cpp
6c68dee2ef38997af818b2ba8d58a353eebb5ec5
[]
no_license
joeyGumer/Pixel_Mirror--Diablo_II
e586292d89822a770ef835cdcc8120e282339f35
a39a837782be00497cb15652fd03c6f8154058b8
refs/heads/master
2021-01-15T15:36:39.857226
2016-10-26T10:04:36
2016-10-26T10:04:36
52,676,876
4
2
null
null
null
null
UTF-8
C++
false
false
4,460
cpp
#include "p2Defs.h" #include "j1App.h" #include "p2Log.h"F #include "j1FileSystem.h" #include "PhysFS/include/physfs.h" #include "SDL/include/SDL.h" #pragma comment( lib, "PhysFS/libx86/physfs.lib" ) j1FileSystem::j1FileSystem() : j1Module() { name.create("file_system"); // need to be created before Awake so other modules can use it char* base_path = SDL_GetBasePath(); PHYSFS_init(base_path); SDL_free(base_path); // By default we include executable's own directory // without this we won't be able to find config.xml :-( AddPath("."); } // Destructor j1FileSystem::~j1FileSystem() { PHYSFS_deinit(); } // Called before render is available bool j1FileSystem::Awake(pugi::xml_node& config) { LOG("Loading File System"); bool ret = true; // Add all paths in configuration in order for(pugi::xml_node path = config.child("path"); path; path = path.next_sibling("path")) { AddPath(path.child_value()); } // Ask SDL for a write dir char* write_path = SDL_GetPrefPath(App->GetOrganization(), App->GetTitle()); if(PHYSFS_setWriteDir(write_path) == 0) LOG("File System error while creating write dir: %s\n", PHYSFS_getLastError()); else { // We add the writing directory as a reading directory too with speacial mount point LOG("Writing directory is %s\n", write_path); AddPath(write_path, GetSaveDirectory()); } SDL_free(write_path); return ret; } // Called before quitting bool j1FileSystem::CleanUp() { LOG("Freeing File System subsystem"); return true; } // Add a new zip file or folder bool j1FileSystem::AddPath(const char* path_or_zip, const char* mount_point) { bool ret = false; if(PHYSFS_mount(path_or_zip, mount_point, 1) == 0) LOG("File System error while adding a path or zip(%s): %s\n", path_or_zip, PHYSFS_getLastError()); else ret = true; return ret; } // Check if a file exists bool j1FileSystem::Exists(const char* file) const { return PHYSFS_exists(file) != 0; } // Check if a file is a directory bool j1FileSystem::IsDirectory(const char* file) const { return PHYSFS_isDirectory(file) != 0; } // Read a whole file and put it in a new buffer unsigned int j1FileSystem::Load(const char* file, char** buffer) const { unsigned int ret = 0; PHYSFS_file* fs_file = PHYSFS_openRead(file); if(fs_file != NULL) { PHYSFS_sint64 size = PHYSFS_fileLength(fs_file); if(size > 0) { *buffer = new char[(uint)size]; PHYSFS_sint64 readed = PHYSFS_read(fs_file, *buffer, 1, (PHYSFS_sint32)size); if(readed != size) { LOG("File System error while reading from file %s: %s\n", file, PHYSFS_getLastError()); RELEASE(buffer); } else ret = (uint)readed; } if(PHYSFS_close(fs_file) == 0) LOG("File System error while closing file %s: %s\n", file, PHYSFS_getLastError()); } else LOG("File System error while opening file %s: %s\n", file, PHYSFS_getLastError()); return ret; } // Read a whole file and put it in a new buffer SDL_RWops* j1FileSystem::Load(const char* file) const { char* buffer; int size = Load(file, &buffer); if(size > 0) { SDL_RWops* r = SDL_RWFromConstMem(buffer, size); if(r != NULL) r->close = close_sdl_rwops; return r; } else return NULL; } int close_sdl_rwops(SDL_RWops *rw) { RELEASE(rw->hidden.mem.base); SDL_FreeRW(rw); return 0; } // Save a whole buffer to disk unsigned int j1FileSystem::Save(const char* file, const char* buffer, unsigned int size) const { unsigned int ret = 0; PHYSFS_file* fs_file = PHYSFS_openWrite(file); if(fs_file != NULL) { PHYSFS_sint64 written = PHYSFS_write(fs_file, (const void*)buffer, 1, size); if(written != size) LOG("File System error while writing to file %s: %s\n", file, PHYSFS_getLastError()); else ret = (uint) written; if(PHYSFS_close(fs_file) == 0) LOG("File System error while closing file %s: %s\n", file, PHYSFS_getLastError()); } else LOG("File System error while opening file %s: %s\n", file, PHYSFS_getLastError()); return ret; } //NOTE: fullfill this bool j1FileSystem::SetWriteDirectory() { return true; } bool j1FileSystem::SaveFileExists() { p2SString save_file("%ssave_state", GetSaveDirectory()); return Exists(save_file.GetString()); } bool j1FileSystem::DeleteSaveFile() { p2SString save_file("save_state"); bool ret = (PHYSFS_delete(save_file.GetString()) != 0); if (ret == false) { LOG("File system error when trying to delete Save State file: %s \n", PHYSFS_getLastError()); } return ret; }
[ "pep3553@gmail.com" ]
pep3553@gmail.com
670ccf77b70fc1ded1dafcc7bd8d7cd612ccd9ff
972ae15c2dcc180f61522484b05d7dfb5b5f7691
/sketches/playersketch2/.localhistory/src/1488722088$stretchMesh.cpp
be7925288f66af24ea75b6d2dd13a76603ac46d3
[]
no_license
k-may/molino-player
e5edf53d2f153dfb9b989362e7090acaf1567819
64dcc5353b8b0ef6d35162c29581d44446135d8a
refs/heads/master
2021-01-23T22:24:07.876586
2017-09-27T14:03:07
2017-09-27T14:03:07
83,127,799
0
0
null
null
null
null
UTF-8
C++
false
false
2,998
cpp
#include "stretchMesh.h" stretchMesh::stretchMesh() { } stretchMesh::~stretchMesh() { } void stretchMesh::update() { updateHead(); updateBody(); updateVerts(); } void stretchMesh::draw() { //draw verts } ofVec2f stretchMesh::checkCollisions() { ofVec2f desired(0, 0); if (headPos.x <= 25) { desired.x = 20; } else if (headPos.x >= ofGetWidth() - 25) { desired.x = -20; } if (headPos.y <= 0) { desired.y = 20; } else if (headPos.y >= ofGetHeight() - 25) { desired.y = -20; } return desired; } void stretchMesh::drawVerts() { ofSetLineWidth(2); ofSetColor(0); int width = 40; ofVec2f a1, a2, b1, b2; ofVec2f[] triangle = new ofVec2f[3]; int vertCount = 0; while (vertCount < vertices.size) { if (vertCount < 2) { a1 = vertices[vertCount++]; a2 = vertices[vertCount++]; } else { a1 = b1; a2 = b2; } b1 = vertices[vertCount++]; b2 = vertices[vertCount++]; ofVec2f[] triangle = = [a1, a2, b2]; this.drawTriangle(this.buffer.ctx, triangle); this.triangles.push(triangle); triangle = [a1, b2, b1]; this.drawTriangle(this.buffer.ctx, triangle); this.triangles.push(triangle); } this.buffer.ctx.stroke(); } void stretchMesh::drawTriangle() { var first = true; var v; for (var j = 0; j < 3; j++) { v = triangle[j]; if (first) { first = false; ctx.moveTo((v.x + 1) * 0.5 * this.buffer.width, (-v.y + 1) * 0.5 * this.buffer.height); } else { ctx.lineTo((v.x + 1) * 0.5 * this.buffer.width, (-v.y + 1) * 0.5 * this.buffer.height); } } v = triangle[0]; ctx.lineTo((v.x + 1) * 0.5 * this.buffer.width, (-v.y + 1) * 0.5 * this.buffer.height); } void stretchMesh::updateHead() { float time = ofGetElapsedTimef(); ofVec2f desiredVelocity = checkCollisions().normalize() * 5.0; ofVec2f noise = ofVec2f(sin(time * 0.0001), cos(time * 0.0001)) * 0.001; acceleration = noise + desiredVelocity; //limit force limit(acceleration, 0.1); speed += acceleration; //limit speed limit(speed, 14.0); headPos += speed; } void stretchMesh::updateBody() { ofVec2f previous(headPos); for (int i = 1; i < body.size; i++) { auto& node = body[i]; node = node.getInterpolated(previous, 0.1); previous = node; } } void stretchMesh::updateVerts() { int width = 40; ofVec2f perp; ofVec2f a1; int vertCount = 0; for (int i = 0; i < body.size - 1; i++) { ofVec2f &node = body[i]; ofVec2f &next = body[i + 1]; perp = ofVec2f(node.y - next.y, -(node.x - next.x)); perp.normalize(); //update verts a1 = ofVec2f(node.x + perp.x * width, node.y + perp.y * width); ofVec2f &v = vertices[vertCount++]; v.x = (a1.x / ofGetWidth()) * 2 - 1; v.y = (1 - a1.y / ofGetHeight()) * 2 - 1; a1 = ofVec2f(node.x + perp.x * -width, node.y + perp.y * -width); ofVec2f &v = vertices[vertCount++]; v.x = (a1.x / ofGetWidth()) * 2 - 1; v.y = (1 - a1.y / ofGetHeight()) * 2 - 1; } } void stretchMesh::limit(ofVec2f & vec, float max) { if (vec.length > max) vec = vec.normalize() * max; }
[ "kevmayo@gmail.com" ]
kevmayo@gmail.com
e971b013be9aa0d3a7c3dd2dd605bc498f5bce60
72d9009d19e92b721d5cc0e8f8045e1145921130
/cppRouting/inst/testfiles/Dijkstra_par/Dijkstra_par_DeepState_TestHarness.cpp
df5209194701015604e376557d55f5bf5966cfdc
[]
no_license
akhikolla/TestedPackages-NoIssues
be46c49c0836b3f0cf60e247087089868adf7a62
eb8d498cc132def615c090941bc172e17fdce267
refs/heads/master
2023-03-01T09:10:17.227119
2021-01-25T19:44:44
2021-01-25T19:44:44
332,027,727
1
0
null
null
null
null
UTF-8
C++
false
false
2,360
cpp
// AUTOMATICALLY GENERATED BY RCPPDEEPSTATE PLEASE DO NOT EDIT BY HAND, INSTEAD EDIT // Dijkstra_par_DeepState_TestHarness_generation.cpp and Dijkstra_par_DeepState_TestHarness_checks.cpp #include <fstream> #include <RInside.h> #include <iostream> #include <RcppDeepState.h> #include <qs.h> #include <DeepState.hpp> Rcpp::NumericVector Dijkstra_par(Rcpp::IntegerVector dep, Rcpp::IntegerVector arr, Rcpp::IntegerVector gfrom, Rcpp::IntegerVector gto, Rcpp::NumericVector gw, int NbNodes); TEST(cppRouting_deepstate_test,Dijkstra_par_test){ RInside R; std::cout << "input starts" << std::endl; IntegerVector dep = RcppDeepState_IntegerVector(); qs::c_qsave(dep,"/home/akhila/fuzzer_packages/fuzzedpackages/cppRouting/inst/testfiles/Dijkstra_par/inputs/dep.qs", "high", "zstd", 1, 15, true, 1); std::cout << "dep values: "<< dep << std::endl; IntegerVector arr = RcppDeepState_IntegerVector(); qs::c_qsave(arr,"/home/akhila/fuzzer_packages/fuzzedpackages/cppRouting/inst/testfiles/Dijkstra_par/inputs/arr.qs", "high", "zstd", 1, 15, true, 1); std::cout << "arr values: "<< arr << std::endl; IntegerVector gfrom = RcppDeepState_IntegerVector(); qs::c_qsave(gfrom,"/home/akhila/fuzzer_packages/fuzzedpackages/cppRouting/inst/testfiles/Dijkstra_par/inputs/gfrom.qs", "high", "zstd", 1, 15, true, 1); std::cout << "gfrom values: "<< gfrom << std::endl; IntegerVector gto = RcppDeepState_IntegerVector(); qs::c_qsave(gto,"/home/akhila/fuzzer_packages/fuzzedpackages/cppRouting/inst/testfiles/Dijkstra_par/inputs/gto.qs", "high", "zstd", 1, 15, true, 1); std::cout << "gto values: "<< gto << std::endl; NumericVector gw = RcppDeepState_NumericVector(); qs::c_qsave(gw,"/home/akhila/fuzzer_packages/fuzzedpackages/cppRouting/inst/testfiles/Dijkstra_par/inputs/gw.qs", "high", "zstd", 1, 15, true, 1); std::cout << "gw values: "<< gw << std::endl; IntegerVector NbNodes(1); NbNodes[0] = RcppDeepState_int(); qs::c_qsave(NbNodes,"/home/akhila/fuzzer_packages/fuzzedpackages/cppRouting/inst/testfiles/Dijkstra_par/inputs/NbNodes.qs", "high", "zstd", 1, 15, true, 1); std::cout << "NbNodes values: "<< NbNodes << std::endl; std::cout << "input ends" << std::endl; try{ Dijkstra_par(dep,arr,gfrom,gto,gw,NbNodes[0]); } catch(Rcpp::exception& e){ std::cout<<"Exception Handled"<<std::endl; } }
[ "akhilakollasrinu424jf@gmail.com" ]
akhilakollasrinu424jf@gmail.com
81e08880aba4a88c13124ae042e3d7ad0cb5a982
9362babf9590942f7e4c9d33468d79066bc3f5a2
/ncnn/src/layer/vulkan/convolutiondepthwise_vulkan.cpp
ad15186df385d12ad2bceeca980867adea873f71
[ "BSD-3-Clause", "Zlib", "BSD-2-Clause" ]
permissive
coko12/face_recognition
76e817603ca8f3339db0e36c576d29325ef4aa9d
47e5afa57ef11f599e5b7af89fe56e08c29fe4ed
refs/heads/master
2022-07-04T20:54:52.162753
2020-05-21T15:42:16
2020-05-21T15:42:16
265,768,501
3
0
null
null
null
null
UTF-8
C++
false
false
34,519
cpp
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. #include "convolutiondepthwise_vulkan.h" #include <algorithm> #include "layer_type.h" #include "layer_shader_type.h" namespace ncnn { DEFINE_LAYER_CREATOR(ConvolutionDepthWise_vulkan) ConvolutionDepthWise_vulkan::ConvolutionDepthWise_vulkan() { support_vulkan = true; support_image_storage = true; padding = 0; pipeline_convolutiondepthwise = 0; pipeline_convolutiondepthwise_pack4 = 0; pipeline_convolutiondepthwise_pack8 = 0; pipeline_convolutiondepthwise_group = 0; pipeline_convolutiondepthwise_group_pack4 = 0; pipeline_convolutiondepthwise_group_pack1to4 = 0; pipeline_convolutiondepthwise_group_pack4to1 = 0; pipeline_convolutiondepthwise_group_pack8 = 0; pipeline_convolutiondepthwise_group_pack1to8 = 0; pipeline_convolutiondepthwise_group_pack4to8 = 0; pipeline_convolutiondepthwise_group_pack8to4 = 0; pipeline_convolutiondepthwise_group_pack8to1 = 0; } int ConvolutionDepthWise_vulkan::create_pipeline(const Option& opt) { const Mat& shape = bottom_shapes.empty() ? Mat() : bottom_shapes[0]; const Mat& out_shape = top_shapes.empty() ? Mat() : top_shapes[0]; // the shape after padding Mat shape_bordered; if (shape.dims != 0) { if (pad_left > 0 || pad_right > 0 || pad_top > 0 || pad_bottom > 0) { shape_bordered = Mat(shape.w + pad_left + pad_right, shape.h + pad_top + pad_bottom, shape.c, (void*)0); } else if ((pad_left == -233 && pad_right == -233 && pad_top == -233 && pad_bottom == -233) || (pad_left == -234 && pad_right == -234 && pad_top == -234 && pad_bottom == -234)) { const int kernel_extent_w = dilation_w * (kernel_w - 1) + 1; const int kernel_extent_h = dilation_h * (kernel_h - 1) + 1; int wpad = kernel_extent_w + (shape.w - 1) / stride_w * stride_w - shape.w; int hpad = kernel_extent_h + (shape.h - 1) / stride_h * stride_h - shape.h; if (wpad > 0 || hpad > 0) { shape_bordered = Mat(shape.w + wpad, shape.h + hpad, shape.c, (void*)0); } } else { shape_bordered = shape; } } { padding = ncnn::create_layer(ncnn::LayerType::Padding); padding->vkdev = vkdev; padding->bottom_shapes.resize(1); padding->bottom_shapes[0] = shape; padding->top_shapes.resize(1); padding->top_shapes[0] = shape_bordered; ncnn::ParamDict pd; pd.set(0, pad_top); pd.set(1, pad_bottom); pd.set(2, pad_left); pd.set(3, pad_right); pd.set(4, 0); pd.set(5, pad_value); padding->load_param(pd); padding->create_pipeline(opt); } const int maxk = kernel_w * kernel_h; int channels = (weight_data_size / group) / maxk / (num_output / group) * group; int elempack = opt.use_shader_pack8 && channels % 8 == 0 ? 8 : channels % 4 == 0 ? 4 : 1; int out_elempack = opt.use_shader_pack8 && num_output % 8 == 0 ? 8 : num_output % 4 == 0 ? 4 : 1; size_t elemsize; size_t out_elemsize; if (opt.use_fp16_storage) { elemsize = elempack * 2u; out_elemsize = out_elempack * 2u; } else if (opt.use_fp16_packed) { elemsize = elempack == 1 ? 4u : elempack * 2u; out_elemsize = out_elempack == 1 ? 4u : out_elempack * 2u; } else { elemsize = elempack * 4u; out_elemsize = out_elempack * 4u; } Mat shape_bordered_packed; if (shape_bordered.dims == 3) shape_bordered_packed = Mat(shape_bordered.w, shape_bordered.h, shape_bordered.c / elempack, (void*)0, elemsize, elempack); Mat out_shape_packed; if (out_shape.dims == 3) out_shape_packed = Mat(out_shape.w, out_shape.h, out_shape.c / out_elempack, (void*)0, out_elemsize, out_elempack); std::vector<vk_specialization_type> specializations(11 + 10); specializations[0].i = kernel_w; specializations[1].i = kernel_h; specializations[2].i = dilation_w; specializations[3].i = dilation_h; specializations[4].i = stride_w; specializations[5].i = stride_h; specializations[6].i = bias_term; specializations[7].i = group; specializations[8].i = activation_type; specializations[9].f = activation_params.w >= 1 ? activation_params[0] : 0.f; specializations[10].f = activation_params.w == 2 ? activation_params[1] : 0.f; // depth-wise if (channels == group && group == num_output) { specializations[11 + 0].i = shape_bordered_packed.dims; specializations[11 + 1].i = shape_bordered_packed.w; specializations[11 + 2].i = shape_bordered_packed.h; specializations[11 + 3].i = shape_bordered_packed.c; specializations[11 + 4].i = shape_bordered_packed.cstep; specializations[11 + 5].i = out_shape_packed.dims; specializations[11 + 6].i = out_shape_packed.w; specializations[11 + 7].i = out_shape_packed.h; specializations[11 + 8].i = out_shape_packed.c; specializations[11 + 9].i = out_shape_packed.cstep; Mat local_size_xyz(8, 8, std::min(4, num_output / out_elempack), (void*)0); if (out_shape_packed.dims != 0) { local_size_xyz.w = std::min(8, out_shape_packed.w); local_size_xyz.h = std::min(8, out_shape_packed.h); local_size_xyz.c = std::min(4, out_shape_packed.c); } // pack1 if (elempack == 1) { pipeline_convolutiondepthwise = new Pipeline(vkdev); pipeline_convolutiondepthwise->set_optimal_local_size_xyz(local_size_xyz); pipeline_convolutiondepthwise->create(LayerShaderType::convolutiondepthwise, opt, specializations); } // pack4 if (elempack == 4) { pipeline_convolutiondepthwise_pack4 = new Pipeline(vkdev); pipeline_convolutiondepthwise_pack4->set_optimal_local_size_xyz(local_size_xyz); pipeline_convolutiondepthwise_pack4->create(LayerShaderType::convolutiondepthwise_pack4, opt, specializations); } // pack8 if (elempack == 8) { pipeline_convolutiondepthwise_pack8 = new Pipeline(vkdev); pipeline_convolutiondepthwise_pack8->set_optimal_local_size_xyz(local_size_xyz); pipeline_convolutiondepthwise_pack8->create(LayerShaderType::convolutiondepthwise_pack8, opt, specializations); } return 0; } // group convolution const int channels_g = channels / group; const int num_output_g = num_output / group; int elempack_g = opt.use_shader_pack8 && channels_g % 8 == 0 ? 8 : channels_g % 4 == 0 ? 4 : 1; int out_elempack_g = opt.use_shader_pack8 && num_output_g % 8 == 0 ? 8 : num_output_g % 4 == 0 ? 4 : 1; size_t elemsize_g; size_t out_elemsize_g; if (opt.use_fp16_storage) { elemsize_g = elempack_g * 2u; out_elemsize_g = out_elempack_g * 2u; } else if (opt.use_fp16_packed) { elemsize_g = elempack_g == 1 ? 4u : elempack_g * 2u; out_elemsize_g = out_elempack_g == 1 ? 4u : out_elempack_g * 2u; } else { elemsize_g = elempack_g * 4u; out_elemsize_g = out_elempack_g * 4u; } Mat shape_bordered_g_packed; if (shape_bordered.dims == 3) shape_bordered_g_packed = Mat(shape_bordered.w, shape_bordered.h, shape_bordered.c / elempack_g, (void*)0, elemsize_g, elempack_g); Mat out_shape_g_packed; if (out_shape.dims == 3) out_shape_g_packed = Mat(out_shape.w, out_shape.h, out_shape.c / out_elempack_g, (void*)0, out_elemsize_g, out_elempack_g); specializations[11 + 0].i = shape_bordered_g_packed.dims; specializations[11 + 1].i = shape_bordered_g_packed.w; specializations[11 + 2].i = shape_bordered_g_packed.h; specializations[11 + 3].i = shape_bordered_g_packed.c; specializations[11 + 4].i = shape_bordered_g_packed.cstep; specializations[11 + 5].i = out_shape_g_packed.dims; specializations[11 + 6].i = out_shape_g_packed.w; specializations[11 + 7].i = out_shape_g_packed.h; specializations[11 + 8].i = out_shape_g_packed.c; specializations[11 + 9].i = out_shape_g_packed.cstep; Mat local_size_xyz(8, 8, std::min(4, num_output / out_elempack_g), (void*)0); if (out_shape_g_packed.dims != 0) { local_size_xyz.w = std::min(8, out_shape_g_packed.w); local_size_xyz.h = std::min(8, out_shape_g_packed.h); local_size_xyz.c = std::min(4, out_shape_g_packed.c); } // pack1 if (elempack_g == 1 && out_elempack_g == 1) { pipeline_convolutiondepthwise_group = new Pipeline(vkdev); pipeline_convolutiondepthwise_group->set_optimal_local_size_xyz(local_size_xyz); pipeline_convolutiondepthwise_group->create(LayerShaderType::convolutiondepthwise_group, opt, specializations); } // pack4 if (elempack_g == 4 && out_elempack_g == 4) { pipeline_convolutiondepthwise_group_pack4 = new Pipeline(vkdev); pipeline_convolutiondepthwise_group_pack4->set_optimal_local_size_xyz(local_size_xyz); pipeline_convolutiondepthwise_group_pack4->create(LayerShaderType::convolutiondepthwise_group_pack4, opt, specializations); } // pack1to4 if (elempack_g == 1 && out_elempack_g == 4) { pipeline_convolutiondepthwise_group_pack1to4 = new Pipeline(vkdev); pipeline_convolutiondepthwise_group_pack1to4->set_optimal_local_size_xyz(local_size_xyz); pipeline_convolutiondepthwise_group_pack1to4->create(LayerShaderType::convolutiondepthwise_group_pack1to4, opt, specializations); } // pack4to1 if (elempack_g == 4 && out_elempack_g == 1) { pipeline_convolutiondepthwise_group_pack4to1 = new Pipeline(vkdev); pipeline_convolutiondepthwise_group_pack4to1->set_optimal_local_size_xyz(local_size_xyz); pipeline_convolutiondepthwise_group_pack4to1->create(LayerShaderType::convolutiondepthwise_group_pack4to1, opt, specializations); } // pack8 if (elempack_g == 8 && out_elempack_g == 8) { pipeline_convolutiondepthwise_group_pack8 = new Pipeline(vkdev); pipeline_convolutiondepthwise_group_pack8->set_optimal_local_size_xyz(local_size_xyz); pipeline_convolutiondepthwise_group_pack8->create(LayerShaderType::convolutiondepthwise_group_pack8, opt, specializations); } // pack1to8 if (elempack_g == 1 && out_elempack_g == 8) { pipeline_convolutiondepthwise_group_pack1to8 = new Pipeline(vkdev); pipeline_convolutiondepthwise_group_pack1to8->set_optimal_local_size_xyz(local_size_xyz); pipeline_convolutiondepthwise_group_pack1to8->create(LayerShaderType::convolutiondepthwise_group_pack1to8, opt, specializations); } // pack4to8 if (elempack_g == 4 && out_elempack_g == 8) { pipeline_convolutiondepthwise_group_pack4to8 = new Pipeline(vkdev); pipeline_convolutiondepthwise_group_pack4to8->set_optimal_local_size_xyz(local_size_xyz); pipeline_convolutiondepthwise_group_pack4to8->create(LayerShaderType::convolutiondepthwise_group_pack4to8, opt, specializations); } // pack8to4 if (elempack_g == 8 && out_elempack_g == 4) { pipeline_convolutiondepthwise_group_pack8to4 = new Pipeline(vkdev); pipeline_convolutiondepthwise_group_pack8to4->set_optimal_local_size_xyz(local_size_xyz); pipeline_convolutiondepthwise_group_pack8to4->create(LayerShaderType::convolutiondepthwise_group_pack8to4, opt, specializations); } // pack8to1 if (elempack_g == 8 && out_elempack_g == 1) { pipeline_convolutiondepthwise_group_pack8to1 = new Pipeline(vkdev); pipeline_convolutiondepthwise_group_pack8to1->set_optimal_local_size_xyz(local_size_xyz); pipeline_convolutiondepthwise_group_pack8to1->create(LayerShaderType::convolutiondepthwise_group_pack8to1, opt, specializations); } return 0; } int ConvolutionDepthWise_vulkan::destroy_pipeline(const Option& opt) { if (padding) { padding->destroy_pipeline(opt); delete padding; padding = 0; } delete pipeline_convolutiondepthwise; pipeline_convolutiondepthwise = 0; delete pipeline_convolutiondepthwise_pack4; pipeline_convolutiondepthwise_pack4 = 0; delete pipeline_convolutiondepthwise_pack8; pipeline_convolutiondepthwise_pack8 = 0; delete pipeline_convolutiondepthwise_group; pipeline_convolutiondepthwise_group = 0; delete pipeline_convolutiondepthwise_group_pack4; pipeline_convolutiondepthwise_group_pack4 = 0; delete pipeline_convolutiondepthwise_group_pack1to4; pipeline_convolutiondepthwise_group_pack1to4 = 0; delete pipeline_convolutiondepthwise_group_pack4to1; pipeline_convolutiondepthwise_group_pack4to1 = 0; delete pipeline_convolutiondepthwise_group_pack8; pipeline_convolutiondepthwise_group_pack8 = 0; delete pipeline_convolutiondepthwise_group_pack1to8; pipeline_convolutiondepthwise_group_pack1to8 = 0; delete pipeline_convolutiondepthwise_group_pack4to8; pipeline_convolutiondepthwise_group_pack4to8 = 0; delete pipeline_convolutiondepthwise_group_pack8to4; pipeline_convolutiondepthwise_group_pack8to4 = 0; delete pipeline_convolutiondepthwise_group_pack8to1; pipeline_convolutiondepthwise_group_pack8to1 = 0; return 0; } int ConvolutionDepthWise_vulkan::upload_model(VkTransfer& cmd, const Option& opt) { if (padding) { padding->upload_model(cmd, opt); } const int maxk = kernel_w * kernel_h; int channels = (weight_data_size / group) / maxk / (num_output / group) * group; int elempack = opt.use_shader_pack8 && channels % 8 == 0 ? 8 : channels % 4 == 0 ? 4 : 1; int out_elempack = opt.use_shader_pack8 && num_output % 8 == 0 ? 8 : num_output % 4 == 0 ? 4 : 1; // depth-wise if (channels == group && group == num_output) { Mat weight_data_packed; Mat weight_data_r2 = weight_data.reshape(maxk, group); convert_packing(weight_data_r2, weight_data_packed, elempack); cmd.record_upload(weight_data_packed, weight_data_gpu, opt); cmd.record_upload(weight_data_packed, weight_data_gpu_image, opt); if (bias_term) { Mat bias_data_packed; convert_packing(bias_data, bias_data_packed, out_elempack); if (opt.use_image_storage) { cmd.record_upload(bias_data_packed, bias_data_gpu_image, opt); } else { cmd.record_upload(bias_data_packed, bias_data_gpu, opt); } } return 0; } // group convolution const int channels_g = channels / group; const int num_output_g = num_output / group; int elempack_g = opt.use_shader_pack8 && channels_g % 8 == 0 ? 8 : channels_g % 4 == 0 ? 4 : 1; int out_elempack_g = opt.use_shader_pack8 && num_output_g % 8 == 0 ? 8 : num_output_g % 4 == 0 ? 4 : 1; // src = kw-kh-inch-outch // dst = pa-pb-kw-kh-inch/pa-outch/pb Mat weight_data_packed_groups; { Mat weight_data_r2_groups = weight_data.reshape(maxk, channels_g, num_output_g * group); weight_data_packed_groups.create(maxk, channels_g/elempack_g, num_output_g/out_elempack_g * group, (size_t)4*elempack_g*out_elempack_g, elempack_g*out_elempack_g); for (int g=0; g<group; g++) { const Mat weight_data_r2 = weight_data_r2_groups.channel_range(num_output_g * g, num_output_g); Mat weight_data_packed = weight_data_packed_groups.channel_range(num_output_g/out_elempack_g * g, num_output_g/out_elempack_g); for (int q=0; q+(out_elempack_g-1)<num_output_g; q+=out_elempack_g) { Mat g0 = weight_data_packed.channel(q/out_elempack_g); for (int p=0; p+(elempack_g-1)<channels_g; p+=elempack_g) { float* g00 = g0.row(p/elempack_g); for (int k=0; k<maxk; k++) { for (int i=0; i<out_elempack_g; i++) { const Mat k0 = weight_data_r2.channel(q+i); for (int j=0; j<elempack_g; j++) { const float* k00 = k0.row(p+j); g00[0] = k00[k]; g00++; } } } } } } } if (opt.use_image_storage) { cmd.record_upload(weight_data_packed_groups, weight_data_gpu_image, opt); } else { cmd.record_upload(weight_data_packed_groups, weight_data_gpu, opt); } if (bias_term) { Mat bias_data_packed; convert_packing(bias_data, bias_data_packed, out_elempack_g); if (opt.use_image_storage) { cmd.record_upload(bias_data_packed, bias_data_gpu_image, opt); } else { cmd.record_upload(bias_data_packed, bias_data_gpu, opt); } } return 0; } int ConvolutionDepthWise_vulkan::forward(const VkMat& bottom_blob, VkMat& top_blob, VkCompute& cmd, const Option& opt) const { int w = bottom_blob.w; int h = bottom_blob.h; int channels = bottom_blob.c; size_t elemsize = bottom_blob.elemsize; int elempack = bottom_blob.elempack; const int kernel_extent_w = dilation_w * (kernel_w - 1) + 1; const int kernel_extent_h = dilation_h * (kernel_h - 1) + 1; VkMat bottom_blob_bordered = bottom_blob; if (pad_left > 0 || pad_right > 0 || pad_top > 0 || pad_bottom > 0) { Option opt_pad = opt; opt_pad.blob_vkallocator = opt.workspace_vkallocator; padding->forward(bottom_blob, bottom_blob_bordered, cmd, opt_pad); } else if (pad_left == -233 && pad_right == -233 && pad_top == -233 && pad_bottom == -233) { int wpad = kernel_extent_w + (w - 1) / stride_w * stride_w - w; int hpad = kernel_extent_h + (h - 1) / stride_h * stride_h - h; if (wpad > 0 || hpad > 0) { Option opt_pad = opt; opt_pad.blob_vkallocator = opt.workspace_vkallocator; VkMat padding_param_blob(4, (size_t)4u, 1, opt.staging_vkallocator); int* padding_params = padding_param_blob.mapped(); padding_params[0] = hpad / 2; padding_params[1] = hpad - hpad / 2; padding_params[2] = wpad / 2; padding_params[3] = wpad - wpad / 2; std::vector<VkMat> padding_inputs(2); padding_inputs[0] = bottom_blob; padding_inputs[1] = padding_param_blob; std::vector<VkMat> padding_outputs(1); padding->forward(padding_inputs, padding_outputs, cmd, opt_pad); bottom_blob_bordered = padding_outputs[0]; } } else if (pad_left == -234 && pad_right == -234 && pad_top == -234 && pad_bottom == -234) { int wpad = kernel_extent_w + (w - 1) / stride_w * stride_w - w; int hpad = kernel_extent_h + (h - 1) / stride_h * stride_h - h; if (wpad > 0 || hpad > 0) { Option opt_pad = opt; opt_pad.blob_vkallocator = opt.workspace_vkallocator; VkMat padding_param_blob(4, (size_t)4u, 1, opt.staging_vkallocator); int* padding_params = padding_param_blob.mapped(); padding_params[0] = hpad - hpad / 2; padding_params[1] = hpad / 2; padding_params[2] = wpad - wpad / 2; padding_params[3] = wpad / 2; std::vector<VkMat> padding_inputs(2); padding_inputs[0] = bottom_blob; padding_inputs[1] = padding_param_blob; std::vector<VkMat> padding_outputs(1); padding->forward(padding_inputs, padding_outputs, cmd, opt_pad); bottom_blob_bordered = padding_outputs[0]; } } w = bottom_blob_bordered.w; h = bottom_blob_bordered.h; int outw = (w - kernel_extent_w) / stride_w + 1; int outh = (h - kernel_extent_h) / stride_h + 1; int out_elempack = opt.use_shader_pack8 && num_output % 8 == 0 ? 8 : num_output % 4 == 0 ? 4 : 1; size_t out_elemsize = elemsize / elempack * out_elempack; if (opt.use_fp16_packed && !opt.use_fp16_storage) { if (out_elempack == 8) out_elemsize = 8*2u; if (out_elempack == 4) out_elemsize = 4*2u; if (out_elempack == 1) out_elemsize = 4u; } top_blob.create(outw, outh, num_output / out_elempack, out_elemsize, out_elempack, opt.blob_vkallocator); if (top_blob.empty()) return -100; // depth-wise if (channels == group / elempack && group / elempack == num_output / elempack) { std::vector<VkMat> bindings(4); bindings[0] = bottom_blob_bordered; bindings[1] = top_blob; bindings[2] = weight_data_gpu; bindings[3] = bias_data_gpu; std::vector<vk_constant_type> constants(10); constants[0].i = bottom_blob_bordered.dims; constants[1].i = bottom_blob_bordered.w; constants[2].i = bottom_blob_bordered.h; constants[3].i = bottom_blob_bordered.c; constants[4].i = bottom_blob_bordered.cstep; constants[5].i = top_blob.dims; constants[6].i = top_blob.w; constants[7].i = top_blob.h; constants[8].i = top_blob.c; constants[9].i = top_blob.cstep; const Pipeline* pipeline = elempack == 8 ? pipeline_convolutiondepthwise_pack8 : elempack == 4 ? pipeline_convolutiondepthwise_pack4 : pipeline_convolutiondepthwise; cmd.record_pipeline(pipeline, bindings, constants, top_blob); return 0; } const int channels_g = channels * elempack / group; const int num_output_g = num_output / group; int elempack_g = opt.use_shader_pack8 && channels_g % 8 == 0 ? 8 : channels_g % 4 == 0 ? 4 : 1; int out_elempack_g = opt.use_shader_pack8 && num_output_g % 8 == 0 ? 8 : num_output_g % 4 == 0 ? 4 : 1; size_t out_elemsize_g = elemsize / elempack * out_elempack_g; if (opt.use_fp16_packed && !opt.use_fp16_storage) { if (out_elempack_g == 8) out_elemsize_g = 8*2u; if (out_elempack_g == 4) out_elemsize_g = 4*2u; if (out_elempack_g == 1) out_elemsize_g = 4u; } // unpacking VkMat bottom_blob_bordered_unpacked = bottom_blob_bordered; if (elempack > elempack_g) { Option opt_pack1 = opt; opt_pack1.blob_vkallocator = opt.workspace_vkallocator; vkdev->convert_packing(bottom_blob_bordered, bottom_blob_bordered_unpacked, elempack_g, cmd, opt_pack1); } VkMat top_blob_unpacked = top_blob; if (out_elempack_g < out_elempack) { top_blob_unpacked.create(outw, outh, num_output / out_elempack_g, out_elemsize_g, out_elempack_g, opt.workspace_vkallocator); if (top_blob_unpacked.empty()) return -100; } std::vector<VkMat> bindings(4); bindings[0] = bottom_blob_bordered_unpacked; bindings[1] = top_blob_unpacked; bindings[2] = weight_data_gpu; bindings[3] = bias_data_gpu; std::vector<vk_constant_type> constants(10); constants[0].i = bottom_blob_bordered_unpacked.dims; constants[1].i = bottom_blob_bordered_unpacked.w; constants[2].i = bottom_blob_bordered_unpacked.h; constants[3].i = bottom_blob_bordered_unpacked.c; constants[4].i = bottom_blob_bordered_unpacked.cstep; constants[5].i = top_blob_unpacked.dims; constants[6].i = top_blob_unpacked.w; constants[7].i = top_blob_unpacked.h; constants[8].i = top_blob_unpacked.c; constants[9].i = top_blob_unpacked.cstep; const Pipeline* pipeline = 0; if (elempack_g == 1 && out_elempack_g == 1) { pipeline = pipeline_convolutiondepthwise_group; } else if (elempack_g == 4 && out_elempack_g == 4) { pipeline = pipeline_convolutiondepthwise_group_pack4; } else if (elempack_g == 1 && out_elempack_g == 4) { pipeline = pipeline_convolutiondepthwise_group_pack1to4; } else if (elempack_g == 4 && out_elempack_g == 1) { pipeline = pipeline_convolutiondepthwise_group_pack4to1; } else if (elempack_g == 8 && out_elempack_g == 8) { pipeline = pipeline_convolutiondepthwise_group_pack8; } else if (elempack_g == 1 && out_elempack_g == 8) { pipeline = pipeline_convolutiondepthwise_group_pack1to8; } else if (elempack_g == 4 && out_elempack_g == 8) { pipeline = pipeline_convolutiondepthwise_group_pack4to8; } else if (elempack_g == 8 && out_elempack_g == 4) { pipeline = pipeline_convolutiondepthwise_group_pack8to4; } else if (elempack_g == 8 && out_elempack_g == 1) { pipeline = pipeline_convolutiondepthwise_group_pack8to1; } cmd.record_pipeline(pipeline, bindings, constants, top_blob_unpacked); // packing if (out_elempack_g < out_elempack) { vkdev->convert_packing(top_blob_unpacked, top_blob, out_elempack, cmd, opt); } else { top_blob = top_blob_unpacked; } return 0; } int ConvolutionDepthWise_vulkan::forward(const VkImageMat& bottom_blob, VkImageMat& top_blob, VkCompute& cmd, const Option& opt) const { int w = bottom_blob.w; int h = bottom_blob.h; int channels = bottom_blob.c; size_t elemsize = bottom_blob.elemsize; int elempack = bottom_blob.elempack; const int kernel_extent_w = dilation_w * (kernel_w - 1) + 1; const int kernel_extent_h = dilation_h * (kernel_h - 1) + 1; VkImageMat bottom_blob_bordered = bottom_blob; if (pad_left > 0 || pad_right > 0 || pad_top > 0 || pad_bottom > 0) { Option opt_pad = opt; opt_pad.blob_vkallocator = opt.workspace_vkallocator; padding->forward(bottom_blob, bottom_blob_bordered, cmd, opt_pad); } else if (pad_left == -233 && pad_right == -233 && pad_top == -233 && pad_bottom == -233) { int wpad = kernel_extent_w + (w - 1) / stride_w * stride_w - w; int hpad = kernel_extent_h + (h - 1) / stride_h * stride_h - h; if (wpad > 0 || hpad > 0) { Option opt_pad = opt; opt_pad.blob_vkallocator = opt.workspace_vkallocator; VkImageMat padding_param_blob(4, (size_t)4u, 1, opt.staging_vkallocator); int* padding_params = padding_param_blob.mapped(); padding_params[0] = hpad / 2; padding_params[1] = hpad - hpad / 2; padding_params[2] = wpad / 2; padding_params[3] = wpad - wpad / 2; std::vector<VkImageMat> padding_inputs(2); padding_inputs[0] = bottom_blob; padding_inputs[1] = padding_param_blob; std::vector<VkImageMat> padding_outputs(1); padding->forward(padding_inputs, padding_outputs, cmd, opt_pad); bottom_blob_bordered = padding_outputs[0]; } } else if (pad_left == -234 && pad_right == -234 && pad_top == -234 && pad_bottom == -234) { int wpad = kernel_extent_w + (w - 1) / stride_w * stride_w - w; int hpad = kernel_extent_h + (h - 1) / stride_h * stride_h - h; if (wpad > 0 || hpad > 0) { Option opt_pad = opt; opt_pad.blob_vkallocator = opt.workspace_vkallocator; VkImageMat padding_param_blob(4, (size_t)4u, 1, opt.staging_vkallocator); int* padding_params = padding_param_blob.mapped(); padding_params[0] = hpad - hpad / 2; padding_params[1] = hpad / 2; padding_params[2] = wpad - wpad / 2; padding_params[3] = wpad / 2; std::vector<VkImageMat> padding_inputs(2); padding_inputs[0] = bottom_blob; padding_inputs[1] = padding_param_blob; std::vector<VkImageMat> padding_outputs(1); padding->forward(padding_inputs, padding_outputs, cmd, opt_pad); bottom_blob_bordered = padding_outputs[0]; } } w = bottom_blob_bordered.w; h = bottom_blob_bordered.h; int outw = (w - kernel_extent_w) / stride_w + 1; int outh = (h - kernel_extent_h) / stride_h + 1; int out_elempack = opt.use_shader_pack8 && num_output % 8 == 0 ? 8 : num_output % 4 == 0 ? 4 : 1; size_t out_elemsize = elemsize / elempack * out_elempack; if (opt.use_fp16_packed && !opt.use_fp16_storage) { if (out_elempack == 8) out_elemsize = 8*2u; if (out_elempack == 4) out_elemsize = 4*2u; if (out_elempack == 1) out_elemsize = 4u; } top_blob.create(outw, outh, num_output / out_elempack, out_elemsize, out_elempack, opt.blob_vkallocator); if (top_blob.empty()) return -100; // depth-wise if (channels == group / elempack && group / elempack == num_output / elempack) { std::vector<VkImageMat> bindings(4); bindings[0] = bottom_blob_bordered; bindings[1] = top_blob; bindings[2] = weight_data_gpu_image; bindings[3] = bias_data_gpu_image; std::vector<vk_constant_type> constants(10); constants[0].i = bottom_blob_bordered.dims; constants[1].i = bottom_blob_bordered.w; constants[2].i = bottom_blob_bordered.h; constants[3].i = bottom_blob_bordered.c; constants[4].i = 0;//bottom_blob_bordered.cstep; constants[5].i = top_blob.dims; constants[6].i = top_blob.w; constants[7].i = top_blob.h; constants[8].i = top_blob.c; constants[9].i = 0;//top_blob.cstep; const Pipeline* pipeline = elempack == 8 ? pipeline_convolutiondepthwise_pack8 : elempack == 4 ? pipeline_convolutiondepthwise_pack4 : pipeline_convolutiondepthwise; cmd.record_pipeline(pipeline, bindings, constants, top_blob); return 0; } const int channels_g = channels * elempack / group; const int num_output_g = num_output / group; int elempack_g = opt.use_shader_pack8 && channels_g % 8 == 0 ? 8 : channels_g % 4 == 0 ? 4 : 1; int out_elempack_g = opt.use_shader_pack8 && num_output_g % 8 == 0 ? 8 : num_output_g % 4 == 0 ? 4 : 1; size_t out_elemsize_g = elemsize / elempack * out_elempack_g; if (opt.use_fp16_packed && !opt.use_fp16_storage) { if (out_elempack_g == 8) out_elemsize_g = 8*2u; if (out_elempack_g == 4) out_elemsize_g = 4*2u; if (out_elempack_g == 1) out_elemsize_g = 4u; } // unpacking VkImageMat bottom_blob_bordered_unpacked = bottom_blob_bordered; if (elempack > elempack_g) { Option opt_pack1 = opt; opt_pack1.blob_vkallocator = opt.workspace_vkallocator; vkdev->convert_packing(bottom_blob_bordered, bottom_blob_bordered_unpacked, elempack_g, cmd, opt_pack1); } VkImageMat top_blob_unpacked = top_blob; if (out_elempack_g < out_elempack) { top_blob_unpacked.create(outw, outh, num_output / out_elempack_g, out_elemsize_g, out_elempack_g, opt.workspace_vkallocator); if (top_blob_unpacked.empty()) return -100; } std::vector<VkImageMat> bindings(4); bindings[0] = bottom_blob_bordered_unpacked; bindings[1] = top_blob_unpacked; bindings[2] = weight_data_gpu_image; bindings[3] = bias_data_gpu_image; std::vector<vk_constant_type> constants(10); constants[0].i = bottom_blob_bordered_unpacked.dims; constants[1].i = bottom_blob_bordered_unpacked.w; constants[2].i = bottom_blob_bordered_unpacked.h; constants[3].i = bottom_blob_bordered_unpacked.c; constants[4].i = 0;//bottom_blob_bordered_unpacked.cstep; constants[5].i = top_blob_unpacked.dims; constants[6].i = top_blob_unpacked.w; constants[7].i = top_blob_unpacked.h; constants[8].i = top_blob_unpacked.c; constants[9].i = 0;//top_blob_unpacked.cstep; const Pipeline* pipeline = 0; if (elempack_g == 1 && out_elempack_g == 1) { pipeline = pipeline_convolutiondepthwise_group; } else if (elempack_g == 4 && out_elempack_g == 4) { pipeline = pipeline_convolutiondepthwise_group_pack4; } else if (elempack_g == 1 && out_elempack_g == 4) { pipeline = pipeline_convolutiondepthwise_group_pack1to4; } else if (elempack_g == 4 && out_elempack_g == 1) { pipeline = pipeline_convolutiondepthwise_group_pack4to1; } else if (elempack_g == 8 && out_elempack_g == 8) { pipeline = pipeline_convolutiondepthwise_group_pack8; } else if (elempack_g == 1 && out_elempack_g == 8) { pipeline = pipeline_convolutiondepthwise_group_pack1to8; } else if (elempack_g == 4 && out_elempack_g == 8) { pipeline = pipeline_convolutiondepthwise_group_pack4to8; } else if (elempack_g == 8 && out_elempack_g == 4) { pipeline = pipeline_convolutiondepthwise_group_pack8to4; } else if (elempack_g == 8 && out_elempack_g == 1) { pipeline = pipeline_convolutiondepthwise_group_pack8to1; } cmd.record_pipeline(pipeline, bindings, constants, top_blob_unpacked); // packing if (out_elempack_g < out_elempack) { vkdev->convert_packing(top_blob_unpacked, top_blob, out_elempack, cmd, opt); } else { top_blob = top_blob_unpacked; } return 0; } } // namespace ncnn
[ "584947226@qq.com" ]
584947226@qq.com
7979f8523590db914264e07ec8dfec2fa5a0eda0
524c4a155d8c05d434a0d2e1447931fffd82f5e2
/lib/Basic/Lexer.cpp
73ee28d8ec16448330aac93ea3aed6dfd6ed3f05
[]
no_license
CiaranWelsh/tinylang
800986880dbb9dea1b71789636c67b9bd42aa167
f3aeb75cf8f6a17084d68b7ea4b526c7e17f7c65
refs/heads/master
2023-08-31T10:59:50.086968
2021-10-12T09:14:14
2021-10-12T09:14:14
416,264,044
0
0
null
null
null
null
UTF-8
C++
false
false
2,188
cpp
// // Created by Ciaran on 11/10/2021. // #include "tinylang/Basic/Lexer.h" namespace charinfo { LLVM_READNONE inline bool isWhitespace(char c) { return c == ' ' || c == '\t' || c == '\f' || c == '\v' || c == '\r' || c == '\n'; } LLVM_READNONE inline bool isDigit(char c) { return c >= '0' && c <= '9'; } LLVM_READNONE inline bool isLetter(char c) { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); } } void Lexer::next(Token &token) { while (*BufferPtr && charinfo::isWhitespace(*BufferPtr)) { ++BufferPtr; } if (!*BufferPtr) { token.Kind = Token::TokenKind::eoi; return; } // check for word if (charinfo::isLetter(*BufferPtr)) { // start the end at the next character // and iterate the end until no more letters const char *end = BufferPtr + 1; while (charinfo::isLetter(end)) { ++end; } llvm::StringRef Name(BufferPtr, end - BufferPtr); Token::TokenKind kind = Named == "with" ? Token::KW_with : Token::ident; formToken(token, end, kind); return; } // check for digit else if (charinfo::isDigit(*BufferPtr)) { const char *end = BufferPtr + 1; while (charinfo::isDigit(end)) { ++end; } formToken(token, end, Token::number); return; } else { switch (*BufferPtr) { #define CASE(Ch, tok) case ch : formToken(Token, BufferPtr+1, tok); break CASE('+', Token::plus); CASE('-', Token::minus); CASE('*', Token::star); CASE('/', Token::slash); CASE('(', Token::Token::l_paren); CASE(')', Token::Token::r_paren); CASE(':', Token::Token::colon); CASE(',', Token::Token::comma); #undef CASE default: formToken(Token, BufferPtr+1, Token::unknown); } } return; } void Lexer::formToken(Token &Tok, const char *TokEnd, Token::TokenKind Kind) { Tok.Kind = Kind; Tok.Text = llvm::StringRef(BufferPtr, TokEnd - BufferPtr); BufferPtr = TokEnd; }
[ "cw00137@gmail.com" ]
cw00137@gmail.com
7e10767cd0c788d26b0d29f3ddca3c0a5df69233
faa64045144bf9c3ea82c1261cdadcbb36443075
/Codeforces/1462D.cpp
4206a55ae7642b1a143c6c611009188a6d362952
[]
no_license
diyajaiswal11/Competitive-Programming
a2c59e8e868ed6f4396be0440a20790ae496766a
0bdbe71a8902800daf1f8316d5b68e968b1b1fec
refs/heads/master
2023-04-11T02:39:18.663281
2021-04-24T17:35:17
2021-04-24T17:35:17
273,734,996
1
0
null
null
null
null
UTF-8
C++
false
false
1,581
cpp
#include<bits/stdc++.h> #include<vector> #include<string> #include<algorithm> #include<iostream> #include <sstream> // for string streams #include <string> using namespace std; #define fastio ios_base::sync_with_stdio(0);cin.tie(NULL);cout.tie(NULL); #define printclock cerr<<"Time : "<<1000*(ld)clock()/(ld)CLOCKS_PER_SEC<<"ms\n" #define MAX 1000000 #define mod 1000000007 #define ll long long int #define ld long double #define fr(i,n) for(ll i = 0; i<n; i++) #define frj(j,i,n) for(ll j = i; j<n; j++) #define frev(i,n) for(ll i = n-1; i>=0; i--) int main() { ll t; cin>>t; while(t--){ ll n,sum=0; cin>>n; vector<int>a(n); for(int i=0;i<n;i++) { cin>>a[i]; sum+=a[i]; } vector<int>fac; for(int i=1;i<=n;i++) { if(sum%i==0) fac.push_back(i); } //cout<<sum<<" - "; sort(fac.begin(),fac.end()); reverse(fac.begin(),fac.end()); for(int i=0;i<fac.size();i++) { fac[i]=sum/fac[i]; //cout<<fac[i]<<" "; } vector<ll>ans; for(int i=0;i<fac.size();i++) { ll target=fac[i],s=0,count=0,flag=0; for(int j=0;j<=n;j++) { if(s>target) { flag=1;break; } if(s==target) { count+=1; s=0; } if(j!=n) s+=a[j]; } if(flag==0) ans.push_back(n-count); } sort(ans.begin(),ans.end()); cout<<ans[0]<<endl; } }
[ "shubhijaiswal2000@gmail.com" ]
shubhijaiswal2000@gmail.com
e416a90ced2cdb5f66af0cd2f52d96f6dc3cf76e
b04232cf868d16e53ba20570a28e3457e8062394
/src/1330.cpp
3312be95be8e6023b1ca1e8c147f57a2af1ea73b
[]
no_license
SeungkwanKang/baekjoon_answers_cpp
7e50ee24f333a8b458a863bcc2ecfebb48937aa9
924ada1340509b9d29f8b1876bbc62b348c22013
refs/heads/main
2023-02-21T21:24:28.296065
2021-01-23T07:24:07
2021-01-23T07:24:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
337
cpp
/* Copyright https://www.acmicpc.net/problem/1330 * Comparing two numbers * KangSK */ #include <iostream> int main(void) { std::cin.tie(NULL); std::ios_base::sync_with_stdio(false); int a, b; std::cin >> a >> b; if (a > b) std::cout << ">\n"; else if (a == b) std::cout << "==\n"; else std::cout << "<\n"; return 0; }
[ "steelyk7@gmail.com" ]
steelyk7@gmail.com
39eea09afc71e3282e036a020bbb488e3f2ba07e
84432492da25d39eda70486c3cfd6cc0d1b16e13
/App/Source/Threading/ThreadPool.cpp
5e188ddf4cdf97156f5b95394ef65327a1105b2f
[ "MIT" ]
permissive
Clymiaru/GDPARCM_RealtimeSceneViewer
997dad7a19e4c55ac5ef5404bbfe852296891702
caf399dc819fe5fcc9c7445f74b1958af09e21de
refs/heads/main
2023-05-13T03:29:11.686323
2021-05-31T17:16:53
2021-05-31T17:16:53
364,503,494
0
0
null
null
null
null
UTF-8
C++
false
false
1,756
cpp
#include "pch.h" #include "ThreadPool.h" #include "PoolWorkerThread.h" ThreadPool::ThreadPool(String name, int numWorkers) { this->name = name; this->numWorkers = numWorkers; for (int i = 0; i < this->numWorkers; i++) this->inactiveThreads.push(new PoolWorkerThread(i, this)); } ThreadPool::~ThreadPool() { } void ThreadPool::startScheduler() { this->running = true; this->Start(); } void ThreadPool::stopScheduler() { this->running = false; } void ThreadPool::scheduleTask(IWorkerAction* action) { this->pendingActions.push(action); } void ThreadPool::run() { while (this->running) { if (this->pendingActions.empty() == false) { if (this->inactiveThreads.empty() == false) { //schedule task PoolWorkerThread* workerThread = this->inactiveThreads.front(); this->inactiveThreads.pop(); this->activeThreads[workerThread->getThreadID()] = workerThread; workerThread->AssignTask(this->pendingActions.front()); workerThread->Start(); //std::cout << "[ThreadPool " << this->name << "] Scheduled task on ID " << workerThread->getThreadID() << std::endl; this->pendingActions.pop(); } //else std::cout << "[ThreadPool " << this->name << "] No more available worker thread" << std::endl; } //else std::cout << "[ThreadPool " << this->name << "] No actions scheduled" << std::endl; } } void ThreadPool::OnFinished(int threadID) { if (this->activeThreads[threadID] != nullptr) { // create a fresh instance of a thread worker after execution delete this->activeThreads[threadID]; this->activeThreads.erase(threadID); this->inactiveThreads.push(new PoolWorkerThread(threadID, this)); //std::cout << "[ThreadPool " << this->name << "] Task ended on ID " << threadID << std::endl; } }
[ "" ]
70d73fde87087fd33f63566be77e190dc0d39dee
7ec7adb25e06d715866bd61f5f03ddee44008b03
/src/util.cpp
d3650e382e596f7a0826389007087fc3b468a190
[ "MIT" ]
permissive
Ebankerio/ebanker-coin
8447ebb0e44815deb04d19973363c1b050515c74
080852d64686f5ebe52ea38c91122ba6c0cf12cd
refs/heads/master
2020-03-17T11:35:53.658580
2018-05-15T18:31:39
2018-05-15T18:31:39
132,846,866
0
0
null
null
null
null
UTF-8
C++
false
false
42,204
cpp
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The EBanker developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef WIN32 // for posix_fallocate #ifdef __linux__ #define _POSIX_C_SOURCE 200112L #endif #include <fcntl.h> #include <sys/stat.h> #include <sys/resource.h> #endif #include "chainparams.h" #include "util.h" #include "sync.h" #include "version.h" #include "ui_interface.h" #include <boost/algorithm/string/join.hpp> #include <boost/algorithm/string/case_conv.hpp> // for to_lower() #include <boost/algorithm/string/predicate.hpp> // for startswith() and endswith() // Work around clang compilation problem in Boost 1.46: // /usr/include/boost/program_options/detail/config_file.hpp:163:17: error: call to function 'to_internal' that is neither visible in the template definition nor found by argument-dependent lookup // See also: http://stackoverflow.com/questions/10020179/compilation-fail-in-boost-librairies-program-options // http://clang.debian.net/status.php?version=3.0&key=CANNOT_FIND_FUNCTION namespace boost { namespace program_options { std::string to_internal(const std::string&); } } #include <boost/program_options/detail/config_file.hpp> #include <boost/program_options/parsers.hpp> #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> #include <boost/foreach.hpp> #include <boost/thread.hpp> #include <openssl/crypto.h> #include <openssl/rand.h> #include <stdarg.h> #ifdef WIN32 #ifdef _MSC_VER #pragma warning(disable:4786) #pragma warning(disable:4804) #pragma warning(disable:4805) #pragma warning(disable:4717) #endif #ifdef _WIN32_WINNT #undef _WIN32_WINNT #endif #define _WIN32_WINNT 0x0501 #ifdef _WIN32_IE #undef _WIN32_IE #endif #define _WIN32_IE 0x0501 #define WIN32_LEAN_AND_MEAN 1 #ifndef NOMINMAX #define NOMINMAX #endif #include <io.h> /* for _commit */ #include "shlobj.h" #elif defined(__linux__) # include <sys/prctl.h> #endif using namespace std; map<string, string> mapArgs; map<string, vector<string> > mapMultiArgs; bool fDebug = false; bool fDebugNet = false; bool fPrintToConsole = false; bool fPrintToDebugger = false; bool fDaemon = false; bool fServer = false; bool fCommandLine = false; string strMiscWarning; bool fNoListen = false; bool fLogTimestamps = false; CMedianFilter<int64> vTimeOffsets(200,0); volatile bool fReopenDebugLog = false; bool fCachedPath[2] = {false, false}; // Init OpenSSL library multithreading support static CCriticalSection** ppmutexOpenSSL; void locking_callback(int mode, int i, const char* file, int line) { if (mode & CRYPTO_LOCK) { ENTER_CRITICAL_SECTION(*ppmutexOpenSSL[i]); } else { LEAVE_CRITICAL_SECTION(*ppmutexOpenSSL[i]); } } LockedPageManager LockedPageManager::instance; // Init class CInit { public: CInit() { // Init OpenSSL library multithreading support ppmutexOpenSSL = (CCriticalSection**)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(CCriticalSection*)); for (int i = 0; i < CRYPTO_num_locks(); i++) ppmutexOpenSSL[i] = new CCriticalSection(); CRYPTO_set_locking_callback(locking_callback); #ifdef WIN32 // Seed random number generator with screen scrape and other hardware sources RAND_screen(); #endif // Seed random number generator with performance counter RandAddSeed(); } ~CInit() { // Shutdown OpenSSL library multithreading support CRYPTO_set_locking_callback(NULL); for (int i = 0; i < CRYPTO_num_locks(); i++) delete ppmutexOpenSSL[i]; OPENSSL_free(ppmutexOpenSSL); } } instance_of_cinit; void RandAddSeed() { // Seed with CPU performance counter int64 nCounter = GetPerformanceCounter(); RAND_add(&nCounter, sizeof(nCounter), 1.5); memset(&nCounter, 0, sizeof(nCounter)); } void RandAddSeedPerfmon() { RandAddSeed(); // This can take up to 2 seconds, so only do it every 10 minutes static int64 nLastPerfmon; if (GetTime() < nLastPerfmon + 10 * 60) return; nLastPerfmon = GetTime(); #ifdef WIN32 // Don't need this on Linux, OpenSSL automatically uses /dev/urandom // Seed with the entire set of perfmon data unsigned char pdata[250000]; memset(pdata, 0, sizeof(pdata)); unsigned long nSize = sizeof(pdata); long ret = RegQueryValueExA(HKEY_PERFORMANCE_DATA, "Global", NULL, NULL, pdata, &nSize); RegCloseKey(HKEY_PERFORMANCE_DATA); if (ret == ERROR_SUCCESS) { RAND_add(pdata, nSize, nSize/100.0); OPENSSL_cleanse(pdata, nSize); printf("RandAddSeed() %lu bytes\n", nSize); } #endif } uint64 GetRand(uint64 nMax) { if (nMax == 0) return 0; // The range of the random source must be a multiple of the modulus // to give every possible output value an equal possibility uint64 nRange = (std::numeric_limits<uint64>::max() / nMax) * nMax; uint64 nRand = 0; do RAND_bytes((unsigned char*)&nRand, sizeof(nRand)); while (nRand >= nRange); return (nRand % nMax); } int GetRandInt(int nMax) { return GetRand(nMax); } uint256 GetRandHash() { uint256 hash; RAND_bytes((unsigned char*)&hash, sizeof(hash)); return hash; } // // OutputDebugStringF (aka printf -- there is a #define that we really // should get rid of one day) has been broken a couple of times now // by well-meaning people adding mutexes in the most straightforward way. // It breaks because it may be called by global destructors during shutdown. // Since the order of destruction of static/global objects is undefined, // defining a mutex as a global object doesn't work (the mutex gets // destroyed, and then some later destructor calls OutputDebugStringF, // maybe indirectly, and you get a core dump at shutdown trying to lock // the mutex). static boost::once_flag debugPrintInitFlag = BOOST_ONCE_INIT; // We use boost::call_once() to make sure these are initialized in // in a thread-safe manner the first time it is called: static FILE* fileout = NULL; static boost::mutex* mutexDebugLog = NULL; static void DebugPrintInit() { assert(fileout == NULL); assert(mutexDebugLog == NULL); boost::filesystem::path pathDebug = GetDataDir() / "debug.log"; fileout = fopen(pathDebug.string().c_str(), "a"); if (fileout) setbuf(fileout, NULL); // unbuffered mutexDebugLog = new boost::mutex(); } int OutputDebugStringF(const char* pszFormat, ...) { int ret = 0; // Returns total number of characters written if (fPrintToConsole) { // print to console va_list arg_ptr; va_start(arg_ptr, pszFormat); ret += vprintf(pszFormat, arg_ptr); va_end(arg_ptr); } else if (!fPrintToDebugger) { static bool fStartedNewLine = true; boost::call_once(&DebugPrintInit, debugPrintInitFlag); if (fileout == NULL) return ret; boost::mutex::scoped_lock scoped_lock(*mutexDebugLog); // reopen the log file, if requested if (fReopenDebugLog) { fReopenDebugLog = false; boost::filesystem::path pathDebug = GetDataDir() / "debug.log"; if (freopen(pathDebug.string().c_str(),"a",fileout) != NULL) setbuf(fileout, NULL); // unbuffered } // Debug print useful for profiling if (fLogTimestamps && fStartedNewLine) ret += fprintf(fileout, "%s ", DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime()).c_str()); if (pszFormat[strlen(pszFormat) - 1] == '\n') fStartedNewLine = true; else fStartedNewLine = false; va_list arg_ptr; va_start(arg_ptr, pszFormat); ret += vfprintf(fileout, pszFormat, arg_ptr); va_end(arg_ptr); } #ifdef WIN32 if (fPrintToDebugger) { static CCriticalSection cs_OutputDebugStringF; // accumulate and output a line at a time { LOCK(cs_OutputDebugStringF); static std::string buffer; va_list arg_ptr; va_start(arg_ptr, pszFormat); buffer += vstrprintf(pszFormat, arg_ptr); va_end(arg_ptr); int line_start = 0, line_end; while((line_end = buffer.find('\n', line_start)) != -1) { OutputDebugStringA(buffer.substr(line_start, line_end - line_start).c_str()); line_start = line_end + 1; ret += line_end-line_start; } buffer.erase(0, line_start); } } #endif return ret; } string vstrprintf(const char *format, va_list ap) { char buffer[50000]; char* p = buffer; int limit = sizeof(buffer); int ret; while (true) { va_list arg_ptr; va_copy(arg_ptr, ap); #ifdef WIN32 ret = _vsnprintf(p, limit, format, arg_ptr); #else ret = vsnprintf(p, limit, format, arg_ptr); #endif va_end(arg_ptr); if (ret >= 0 && ret < limit) break; if (p != buffer) delete[] p; limit *= 2; p = new char[limit]; if (p == NULL) throw std::bad_alloc(); } string str(p, p+ret); if (p != buffer) delete[] p; return str; } string real_strprintf(const char *format, int dummy, ...) { va_list arg_ptr; va_start(arg_ptr, dummy); string str = vstrprintf(format, arg_ptr); va_end(arg_ptr); return str; } string real_strprintf(const std::string &format, int dummy, ...) { va_list arg_ptr; va_start(arg_ptr, dummy); string str = vstrprintf(format.c_str(), arg_ptr); va_end(arg_ptr); return str; } bool error(const char *format, ...) { va_list arg_ptr; va_start(arg_ptr, format); std::string str = vstrprintf(format, arg_ptr); va_end(arg_ptr); printf("ERROR: %s\n", str.c_str()); return false; } void ParseString(const string& str, char c, vector<string>& v) { if (str.empty()) return; string::size_type i1 = 0; string::size_type i2; while (true) { i2 = str.find(c, i1); if (i2 == str.npos) { v.push_back(str.substr(i1)); return; } v.push_back(str.substr(i1, i2-i1)); i1 = i2+1; } } string FormatMoney(int64 n, bool fPlus) { // Note: not using straight sprintf here because we do NOT want // localized number formatting. int64 n_abs = (n > 0 ? n : -n); int64 quotient = n_abs/COIN; int64 remainder = n_abs%COIN; string str = strprintf("%"PRI64d".%08"PRI64d, quotient, remainder); // Right-trim excess zeros before the decimal point: int nTrim = 0; for (int i = str.size()-1; (str[i] == '0' && isdigit(str[i-2])); --i) ++nTrim; if (nTrim) str.erase(str.size()-nTrim, nTrim); if (n < 0) str.insert((unsigned int)0, 1, '-'); else if (fPlus && n > 0) str.insert((unsigned int)0, 1, '+'); return str; } bool ParseMoney(const string& str, int64& nRet) { return ParseMoney(str.c_str(), nRet); } bool ParseMoney(const char* pszIn, int64& nRet) { string strWhole; int64 nUnits = 0; const char* p = pszIn; while (isspace(*p)) p++; for (; *p; p++) { if (*p == '.') { p++; int64 nMult = CENT*10; while (isdigit(*p) && (nMult > 0)) { nUnits += nMult * (*p++ - '0'); nMult /= 10; } break; } if (isspace(*p)) break; if (!isdigit(*p)) return false; strWhole.insert(strWhole.end(), *p); } for (; *p; p++) if (!isspace(*p)) return false; if (strWhole.size() > 10) // guard against 63 bit overflow return false; if (nUnits < 0 || nUnits > COIN) return false; int64 nWhole = atoi64(strWhole); int64 nValue = nWhole*COIN + nUnits; nRet = nValue; return true; } static const signed char phexdigit[256] = { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1, -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, }; bool IsHex(const string& str) { BOOST_FOREACH(unsigned char c, str) { if (phexdigit[c] < 0) return false; } return (str.size() > 0) && (str.size()%2 == 0); } vector<unsigned char> ParseHex(const char* psz) { // convert hex dump to vector vector<unsigned char> vch; while (true) { while (isspace(*psz)) psz++; signed char c = phexdigit[(unsigned char)*psz++]; if (c == (signed char)-1) break; unsigned char n = (c << 4); c = phexdigit[(unsigned char)*psz++]; if (c == (signed char)-1) break; n |= c; vch.push_back(n); } return vch; } vector<unsigned char> ParseHex(const string& str) { return ParseHex(str.c_str()); } static void InterpretNegativeSetting(string name, map<string, string>& mapSettingsRet) { // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set if (name.find("-no") == 0) { std::string positive("-"); positive.append(name.begin()+3, name.end()); if (mapSettingsRet.count(positive) == 0) { bool value = !GetBoolArg(name, false); mapSettingsRet[positive] = (value ? "1" : "0"); } } } void ParseParameters(int argc, const char* const argv[]) { mapArgs.clear(); mapMultiArgs.clear(); for (int i = 1; i < argc; i++) { std::string str(argv[i]); std::string strValue; size_t is_index = str.find('='); if (is_index != std::string::npos) { strValue = str.substr(is_index+1); str = str.substr(0, is_index); } #ifdef WIN32 boost::to_lower(str); if (boost::algorithm::starts_with(str, "/")) str = "-" + str.substr(1); #endif if (str[0] != '-') break; mapArgs[str] = strValue; mapMultiArgs[str].push_back(strValue); } // New 0.6 features: BOOST_FOREACH(const PAIRTYPE(string,string)& entry, mapArgs) { string name = entry.first; // interpret --foo as -foo (as long as both are not set) if (name.find("--") == 0) { std::string singleDash(name.begin()+1, name.end()); if (mapArgs.count(singleDash) == 0) mapArgs[singleDash] = entry.second; name = singleDash; } // interpret -nofoo as -foo=0 (and -nofoo=0 as -foo=1) as long as -foo not set InterpretNegativeSetting(name, mapArgs); } } std::string GetArg(const std::string& strArg, const std::string& strDefault) { if (mapArgs.count(strArg)) return mapArgs[strArg]; return strDefault; } int64 GetArg(const std::string& strArg, int64 nDefault) { if (mapArgs.count(strArg)) return atoi64(mapArgs[strArg]); return nDefault; } bool GetBoolArg(const std::string& strArg, bool fDefault) { if (mapArgs.count(strArg)) { if (mapArgs[strArg].empty()) return true; return (atoi(mapArgs[strArg]) != 0); } return fDefault; } bool SoftSetArg(const std::string& strArg, const std::string& strValue) { if (mapArgs.count(strArg)) return false; mapArgs[strArg] = strValue; return true; } bool SoftSetBoolArg(const std::string& strArg, bool fValue) { if (fValue) return SoftSetArg(strArg, std::string("1")); else return SoftSetArg(strArg, std::string("0")); } string EncodeBase64(const unsigned char* pch, size_t len) { static const char *pbase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; string strRet=""; strRet.reserve((len+2)/3*4); int mode=0, left=0; const unsigned char *pchEnd = pch+len; while (pch<pchEnd) { int enc = *(pch++); switch (mode) { case 0: // we have no bits strRet += pbase64[enc >> 2]; left = (enc & 3) << 4; mode = 1; break; case 1: // we have two bits strRet += pbase64[left | (enc >> 4)]; left = (enc & 15) << 2; mode = 2; break; case 2: // we have four bits strRet += pbase64[left | (enc >> 6)]; strRet += pbase64[enc & 63]; mode = 0; break; } } if (mode) { strRet += pbase64[left]; strRet += '='; if (mode == 1) strRet += '='; } return strRet; } string EncodeBase64(const string& str) { return EncodeBase64((const unsigned char*)str.c_str(), str.size()); } vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid) { static const int decode64_table[256] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }; if (pfInvalid) *pfInvalid = false; vector<unsigned char> vchRet; vchRet.reserve(strlen(p)*3/4); int mode = 0; int left = 0; while (1) { int dec = decode64_table[(unsigned char)*p]; if (dec == -1) break; p++; switch (mode) { case 0: // we have no bits and get 6 left = dec; mode = 1; break; case 1: // we have 6 bits and keep 4 vchRet.push_back((left<<2) | (dec>>4)); left = dec & 15; mode = 2; break; case 2: // we have 4 bits and get 6, we keep 2 vchRet.push_back((left<<4) | (dec>>2)); left = dec & 3; mode = 3; break; case 3: // we have 2 bits and get 6 vchRet.push_back((left<<6) | dec); mode = 0; break; } } if (pfInvalid) switch (mode) { case 0: // 4n base64 characters processed: ok break; case 1: // 4n+1 base64 character processed: impossible *pfInvalid = true; break; case 2: // 4n+2 base64 characters processed: require '==' if (left || p[0] != '=' || p[1] != '=' || decode64_table[(unsigned char)p[2]] != -1) *pfInvalid = true; break; case 3: // 4n+3 base64 characters processed: require '=' if (left || p[0] != '=' || decode64_table[(unsigned char)p[1]] != -1) *pfInvalid = true; break; } return vchRet; } string DecodeBase64(const string& str) { vector<unsigned char> vchRet = DecodeBase64(str.c_str()); return string((const char*)&vchRet[0], vchRet.size()); } string EncodeBase32(const unsigned char* pch, size_t len) { static const char *pbase32 = "abcdefghijklmnopqrstuvwxyz234567"; string strRet=""; strRet.reserve((len+4)/5*8); int mode=0, left=0; const unsigned char *pchEnd = pch+len; while (pch<pchEnd) { int enc = *(pch++); switch (mode) { case 0: // we have no bits strRet += pbase32[enc >> 3]; left = (enc & 7) << 2; mode = 1; break; case 1: // we have three bits strRet += pbase32[left | (enc >> 6)]; strRet += pbase32[(enc >> 1) & 31]; left = (enc & 1) << 4; mode = 2; break; case 2: // we have one bit strRet += pbase32[left | (enc >> 4)]; left = (enc & 15) << 1; mode = 3; break; case 3: // we have four bits strRet += pbase32[left | (enc >> 7)]; strRet += pbase32[(enc >> 2) & 31]; left = (enc & 3) << 3; mode = 4; break; case 4: // we have two bits strRet += pbase32[left | (enc >> 5)]; strRet += pbase32[enc & 31]; mode = 0; } } static const int nPadding[5] = {0, 6, 4, 3, 1}; if (mode) { strRet += pbase32[left]; for (int n=0; n<nPadding[mode]; n++) strRet += '='; } return strRet; } string EncodeBase32(const string& str) { return EncodeBase32((const unsigned char*)str.c_str(), str.size()); } vector<unsigned char> DecodeBase32(const char* p, bool* pfInvalid) { static const int decode32_table[256] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }; if (pfInvalid) *pfInvalid = false; vector<unsigned char> vchRet; vchRet.reserve((strlen(p))*5/8); int mode = 0; int left = 0; while (1) { int dec = decode32_table[(unsigned char)*p]; if (dec == -1) break; p++; switch (mode) { case 0: // we have no bits and get 5 left = dec; mode = 1; break; case 1: // we have 5 bits and keep 2 vchRet.push_back((left<<3) | (dec>>2)); left = dec & 3; mode = 2; break; case 2: // we have 2 bits and keep 7 left = left << 5 | dec; mode = 3; break; case 3: // we have 7 bits and keep 4 vchRet.push_back((left<<1) | (dec>>4)); left = dec & 15; mode = 4; break; case 4: // we have 4 bits, and keep 1 vchRet.push_back((left<<4) | (dec>>1)); left = dec & 1; mode = 5; break; case 5: // we have 1 bit, and keep 6 left = left << 5 | dec; mode = 6; break; case 6: // we have 6 bits, and keep 3 vchRet.push_back((left<<2) | (dec>>3)); left = dec & 7; mode = 7; break; case 7: // we have 3 bits, and keep 0 vchRet.push_back((left<<5) | dec); mode = 0; break; } } if (pfInvalid) switch (mode) { case 0: // 8n base32 characters processed: ok break; case 1: // 8n+1 base32 characters processed: impossible case 3: // +3 case 6: // +6 *pfInvalid = true; break; case 2: // 8n+2 base32 characters processed: require '======' if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || p[4] != '=' || p[5] != '=' || decode32_table[(unsigned char)p[6]] != -1) *pfInvalid = true; break; case 4: // 8n+4 base32 characters processed: require '====' if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || decode32_table[(unsigned char)p[4]] != -1) *pfInvalid = true; break; case 5: // 8n+5 base32 characters processed: require '===' if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || decode32_table[(unsigned char)p[3]] != -1) *pfInvalid = true; break; case 7: // 8n+7 base32 characters processed: require '=' if (left || p[0] != '=' || decode32_table[(unsigned char)p[1]] != -1) *pfInvalid = true; break; } return vchRet; } string DecodeBase32(const string& str) { vector<unsigned char> vchRet = DecodeBase32(str.c_str()); return string((const char*)&vchRet[0], vchRet.size()); } bool WildcardMatch(const char* psz, const char* mask) { while (true) { switch (*mask) { case '\0': return (*psz == '\0'); case '*': return WildcardMatch(psz, mask+1) || (*psz && WildcardMatch(psz+1, mask)); case '?': if (*psz == '\0') return false; break; default: if (*psz != *mask) return false; break; } psz++; mask++; } } bool WildcardMatch(const string& str, const string& mask) { return WildcardMatch(str.c_str(), mask.c_str()); } static std::string FormatException(std::exception* pex, const char* pszThread) { #ifdef WIN32 char pszModule[MAX_PATH] = ""; GetModuleFileNameA(NULL, pszModule, sizeof(pszModule)); #else const char* pszModule = "ebanker"; #endif if (pex) return strprintf( "EXCEPTION: %s \n%s \n%s in %s \n", typeid(*pex).name(), pex->what(), pszModule, pszThread); else return strprintf( "UNKNOWN EXCEPTION \n%s in %s \n", pszModule, pszThread); } void LogException(std::exception* pex, const char* pszThread) { std::string message = FormatException(pex, pszThread); printf("\n%s", message.c_str()); } void PrintException(std::exception* pex, const char* pszThread) { std::string message = FormatException(pex, pszThread); printf("\n\n************************\n%s\n", message.c_str()); fprintf(stderr, "\n\n************************\n%s\n", message.c_str()); strMiscWarning = message; throw; } void PrintExceptionContinue(std::exception* pex, const char* pszThread) { std::string message = FormatException(pex, pszThread); printf("\n\n************************\n%s\n", message.c_str()); fprintf(stderr, "\n\n************************\n%s\n", message.c_str()); strMiscWarning = message; } boost::filesystem::path GetDefaultDataDir() { namespace fs = boost::filesystem; // Windows < Vista: C:\Documents and Settings\Username\Application Data\EBanker // Windows >= Vista: C:\Users\Username\AppData\Roaming\EBanker // Mac: ~/Library/Application Support/EBanker // Unix: ~/.ebanker #ifdef WIN32 // Windows return GetSpecialFolderPath(CSIDL_APPDATA) / "EBanker"; #else fs::path pathRet; char* pszHome = getenv("HOME"); if (pszHome == NULL || strlen(pszHome) == 0) pathRet = fs::path("/"); else pathRet = fs::path(pszHome); #ifdef MAC_OSX // Mac pathRet /= "Library/Application Support"; fs::create_directory(pathRet); return pathRet / "EBanker"; #else // Unix return pathRet / ".ebanker"; #endif #endif } const boost::filesystem::path &GetDataDir(bool fNetSpecific) { namespace fs = boost::filesystem; static fs::path pathCached[2]; static CCriticalSection csPathCached; fs::path &path = pathCached[fNetSpecific]; // This can be called during exceptions by printf, so we cache the // value so we don't have to do memory allocations after that. if (fCachedPath[fNetSpecific]) return path; LOCK(csPathCached); if (mapArgs.count("-datadir")) { path = fs::system_complete(mapArgs["-datadir"]); if (!fs::is_directory(path)) { path = ""; return path; } } else { path = GetDefaultDataDir(); } if (fNetSpecific) path /= Params().DataDir(); fs::create_directories(path); fCachedPath[fNetSpecific] = true; return path; } boost::filesystem::path GetConfigFile() { boost::filesystem::path pathConfigFile(GetArg("-conf", "ebanker.conf")); if (!pathConfigFile.is_complete()) pathConfigFile = GetDataDir(false) / pathConfigFile; return pathConfigFile; } void ReadConfigFile(map<string, string>& mapSettingsRet, map<string, vector<string> >& mapMultiSettingsRet) { boost::filesystem::ifstream streamConfig(GetConfigFile()); if (!streamConfig.good()) return; // No ebanker.conf file is OK // clear path cache after loading config file fCachedPath[0] = fCachedPath[1] = false; set<string> setOptions; setOptions.insert("*"); for (boost::program_options::detail::config_file_iterator it(streamConfig, setOptions), end; it != end; ++it) { // Don't overwrite existing settings so command line settings override ebanker.conf string strKey = string("-") + it->string_key; if (mapSettingsRet.count(strKey) == 0) { mapSettingsRet[strKey] = it->value[0]; // interpret nofoo=1 as foo=0 (and nofoo=0 as foo=1) as long as foo not set) InterpretNegativeSetting(strKey, mapSettingsRet); } mapMultiSettingsRet[strKey].push_back(it->value[0]); } } boost::filesystem::path GetPidFile() { boost::filesystem::path pathPidFile(GetArg("-pid", "ebankerd.pid")); if (!pathPidFile.is_complete()) pathPidFile = GetDataDir() / pathPidFile; return pathPidFile; } #ifndef WIN32 void CreatePidFile(const boost::filesystem::path &path, pid_t pid) { FILE* file = fopen(path.string().c_str(), "w"); if (file) { fprintf(file, "%d\n", pid); fclose(file); } } #endif bool RenameOver(boost::filesystem::path src, boost::filesystem::path dest) { #ifdef WIN32 return MoveFileExA(src.string().c_str(), dest.string().c_str(), MOVEFILE_REPLACE_EXISTING); #else int rc = std::rename(src.string().c_str(), dest.string().c_str()); return (rc == 0); #endif /* WIN32 */ } void FileCommit(FILE *fileout) { fflush(fileout); // harmless if redundantly called #ifdef WIN32 _commit(_fileno(fileout)); #else #if defined(__linux__) || defined(__NetBSD__) fdatasync(fileno(fileout)); #else fsync(fileno(fileout)); #endif #endif } int GetFilesize(FILE* file) { int nSavePos = ftell(file); int nFilesize = -1; if (fseek(file, 0, SEEK_END) == 0) nFilesize = ftell(file); fseek(file, nSavePos, SEEK_SET); return nFilesize; } bool TruncateFile(FILE *file, unsigned int length) { #if defined(WIN32) return _chsize(_fileno(file), length) == 0; #else return ftruncate(fileno(file), length) == 0; #endif } // this function tries to raise the file descriptor limit to the requested number. // It returns the actual file descriptor limit (which may be more or less than nMinFD) int RaiseFileDescriptorLimit(int nMinFD) { #if defined(WIN32) return 2048; #else struct rlimit limitFD; if (getrlimit(RLIMIT_NOFILE, &limitFD) != -1) { if (limitFD.rlim_cur < (rlim_t)nMinFD) { limitFD.rlim_cur = nMinFD; if (limitFD.rlim_cur > limitFD.rlim_max) limitFD.rlim_cur = limitFD.rlim_max; setrlimit(RLIMIT_NOFILE, &limitFD); getrlimit(RLIMIT_NOFILE, &limitFD); } return limitFD.rlim_cur; } return nMinFD; // getrlimit failed, assume it's fine #endif } // this function tries to make a particular range of a file allocated (corresponding to disk space) // it is advisory, and the range specified in the arguments will never contain live data void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length) { #if defined(WIN32) // Windows-specific version HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file)); LARGE_INTEGER nFileSize; int64 nEndPos = (int64)offset + length; nFileSize.u.LowPart = nEndPos & 0xFFFFFFFF; nFileSize.u.HighPart = nEndPos >> 32; SetFilePointerEx(hFile, nFileSize, 0, FILE_BEGIN); SetEndOfFile(hFile); #elif defined(MAC_OSX) // OSX specific version fstore_t fst; fst.fst_flags = F_ALLOCATECONTIG; fst.fst_posmode = F_PEOFPOSMODE; fst.fst_offset = 0; fst.fst_length = (off_t)offset + length; fst.fst_bytesalloc = 0; if (fcntl(fileno(file), F_PREALLOCATE, &fst) == -1) { fst.fst_flags = F_ALLOCATEALL; fcntl(fileno(file), F_PREALLOCATE, &fst); } ftruncate(fileno(file), fst.fst_length); #elif defined(__linux__) // Version using posix_fallocate off_t nEndPos = (off_t)offset + length; posix_fallocate(fileno(file), 0, nEndPos); #else // Fallback version // TODO: just write one byte per block static const char buf[65536] = {}; fseek(file, offset, SEEK_SET); while (length > 0) { unsigned int now = 65536; if (length < now) now = length; fwrite(buf, 1, now, file); // allowed to fail; this function is advisory anyway length -= now; } #endif } void ShrinkDebugFile() { // Scroll debug.log if it's getting too big boost::filesystem::path pathLog = GetDataDir() / "debug.log"; FILE* file = fopen(pathLog.string().c_str(), "r"); if (file && GetFilesize(file) > 10 * 1000000) { // Restart the file with some of the end char pch[200000]; fseek(file, -sizeof(pch), SEEK_END); int nBytes = fread(pch, 1, sizeof(pch), file); fclose(file); file = fopen(pathLog.string().c_str(), "w"); if (file) { fwrite(pch, 1, nBytes, file); fclose(file); } } else if (file != NULL) fclose(file); } // // "Never go to sea with two chronometers; take one or three." // Our three time sources are: // - System clock // - Median of other nodes clocks // - The user (asking the user to fix the system clock if the first two disagree) // static int64 nMockTime = 0; // For unit testing int64 GetTime() { if (nMockTime) return nMockTime; return time(NULL); } void SetMockTime(int64 nMockTimeIn) { nMockTime = nMockTimeIn; } static int64 nTimeOffset = 0; int64 GetTimeOffset() { return nTimeOffset; } int64 GetAdjustedTime() { return GetTime() + GetTimeOffset(); } void AddTimeData(const CNetAddr& ip, int64 nTime) { int64 nOffsetSample = nTime - GetTime(); // Ignore duplicates static set<CNetAddr> setKnown; if (!setKnown.insert(ip).second) return; // Add data vTimeOffsets.input(nOffsetSample); printf("Added time data, samples %d, offset %+"PRI64d" (%+"PRI64d" minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60); if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1) { int64 nMedian = vTimeOffsets.median(); std::vector<int64> vSorted = vTimeOffsets.sorted(); // Only let other nodes change our time by so much if (abs64(nMedian) < 70 * 60) { nTimeOffset = nMedian; } else { nTimeOffset = 0; static bool fDone; if (!fDone) { // If nobody has a time different than ours but within 5 minutes of ours, give a warning bool fMatch = false; BOOST_FOREACH(int64 nOffset, vSorted) if (nOffset != 0 && abs64(nOffset) < 5 * 60) fMatch = true; if (!fMatch) { fDone = true; string strMessage = _("Warning: Please check that your computer's date and time are correct! If your clock is wrong EBanker will not work properly."); strMiscWarning = strMessage; printf("*** %s\n", strMessage.c_str()); uiInterface.ThreadSafeMessageBox(strMessage, "", CClientUIInterface::MSG_WARNING); } } } if (fDebug) { BOOST_FOREACH(int64 n, vSorted) printf("%+"PRI64d" ", n); printf("| "); } printf("nTimeOffset = %+"PRI64d" (%+"PRI64d" minutes)\n", nTimeOffset, nTimeOffset/60); } } uint32_t insecure_rand_Rz = 11; uint32_t insecure_rand_Rw = 11; void seed_insecure_rand(bool fDeterministic) { //The seed values have some unlikely fixed points which we avoid. if(fDeterministic) { insecure_rand_Rz = insecure_rand_Rw = 11; } else { uint32_t tmp; do { RAND_bytes((unsigned char*)&tmp, 4); } while(tmp == 0 || tmp == 0x9068ffffU); insecure_rand_Rz = tmp; do { RAND_bytes((unsigned char*)&tmp, 4); } while(tmp == 0 || tmp == 0x464fffffU); insecure_rand_Rw = tmp; } } string FormatVersion(int nVersion) { if (nVersion%100 == 0) return strprintf("%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100); else return strprintf("%d.%d.%d.%d", nVersion/1000000, (nVersion/10000)%100, (nVersion/100)%100, nVersion%100); } string FormatFullVersion() { return CLIENT_BUILD; } // Format the subversion field according to BIP 14 spec (https://en.bitcoin.it/wiki/BIP_0014) std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments) { std::ostringstream ss; ss << "/"; ss << name << ":" << FormatVersion(nClientVersion); if (!comments.empty()) ss << "(" << boost::algorithm::join(comments, "; ") << ")"; ss << "/"; return ss.str(); } #ifdef WIN32 boost::filesystem::path GetSpecialFolderPath(int nFolder, bool fCreate) { namespace fs = boost::filesystem; char pszPath[MAX_PATH] = ""; if(SHGetSpecialFolderPathA(NULL, pszPath, nFolder, fCreate)) { return fs::path(pszPath); } printf("SHGetSpecialFolderPathA() failed, could not obtain requested path.\n"); return fs::path(""); } #endif boost::filesystem::path GetTempPath() { #if BOOST_FILESYSTEM_VERSION == 3 return boost::filesystem::temp_directory_path(); #else // TODO: remove when we don't support filesystem v2 anymore boost::filesystem::path path; #ifdef WIN32 char pszPath[MAX_PATH] = ""; if (GetTempPathA(MAX_PATH, pszPath)) path = boost::filesystem::path(pszPath); #else path = boost::filesystem::path("/tmp"); #endif if (path.empty() || !boost::filesystem::is_directory(path)) { printf("GetTempPath(): failed to find temp path\n"); return boost::filesystem::path(""); } return path; #endif } void runCommand(std::string strCommand) { int nErr = ::system(strCommand.c_str()); if (nErr) printf("runCommand error: system(%s) returned %d\n", strCommand.c_str(), nErr); } void RenameThread(const char* name) { #if defined(PR_SET_NAME) // Only the first 15 characters are used (16 - NUL terminator) ::prctl(PR_SET_NAME, name, 0, 0, 0); #elif 0 && (defined(__FreeBSD__) || defined(__OpenBSD__)) // TODO: This is currently disabled because it needs to be verified to work // on FreeBSD or OpenBSD first. When verified the '0 &&' part can be // removed. pthread_set_name_np(pthread_self(), name); #elif defined(MAC_OSX) && defined(__MAC_OS_X_VERSION_MAX_ALLOWED) // pthread_setname_np is XCode 10.6-and-later #if __MAC_OS_X_VERSION_MAX_ALLOWED >= 1060 pthread_setname_np(name); #endif #else // Prevent warnings for unused parameters... (void)name; #endif }
[ "37302933+Ebankerio@users.noreply.github.com" ]
37302933+Ebankerio@users.noreply.github.com
da4b10eb492d748581fd9e8b566d10d4a1d45ce2
aee6c7031eb939736f6b008a3827a53d01831b41
/include/dynamic_mem_c.hpp
1cb9c2fe393355cd5284ac97c36a58765acc4b2e
[]
no_license
taka0628/CryptTool
894fc86abe97a523e356a8cddcfda7cdae3ed04a
cf66482b4c4102d4bff6b2d3004b79b7cab5274c
refs/heads/master
2023-08-11T08:29:43.889269
2021-09-15T10:06:56
2021-09-15T10:06:56
403,269,308
0
0
null
null
null
null
UTF-8
C++
false
false
706
hpp
#ifndef ___DYNAMIC_MEM_HPP #define ___DYNAMIC_MEM_HPP #include <memory.h> #include <stdio.h> #include <cstdio> #include <cstdlib> #include <vector> #include <iostream> #include <memory> #include <string> #include <vector> #include <sstream> #include "macro.hpp" class dynamic_mem_c { private: dynamic_mem_c(const dynamic_mem_c &); uint size; public: dynamic_mem_c(); ~dynamic_mem_c(); unsigned char *mem; void d_new(uint size); void d_free(); int get_size() const; void copy(std::string &dest, const uint size) const; bool set_data(const u_char *in, const uint size); void print_data() const; void clear(); std::string to_string() const; }; #endif
[ "takatsun15@gmail.com" ]
takatsun15@gmail.com
0924adc7976d5e24d4aeb48c67fa7af5bc9a5cac
90ba67a9ffd845f888860cc2fbc099b2af9d7a52
/B_Maria_Breaks_the_Self_isolation.cpp
fca73204837657815bc8039b61887748be0c3dfc
[]
no_license
AmanRawat1298/CodeForces
a6e7f52d063bc32647035aee9304a7420d76a7b9
b63c035457d8d5993dc2e846e01dbbdb1edb8f3c
refs/heads/master
2023-02-03T03:22:08.489591
2020-12-17T15:30:33
2020-12-17T15:30:33
267,936,546
0
0
null
null
null
null
UTF-8
C++
false
false
648
cpp
#include <iostream> #include <bits/stdc++.h> using namespace std; typedef long long ll; int main() { int t; cin>>t; while(t--) { int n; cin>>n; int val; vector <int> v; for( int i=0; i<n; i++) { cin>>val; v.push_back(val); } sort(v.begin(), v.end()); int sum =1, present =1; for(int i=0; i<n; i++) { if(v[i] <= present) { present++; sum = present; } else present++; } cout<<sum<<endl; } return 0; }
[ "aman.r1298@gmail.com" ]
aman.r1298@gmail.com
09d91ff7eb4538dbe2aa15aecc09c7bd0b78af0a
3db7242c67d3b0c69aea62137f830da87accc608
/PalindromeTextSelfMade.cpp
63779a1c2056bea75187e356503f53025c4f3618
[]
no_license
alfifutuhi13/cpp-practice
be291d25b3d6795a402c8b417c4761c6b65a71d1
b6d76faa09027a31b1845e7d450ec727c2bbece4
refs/heads/main
2023-01-22T18:06:49.194471
2020-12-01T22:49:50
2020-12-01T22:49:50
317,687,387
0
0
null
null
null
null
UTF-8
C++
false
false
555
cpp
/* Palindrome test By Alfi Futuhi */ #include <iostream> #include <string.h> using namespace std; int main(){ //deklarasi variabel char input[100]; int i=0; int j=0; int length; cout<<"Masukkan input string: "; cin>>input; cout<<endl; length=strlen(input); for (i=0;i<length;i++){ if(input[i]==input[length-1-i]){ j++; } } if (j==i){ cout<<input<<" is a palindrome"<<endl; } else{ cout<<input<<" is not a palindrome"<<endl; } return 0; }
[ "noreply@github.com" ]
noreply@github.com
35a3b7397cc1207579670c2ce1526bace428dc6d
2d04a7a667ea3dfa56fd24ec2f6a5255ba11a958
/WiFi_AP/WiFi_AP.ino
0a93018b76d7279ca5e10b43db96876f8468ea34
[]
no_license
MedeirosL/ESP8266_ArduinoIDE
7c642782f1ec67682a17bf29c23987b834f01e84
52a51f4130b545d57d32a8a0a9ae324c84774a3b
refs/heads/master
2023-08-01T10:28:01.132103
2021-10-04T16:23:54
2021-10-04T16:24:25
412,268,593
0
0
null
null
null
null
UTF-8
C++
false
false
410
ino
#include <ESP8266WiFi.h> #define APSSID "XXXXXXXXXXXXXX" #define APPASS "12345678" void setup() { Serial.begin(115200); Serial.println(); Serial.print("Setting soft-AP network..."); WiFi.softAP(APSSID, APPASS); Serial.println("Ok!"); } void loop() { if(WiFi.softAPgetStationNum()>0){ Serial.print("Stations connected: "); Serial.println(WiFi.softAPgetStationNum()); } delay(1000); }
[ "lucasperesm@gmail.com" ]
lucasperesm@gmail.com
cc5e2b737617862c359ec0868bce07887972d339
b6ae8feca67392d8d350a84c9c0b88ea8e21c031
/src/cpp/JSONInterface/JsonGetUserInfos.h
10b490e11480fb9e2692062da93f91e9c2aeec8c
[]
no_license
gradido/gradido_login_server
3192135cc563b068ebc9b9eb4ac416c1dae29f88
ca71af1817a801db9a108c205bc298250d498c4b
refs/heads/master
2023-03-23T15:38:55.649220
2021-03-14T09:21:18
2021-03-14T09:21:18
335,353,004
0
0
null
null
null
null
UTF-8
C++
false
false
435
h
#ifndef __JSON_INTERFACE_JSON_GET_USER_INFOS_ #define __JSON_INTERFACE_JSON_GET_USER_INFOS_ #include "JsonRequestHandler.h" /*! * @author Dario Rekowski * @date 2020-03-21 * @brief call to get more infos about user * * works only for admins */ class JsonGetUserInfos : public JsonRequestHandler { public: Poco::JSON::Object* handle(Poco::Dynamic::Var params); protected: }; #endif // __JSON_INTERFACE_JSON_GET_USER_INFOS_
[ "dario.rekowski@gmx.de" ]
dario.rekowski@gmx.de
6779a40f26805774947f0e9986d47d7e4ed8f0ce
1a52dbc0c2a9ec68262ce95ce1b5dd3a8b72c9b1
/PA5/Matrix.cpp
c621ba551b7c662cc8c8b298b0042608a8dd7d7b
[]
no_license
ChewOAo/SIMD
d011d9d57e107402d727c32641ac3c8dfb28d217
4d2cf2eac70dc673238d91aa467d69e321a86883
refs/heads/master
2020-05-27T05:30:01.076951
2017-10-30T02:35:48
2017-10-30T02:35:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,196
cpp
//---------------------------------------------------------------------------- // Copyright Ed Keenan 2017 // Optimized C++ //---------------------------------------------------------------------------- #include "Matrix.h" // Add code Vect4D Matrix::operator * (const Vect4D &v) { // Pretty confident this is correct return Vect4D(v0.realDot(v), v1.realDot(v), v2.realDot(v), v3.realDot(v)); } Matrix Matrix::operator * (const Matrix &t) { // Pretty confident this is correct Vect4D tmp1 = Vect4D(t.m0, t.m4, t.m8, t.m12); Vect4D tmp2 = Vect4D(t.m1, t.m5, t.m9, t.m13); Vect4D tmp3 = Vect4D(t.m2, t.m6, t.m10, t.m14); Vect4D tmp4 = Vect4D(t.m3, t.m7, t.m11, t.m15); Vect4D fin1 = Vect4D(v0.realDot(tmp1), v0.realDot(tmp2), v0.realDot(tmp3),v0.realDot(tmp4)); Vect4D fin2 = Vect4D(v1.realDot(tmp1), v1.realDot(tmp2), v1.realDot(tmp3), v1.realDot(tmp4)); Vect4D fin3 = Vect4D(v2.realDot(tmp1), v2.realDot(tmp2), v2.realDot(tmp3), v2.realDot(tmp4)); Vect4D fin4 = Vect4D(v3.realDot(tmp1), v3.realDot(tmp2), v3.realDot(tmp3), v3.realDot(tmp4)); Matrix mat = Matrix(fin1, fin2, fin3, fin4); return mat; } // --- End of File ---------------
[ "trapper@Elliots-MacBook-Pro.local" ]
trapper@Elliots-MacBook-Pro.local
8164102da1fba2336a8d97d1edbb27cfd93c38ff
13a32b92b1ba8ffb07e810dcc8ccdf1b8b1671ab
/home--tommy--mypy/mypy/lib/python2.7/site-packages/pystan/stan/lib/stan_math/test/unit/math/fwd/scal/fun/log_rising_factorial_test.cpp
a41586092ab9e4a2cb028dd928422e5118466916
[ "Unlicense", "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
tommybutler/mlearnpy2
8ec52bcd03208c9771d8d02ede8eaa91a95bda30
9e5d377d0242ac5eb1e82a357e6701095a8ca1ff
refs/heads/master
2022-10-24T23:30:18.705329
2022-10-17T15:41:37
2022-10-17T15:41:37
118,529,175
0
2
Unlicense
2022-10-15T23:32:18
2018-01-22T23:27:10
Python
UTF-8
C++
false
false
2,251
cpp
#include <stan/math/fwd/scal.hpp> #include <gtest/gtest.h> #include <boost/math/special_functions/digamma.hpp> #include <test/unit/math/fwd/scal/fun/nan_util.hpp> TEST(AgradFwdLogRisingFactorial,Fvar) { using stan::math::fvar; using stan::math::log_rising_factorial; using boost::math::digamma; fvar<double> a(4.0, 1.0); fvar<double> x = log_rising_factorial(a, 1.0); EXPECT_FLOAT_EQ(std::log(4.0), x.val_); EXPECT_FLOAT_EQ(0.25, x.d_); //finite diff double eps = 1e-6; EXPECT_FLOAT_EQ((stan::math::log_rising_factorial(4.0 + eps, 1.0) - stan::math::log_rising_factorial(4.0 - eps, 1.0)) / (2 * eps), x.d_); fvar<double> c(-3.0, 2.0); EXPECT_THROW(log_rising_factorial(c, 2), std::domain_error); // EXPECT_THROW(log_rising_factorial(2, c), std::domain_error); EXPECT_THROW(log_rising_factorial(c, c), std::domain_error); x = log_rising_factorial(a,a); EXPECT_FLOAT_EQ(std::log(840.0), x.val_); EXPECT_FLOAT_EQ((2 * digamma(8) - digamma(4)), x.d_); x = log_rising_factorial(5, a); EXPECT_FLOAT_EQ(std::log(1680.0), x.val_); EXPECT_FLOAT_EQ(digamma(9), x.d_); //finite diff EXPECT_FLOAT_EQ((stan::math::log_rising_factorial(5.0, 4.0 + eps) - stan::math::log_rising_factorial(5.0, 4.0 - eps)) / (2 * eps), x.d_); } TEST(AgradFwdLogRisingFactorial,FvarFvarDouble) { using stan::math::fvar; using stan::math::log_rising_factorial; using boost::math::digamma; fvar<fvar<double> > x; x.val_.val_ = 4.0; x.val_.d_ = 1.0; fvar<fvar<double> > y; y.val_.val_ = 3.0; y.d_.val_ = 1.0; fvar<fvar<double> > a = log_rising_factorial(x,y); EXPECT_FLOAT_EQ(std::log(120.0), a.val_.val_); EXPECT_FLOAT_EQ(0.61666667, a.val_.d_); EXPECT_FLOAT_EQ(1.8727844, a.d_.val_); EXPECT_FLOAT_EQ(0.15354517, a.d_.d_); } struct log_rising_factorial_fun { template <typename T0, typename T1> inline typename boost::math::tools::promote_args<T0,T1>::type operator()(const T0 arg1, const T1 arg2) const { return log_rising_factorial(arg1,arg2); } }; TEST(AgradFwdLogRisingFactorial, nan) { log_rising_factorial_fun log_rising_factorial_; test_nan_fwd(log_rising_factorial_,3.0,5.0,false); }
[ "tbutler.github@internetalias.net" ]
tbutler.github@internetalias.net
13e7f25aaa2f6189472c92a072129b5fff39c3cd
4e20af0b80489276cecced81605ce0f1367248f1
/rodcutting.cpp
11b15dd2c2bc951d2f26e34ac4f3c0eaa6171140
[]
no_license
arshdeep/Programming
0ca9f63c99c551694964d04dd2b90a27b7a584d0
b9aad77b1ecb089ca3b525450932343b65e5a717
refs/heads/master
2021-01-21T09:59:13.573403
2015-07-05T09:50:29
2015-07-05T09:50:29
24,015,388
0
0
null
null
null
null
UTF-8
C++
false
false
1,119
cpp
#include <limits.h> #include <iostream> #include <vector> using namespace std; int cutRodRec(int *p, int n) { if (n <= 0) return 0; int max = INT_MIN; for (int i = 0; i < n; ++i) { max = std::max(max, p[i] + cutRodRec(p, n - i - 1)); } return max; } int rodCut(int *p, int n) { vector<int> dp(n + 1); for (int i = 1; i <= n; ++i) { int max = INT_MIN; for (int j = 0; j < i; j++) { max = std::max(p[j] + dp[i - j - 1], max); } dp[i] = max; } cout<< "Possible cuts at: "; int nBestCut = dp[n]; int nCurLen = n; while (nBestCut > 0) { for (int i = 1; i <= nCurLen; i++) { if (nBestCut == p[i-1] + dp[nCurLen-i]) { nBestCut -= p[i-1]; cout<<i << " "; nCurLen -= i; continue; } } } cout <<endl; return dp[n]; } // Driver program to test above functions int main() { int arr[] = {1, 5, 8, 9, 10, 17, 17, 20, 24, 30}; int size = sizeof(arr)/sizeof(arr[0]); printf("Maximum Obtainable Value is %d\n", rodCut(arr, size)); getchar(); return 0; }
[ "arshdeep.singh86@gmail.com" ]
arshdeep.singh86@gmail.com
43551d0c58e14cb7260b1adae639da5606e42246
600916581fc9b0e2d1a22827405a5ed07f5a5e4b
/StRoot/StFttDigiMaker/StFttDigiMaker.cxx
bdb31e5bae2dbec9526c76eae80f692d4d5306a5
[]
no_license
jdbrice/stgc-offline
a4fb9b484ce649871dc65fc8acc35b22ec28119a
20e85f2edec96af2922048efa3217d3eb27ab8f2
refs/heads/master
2023-03-29T06:45:24.052549
2021-03-31T20:21:50
2021-03-31T20:21:50
353,479,294
0
0
null
null
null
null
UTF-8
C++
false
false
4,069
cxx
/*************************************************************************** * * $Id: StFttDigiMaker.cxx,v 1.4 2019/03/08 18:45:40 fseck Exp $ * * Author: Florian Seck, April 2018 *************************************************************************** * * Description: StFttDigiMaker - class to fill the StEvent from DAQ reader: * unpack raw data & save StETofHeader & StETofDigis in StETofCollection * *************************************************************************** * * $Log: StFttDigiMaker.cxx,v $ * Revision 1.4 2019/03/08 18:45:40 fseck * save middle value of tot bin as raw tot of the digi * * Revision 1.3 2019/02/19 20:32:09 fseck * update for unpacking year 2019+ daq files * * Revision 1.2 2018/07/27 13:58:12 fseck * small change to compile also in 64bit mode * * Revision 1.1 2018/07/25 14:39:40 jeromel * Peer reviewed Raghav+Jerome - code from Florian Seck * * ***************************************************************************/ #include <vector> #include <map> #include <array> #include <algorithm> // std::is_sorted #include "StRTSBaseMaker.h" #include "StDAQMaker/StDAQReader.h" #include "StRtsTable.h" #include "StEvent.h" #include "StFttDigiMaker.h" //_____________________________________________________________ StFttDigiMaker::StFttDigiMaker( const char* name ) : StRTSBaseMaker( "stgc", name ), // mEvent( 0 ), /// pointer to StEvent mRunYear( 0 ), /// year in which the data was taken (switch at 1st Oct) mDebug( false ) /// print out of all full messages for debugging { LOG_DEBUG << "StFttDigiMaker::ctor" << endm; } //_____________________________________________________________ StFttDigiMaker::~StFttDigiMaker() { /* no op */ } //_____________________________________________________________ Int_t StFttDigiMaker::Init() { LOG_INFO << "StFttDigiMaker::Init" << endm; return kStOk; } //_____________________________________________________________ Int_t StFttDigiMaker::InitRun( Int_t runnumber ) { mRunYear = ( runnumber + 727000 ) / 1000000 + 1999; LOG_INFO << "runnumber: " << runnumber << " --> year: " << mRunYear << endm; return kStOk; } //_____________________________________________________________ Int_t StFttDigiMaker::FinishRun( Int_t runnumber ) { return kStOk; } //_____________________________________________________________ Int_t StFttDigiMaker::Finish() { return kStOk; } //_____________________________________________________________ Int_t StFttDigiMaker::Make() { LOG_INFO << "StFttDigiMaker::Make()" << endm; mRawVMM.clear(); StRtsTable* daqdta = GetNext( "vmm" ); if ( daqdta == nullptr ) { LOG_WARN << "StFttDigiMaker::Make() - NO STGC DATA found in event" << endm; return kStOk; } // do unpacking of the raw data int inputSizeBytes = daqdta->GetSize(); LOG_INFO << "StFttDigiMaker::Make() - InputSize (bytes): " << inputSizeBytes << endm; LOG_INFO << "Sector: " << daqdta->Sector() << endm; LOG_INFO << "Pad: " << daqdta->Pad() << endm; LOG_INFO << "Row: " << daqdta->Row() << endm; LOG_INFO << "Rdo: " << daqdta->Rdo() << endm; mRdo = daqdta->Rdo(); mSec = daqdta->Sector(); mPad = daqdta->Pad(); if( mDebug ) { LOG_DEBUG << "StFttDigiMaker::Make() - InputSize (bytes): " << inputSizeBytes << endm; } LOG_INFO << "ROWS: " << daqdta->GetNRows() << endm; // struct stgc_vmm_t *vmm = (stgc_vmm_t *) ( *daqdta->begin() ); int len = 1; // LOG_INFO << "size: " << sizeof(vmm) << ", size: " << sizeof(stgc_vmm_t) << endm; for (auto it = daqdta->begin(); it != daqdta->end(); ++it) { struct stgc_vmm_t *vmm = (stgc_vmm_t *) ( *it ); u_char feb = vmm[0].feb_vmm >> 2 ; // feb [0..5] u_char vm = vmm[0].feb_vmm & 3 ; // VMM [0..3] printf(" FEB %d:%d, ch %02d: ADC %d, BCID %d\n",feb,vm,vmm[0].ch,vmm[0].adc,vmm[0].bcid) ; mRawVMM.push_back( *vmm ); } return kStOk; }
[ "jdb12@rice.edu" ]
jdb12@rice.edu
0ea33565b9a58d7bd85633ae71297b6de69c679f
6aeccfb60568a360d2d143e0271f0def40747d73
/sandbox/random/boost/random/mkl/tr1/distributions.hpp
8f8d39f53ec7499415823169ed6a17d36c04dc3e
[]
no_license
ttyang/sandbox
1066b324a13813cb1113beca75cdaf518e952276
e1d6fde18ced644bb63e231829b2fe0664e51fac
refs/heads/trunk
2021-01-19T17:17:47.452557
2013-06-07T14:19:55
2013-06-07T14:19:55
13,488,698
1
3
null
2023-03-20T11:52:19
2013-10-11T03:08:51
C++
UTF-8
C++
false
false
3,737
hpp
// Copyright Fabian Bösch 2013 // // Use, modification and distribution are subject to the // Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt // or copy at http://www.boost.org/LICENSE_1_0.txt) /** * @file * @brief This file contains specializations for the variate_generator class template for TR1 random distribution classes and MKL engines. */ #ifndef BOOST_RANDOM_MKL_VARIATE_GENERATOR_SPECIALIZATION_TR1_DISTRIBUTIONS_HPP #define BOOST_RANDOM_MKL_VARIATE_GENERATOR_SPECIALIZATION_TR1_DISTRIBUTIONS_HPP #include <boost/config.hpp> #ifdef BOOST_HAS_TR1_RANDOM #include "../variate_generator_specialization.hpp" #include <tr1/random.h> #include <limits> #ifndef DOXYGEN_SHOULD_SKIP_THIS namespace boost { namespace random { // discrete uniform distribution BOOST_RANDOM_MKL_VARIATE_GENERATOR_SPEZIALIZATION_DISC_UNIFORM_TR1( std::tr1::uniform_int<int>, viRngUniform, VSL_RNG_METHOD_UNIFORM_STD, BOOST_RANDOM_MKL_CONCAT( _dist.min(), _dist.max()), _dist.max() ) // continuous uniform distribution BOOST_RANDOM_MKL_VARIATE_GENERATOR_SPEZIALIZATION_TR1( std::tr1::uniform_real<float>, vsRngUniform, VSL_RNG_METHOD_UNIFORM_STD, BOOST_RANDOM_MKL_CONCAT( _dist.min(), _dist.max() ) ) BOOST_RANDOM_MKL_VARIATE_GENERATOR_SPEZIALIZATION_TR1( std::tr1::uniform_real<double>, vdRngUniform, VSL_RNG_METHOD_UNIFORM_STD, BOOST_RANDOM_MKL_CONCAT( _dist.min(), _dist.max() ) ) // bernoulli distribution BOOST_RANDOM_MKL_VARIATE_GENERATOR_SPEZIALIZATION_TR1_2( std::tr1::bernoulli_distribution, viRngBernoulli, VSL_RNG_METHOD_BERNOULLI_ICDF, _dist.p(), int ) // binomial distribution BOOST_RANDOM_MKL_VARIATE_GENERATOR_SPEZIALIZATION_TR1( BOOST_RANDOM_MKL_CONCAT(std::tr1::binomial_distribution<int, double>), viRngBinomial, VSL_RNG_METHOD_BINOMIAL_BTPE, BOOST_RANDOM_MKL_CONCAT( _dist.t(), _dist.p() ) ) // geometric distribution BOOST_RANDOM_MKL_VARIATE_GENERATOR_SPEZIALIZATION_TR1( BOOST_RANDOM_MKL_CONCAT(std::tr1::geometric_distribution<int, double>), viRngGeometric, VSL_RNG_METHOD_GEOMETRIC_ICDF, _dist.p() ) // poisson distribution BOOST_RANDOM_MKL_VARIATE_GENERATOR_SPEZIALIZATION_TR1( BOOST_RANDOM_MKL_CONCAT(std::tr1::poisson_distribution<int, double>), viRngPoisson, VSL_RNG_METHOD_POISSON_POISNORM, _dist.mean() ) // exponential distribution BOOST_RANDOM_MKL_VARIATE_GENERATOR_SPEZIALIZATION_TR1( std::tr1::exponential_distribution<float>, vsRngExponential, VSL_RNG_METHOD_EXPONENTIAL_ICDF, BOOST_RANDOM_MKL_CONCAT( 0, 1/_dist.lambda() ) ) BOOST_RANDOM_MKL_VARIATE_GENERATOR_SPEZIALIZATION_TR1( std::tr1::exponential_distribution<double>, vdRngExponential, VSL_RNG_METHOD_EXPONENTIAL_ICDF, BOOST_RANDOM_MKL_CONCAT( 0, 1/_dist.lambda() ) ) // gamma distribution BOOST_RANDOM_MKL_VARIATE_GENERATOR_SPEZIALIZATION_TR1( std::tr1::gamma_distribution<float>, vsRngGamma, VSL_RNG_METHOD_GAMMA_GNORM, BOOST_RANDOM_MKL_CONCAT( _dist.alpha(), 0, 1 ) ) BOOST_RANDOM_MKL_VARIATE_GENERATOR_SPEZIALIZATION_TR1( std::tr1::gamma_distribution<double>, vdRngGamma, VSL_RNG_METHOD_GAMMA_GNORM, BOOST_RANDOM_MKL_CONCAT( _dist.alpha(), 0, 1 ) ) // normal distribution BOOST_RANDOM_MKL_VARIATE_GENERATOR_SPEZIALIZATION_TR1( std::tr1::normal_distribution<float>, vsRngGaussian, VSL_RNG_METHOD_GAUSSIAN_BOXMULLER2, BOOST_RANDOM_MKL_CONCAT( _dist.mean(), _dist.sigma() ) ) BOOST_RANDOM_MKL_VARIATE_GENERATOR_SPEZIALIZATION_TR1( std::tr1::normal_distribution<double>, vdRngGaussian, VSL_RNG_METHOD_GAUSSIAN_BOXMULLER2, BOOST_RANDOM_MKL_CONCAT( _dist.mean(), _dist.sigma() ) ) } // random } // boost #endif // DOXYGEN_SHOULD_SKIP_THIS #endif // BOOST_HAS_TR1_RANDOM #endif // BOOST_RANDOM_MKL_VARIATE_GENERATOR_SPECIALIZATION_TR1_DISTRIBUTIONS_HPP
[ "boeschf@student.ethz.ch" ]
boeschf@student.ethz.ch
7055fc8fc569ac3cb80859938889f50ead2eed67
6bbe1c558a94e2c886fc1afa8ca7be20663a343e
/MinhasApostilas/Formularios/editardocumento.h
d2cb1cf18e5961e3338616b4c815f01891d167c7
[]
no_license
micdoug/MinhasApostilas
c550def164ffdafdaa787283bb7ef1ae54d43ac7
fe492a00dccb33db27fe1d14eaac7e820e8f7384
refs/heads/master
2020-05-30T21:14:35.878760
2014-11-15T12:05:23
2014-11-15T12:05:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,203
h
/* ---------------------------------------------------------------------- * Arquivo: editardocumento.h * Descrição: Arquivo de implementação da classe Formularios::EditarDocumento. * * Autor: Michael Dougras da Silva * Contato: micdoug.silva@gmail.com * ----------------------------------------------------------------------*/ #ifndef FORMULARIOS_EDITARDOCUMENTO_H #define FORMULARIOS_EDITARDOCUMENTO_H #include <QDialog> #include <QStringList> #include "../Entidades/documento.h" namespace Ui { class EditarDocumento; } namespace Formularios { class EditarDocumento : public QDialog { Q_OBJECT public: EditarDocumento(const Entidades::Documento &documento, QWidget *parent=0); virtual ~EditarDocumento(); Entidades::Documento documento() const; private slots: void fazerUpload(); void fazerDownload(); private: Ui::EditarDocumento *ui; Entidades::Documento m_documento; QStringList m_propriedades; //Métodos auxiliares void documentoAtualizado(const QString &propriedade, const QVariant &valor); void bind(); }; } // namespace Formularios #endif // FORMULARIOS_EDITARDOCUMENTO_H
[ "micdoug.silva@gmail.com" ]
micdoug.silva@gmail.com
a7a7694ce21a19ee9aeb999d8cdb73788ef2a1f5
776c8a5821eb8cd1357439454c9c20c9da239afb
/June~October, 2020/2020-06-26/5639_강민경.cpp
657e00fba95ce8005ceef1b07b428f24bbdb2915
[]
no_license
JinYeJin/algorithm-study
85d84a726e0f7bb78a2da37504bc04a42b3906ea
538c911e6adcdad3bfed3d9f76ccb30804dfb768
refs/heads/master
2023-07-04T16:09:12.101837
2021-08-14T02:23:44
2021-08-14T02:23:44
272,363,049
8
2
null
null
null
null
UTF-8
C++
false
false
826
cpp
// https://www.acmicpc.net/problem/5639 이진검색트리 // 런타임 #include<iostream> #include<cstdio> using namespace std; struct Tree { int left = 0; int right = 0; }; Tree tree[100002]; void postOrder(int node) { if (tree[node].left != 0) { postOrder(tree[node].left); } if (tree[node].right != 0) { postOrder(tree[node].right); } cout << node << endl; } int main() { int root; int value; cin >> root; while (cin >> value) { int node = root; while (true) { if (node < value) { if (tree[node].right != 0) { node = tree[node].right; } else { tree[node].right = value; break; } } else { if (tree[node].left != 0) { node = tree[node].left; } else { tree[node].left = value; break; } } } } postOrder(root); return 0; }
[ "noreply@github.com" ]
noreply@github.com
5e2e0802b53aa631ba2222a20fea15a935024c21
0908633d75c32ed07770749508930c224a4746d7
/test1/gpu_wrappers.cpp
67d0d2198871d6a2ea3362b53677077a84b4c03a
[]
no_license
stereotype441/opengl-experiments
772f8850111a3914a19e5d9e954d0f7c3f7a88d3
e28f016886acc050548bdfed177910e71e28985a
refs/heads/master
2021-01-23T08:00:15.455549
2011-06-09T01:16:09
2011-06-09T01:16:09
1,804,767
0
0
null
null
null
null
UTF-8
C++
false
false
3,370
cpp
#include "gpu_wrappers.h" #include <iostream> using namespace std; inline GLvoid const *translate_offset(size_t offset) { return static_cast<char const *>(NULL) + offset; } void set_vertices(GpuBuffer const *buffer, size_t offset) { glBindBuffer(GL_ARRAY_BUFFER, buffer->handle()); glVertexPointer(3, // Num components in each vector GL_FLOAT, // Data type of each vector component 0, // Stride, or 0 if packed translate_offset(offset)); glBindBuffer(GL_ARRAY_BUFFER, 0); // Unbind for safety glEnableClientState(GL_VERTEX_ARRAY); } void set_normals(GpuBuffer const *buffer, size_t offset) { glBindBuffer(GL_ARRAY_BUFFER, buffer->handle()); glNormalPointer(GL_FLOAT, // Data type of each vector component 0, // Stride, or 0 if packed translate_offset(offset)); glBindBuffer(GL_ARRAY_BUFFER, 0); // Unbind for safety glEnableClientState(GL_NORMAL_ARRAY); } void set_scalar_vertex_attrib( GpuBuffer const *buffer, GLuint attrib_handle, size_t offset) { glBindBuffer(GL_ARRAY_BUFFER, buffer->handle()); glVertexAttribPointer(attrib_handle, // Attribute to assign 1, // Number of vector elements GL_FLOAT, // Data type of each vector component GL_FALSE, // Auto-normalization flag 0, // Stride translate_offset(offset)); glBindBuffer(GL_ARRAY_BUFFER, 0); // Unbind for safety glEnableVertexAttribArray(attrib_handle); } void draw_elements(GpuBuffer const *buffer, size_t count, size_t offset) { glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffer->handle()); glDrawElements( GL_TRIANGLES, count, GL_UNSIGNED_INT, translate_offset(offset)); } GpuShader::GpuShader(GLenum type, char const *source, size_t length) : m_handle(glCreateShader(type)) { GLchar const *source_strings[1] = { source }; GLint source_lengths[1] = { length }; glShaderSource(m_handle, 1, source_strings, source_lengths); glCompileShader(m_handle); GLint success; glGetShaderiv(m_handle, GL_COMPILE_STATUS, &success); if (!success) { GLint info_log_length; glGetShaderiv(m_handle, GL_INFO_LOG_LENGTH, &info_log_length); GLchar *msg = new GLchar[info_log_length]; glGetShaderInfoLog(m_handle, info_log_length, NULL, msg); cout << "Compile failed: " << msg << endl; delete msg; throw GpuException(); } } GpuProgram::GpuProgram() : m_handle(glCreateProgram()) { } void GpuProgram::Attach(GpuShader const &shader) { glAttachShader(m_handle, shader.handle()); } void GpuProgram::Link() { glLinkProgram(m_handle); GLint success; glGetProgramiv(m_handle, GL_LINK_STATUS, &success); if (!success) { GLint info_log_length; glGetProgramiv(m_handle, GL_INFO_LOG_LENGTH, &info_log_length); GLchar *msg = new GLchar[info_log_length]; glGetProgramInfoLog(m_handle, info_log_length, NULL, msg); cout << "Compile failed: " << msg << endl; delete msg; throw GpuException(); } } GLint GpuProgram::get_attrib_loc(char const *name) const { return glGetAttribLocation(m_handle, name); } GLint GpuProgram::get_uniform_loc(char const *name) const { return glGetUniformLocation(m_handle, name); } void set_program(GpuProgram const *program) { glUseProgram(program->handle()); }
[ "stereotype441@gmail.com" ]
stereotype441@gmail.com
cd53435a131e8bb5223783fe294de313d2d63d67
27b54cc1cf5a51fac663ae288bd0a58ca2c51b81
/Code/field.cpp
d9264dfb8587ceac2b4342d0bc3cfda44a3c7fbd
[]
no_license
bgazanion/graph-qtcharts
daef394fd936eaa053cb5746d8cd57e864d4dadb
15db345ced91496337988a6d40a4bcbb0ff03ebd
refs/heads/master
2020-04-09T03:48:10.600123
2018-12-03T12:31:15
2018-12-03T12:31:15
159,997,269
2
0
null
null
null
null
UTF-8
C++
false
false
3,449
cpp
#include "field.h" Field::Field() { m_size = 0; m_name = ""; m_data = {}; } unsigned int Field::getSize() { return m_size; } const std::string& Field::getName() { return m_name; } const std::vector<float>* Field::getData() { return &m_data; } void Field::print(int number) { std::cout << "---- info ----" << std::endl; std::cout << "name: " << m_name << std::endl; std::cout << "size: " << m_size << std::endl; std::cout << "---- data ----" << std::endl; if (m_size ==0) { std::cout << " empty " << std::endl; } else if (number == 0) { for (unsigned int i=0; i<m_size; i++) { std::cout << " " << i << ": " << m_data[i] << std::endl; } } else if (number > 0) { for (unsigned int i=0; i<static_cast<unsigned int>(number); i++) { std::cout << " " << i << ": " << m_data[i] << std::endl; } } else { for (unsigned int i=0; i<static_cast<unsigned int>(number); i++) { std::cout << " " << i << ": " << m_data[m_size-i-1] << std::endl; } } std::cout << std::endl; } std::array<float, 2> Field::getRange() { float max = std::numeric_limits<float>::min();; float min = std::numeric_limits<float>::max();; for (float value : *this->getData()) { if (value > max) { max = value; } if (value < min) { min = value; } } return {min, max}; } void Field::setSize(unsigned int size) { // note: we reset m_data to avoid size mismatch m_size = size; m_data.resize( size ); } void Field::setName(std::string name) { m_name = name; } void Field::setData(std::vector<float> *data) { // check input array size matches m_size if (m_size == data->size()) { m_data = *data; } else { std::cout << "setData: size mismatch -> use setSize first" << std::endl; } } void Field::setValue(float value, unsigned int index) { if (index < m_size) { m_data[index] = value; } else { std::cout << "setValue: index exceeds data size" << std::endl; } } void Field::randomize(float min, float max) { // size unsigned int size = this->getSize(); // random name unsigned int stringSize = static_cast<unsigned int>(generateRandomInt(4, 12)); this->setName(generateRandomString(stringSize)); // field values for (unsigned int i=0; i<size; i++) { this->setValue(generateRandomFloat(min, max), i); } } std::vector<unsigned int> Field::getOrderedIndices() { std::vector<float> sortedData = m_data; std::vector<unsigned int> sortedIndex; sortedIndex.resize(m_size); for (unsigned int i=0; i<m_size; ++i) sortedIndex[i] = i; unsigned int minIndex; for (unsigned int i=0; i<m_size; ++i) { minIndex = i; // find index of min value in [index, ...] for (unsigned int index=i; index<m_size; ++index) { if (sortedData[index]<sortedData[minIndex]) { minIndex = index; } } // swap values at pos. i and minIndex for sortedData and sortedIndex std::swap(sortedData[i], sortedData[minIndex]); std::swap(sortedIndex[i], sortedIndex[minIndex]); } return sortedIndex; }
[ "bertrand@gazanion.com" ]
bertrand@gazanion.com
2f3b4dfa74e6cdf583fb039a0d60c7248c21a31e
55bebcacdf42122df6c95bb137f90ffcc8b03875
/calc.cpp
3905486e0155716fdf61313fd4fb02c25fe366ba
[]
no_license
aleksiwithlove/examples
1051b6dccde74c5d81703983f8ccb46564543613
1e449b764b5547a3fd7e02dfa1cc844732d78715
refs/heads/master
2020-05-20T07:59:23.484739
2015-05-05T07:49:48
2015-05-05T07:49:48
33,911,582
0
0
null
null
null
null
UTF-8
C++
false
false
1,256
cpp
#include<iostream> #include<cmath> #include<string> #include <FL/Fl.H> #include <FL/Fl_Window.H> #include <FL/fl_draw.H> #include <cmath> #include <FL/Fl_Input.H> #include <FL/Fl_Button.H> #include "string.h" #include "stdlib.h" #include <cstring> #include <sstream> #include <string> using namespace std; class M_Win:public Fl_Window{ public: Fl_Input *inp1; Fl_Input *inp2; Fl_Input *inp3; Fl_Button *bt; M_Win(int w, int h): Fl_Window(w, h) { resizable(this); inp1 = new Fl_Input(40,40,60,60); inp2 = new Fl_Input(140,40,60,60); inp3 = new Fl_Input(240,40,60,60); bt = new Fl_Button(40, 100, 30, 30, "+"); show(); } void draw() { Fl_Window::draw(); fl_color(250, 18, 50); } }; const char* ToString(int val) { stringstream stream; stream << val; return stream.str().c_str(); } int ToInt(const char* val) { string str(val); stringstream stream(str); int z; stream >> z; return z; } void my_callback(Fl_Widget* winp, void*p) { M_Win * win=(M_Win *)p; int x = ToInt(win->inp1->value()); int y = ToInt(win->inp2->value()); //int z = x+y; win->inp3->value(ToString(x+y)); } int main(){ M_Win win(400, 800); win.bt ->callback(my_callback,&win); return Fl::run(); }
[ "alexsvyatova@gmail.com" ]
alexsvyatova@gmail.com
1d5b2393391e502aada0fe10af07c9af7bda0399
dd80a584130ef1a0333429ba76c1cee0eb40df73
/external/chromium_org/chrome/test/remoting/launch_browsertest.cc
c08d69ca936310f7e6414d55c9ed6a2356fe6280
[ "MIT", "BSD-3-Clause" ]
permissive
karunmatharu/Android-4.4-Pay-by-Data
466f4e169ede13c5835424c78e8c30ce58f885c1
fcb778e92d4aad525ef7a995660580f948d40bc9
refs/heads/master
2021-03-24T13:33:01.721868
2017-02-18T17:48:49
2017-02-18T17:48:49
81,847,777
0
2
MIT
2020-03-09T00:02:12
2017-02-13T16:47:00
null
UTF-8
C++
false
false
424
cc
// Copyright 2013 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 "chrome/test/remoting/remote_desktop_browsertest.h" namespace remoting { IN_PROC_BROWSER_TEST_F(RemoteDesktopBrowserTest, MANUAL_Launch) { VerifyInternetAccess(); Install(); LaunchChromotingApp(); Cleanup(); } } // namespace remoting
[ "karun.matharu@gmail.com" ]
karun.matharu@gmail.com
b019eba5dfb5879a7f7286e3bffbe60819068a8d
103ce1aef509e106396687667c855f6c17d671ef
/src/worker.cpp
322d35e4031851351ecd6b5f13099f48cadb11f2
[]
no_license
lxlyh/gude
3f5fc11790f3b8189357cbaa0d556d83587e0c43
9dfa8755d1d24c563576dce53c088447cbeedb89
refs/heads/main
2023-05-01T17:53:59.823982
2021-05-05T02:05:57
2021-05-05T02:05:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,307
cpp
#include "worker.h" #include "config.h" namespace gude { void WorkerManager::add(Scheduler::ptr s) { m_datas[s->getName()] = s; } Scheduler::ptr WorkerManager::get(const std::string& name) { auto it = m_datas.find(name); if (it == m_datas.end()) return nullptr; return it->second; } void WorkerManager::del(const std::string& name) { auto it = m_datas.find(name); if (it == m_datas.end()) return; m_datas.erase(it); } void WorkerManager::clear() { for (auto& i : m_datas) { i.second->schedule([](){}); i.second->stop(); } m_datas.clear(); } IOManager::ptr WorkerManager::getAsIOManager(const std::string& name) { return std::dynamic_pointer_cast<IOManager>(get(name)); } bool WorkerManager::init(const std::unordered_map<std::string, uint32_t>& v) { for (auto& i : v) { Scheduler::ptr s = std::make_shared<IOManager>(i.second, false, i.first); add(s); } return true; } std::string WorkerManager::toString() { std::stringstream ss; ss << "workers numbers: " << total(); for (auto& i : m_datas) { ss << std::endl << " " << i.first << ": " << i.second->toString(); } return ss.str(); } }
[ "1125498083@qq.com" ]
1125498083@qq.com
dc1a8eb606816a2cc9059a6a76e989a3e86aa22d
e4cc95ec952cfc183ae3c1122d145497a580f305
/src/qt/terracredit/tooltipmenu.h
e1d9eb86cf440d27bd1b30658e4f8d971e1ac3ae
[ "MIT" ]
permissive
jakilwq/TerraCredit
80866e19dde3e67efbec7ede705d5046b0973c1f
56c8833c79a2485ae9a4d101f9b7267b867a3cdf
refs/heads/master
2022-12-15T21:58:42.421232
2020-09-04T06:51:03
2020-09-04T06:51:03
292,806,732
0
0
null
2020-09-04T09:27:12
2020-09-04T09:27:12
null
UTF-8
C++
false
false
1,393
h
// Copyright (c) 2019 The TERRACREDIT developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef TOOLTIPMENU_H #define TOOLTIPMENU_H #include "qt/terracredit/pwidget.h" #include <QWidget> #include <QModelIndex> class TERRACREDITGUI; class WalletModel; namespace Ui { class TooltipMenu; } QT_BEGIN_NAMESPACE class QModelIndex; QT_END_NAMESPACE class TooltipMenu : public PWidget { Q_OBJECT public: explicit TooltipMenu(TERRACREDITGUI* _window, QWidget *parent = nullptr); ~TooltipMenu() override; void setIndex(const QModelIndex &index); virtual void showEvent(QShowEvent *event) override; void setEditBtnText(QString btnText); void setDeleteBtnText(QString btnText); void setCopyBtnText(QString btnText); void setLastBtnText(QString btnText, int minHeight = 30); void setCopyBtnVisible(bool visible); void setDeleteBtnVisible(bool visible); void setEditBtnVisible(bool visible); void setLastBtnVisible(bool visible); signals: void onDeleteClicked(); void onCopyClicked(); void onEditClicked(); void onLastClicked(); private slots: void deleteClicked(); void copyClicked(); void editClicked(); void lastClicked(); private: Ui::TooltipMenu *ui; QModelIndex index; }; #endif // TOOLTIPMENU_H
[ "alonewolf2ksk@gmail.com" ]
alonewolf2ksk@gmail.com
e4600657cbbe2d7a714b00636a350fd8bbf27e1e
6fe2d3c27c4cb498b7ad6d9411cc8fa69f4a38f8
/algorithms/algorithms-cplusplus/leetcode/Question_0107_Binary_Tree_Level_Order_Traversal_II.cc
4dbfd17b3bcc96804cdb18a163b840f6b8cc0747
[]
no_license
Lanceolata/code
aae54af632a212c878ce45b11dab919bba55bcb3
f7d5a7de27c3cc8a7a4abf63eab9ff9b21d512fb
refs/heads/master
2022-09-01T04:26:56.190829
2021-07-29T05:14:40
2021-07-29T05:14:40
87,202,214
0
0
null
null
null
null
UTF-8
C++
false
false
998
cc
#include <vector> #include <queue> using namespace std; // Definition for a binary tree node. struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode() : val(0), left(nullptr), right(nullptr) {} TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} }; class Solution { public: vector<vector<int>> levelOrderBottom(TreeNode* root) { vector<vector<int>> res; if (!root) { return res; } queue<TreeNode*> q; q.push(root); while (!q.empty()) { size_t size = q.size(); vector<int> vec; while (size-- > 0) { TreeNode* node = q.front(); q.pop(); vec.push_back(node->val); if (node->left) { q.push(node->left); } if (node->right) { q.push(node->right); } } res.push_back(vec); } return vector<vector<int>>(res.rbegin(), res.rend()); } };
[ "lanceolatayuan@gmail.com" ]
lanceolatayuan@gmail.com
3bf95c0a3999dab8f48639f8d0fa0d5a39e1ffdb
c4fe0288aa575d90f1b2d72cf5beb8ac8d943abd
/v1.7_7_segment/v1.7_7_segment.ino
dca2d062ba7917ffc6cc20cba559f6d0546e4d17
[]
no_license
jiamingla/4-7_segment-with-colon-using-arduino
a6834ad7ff52c4bb35d5351bf1b45f4bf1ae9127
7f3126b74ed0971556555d0e75d9f6efa72892e9
refs/heads/master
2021-09-29T02:09:37.435705
2018-11-22T16:21:21
2018-11-22T16:21:21
115,511,859
0
0
null
null
null
null
UTF-8
C++
false
false
9,646
ino
/***************************************************************************** * Name: v1.7_7_segment.ino * Created: 2017/12/28 05:13 AM (GMT+8) yyyy/mm/dd * Author: Jiamingla ******************************************************************************/ /*七段顯示器1.7版 2017/12/29 使用 Arduino Mega 2560 版本更新: 先顯示8888,輸入數字選擇模式再顯示功能並持續動作 冒號能動了 當前時間 0000~9999 9999~0000 輸入四位數字並顯示 不能暫停的倒數計時器 既有功能: 當前時間 0000~9999 9999~0000 輸入四位數字並顯示 不能暫停的倒數計時器 */ /*四個七段 + 冒號(由左至右排列) 8/8/:/8/8 每個腳位前綴 0/1/4/2/3 0用上的腳位定義為:22,24,26,28,30,32,34 1用上的腳位定義為:23,25,27,29,31,33,35 2用上的腳位定義為:36,38,40,42,44,46,48 3用上的腳位定義為:37,39,41,43,45,47,49 4用上的腳位定義為:50(暫定) */ //定義腳位 // Mega Pin I/O definitions //0的PIN #define pin_0_a 22 #define pin_0_b 24 #define pin_0_c 26 #define pin_0_d 28 #define pin_0_e 30 #define pin_0_f 32 #define pin_0_g 34 //1的PIN #define pin_1_a 23 #define pin_1_b 25 #define pin_1_c 27 #define pin_1_d 29 #define pin_1_e 31 #define pin_1_f 33 #define pin_1_g 35 //2的PIN #define pin_2_a 36 #define pin_2_b 38 #define pin_2_c 40 #define pin_2_d 42 #define pin_2_e 44 #define pin_2_f 46 #define pin_2_g 48 //3的PIN #define pin_3_a 37 #define pin_3_b 39 #define pin_3_c 41 #define pin_3_d 43 #define pin_3_e 45 #define pin_3_f 47 #define pin_3_g 49 //4的PIN #define pin_4_a 50 #define pin_4_b 51 //定義七段顯示器位數 byte i; #include <SoftwareSerial.h> //引用「軟體序列埠程式庫」 SoftwareSerial BT(10,9); //自訂的城市物件名稱 接收腳 傳送腳 // 宣告時間計數器 Timers unsigned long time_previous; //宣告一個數字作輸入用 int number = 0; //宣告一個秒單位有多長(預設一秒)(用於改速度) Setup second setting int ms = 1000; //宣告冒號明暗 預設true恆亮 boolean colon = true; //宣告小時數、分鐘數、秒數 byte Chour; byte Cminute; byte Csecond; //宣告功能轉換 byte mode; //因為Serial.read一次只能讀一個值,偶爾也需要讀取字串 String s = ""; const byte seg4[4][7] = { {pin_0_a,pin_0_b,pin_0_c,pin_0_d,pin_0_e,pin_0_f,pin_0_g}, {pin_1_a,pin_1_b,pin_1_c,pin_1_d,pin_1_e,pin_1_f,pin_1_g}, {pin_2_a,pin_2_b,pin_2_c,pin_2_d,pin_2_e,pin_2_f,pin_2_g}, {pin_3_a,pin_3_b,pin_3_c,pin_3_d,pin_3_e,pin_3_f,pin_3_g} }; //七段顯示器零到十 const byte seven_seg_digits[10][7] = { { 1,1,1,1,1,1,0 }, // = 0 { 0,1,1,0,0,0,0 }, // = 1 { 1,1,0,1,1,0,1 }, // = 2 { 1,1,1,1,0,0,1 }, // = 3 { 0,1,1,0,0,1,1 }, // = 4 { 1,0,1,1,0,1,1 }, // = 5 { 1,0,1,1,1,1,1 }, // = 6 { 1,1,1,0,0,0,0 }, // = 7 { 1,1,1,1,1,1,1 }, // = 8 { 1,1,1,0,0,1,1 } // = 9 }; // 一支方便的函式,以格式字串輸出到序列埠 void pf(const char *fmt, ... ){ char tmp[128]; // max is 128 chars va_list args; //宣告一個指標,讓它指向引數串列。 va_start (args, fmt ); //初始化這個指標,讓它真正指向正確的引數串列開頭。 vsnprintf(tmp, 128, fmt, args); va_end (args); //清除這個指標,把它設為NULL。 Serial.print(tmp); } // 設定某個七段顯示器所顯示的數字, // 參數pos為0~3,指出想要更新哪一個七段顯示器, // 參數n為0~9,顯示數字 void setDigit(byte pos,byte n) { if(pos < 0 || 3 < pos) { pf("error pos=%d\n", pos); return; } if(0 <= n && n <= 9) { for(int j = 0;j < 7;j++) { digitalWrite(seg4[pos][j],seven_seg_digits[n][j]); } } } // 設定整個四合一型七段顯示器想要顯示的數字 // 參數number的範圍應是0~9999 // 數字小於1000前面會因為剛好而補上0 void setNumber(int number) { int n0, n1, n2, n3; n3 = number / 1000; number %= 1000; n2 = number / 100; number %= 100; n1 = number / 10; n0 = number % 10; // 求出每個位數的值後,分別更新 // 注意,此處以delay(5)隔開每個位數的更新(葉難版本) //可嘗試使用無延遲版本(家名版本) setDigit(0, n3); setDigit(1, n2); setDigit(2, n1); setDigit(3, n0); } // 冒號(: colon),提起下文或總結上文的符號。 // 控制冒號亮暗 void colonswitch() { delay(ms); colon = !colon; digitalWrite(pin_4_a,colon); digitalWrite(pin_4_b,colon); } // 從0000上數到9999 void from0000to9999() { // 經過一秒單位後就讓number加1 unsigned long time_now = millis(); if(number == 9999) number = 0; if(time_now - time_previous > ms) { number++; time_previous += ms; //依次使時間計數器加一個秒單位 pf("number=%d\n", number);//把數字也顯示在序列埠上 } // 不斷地寫入數字 setNumber(number); // 冒號動作 colonswitch(); } // 從9999下數到0000 void from9999to0000() { // 經過一秒單位後就讓number減1 unsigned long time_now = millis(); if(number == 0) number = 9999; if(time_now - time_previous > ms) { number--; time_previous += ms; //依次使時間計數器加一個秒單位 pf("number=%d\n", number);//把數字也顯示在序列埠上 } // 不斷地寫入數字 setNumber(number); // 冒號動作 colonswitch(); } // 設定當前時分 void setTimenow() { setNumber(Chour*100 + Cminute); //設定當前時分 colonswitch(); //冒號動作 裡頭有延遲一個秒單位 Csecond++; //秒數加1 if(Csecond == 60) //當59秒跳到60秒的時候 { Csecond = 0; Cminute++; } if(Cminute == 60) //當59分跳到60分的時候 { Cminute = 0; Chour++; } if(Chour == 24) //當23時跳到24時的時候 Chour = 0; } // 倒數計時器 void countDowntimer() { byte Ccs = 100; // 厘秒(10^-2秒) if(Chour >= 1)// 如果倒數時間大於等於1小時 while(Chour > 1) { setNumber(Chour*100 + Cminute); //設定當前時分 colonswitch(); //冒號動作 裡頭有延遲一個秒單位 Csecond--; //秒數減1 if(Csecond == -1) // 0秒下數到59秒的時候 { Csecond = 59; Cminute--; } if(Cminute == -1) // 0分下數到59分的時候 { Cminute = 59; Chour--; } } else if(Cminute >= 1) // 如果倒數時間小於1小時又大於1分鐘 while(Cminute > 1) { setNumber(Cminute*100 + Csecond); //設定當前分秒 colonswitch(); //冒號動作 裡頭有延遲一個秒單位 Csecond--; //秒數減1 if(Csecond == -1) // 0秒下數到59秒的時候 { Csecond = 59; Cminute--; } } else { /* time_previous = millis(); while(Csecond > 1) // 如果倒數時間小於1分鐘 { setNumber(Csecond*100+Ccs); //設定當前秒厘秒 (厘秒未測試) unsigned long time_now = millis(); for(i=0;i<100;i++) { time_now = millis(); if(time_now - time_previous > 10) { Ccs--; time_previous += 10; //依次使時間計數器加10毫秒 setNumber(Csecond*100+Ccs); } } colon = !colon; digitalWrite(pin_4_a,colon); digitalWrite(pin_4_b,colon); //冒號動作 Csecond--; //秒數減1 } */ while(Csecond > 1) // 如果倒數時間小於1分鐘 { setNumber(Csecond*100); // 設定當前秒厘秒 (厘秒未測試) colonswitch(); // 冒號動作 有延遲1秒 Csecond--; //秒數減1 } } } void setup() { // 開啟序列埠, 通訊速率為 9600 bps // Setup Serial communications for Printing to console and debugging Serial.begin(9600); BT.begin(9600); BT.begin(9600); // 宣告4顆七段顯示器的腳位為輸出 // Setup pins for(int i = 0;i < 4;i++) for(int j = 0;j < 7;j++) pinMode(seg4[i][j],OUTPUT); // 設定時間計數器 Setup Timers time_previous = millis(); } void loop() { // 檢查是否有資料可供讀取 if (Serial.available() > 0 || BT.available() > 0) { char c = Serial.read(); mode = Serial.read(); switch(mode) { // 當前時分 case 0: // 從手機端取得三個時間數值 Chour = Serial.read(); Cminute = Serial.read(); Csecond = Serial.read(); while(Serial.available() == 0) { setTimenow(); pf("Time = %d : %d : %d ",Chour,Cminute,Csecond); } break; //從0000上數到9999 case 1: while(Serial.available() == 0) from0000to9999(); break; // 從9999下數到0000 case 2: while(Serial.available() == 0) from9999to0000(); break; // 輸入一個數字並顯示 case 3: number = Serial.read(); if(number > 9999 || number < 0) // 如果數字輸入錯誤則退出 break; while(Serial.available() == 0) { setNumber(number); colonswitch(); } break; // 倒數計時器 case 4: // // 從手機端取得三個時間數值 Chour = Serial.read(); Cminute = Serial.read(); Csecond = Serial.read(); countDowntimer(); while(Serial.available() == 0) { setNumber(0); colonswitch(); } break; // case 5: break; } } else { // 測試時全亮 setNumber(8888); colonswitch(); } }
[ "noreply@github.com" ]
noreply@github.com
7db957018c86f1d87d4f392c76889d3c87e9511b
2e3bc275f1ad76df966e9d19561b5cad79839b84
/tensorflow/core/kernels/ragged_tensor_to_tensor_op.cc
ca9e1836c82127c48c384ae053a8a274a2192898
[ "Apache-2.0" ]
permissive
themikem/tensorflow
624ee656d2dbc95ee9774538f20b57808e08dd4c
5deca4e0eb2d15022b6645c2d5289f1a68717dbd
refs/heads/master
2020-09-16T14:26:39.745634
2019-11-24T16:52:28
2019-11-24T16:58:32
223,794,503
2
2
Apache-2.0
2019-12-26T06:32:55
2019-11-24T18:59:30
null
UTF-8
C++
false
false
22,923
cc
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #define EIGEN_USE_THREADS #include <stddef.h> #include <algorithm> #include <string> #include <vector> #include "tensorflow/core/framework/kernel_def_builder.h" #include "tensorflow/core/framework/numeric_types.h" #include "tensorflow/core/framework/op.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/register_types.h" #include "tensorflow/core/framework/shape_inference.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/framework/tensor_shape.h" #include "tensorflow/core/framework/tensor_shape.pb.h" #include "tensorflow/core/framework/tensor_types.h" #include "tensorflow/core/framework/types.h" #include "tensorflow/core/kernels/broadcast_to_op.h" #include "tensorflow/core/kernels/list_kernels.h" #include "tensorflow/core/lib/bfloat16/bfloat16.h" #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/lib/core/status.h" #include "tensorflow/core/ops/ragged_to_dense_util.h" #include "tensorflow/core/platform/types.h" #include "tensorflow/core/util/bcast.h" namespace tensorflow { namespace { typedef Eigen::ThreadPoolDevice CPUDevice; using ::std::vector; const int kShapeInputIndex = 0; const int kValueInputIndex = 1; const int kDefaultValueInputIndex = 2; const int kFirstPartitionInputIndex = 3; template <typename INDEX_TYPE> class RaggedTensorToTensorBaseOp : public OpKernel { public: typedef typename ::tensorflow::TTypes<const INDEX_TYPE>::Flat RowPartitionTensor; explicit RaggedTensorToTensorBaseOp(OpKernelConstruction* context) : OpKernel(context) { OP_REQUIRES_OK(context, GetRowPartitionTypes<OpKernelConstruction>( context, &row_partition_types_)); ragged_rank_ = GetRaggedRank(row_partition_types_); } // Returns the relationship between dimension and dimension + 1. RowPartitionType GetRowPartitionTypeByDimension(int dimension) { if (row_partition_types_[0] == RowPartitionType::FIRST_DIM_SIZE) { return row_partition_types_[dimension + 1]; } else { return row_partition_types_[dimension]; } } // Returns the relationship between dimension and dimension + 1. RowPartitionTensor GetRowPartitionTensor(OpKernelContext* c, int dimension) { if (row_partition_types_[0] == RowPartitionType::FIRST_DIM_SIZE) { return c->input(dimension + 1 + kFirstPartitionInputIndex) .flat<INDEX_TYPE>(); } else { return c->input(dimension + kFirstPartitionInputIndex).flat<INDEX_TYPE>(); } } Status GetMaxWidth(OpKernelContext* c, int dimension, INDEX_TYPE* result) { const RowPartitionTensor row_partition_tensor = GetRowPartitionTensor(c, dimension - 1); switch (GetRowPartitionTypeByDimension(dimension - 1)) { case RowPartitionType::VALUE_ROWIDS: *result = GetMaxWidthValueRowID(row_partition_tensor); return Status::OK(); case RowPartitionType::ROW_SPLITS: *result = GetMaxWidthRowSplit(row_partition_tensor); return Status::OK(); default: return errors::InvalidArgument( "Cannot handle partition type ", RowPartitionTypeToString( GetRowPartitionTypeByDimension(dimension - 1))); } } static INDEX_TYPE GetMaxWidthRowSplit(const RowPartitionTensor& row_split) { const INDEX_TYPE tensor_length = row_split.size(); if (tensor_length == 0 || tensor_length == 1) { return 0; } INDEX_TYPE max_width = 0; for (INDEX_TYPE i = 0; i < tensor_length - 1; ++i) { const INDEX_TYPE current_width = row_split(i + 1) - row_split(i); if (current_width > max_width) { max_width = current_width; } } return max_width; } static INDEX_TYPE GetMaxWidthValueRowID( const RowPartitionTensor& value_rowids) { const INDEX_TYPE index_length = value_rowids.size(); if (index_length == 0) { return 0; } INDEX_TYPE first_equal_index = 0; INDEX_TYPE first_equal_index_value = value_rowids(0); INDEX_TYPE max_width = 0; for (INDEX_TYPE i = 1; i < index_length; ++i) { const INDEX_TYPE value = value_rowids(i); if (value != first_equal_index_value) { first_equal_index_value = value; max_width = std::max(i - first_equal_index, max_width); first_equal_index = i; } } return std::max(index_length - first_equal_index, max_width); } Status CalculateOutputSize(INDEX_TYPE first_dim, OpKernelContext* c, vector<INDEX_TYPE>* result) { TensorShapeProto value_shape_proto; c->input(kValueInputIndex).shape().AsProto(&value_shape_proto); TensorShapeProto default_value_shape_proto; c->input(kDefaultValueInputIndex) .shape() .AsProto(&default_value_shape_proto); TensorShapeProto output_shape_proto; TF_RETURN_IF_ERROR(ValidateDefaultValueShape(default_value_shape_proto, value_shape_proto)); TensorShapeProto shape_proto; { PartialTensorShape partial_tensor_shape; TF_RETURN_IF_ERROR(TensorShapeFromTensor(c->input(kShapeInputIndex), &partial_tensor_shape)); partial_tensor_shape.AsProto(&shape_proto); } TF_RETURN_IF_ERROR(CombineRaggedTensorToTensorShapes( ragged_rank_, shape_proto, value_shape_proto, &output_shape_proto)); result->reserve(output_shape_proto.dim_size()); for (const TensorShapeProto::Dim& dim : output_shape_proto.dim()) { // Note that this may be -1 (if dimension size is unknown). result->push_back(dim.size()); } if ((*result)[0] < 0) { (*result)[0] = first_dim; } for (int i = 1; i <= ragged_rank_; ++i) { if ((*result)[i] < 0) { TF_RETURN_IF_ERROR(GetMaxWidth(c, i, &(*result)[i])); } } return Status::OK(); } /** * The output_index represents the index in the output tensor * where the first element of a particular dimension would be written. * If it is -1, it indicates that the index is out of scope. * Example, given first_dimension = 10, first_dimension_output = 6, * and output_index_multiplier = 100: * result = [0 100 200 300 400 500 -1 -1 -1 -1] * If first_dimension_output = 11 instead, then: * result = [0 100 200 300 400 500 600 700 800 900] */ void CalculateFirstParentOutputIndex(INDEX_TYPE first_dimension, INDEX_TYPE output_index_multiplier, INDEX_TYPE first_dimension_output, vector<INDEX_TYPE>* result) { const INDEX_TYPE min_dimension = std::min(first_dimension, first_dimension_output); result->reserve(first_dimension); int current_output_index = 0; for (INDEX_TYPE i = 0; i < min_dimension; ++i, current_output_index += output_index_multiplier) { result->push_back(current_output_index); } for (INDEX_TYPE i = min_dimension; i < first_dimension; ++i) { result->push_back(-1); } DCHECK_EQ(result->size(), first_dimension); } void CalculateOutputIndexRowSplit( const RowPartitionTensor& row_split, const vector<INDEX_TYPE>& parent_output_index, INDEX_TYPE output_index_multiplier, INDEX_TYPE output_size, vector<INDEX_TYPE>* result) { INDEX_TYPE row_split_size = row_split.size(); if (row_split_size > 0) { result->reserve(row_split(row_split_size - 1)); } for (INDEX_TYPE i = 0; i < row_split_size - 1; ++i) { INDEX_TYPE row_length = row_split(i + 1) - row_split(i); INDEX_TYPE real_length = std::min(output_size, row_length); INDEX_TYPE parent_output_index_current = parent_output_index[i]; if (parent_output_index_current == -1) { real_length = 0; } for (INDEX_TYPE j = 0; j < real_length; ++j) { result->push_back(parent_output_index_current); parent_output_index_current += output_index_multiplier; } for (INDEX_TYPE j = 0; j < row_length - real_length; ++j) { result->push_back(-1); } } if (row_split_size > 0) { DCHECK_EQ(result->size(), row_split(row_split_size - 1)); } } // Calculate the output index of the first element of a list. // The parent_output_index is the same computation for the previous list. // -1 indicates an element or list that is out of range. // The output_index_multiplier is the number of output indices one moves // forward for each column. // E.g., given: // value_rowids:[0 1 2 2 2 3 5 5 6] // parent_output_index:[1000 1100 2000 2100 -1 3000 4000] // output_index_multiplier: 10 // output_size: 2 // You get: // result = [1000 1100 2000 2010 -1 2100 -1 -1 3000] // result[0] = parent_output_index[value_rowids[0]] // result[1] = parent_output_index[value_rowids[1]] // result[2] = parent_output_index[value_rowids[2]] // result[3] = parent_output_index[value_rowids[2] + 10] // result[4] = -1 because it is the third element the size is 2. // result[5] = parent_output_index[value_rowids[3]] // result[6] = -1 because parent_output_index[value_rowids[6]] == -1 // result[7] = -1 because parent_output_index[value_rowids[6]] == -1 // result[8] = parent_output_index[value_rowids[7]] void CalculateOutputIndexValueRowID( const RowPartitionTensor& value_rowids, const vector<INDEX_TYPE>& parent_output_index, INDEX_TYPE output_index_multiplier, INDEX_TYPE output_size, vector<INDEX_TYPE>* result) { const INDEX_TYPE index_size = value_rowids.size(); result->reserve(index_size); if (index_size == 0) { return; } INDEX_TYPE current_output_column = 0; INDEX_TYPE current_value_rowid = value_rowids(0); DCHECK_LT(current_value_rowid, parent_output_index.size()); INDEX_TYPE current_output_index = parent_output_index[current_value_rowid]; result->push_back(current_output_index); for (INDEX_TYPE i = 1; i < index_size; ++i) { INDEX_TYPE next_value_rowid = value_rowids(i); if (next_value_rowid == current_value_rowid) { if (current_output_index >= 0) { ++current_output_column; if (current_output_column < output_size) { current_output_index += output_index_multiplier; } else { current_output_index = -1; } } } else { current_output_column = 0; current_value_rowid = next_value_rowid; DCHECK_LT(next_value_rowid, parent_output_index.size()); current_output_index = parent_output_index[next_value_rowid]; } result->push_back(current_output_index); } DCHECK_EQ(result->size(), value_rowids.size()); } Status CalculateOutputIndex(OpKernelContext* context, int dimension, const vector<INDEX_TYPE>& parent_output_index, INDEX_TYPE output_index_multiplier, INDEX_TYPE output_size, vector<INDEX_TYPE>* result) { const RowPartitionTensor row_partition_tensor = GetRowPartitionTensor(context, dimension); auto partition_type = GetRowPartitionTypeByDimension(dimension); switch (partition_type) { case RowPartitionType::VALUE_ROWIDS: CalculateOutputIndexValueRowID( row_partition_tensor, parent_output_index, output_index_multiplier, output_size, result); return tensorflow::Status::OK(); case RowPartitionType::ROW_SPLITS: CalculateOutputIndexRowSplit(row_partition_tensor, parent_output_index, output_index_multiplier, output_size, result); return tensorflow::Status::OK(); default: return errors::InvalidArgument( "Unsupported partition type:", RowPartitionTypeToString(partition_type)); } } Status GetFirstDimensionSize(OpKernelContext* context, INDEX_TYPE* result) { const Tensor first_partition_tensor = context->input(kFirstPartitionInputIndex); const RowPartitionType first_partition_type = row_partition_types_[0]; switch (first_partition_type) { case RowPartitionType::FIRST_DIM_SIZE: *result = first_partition_tensor.scalar<INDEX_TYPE>()(); return Status::OK(); case RowPartitionType::VALUE_ROWIDS: return errors::InvalidArgument( "Cannot handle VALUE_ROWIDS in first dimension."); case RowPartitionType::ROW_SPLITS: *result = first_partition_tensor.shape().dim_size(0) - 1; return Status::OK(); default: return errors::InvalidArgument( "Cannot handle type ", RowPartitionTypeToString(first_partition_type)); } } void Compute(OpKernelContext* context) override { INDEX_TYPE first_dimension; OP_REQUIRES_OK(context, GetFirstDimensionSize(context, &first_dimension)); vector<INDEX_TYPE> output_size; OP_REQUIRES_OK(context, CalculateOutputSize(first_dimension, context, &output_size)); vector<INDEX_TYPE> multiplier; multiplier.resize(ragged_rank_ + 1); multiplier[multiplier.size() - 1] = 1; for (int i = multiplier.size() - 2; i >= 0; --i) { multiplier[i] = multiplier[i + 1] * output_size[i + 1]; } // Full size of the tensor. TensorShape output_shape; OP_REQUIRES_OK(context, TensorShapeUtils::MakeShape(output_size, &output_shape)); Tensor* output_tensor = nullptr; OP_REQUIRES_OK(context, context->allocate_output(0, output_shape, &output_tensor)); const INDEX_TYPE full_size = multiplier[0] * output_size[0]; if (full_size > 0) { vector<INDEX_TYPE> output_index, new_output_index; int nvals = context->input(kValueInputIndex).shape().dim_size(0); output_index.reserve(nvals); new_output_index.reserve(nvals); CalculateFirstParentOutputIndex(first_dimension, multiplier[0], output_size[0], &output_index); for (int i = 1; i <= ragged_rank_; ++i) { OP_REQUIRES_OK(context, CalculateOutputIndex( context, i - 1, output_index, multiplier[i], output_size[i], &new_output_index)); output_index.swap(new_output_index); new_output_index.clear(); } SetOutput(context, ragged_rank_, output_index, output_tensor); } } virtual void SetOutput(OpKernelContext* context, int ragged_rank, const vector<INDEX_TYPE>& output_index, Tensor* output_tensor) = 0; private: vector<RowPartitionType> row_partition_types_; int ragged_rank_; }; template <typename VALUE_TYPE, typename INDEX_TYPE> void slow_copy_array(VALUE_TYPE* dst, const VALUE_TYPE* src, INDEX_TYPE size) { for (INDEX_TYPE index = 0; index < size; ++index) { dst[index] = src[index]; } } template <typename VALUE_TYPE, typename INDEX_TYPE> void copy_array(VALUE_TYPE* dst, const VALUE_TYPE* src, INDEX_TYPE size) { memcpy(dst, src, size * sizeof(VALUE_TYPE)); } template <> void copy_array<string, int64>(string* dst, const string* src, int64 size) { slow_copy_array(dst, src, size); } template <> void copy_array<string, int32>(string* dst, const string* src, int32 size) { slow_copy_array(dst, src, size); } // If we don't specialize for Eigen::half, we get: // undefined behavior, destination object type 'Eigen::half' // is not TriviallyCopyable template <> void copy_array<Eigen::half, int64>(Eigen::half* dst, const Eigen::half* src, int64 size) { slow_copy_array(dst, src, size); } template <> void copy_array<Eigen::half, int32>(Eigen::half* dst, const Eigen::half* src, int32 size) { slow_copy_array(dst, src, size); } template <typename VALUE_TYPE, typename INDEX_TYPE> class RaggedTensorToTensorOp : public RaggedTensorToTensorBaseOp<INDEX_TYPE> { public: explicit RaggedTensorToTensorOp(OpKernelConstruction* context) : RaggedTensorToTensorBaseOp<INDEX_TYPE>(context) {} void SetOutput(OpKernelContext* context, int ragged_rank, const vector<INDEX_TYPE>& output_index, Tensor* output_tensor) override { // Note: it's ok to use OP_REQUIRES_OK (rather than TF_RETURN_IF_ERROR) // in this function, but only because it's the last thing we do before // returning from Compute(). if (output_tensor->NumElements() == 0) return; const auto& values_tensor = context->input(kValueInputIndex); const VALUE_TYPE* values_base = values_tensor.flat<VALUE_TYPE>().data(); const auto& default_value_tensor = context->input(kDefaultValueInputIndex); VALUE_TYPE* output_base = output_tensor->flat<VALUE_TYPE>().data(); TensorShape element_shape = output_tensor->shape(); element_shape.RemoveDimRange(0, ragged_rank + 1); int value_element_size = element_shape.num_elements(); size_t output_index_size = output_index.size(); // Broadcast the default value to value_element_size. (We can skip this // if default_value_tensor.NumElements() == 1, since we use std::fill // when that's true.) const VALUE_TYPE* default_value = default_value_tensor.flat<VALUE_TYPE>().data(); Tensor bcast_default; // Temporary tensor for result of broadcast if (default_value_tensor.NumElements() != value_element_size && default_value_tensor.NumElements() != 1) { const auto& src_shape = default_value_tensor.shape(); BCast bcast(BCast::FromShape(src_shape), BCast::FromShape(element_shape), /*fewer_dims_optimization=*/true); // Note: bcast should always be valid, since we rejected any incompatible // shapes when we called ValidateDefaultValueShape(). OP_REQUIRES(context, bcast.IsValid(), errors::InvalidArgument("Error broadcasting default_value")); OP_REQUIRES_OK(context, context->allocate_temp(default_value_tensor.dtype(), element_shape, &bcast_default)); const CPUDevice& device = context->eigen_device<CPUDevice>(); functor::BroadcastTo<CPUDevice, VALUE_TYPE>()( device, context, bcast_default, element_shape, default_value_tensor, src_shape, bcast); default_value = bcast_default.flat<VALUE_TYPE>().data(); } // Loop through the output_index vector, finding contiguous regions that // should be copied. Once we find the end of a contiguous region, copy it // and add any necessary padding (with default_value). INDEX_TYPE src_start = 0; // Start of contiguous region (in values) INDEX_TYPE dst_start = 0; // Destination for contiguous region (in output) INDEX_TYPE dst_end = 0; // Destination for contiguous region (in output) for (int src_i = 0; src_i <= output_index_size; ++src_i) { // dst_i is the destination where the value at src_i should be copied. INDEX_TYPE dst_i = src_i < output_index_size ? output_index[src_i] : -1; // If we're still in a contiguous region, then update dst_end go to the // next src_i. if (dst_i == dst_end) { ++dst_end; continue; } // We found the end of contiguous region. This can be because we found // a gap (dst_i > dst_end), or a source value that shouldn't be copied // because it's out-of-bounds (dst_i == -1), or the end of the tensor // (dst_i = -1). if (dst_start < dst_end) { // Copy the contiguous region. const VALUE_TYPE* src = values_base + src_start * value_element_size; VALUE_TYPE* dst = output_base + dst_start * value_element_size; INDEX_TYPE nvals = (dst_end - dst_start) * value_element_size; copy_array<VALUE_TYPE, INDEX_TYPE>(dst, src, nvals); } // Add any necessary padding (w/ default_value). if (src_i >= output_index_size) { // We reached the end of values: pad to the end of output. size_t output_size = output_tensor->NumElements(); dst_i = output_size / value_element_size; } if (dst_i > dst_end) { if (default_value_tensor.NumElements() == 1) { std::fill(output_base + dst_end * value_element_size, output_base + dst_i * value_element_size, *default_value); dst_end = dst_i; } else { while (dst_i > dst_end) { VALUE_TYPE* dst = output_base + dst_end * value_element_size; copy_array<VALUE_TYPE, INDEX_TYPE>(dst, default_value, value_element_size); ++dst_end; } } } // Update indices. if (dst_i < 0) { // src_i should be skipped -- leave it out of the contiguous region. src_start = src_i + 1; dst_start = dst_end; } else { // src_i should be copied -- include it in the contiguous region. src_start = src_i; dst_start = dst_end; dst_end = dst_start + 1; } } } }; #define REGISTER_CPU_KERNEL_INDEX_TYPE(value_type, index_type) \ REGISTER_KERNEL_BUILDER(Name("RaggedTensorToTensor") \ .Device(DEVICE_CPU) \ .TypeConstraint<value_type>("T") \ .TypeConstraint<index_type>("Tindex"), \ RaggedTensorToTensorOp<value_type, index_type>); #define REGISTER_CPU_KERNEL(value_type) \ REGISTER_CPU_KERNEL_INDEX_TYPE(value_type, tensorflow::int64); \ REGISTER_CPU_KERNEL_INDEX_TYPE(value_type, tensorflow::int32); TF_CALL_POD_TYPES(REGISTER_CPU_KERNEL); TF_CALL_string(REGISTER_CPU_KERNEL); TF_CALL_QUANTIZED_TYPES(REGISTER_CPU_KERNEL); TF_CALL_quint16(REGISTER_CPU_KERNEL); TF_CALL_qint16(REGISTER_CPU_KERNEL); TF_CALL_uint32(REGISTER_CPU_KERNEL); TF_CALL_uint64(REGISTER_CPU_KERNEL); #undef REGISTER_CPU_KERNEL } // namespace } // namespace tensorflow
[ "gardener@tensorflow.org" ]
gardener@tensorflow.org
bd3793c3ccb87836c132bd13c0c2366dd7a70c1d
5d65fecb377f7b9a1cf3dcd68302f3612e841307
/C++/07. Other Concepts/01. C++ Class Templates/ClassTemplates.cpp
9229bfdd55ef93c00fb30a17135d65047c2d5187
[ "MIT" ]
permissive
AdityaSingh17/HackerRank-Solutions
74ae4b0bf253a33e7ef11f29d7fc65bbadcdec0b
65b7fcd6e82be242fcc7e5b1771941206a8b7940
refs/heads/master
2023-01-04T21:26:03.108488
2020-11-04T04:59:06
2020-11-04T04:59:06
281,844,471
0
0
null
null
null
null
UTF-8
C++
false
false
1,557
cpp
// C++ Class Templates // Problem Link: https://www.hackerrank.com/challenges/c-class-templates/problem #include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> #include <cassert> using namespace std; /*Write the class AddElements here*/ #include <string> // class template: template <class T> class AddElements { T element; public: AddElements(T arg) { element = arg; } T add(T x) { return x + element; } }; // class template specialization: template <> class AddElements<string> { string element; public: AddElements(string arg) { element = arg; } string concatenate(string arg) { string s = element + arg; return s; } }; int main() { int n, i; cin >> n; for (i = 0; i < n; i++) { string type; cin >> type; if (type == "float") { double element1, element2; cin >> element1 >> element2; AddElements<double> myfloat(element1); cout << myfloat.add(element2) << endl; } else if (type == "int") { int element1, element2; cin >> element1 >> element2; AddElements<int> myint(element1); cout << myint.add(element2) << endl; } else if (type == "string") { string element1, element2; cin >> element1 >> element2; AddElements<string> mystring(element1); cout << mystring.concatenate(element2) << endl; } } return 0; }
[ "adityarsingh17@gmail.com" ]
adityarsingh17@gmail.com
e2e9fcab94c5bfb81e69f7a2e48b2fc815afd1c3
73d59719f5323d6f16c33928ba93e85aaa87a02b
/src/gel/device/FbxModel.hpp
4d04481d22a02eb70f26794c378e780902491961
[]
no_license
desktopgame/tank-fight
8254b02576e506fb4f55b8c625b830e614989826
f913dd49e18c1751c7138fa0f4a2abaaedf2d556
refs/heads/master
2020-05-29T20:29:39.102173
2019-06-18T12:53:52
2019-06-18T12:53:52
189,353,210
0
0
null
null
null
null
UTF-8
C++
false
false
1,384
hpp
#ifndef GEL_DEVICE_FBXMODEL_HPP #define GEL_DEVICE_FBXMODEL_HPP #include <GLFW/glfw3.h> #include <memory> #include <vector> #include "FbxMeshInfo.hpp" #include "../model/Vector2.hpp" #include "../model/Vector3.hpp" #include "FbxMaterial.hpp" #include "IModel.hpp" #include "PngTexture.hpp" #include "fbxsdk.h" namespace gel { class FbxModel : public IModel { public: FbxModel(FbxManager* fbxManager); void load(const std::string& path) override; void unload(const std::string& path) override; void draw() override; AABB getAABB() const override; private: void drawMeshInfo(FbxMeshInfo& meshInfo); void collectRecMesh(FbxNode* rootNode, std::vector<FbxMesh*>& dest); void collectMesh(FbxNode* rootNode, std::vector<FbxMesh*>& dest); FbxMesh* mapVertex(FbxMesh* fbxMesh, FbxMeshInfo& dest); FbxMesh* mapVertexIndex(FbxMesh* fbxMesh, FbxMeshInfo& dest); FbxMesh* mapNormal(FbxMesh* fbxMesh, FbxMeshInfo& dest); FbxMesh* mapUV(FbxMesh* fbxMesh, FbxMeshInfo& dest); FbxMesh* mapMaterial(FbxMesh* fbxMesh, FbxMeshInfo& dest); FbxMesh* mapSide(FbxMesh* fbxMesh, FbxMeshInfo& dest); FbxManager* fbxManager; FbxScene* fbxScene; FbxImporter* fbxImporter; std::vector<FbxMeshInfo> vinfo; AABB aabb; }; } // namespace gel #endif
[ "koya0306@outlook.jp" ]
koya0306@outlook.jp
040086b572fce09e9b94fc275eda737a479290f0
25f4c06e9bb1b03da367fc5981dbfe1ddd970d28
/c++/suffix_array_n_logn.cpp
a2120d93510ab1be006cfdcf825f15e08457ce44
[]
no_license
Shubzedm007/Hactoberfest-accepted
78426a64c87a6bf65b97982e060b9b2722575c08
636482068735558785837b01aef2d33b8c9e6dc3
refs/heads/main
2023-08-22T10:31:33.662572
2021-10-16T10:38:44
2021-10-16T10:38:44
417,795,809
1
0
null
2021-10-16T10:38:45
2021-10-16T10:37:35
null
UTF-8
C++
false
false
1,313
cpp
#include <bits/stdc++.h> using namespace std; typedef long long ll; void count_sort(vector<ll>&p,vector<ll>&c) { ll n=p.size(); vector<ll>cnt(n); for(auto x:c) cnt[x]++; vector<ll>pos(n),p_new(n); pos[0]=0; for(ll i=1;i<n;i++) pos[i]=pos[i-1]+cnt[i-1]; for(auto x:p) { ll i=c[x]; p_new[pos[i]]=x; pos[i]++; } p=p_new; } int main() { string s; cin>>s; s=s+"$"; ll n=s.size(); vector<ll> p(n),c(n); //k=0 { std::vector<pair<char,ll>>a(n) ; for(ll i=0;i<n;i++)a[i]={s[i],i}; sort(a.begin(),a.end()); for(ll i=0;i<n;i++)p[i]=a[i].second; c[p[0]]=0; for(ll i=1;i<n;i++) { if(a[i].first==a[i-1].first) c[p[i]]=c[p[i-1]]; else c[p[i]]=c[p[i-1]]+1; } } ll k=0; while((1<<k)<n) { for(ll i=0;i<n;i++) { p[i]=(p[i]-(1<<k)+n)%n; } count_sort(p,c); vector<ll>c_new(n); c_new[p[0]]=0; for(ll i=1;i<n;i++) { pair<ll,ll>prev={c[p[i-1]],c[(p[i-1]+(1<<k))%n]}; pair<ll,ll>now={c[p[i]],c[(p[i]+(1<<k))%n]}; if(now==prev) c_new[p[i]]=c_new[p[i-1]]; else c_new[p[i]]=c_new[p[i-1]]+1; } c=c_new; k++; } for(ll i=0;i<n;i++) cout<<p[i]<<' '; return 0; }
[ "dinsha.jaiswal123@gmail.com" ]
dinsha.jaiswal123@gmail.com
70b8734f5945b3d7f2670a4e5d2c79786f0e5b07
bc394713fc829dcdf97cbd81e639a79218ce3ff7
/Log.h
48e34db5a3729e31c2046bfaf704a70d74bbd025
[]
no_license
michalmendrek/PolingLoger
318620857686c030280b9222339f83a56c255453
bcd754286222fef42f187a76cf3f0b14fe76df79
refs/heads/master
2020-07-29T03:54:39.373328
2019-09-20T10:28:42
2019-09-20T10:28:42
209,659,796
0
0
null
null
null
null
UTF-8
C++
false
false
360
h
#ifndef LOG_H #define LOG_H #include <fstream> #include <string> class Log { private: std::ifstream File; ssize_t LastEnd; int GetLineNumber(); ssize_t GetLastEndFullLineAproach(); public: Log(std::string FileName); ~Log(); std::string ReadNewLines(); std::string ReadNLastLinesOfFile(int num); std::string ReadWholeLogFile(); }; #endif
[ "michal.mendrek@intive.com" ]
michal.mendrek@intive.com
758501e83376cc75d30663183991bae565188d9b
ad71ab3c39785830a112951075afe97c9948f5bc
/ZF/ZFUIKit/zfsrc/ZFUIKit/ZFUIView.h
ac0f546891dcdbf3859ae66bce895fcaa0ab30ea
[ "Vim", "MIT" ]
permissive
ZFFrameworkDist/ZFFramework
0f8027126ef41e59c762cd68d878cac28fae1ea4
6b498e7b95ee6d6aaa28d8369eef8c2ff94daaf7
refs/heads/master
2021-08-04T04:40:41.207724
2021-05-25T08:36:10
2021-05-25T08:36:10
120,870,315
0
0
null
null
null
null
UTF-8
C++
false
false
42,019
h
/** * @file ZFUIView.h * @brief base class of all UI views */ #ifndef _ZFI_ZFUIView_h_ #define _ZFI_ZFUIView_h_ #include "ZFUIViewType.h" #include "ZFUIMouseEvent.h" #include "ZFUIKeyEvent.h" #include "ZFUIWheelEvent.h" ZF_NAMESPACE_GLOBAL_BEGIN /** @brief keyword for serialize */ #define ZFSerializableKeyword_ZFUIView_internalImplView "internalImplView" /** @brief keyword for serialize */ #define ZFSerializableKeyword_ZFUIView_internalBgView "internalBgView" /** @brief keyword for serialize */ #define ZFSerializableKeyword_ZFUIView_internalFgView "internalFgView" /** @brief keyword for serialize */ #define ZFSerializableKeyword_ZFUIView_child "child" /** @brief keyword for serialize */ #define ZFSerializableKeyword_ZFUIView_layoutParam "layoutParam" // ============================================================ zfclassFwd ZFUIView; /** * @brief see #ZFUIView::nativeImplView */ typedef void (*ZFUIViewNativeImplViewDeleteCallback)(ZF_IN ZFUIView *view, ZF_IN void *nativeImplView); // ============================================================ // ZFUIView zfclassFwd _ZFP_ZFUIViewPrivate; /** * @brief base class of all UI views * * ZFUIView has these layer of views: * - internal impl view: * for subclass to add views behind native impl view * - internal native view: * for impl to achieve different functions, internal use only * - internal background view: * for subclass to add background views * - normal view: * common children views * - internal foreground view: * for subclass to add foreground views * * all view layer is implemented internally by simple view management\n * \n * ZFUIView is serializable and styleable, see #ZFSerializable and #ZFStyleable for more info, * all property and normal children views would be serialized and styled automatically, * but internal views must be processed by subclass manually\n * \n * serializable data: * @code * <ViewClass> * // optional, see #internalViewAutoSerializeTagAdd * <ChildClass category="internalImplView" > * // optional, see #internalViewAutoSerializeTagAdd * <ChildClass category="internalBgView" > * </ChildClass> * // optional, see #internalViewAutoSerializeTagAdd * <ChildClass category="internalFgView" > * </ChildClass> * * <ChildClass category="child" > * // layout param for parent, optional * <LayoutParamClass category="layoutParam" ... /> * </ChildClass> * ... // all children * </ViewClass> * @endcode * by default, internal views won't be serialized automatically, * except matches these condition: * - have the viewId of your internal view been set * - have the same viewId registered by #internalViewAutoSerializeTagAdd * * \n * ADVANCED:\n * we allow add native view to ZFUIView environment, * for how to, refer to #ZFUINativeViewWrapper\n * we also allow add ZFUIView to native view, * for how to, refer to #ZFUISysWindow::nativeWindowEmbed */ zfclass ZF_ENV_EXPORT ZFUIView : zfextends ZFStyleableObject { ZFOBJECT_DECLARE(ZFUIView, ZFStyleableObject) ZFSTYLE_DEFAULT_DECLARE(ZFUIView) public: // ============================================================ // events /** * @brief see #ZFObject::observerNotify * * called when child added or removed or order changed, * may be normal child or internal child */ ZFOBSERVER_EVENT(ViewChildOnChange) /** * @brief see #ZFObject::observerNotify * * called when child added to this view, * param0 is the child, * param1 is #ZFUIViewChildLayer */ ZFOBSERVER_EVENT(ViewChildOnAdd) /** * @brief see #ZFObject::observerNotify * * called when child removed from this view, * param0 is the child, * param1 is #ZFUIViewChildLayer */ ZFOBSERVER_EVENT(ViewChildOnRemove) /** * @brief see #ZFObject::observerNotify * * called when this view added to parent, * param0 is the parent added to */ ZFOBSERVER_EVENT(ViewOnAddToParent) /** * @brief see #ZFObject::observerNotify * * param0 is the parent removed from */ ZFOBSERVER_EVENT(ViewOnRemoveFromParent) /** * @brief see #ZFObject::observerNotify * * called when this view or parent view's #UIScale or #UIScaleFixed changed */ ZFOBSERVER_EVENT(UIScaleOnChange) /** * @brief see #ZFObject::observerNotify * * called when view's focus state changed, both obtain or resign */ ZFOBSERVER_EVENT(ViewFocusOnChange) /** * @brief see #ZFObject::observerNotify * * param0 is the #ZFUIEvent */ ZFOBSERVER_EVENT(ViewOnEvent) /** * @brief see #ZFObject::observerNotify * * called when #layoutRequest called */ ZFOBSERVER_EVENT(ViewLayoutOnLayoutRequest) /** * @brief see #ZFObject::observerNotify * * param0 is a #ZFUIViewMeasureResult, * you may change the measured size to override the measure result */ ZFOBSERVER_EVENT(ViewLayoutOnMeasureFinish) /** * @brief see #ZFObject::observerNotify * * #viewFrame would be updated before this method, * use #viewFramePrev if necessary, * you may safely modify children's #layoutParam during this method */ ZFOBSERVER_EVENT(ViewLayoutOnLayoutPrepare) /** * @brief see #ZFObject::observerNotify * * called to do actual layout steps */ ZFOBSERVER_EVENT(ViewLayoutOnLayout) /** * @brief see #ZFObject::observerNotify * * called when layout finished, * typically you should not modify #layoutParam during this event */ ZFOBSERVER_EVENT(ViewLayoutOnLayoutFinish) /** * @brief see #ZFObject::observerNotify * * called when #nativeImplViewMarginUpdate and value differs from old */ ZFOBSERVER_EVENT(NativeImplViewMarginOnUpdate) // ============================================================ // serialize public: /** * @brief store ref layout param for this view for reducing serialization output size * * if set, while serializing this view's layout param, * the ref one would be used as reference object to filter out contents that didn't change * (see #ZFSerializable::serializeToData)\n * by default, all children would have it's parent's default layout param (#layoutParamCreate) * as the ref layout param, during adding to parent */ virtual void serializableRefLayoutParam(ZF_IN ZFUILayoutParam *serializableRefLayoutParam); /** @brief see #serializableRefLayoutParam */ virtual ZFUILayoutParam *serializableRefLayoutParam(void); protected: zfoverride virtual zfbool serializableOnSerializeFromData(ZF_IN const ZFSerializableData &serializableData, ZF_OUT_OPT zfstring *outErrorHint = zfnull, ZF_OUT_OPT ZFSerializableData *outErrorPos = zfnull); zfoverride virtual zfbool serializableOnSerializeToData(ZF_IN_OUT ZFSerializableData &serializableData, ZF_IN ZFSerializable *referencedOwnerOrNull, ZF_OUT_OPT zfstring *outErrorHint = zfnull); /** * @brief whether we should serialize all children * * by default, #ZFUIView would serialize all normal child views, * for some adapter view it may be not necessary, * you may override this method to disable the auto serialization of child views */ virtual inline zfbool serializableOnCheckNeedSerializeChildren(void) { return zftrue; } public: // ============================================================ // properties /** * @brief used to identify a view, empty by default * * this is useful when you want to find a view from a complicated view tree, * see #ZFUIView::childFindById * @note it's OK that two view have same view id, * however it's recommended to make it unique */ ZFPROPERTY_ASSIGN(zfstring, viewId) /** * @brief visible or not, zftrue by default */ ZFPROPERTY_ASSIGN_WITH_INIT(zfbool, viewVisible, zftrue) ZFPROPERTY_ON_ATTACH_DECLARE(zfbool, viewVisible) /** * @brief view's alpha, 1 by default */ ZFPROPERTY_ASSIGN_WITH_INIT(zffloat, viewAlpha, 1) ZFPROPERTY_ON_VERIFY_DECLARE(zffloat, viewAlpha) ZFPROPERTY_ON_ATTACH_DECLARE(zffloat, viewAlpha) /** * @brief whether the view should receive user interaction * (doesn't affect children, see #viewUIEnableTree) */ ZFPROPERTY_ASSIGN_WITH_INIT(zfbool, viewUIEnable, zftrue) ZFPROPERTY_ON_ATTACH_DECLARE(zfbool, viewUIEnable) /** * @brief whether the view as well as all its children should receive user interaction, * see #viewUIEnable */ ZFPROPERTY_ASSIGN_WITH_INIT(zfbool, viewUIEnableTree, zftrue) ZFPROPERTY_ON_ATTACH_DECLARE(zfbool, viewUIEnableTree) /** * @brief whether enable mouse hover event, see #ZFUIView::viewEventOnMouseEvent, false by default */ ZFPROPERTY_ASSIGN(zfbool, viewMouseHoverEventEnable) ZFPROPERTY_ON_ATTACH_DECLARE(zfbool, viewMouseHoverEventEnable) /** * @brief whether the view can be focused, false by default */ ZFPROPERTY_ASSIGN(zfbool, viewFocusable) ZFPROPERTY_ON_ATTACH_DECLARE(zfbool, viewFocusable) /** * @brief whether try to obtain focus when clicked down, true by default */ ZFPROPERTY_ASSIGN_WITH_INIT(zfbool, viewFocusObtainWhenClick, zftrue) /** * @brief the view's frame * * typicall, this property would be updated automatically by parent's #layoutOnLayout, * but you may also change this property manually, * for example, to achieve custom animation logic, * if you do so, the frame would be kept * and parent's layout logic would be ignored, * until you call #viewFrameReset */ ZFMETHOD_DECLARE_0(ZFUIRect const &, viewFrame) /** @brief see #viewFrame */ ZFMETHOD_DECLARE_1(void, viewFrame, ZFMP_IN(ZFUIRect const &, viewFrame)) /** @brief previous #viewFrame */ ZFMETHOD_DECLARE_0(const ZFUIRect &, viewFramePrev) /** @brief see #viewFrame */ ZFMETHOD_DECLARE_0(void, viewFrameReset) /** @brief see #viewFrame */ ZFMETHOD_DECLARE_0(zffloat const &, viewX) /** @brief see #viewFrame */ ZFMETHOD_DECLARE_1(void, viewX, ZFMP_IN(zffloat const &, propertyValue)) /** @brief see #viewFrame */ ZFMETHOD_DECLARE_0(zffloat const &, viewY) /** @brief see #viewFrame */ ZFMETHOD_DECLARE_1(void, viewY, ZFMP_IN(zffloat const &, propertyValue)) /** @brief see #viewFrame */ ZFMETHOD_DECLARE_0(zffloat const &, viewWidth) /** @brief see #viewFrame */ ZFMETHOD_DECLARE_1(void, viewWidth, ZFMP_IN(zffloat const &, propertyValue)) /** @brief see #viewFrame */ ZFMETHOD_DECLARE_0(zffloat const &, viewHeight) /** @brief see #viewFrame */ ZFMETHOD_DECLARE_1(void, viewHeight, ZFMP_IN(zffloat const &, propertyValue)) /** @brief see #viewFrame */ ZFMETHOD_DECLARE_0(zffloat const &, viewCenterX) /** @brief see #viewFrame */ ZFMETHOD_DECLARE_1(void, viewCenterX, ZFMP_IN(zffloat const &, propertyValue)) /** @brief see #viewFrame */ ZFMETHOD_DECLARE_0(zffloat const &, viewCenterY) /** @brief see #viewFrame */ ZFMETHOD_DECLARE_1(void, viewCenterY, ZFMP_IN(zffloat const &, propertyValue)) /** * @brief prefered size, #ZFUISizeInvalid by default * * if no actual rule to measure the view, * the prefered size would be used to measure the view, * if prefered size not set, size hint would be used */ ZFPROPERTY_ASSIGN_WITH_INIT(ZFUISize, viewSizePrefer, ZFUISizeInvalid()) ZFPROPERTY_ON_ATTACH_DECLARE(ZFUISize, viewSizePrefer) /** * @brief min size, #ZFUISizeZero by default */ ZFPROPERTY_ASSIGN(ZFUISize, viewSizeMin) ZFPROPERTY_ON_ATTACH_DECLARE(ZFUISize, viewSizeMin) /** * @brief max size, negative value means not set, #ZFUISizeInvalid by default */ ZFPROPERTY_ASSIGN_WITH_INIT(ZFUISize, viewSizeMax, ZFUISizeInvalid()) ZFPROPERTY_ON_ATTACH_DECLARE(ZFUISize, viewSizeMax) /** * @brief background color, #ZFUIColorZero by default */ ZFPROPERTY_ASSIGN_WITH_INIT(ZFUIColor, viewBackgroundColor, ZFUIColorZero()) ZFPROPERTY_ON_ATTACH_DECLARE(ZFUIColor, viewBackgroundColor) // ============================================================ // transform /** * @brief translate for the view * * when impl not available, setting this value would have no effect */ ZFPROPERTY_ASSIGN_WITH_INIT(zffloat, viewTranslateX, 0) ZFPROPERTY_ON_ATTACH_DECLARE(zffloat, viewTranslateX) /** @brief see #viewTranslateX */ ZFPROPERTY_ASSIGN_WITH_INIT(zffloat, viewTranslateY, 0) ZFPROPERTY_ON_ATTACH_DECLARE(zffloat, viewTranslateY) /** * @brief scale for the view * * when impl not available, setting this value would have no effect */ ZFPROPERTY_ASSIGN_WITH_INIT(zffloat, viewScaleX, 1) ZFPROPERTY_ON_VERIFY_DECLARE(zffloat, viewScaleX) /** @brief see #viewScaleX */ ZFPROPERTY_ASSIGN_WITH_INIT(zffloat, viewScaleY, 1) ZFPROPERTY_ON_VERIFY_DECLARE(zffloat, viewScaleY) /** * @brief rotation for the view * * the rotation is in Z axis, * range in [0, 360), * any value out of range would be fixed to [0, 360)\n * when impl not available, setting this value would have no effect */ ZFPROPERTY_ASSIGN_WITH_INIT(zffloat, viewRotate, 0) ZFPROPERTY_ON_VERIFY_DECLARE(zffloat, viewRotate) // ============================================================ // init and dealloc protected: zfoverride virtual void objectOnInit(void); zfoverride virtual void objectOnDealloc(void); zfoverride virtual void objectOnDeallocPrepare(void); public: zfoverride virtual zfidentity objectHash(void); zfoverride virtual ZFCompareResult objectCompare(ZF_IN ZFObject *anotherObj); protected: zfoverride virtual void objectInfoOnAppend(ZF_IN_OUT zfstring &ret); // ============================================================ public: /** * @brief native implementation view * * first child of #nativeView, layout below all other child views, * for internal implementation use only, * for example, a ImageView's implementation may use native view * and set it as internalNativeView\n * subclass must not override parent, * if really necessary, use #internalBgViewAdd\n * use with caution * @see nativeView */ ZFMETHOD_DECLARE_0(void *, nativeImplView) /** * @brief inner margin between #ZFUIView and the internal #nativeImplView * * use #nativeImplViewMarginUpdate to update this value, * and it's ensured to be called during #ZFObject::objectOnInitFinish\n * subclass should override #nativeImplViewMarginImplUpdate to implement custom margin, * and manually call #nativeImplViewMarginUpdate if necessary\n * this value can also be controlled by app level code by #nativeImplViewMarginCustom */ ZFMETHOD_DECLARE_0(const ZFUIMargin &, nativeImplViewMargin) /** * @brief see #nativeImplViewMargin, * #layoutRequest if the final value actually changed */ ZFMETHOD_DECLARE_0(void, nativeImplViewMarginUpdate) /** * @brief frame of #nativeImplView */ ZFMETHOD_DECLARE_0(const ZFUIRect &, nativeImplViewFrame) /** * @brief see #nativeImplViewMargin, #ZFUIMarginZero by default */ ZFPROPERTY_ASSIGN(ZFUIMargin, nativeImplViewMarginCustom) ZFPROPERTY_ON_ATTACH_DECLARE(ZFUIMargin, nativeImplViewMarginCustom) protected: /** * @brief see #nativeImplView */ zffinal void nativeImplView(ZF_IN void *nativeImplView, ZF_IN ZFUIViewNativeImplViewDeleteCallback nativeImplViewDeleteCallback); /** * @brief see #nativeImplViewMargin, * subclass must call super and "append" to existing margin */ virtual inline void nativeImplViewMarginImplUpdate(ZF_IN_OUT ZFUIMargin &nativeImplViewMargin) { } /** * @brief see #EventNativeImplViewMarginOnUpdate */ virtual inline void nativeImplViewMarginOnUpdate(void) { this->observerNotify(ZFUIView::EventNativeImplViewMarginOnUpdate()); } /** * @brief called to layout #nativeImplView */ virtual void nativeImplViewOnLayout(ZF_OUT ZFUIRect &ret, ZF_IN const ZFUIRect &bounds, ZF_IN const ZFUIMargin &nativeImplViewMargin) { ZFUIRectApplyMargin(ret, bounds, nativeImplViewMargin); } // ============================================================ protected: /** * @brief called to add or remove view to impl * * subclass may override this method to add child to other container\n * to implement this, you must implement all these methods: * - #implChildOnAdd : called to add to impl * - #implChildOnRemove : called to remove from impl * - #implChildOnRemoveAllForDealloc : called to remove from impl during parent dealloc */ virtual void implChildOnAdd(ZF_IN ZFUIView *child, ZF_IN zfindex virtualIndex, ZF_IN ZFUIViewChildLayerEnum childLayer, ZF_IN zfindex childLayerIndex); /** * @brief see #implChildOnAdd, #implChildOnRemoveAllForDealloc */ virtual void implChildOnRemove(ZF_IN ZFUIView *child, ZF_IN zfindex virtualIndex, ZF_IN ZFUIViewChildLayerEnum childLayer, ZF_IN zfindex childLayerIndex); /** * @brief called to remove all children during parent dealloc for performance * * for normal children management, * each child would be removed one by one and fire child change event when #childRemoveAll, * which is not necessary during parent dealloc * (which may cause performance issue), * so we use this method to remove all children directly during parent dealloc * to improve performance */ virtual void implChildOnRemoveAllForDealloc(void); public: /** * @brief native container view * * the actual type of this is defined by implementation, * and it's not recommended to use in your application\n * \n * for how to add ZFUIView to native view, please refer to #ZFUIView\n * for how to add native view to ZFUIView, please refer to #ZFUINativeViewWrapper\n * for how to access native implementation, please refer to #nativeImplView */ ZFMETHOD_DECLARE_0(void *, nativeView) static void _ZFP_ZFUIView_nativeViewNotifyAdd(ZF_IN ZFUIView *view, ZF_IN void *nativeParentView); static void _ZFP_ZFUIView_nativeViewNotifyRemove(ZF_IN ZFUIView *view); // ============================================================ // view focus public: /** * @brief whether the view currently focused */ ZFMETHOD_DECLARE_0(zfbool, viewFocused) /** * @brief request to obtain or resign focus, * result can be checked by #viewFocused * * only focused view can receive key events */ ZFMETHOD_DECLARE_1(void, viewFocusRequest, ZFMP_IN(zfbool, viewFocus)) zffinal void _ZFP_ZFUIView_viewFocusOnChange(void) { this->viewFocusOnChange(); } /** * @brief recursively to find focused child, take care of performance */ ZFMETHOD_DECLARE_0(ZFUIView *, viewFocusFind) protected: /** @brief see #EventViewFocusOnChange */ virtual inline void viewFocusOnChange(void) { this->observerNotify(ZFUIView::EventViewFocusOnChange()); } // ============================================================ // parent public: zffinal void _ZFP_ZFUIView_parentChanged(ZF_IN ZFUIView *parentView, ZF_IN ZFUILayoutParam *layoutParam, ZF_IN ZFUIViewChildLayerEnum viewLayer); /** * @brief parent view or null if none */ ZFMETHOD_DECLARE_0(ZFUIView *, viewParent) /** * @brief remove this view from parent or do nothing if no parent * * can remove normal child view or internal view */ ZFMETHOD_DECLARE_0(void, viewRemoveFromParent) // ============================================================ // scale settings public: /** * @brief UI scale for view tree * * ZFUIView use a special scale logic to adapt various screen sizes, * which contain these scale values: * - app scale:\n * app's custom scale, accessed by #UIScale, 1 by default\n * you may change this view to apply scale for entire view tree, * every child view may have different scale setting, * the final scale can be accessed by #UIScaleInherited * - impl scale:\n * accessed by #UIScaleForImpl, it's value depends on impl\n * automatically changed while adding a ZFUIView to native view, * can not be changed by app * - fixed scale:\n * accessed by #UIScaleFixed, always equal to * (#UIScaleInherited * #UIScale * #UIScaleForImpl)\n * all size unit would be applied with this value * before passing to implementations, * can not be changed by app * - impl physical scale:\n * accessed by #UIScaleForPixel, it's value depends on impl\n * to access final pixel size: * view's size * #UIScaleInherited * #UIScale * #UIScaleForPixel * * in general: * - for app:\n * usually you have no need to worry about scales, * all elements can be assigned as fixed size, * such as 48 for a button's height and 21 for a small textView's height, * it will be scaled automatically while rendering to different size's or DPI's devices\n * you may use #UIScale to control custom scale logic * - for implementation:\n * you have no need to worry about element's logical size, * everything would be scaled to desired size unit * depending on the scale value that impl returned * * \n * since scale may affect impl's pixel size, * size-related property should be flushed manually while scale changed, * subclass should override #UIScaleOnChange to update them, * which would be called if #UIScaleFixed really changed * \n * #UIScale usually used for scale for entire view tree, * all layout and touch position would be scaled properly, * however, changing #UIScale for a deep view tree may consume must time\n * for temporarily scale, typically for animation, * use #viewScaleX instead */ ZFPROPERTY_ASSIGN_WITH_INIT(zffloat, UIScale, 1) ZFPROPERTY_ON_VERIFY_DECLARE(zffloat, UIScale) ZFPROPERTY_ON_ATTACH_DECLARE(zffloat, UIScale) /** @brief see #UIScale */ ZFMETHOD_DECLARE_0(zffloat, UIScaleInherited) /** @brief see #UIScale */ ZFMETHOD_DECLARE_0(zffloat, UIScaleForImpl) /** @brief see #UIScale */ ZFMETHOD_DECLARE_0(zffloat, UIScaleForPixel) /** @brief see #UIScale */ ZFMETHOD_DECLARE_0(zffloat, UIScaleFixed) protected: /** * @brief see #UIScale, ensured called only when scale value actually changed * * after this method, #EventUIScaleOnChange would be fired */ virtual void UIScaleOnChange(void); // ============================================================ // layout logic public: /** * @brief create layout param, * calling #layoutParamClass to create instance * and #layoutParamOnUpdate to update */ ZFMETHOD_DECLARE_0(zfautoObjectT<ZFUILayoutParam *>, layoutParamCreate) protected: /** * @brief see #layoutParamCreate * * you should override this method to declare your layout param class */ virtual const ZFClass *layoutParamClass(void); /** * @brief see #layoutParamCreate */ virtual inline void layoutParamOnUpdate(ZF_IN ZFUILayoutParam *layoutParam) { } public: /** * @brief manually set layout param * * this method can be called even if this view has no parent, * the layout param would be serialized while serializing the view itself\n * while adding to another container view with different layout param type, * a new layout param would be created and applied style from the existing one */ ZFMETHOD_DECLARE_1(void, layoutParam, ZFMP_IN(ZFUILayoutParam *, layoutParam)) /** * @brief get self's layout param, valid only while the view has parent * * return null if the view has no parent, * automatically invoke the view's #layoutRequest if the layout param's property changed */ ZFMETHOD_DECLARE_0(ZFUILayoutParam *, layoutParam) /** * @brief see #layoutParam */ template<typename T_LayoutParam> T_LayoutParam layoutParam(void) { return ZFCastZFObjectUnchecked(T_LayoutParam, this->layoutParam()); } public: /** * @brief set need layout */ ZFMETHOD_DECLARE_0(void, layoutRequest) /** * @brief true if need layout */ ZFMETHOD_DECLARE_0(zfbool, layoutRequested) /** * @brief true if currently being layouted */ ZFMETHOD_DECLARE_0(zfbool, layouting) /** * @brief measure the view * * call #layoutOnMeasure to see the needed size for this view\n * note that internal views won't be measured * @see layoutMeasuredSize */ ZFMETHOD_DECLARE_2(const ZFUISize &, layoutMeasure, ZFMP_IN(const ZFUISize &, sizeHint), ZFMP_IN(const ZFUISizeParam &, sizeParam)) /** * @brief get measured size, invalid if not measured */ ZFMETHOD_DECLARE_0(const ZFUISize &, layoutMeasuredSize) /** * @brief force to layout if need */ ZFMETHOD_DECLARE_0(void, layoutIfNeed) /** * @brief get child offset to this view * * for views that have offset logic (typically scroll views), * use this method to access the offset to its parent, * child's #viewFrame plus this offset should be the actual * offset to parent's edge\n * subclass should override #layoutChildOffsetOnUpdate * to supply this value */ ZFMETHOD_DECLARE_0(ZFUIPoint, layoutChildOffset) public: void _ZFP_ZFUIView_notifyLayoutView(ZF_IN const ZFUIRect &viewFrame); protected: /** * @brief called during #layoutRequest */ virtual void layoutOnLayoutRequest(void); /** * @brief called by #layoutMeasure to decide the view's size * * you may override without call super to supply your own layout logic\n * \n * note that we doesn't ensure layoutOnMeasure would be called during layout steps, * only layout that has wrap content features may call #layoutMeasure * to calculate children's size\n * \n * sizeHint means the max size child should reach, see #ZFUISizeType for more info\n * \n * return a negative value means the view doesn't care about size, * let #ZFUIView::viewSizePrefer to decide final result size\n * \n * @note there's some repeatly work that #layoutMeasure would have done for you, * you should not repeat it again for performance: * - filter out the case that both sizeParam are fixed or fill parent * - apply sizeHint by #ZFUILayoutParam::sizeHintApply * - fix result size in range [viewSizeMin, viewSizeMax] * @note for impl views (such as text view), * you should manually take care of #nativeImplViewMargin * during measure and layout steps */ virtual inline void layoutOnMeasure(ZF_OUT ZFUISize &ret, ZF_IN const ZFUISize &sizeHint, ZF_IN const ZFUISizeParam &sizeParam) { } /** @brief see #EventViewLayoutOnMeasureFinish */ virtual inline void layoutOnMeasureFinish(ZF_IN_OUT ZFUISize &measuredSize, ZF_IN const ZFUISize &sizeHint, ZF_IN const ZFUISizeParam &sizeParam) { } /** @brief see #EventViewLayoutOnLayoutPrepare */ virtual inline void layoutOnLayoutPrepare(ZF_IN const ZFUIRect &bounds) { } /** * @brief called by #viewFrame to layout the view and children * * it's valid for subclass to override without calling zfsuper::layoutOnLayout, * which means subclass would override all layout steps in parent\n * \n * note that we doesn't ensure layoutOnMeasure would be called before layoutOnLayout */ virtual void layoutOnLayout(ZF_IN const ZFUIRect &bounds); /** @brief see #EventViewLayoutOnLayoutFinish */ virtual inline void layoutOnLayoutFinish(ZF_IN const ZFUIRect &bounds) { } /** @brief see #layoutChildOffset */ virtual inline void layoutChildOffsetOnUpdate(ZF_IN_OUT ZFUIPoint &ret) { } // ============================================================ // children management public: /** * @brief find view by viewId, return the view or null if not found */ ZFMETHOD_DECLARE_3(ZFUIView *, childFindById, ZFMP_IN(const zfchar *, viewId), ZFMP_IN_OPT(zfbool, findRecursively, zftrue), ZFMP_IN_OPT(zfbool, includeInternalViews, zffalse)) public: /** * @brief add view with layout param, param must be created by #layoutParamCreate * * if layoutParam is null (by default), create new one by #layoutParamCreate\n * if layoutParam is type of #layoutParamClass and not null, it would be used directly, * otherwise, a new layout param would be created * and source layout param would be copied to the newly created layout param */ ZFMETHOD_DECLARE_3(void, childAdd, ZFMP_IN(ZFUIView *, view), ZFMP_IN_OPT(ZFUILayoutParam *, layoutParam, zfnull), ZFMP_IN_OPT(zfindex, atIndex, zfindexMax())) /** * @brief util method for #childAdd */ ZFMETHOD_DECLARE_5(void, childAdd, ZFMP_IN(ZFUIView *, view), ZFMP_IN(const ZFUISizeParam &, sizeParam), ZFMP_IN_OPT(ZFUIAlignFlags const &, layoutAlign, ZFUIAlign::e_LeftInner | ZFUIAlign::e_TopInner), ZFMP_IN_OPT(ZFUIMargin const &, layoutMargin, ZFUIMarginZero()), ZFMP_IN_OPT(const ZFUISize &, sizeHint, ZFUISizeInvalid())) /** * @brief remove view or do nothing if view isn't added to this view */ ZFMETHOD_DECLARE_1(void, childRemove, ZFMP_IN(ZFUIView *, view)) /** * @brief remove view at index or assert fail if index out of range */ ZFMETHOD_DECLARE_1(void, childRemoveAtIndex, ZFMP_IN(zfindex, index)) /** * @brief remove all child view */ ZFMETHOD_DECLARE_0(void, childRemoveAll) /** * @brief move view, make toIndexOrIndexMax as zfindexMax() to move to top most, * and 0 to bottom most, do nothing if index invalid or have no change * * assert fail if fromIndex out of range, or toIndexOrIndexMax isn't zfindexMax() and out of range\n * moving a view would cause #layoutRequest being called */ ZFMETHOD_DECLARE_2(void, childMove, ZFMP_IN(zfindex, fromIndex), ZFMP_IN(zfindex, toIndexOrIndexMax)) /** * @brief see #childMove */ ZFMETHOD_DECLARE_2(void, childMove, ZFMP_IN(ZFUIView *, child), ZFMP_IN(zfindex, toIndexOrIndexMax)) /** * @brief replace child at index, assert fail if index out of range * or view to replace already has parent */ ZFMETHOD_DECLARE_2(void, childReplaceAtIndex, ZFMP_IN(zfindex, atIndex), ZFMP_IN(ZFUIView *, toReplace)) /** * @brief get child view count */ ZFMETHOD_DECLARE_0(zfindex, childCount) /** * @brief get child view at index or assert fail if out of range */ ZFMETHOD_DECLARE_1(ZFUIView *, childAtIndex, ZFMP_IN(zfindex, index)) /** * @brief return index of view or zfindexMax() if not child of this view */ ZFMETHOD_DECLARE_1(zfindex, childFind, ZFMP_IN(ZFUIView *, view)) /** * @brief get the child view array */ ZFMETHOD_DECLARE_0(ZFCoreArrayPOD<ZFUIView *>, childArray) /** * @brief this view belongs to which layer of parent, * valid only if #viewParent is not null * * would be #ZFUIViewChildLayer::e_Normal if no parent */ ZFMETHOD_DECLARE_0(ZFUIViewChildLayerEnum, viewLayer) /** * @brief return all children including internal views, see #childArray * * children are ensured ordered by (impl, bg, normal, fg) views */ ZFMETHOD_DECLARE_0(ZFCoreArrayPOD<ZFUIView *>, childRawArray) // ============================================================ // events protected: /** @brief see #EventViewChildOnChange */ virtual void viewChildOnChange(void); /** @brief see #EventViewChildOnAdd */ virtual void viewChildOnAdd(ZF_IN ZFUIView *child, ZF_IN ZFUIViewChildLayerEnum childLayer); /** @brief see #EventViewChildOnRemove */ virtual void viewChildOnRemove(ZF_IN ZFUIView *child, ZF_IN ZFUIViewChildLayerEnum childLayer); /** @brief see #EventViewOnAddToParent */ virtual void viewOnAddToParent(ZF_IN ZFUIView *parent); /** @brief see #EventViewOnRemoveFromParent */ virtual void viewOnRemoveFromParent(ZF_IN ZFUIView *parent); // ============================================================ // internal views public: /** @brief see #internalBgViewAdd */ ZFMETHOD_DECLARE_3(void, internalImplViewAdd, ZFMP_IN(ZFUIView *, view), ZFMP_IN_OPT(ZFUILayoutParam *, layoutParam, zfnull), ZFMP_IN_OPT(zfbool, addAsTopMost, zftrue)) /** @brief see #internalBgViewAdd */ ZFMETHOD_DECLARE_1(void, internalImplViewRemove, ZFMP_IN(ZFUIView *, view)) /** @brief see #internalBgViewAdd */ ZFMETHOD_DECLARE_0(ZFCoreArrayPOD<ZFUIView *>, internalImplViewArray) public: /** * @brief internal view which is independent from normal view * * we have these layers in ZFUIView module: * - internal impl view * - internal background view * - normal view * - internal foreground view * * each layer is independent and has the same interface to add or remove view\n * to make the interfaces cleaner, the internal ones are named with * "internalBgView" and "internalFgView" as pre-fix, * such as #internalBgViewAdd and #internalBgViewRemove * (considering the #childAdd and #childRemove)\n * \n * internal views has no measure steps, its size always depends on parent's size */ ZFMETHOD_DECLARE_3(void, internalBgViewAdd, ZFMP_IN(ZFUIView *, view), ZFMP_IN_OPT(ZFUILayoutParam *, layoutParam, zfnull), ZFMP_IN_OPT(zfbool, addAsTopMost, zftrue)) /** @brief see #internalBgViewAdd */ ZFMETHOD_DECLARE_1(void, internalBgViewRemove, ZFMP_IN(ZFUIView *, view)) /** * @brief usually for debug use only, try to avoid use this in your app for other purpose */ ZFMETHOD_DECLARE_0(ZFCoreArrayPOD<ZFUIView *>, internalBgViewArray) public: /** @brief see #internalBgViewAdd */ ZFMETHOD_DECLARE_3(void, internalFgViewAdd, ZFMP_IN(ZFUIView *, view), ZFMP_IN_OPT(ZFUILayoutParam *, layoutParam, zfnull), ZFMP_IN_OPT(zfbool, addAsTopMost, zftrue)) /** @brief see #internalBgViewAdd */ ZFMETHOD_DECLARE_1(void, internalFgViewRemove, ZFMP_IN(ZFUIView *, view)) /** @brief see #internalBgViewAdd */ ZFMETHOD_DECLARE_0(ZFCoreArrayPOD<ZFUIView *>, internalFgViewArray) // ============================================================ // other internal view logic public: /** * @brief used to apply auto serialize logic to internal views * * by default, internal views won't be serialized automatically, * you may make it available by: * - have internal view's viewId set * - have same id set by this method * * while serializing, if an internal view with same id already exists, * we would copy style from serialize data to the existing one instead */ ZFMETHOD_DECLARE_1(void, internalViewAutoSerializeTagAdd, ZFMP_IN(const zfchar *, tag)) /** @brief see #internalViewAutoSerializeTagAdd */ ZFMETHOD_DECLARE_1(void, internalViewAutoSerializeTagRemove, ZFMP_IN(const zfchar *, tag)) /** @brief see #internalViewAutoSerializeTagAdd */ ZFMETHOD_DECLARE_0(void, internalViewAutoSerializeTagRemoveAll) /** @brief see #internalViewAutoSerializeTagAdd */ ZFMETHOD_DECLARE_1(void, internalViewAutoSerializeTagGetAllT, ZFMP_IN_OUT(ZFCoreArray<zfstring> &, ret)) /** @brief see #internalViewAutoSerializeTagAdd */ ZFMETHOD_DECLARE_0(ZFCoreArray<zfstring>, internalViewAutoSerializeTagGetAll) protected: /** * @brief called to check whether the internal view should be layouted using default layout logic, * return true by default */ virtual inline zfbool internalViewShouldLayout(ZF_IN ZFUIView *internalView) { return zftrue; } /** @brief see #internalBgViewAdd */ virtual void internalViewOnLayout(ZF_IN const ZFUIRect &bounds); // ============================================================ // UI events public: /** * @brief directly send a event, use with caution */ ZFMETHOD_DECLARE_1(void, viewEventSend, ZFMP_IN(ZFUIEvent *, event)) protected: /** * @brief notified when a ZFUIEvent occurred * * default behavior is to dispatch event depends on event type\n * you may override without call super's method, to override the event\n * you should update #ZFUIEvent::eventResolved if resolved */ virtual void viewEventOnEvent(ZF_IN ZFUIEvent *event); // ============================================================ // events protected: /** * @brief called when mouse event occurred * * due to some limitations, we doesn't support intercept mouse event, * event dispatch logic depends on implementation, * you may use native view to achieve if necessary\n * \n * mouse hover event would only be fired if #viewMouseHoverEventEnable\n * \n * by default, this method would simply resolve the event if this view is enabled, * you may override without call super's method, to override the event */ virtual void viewEventOnMouseEvent(ZF_IN ZFUIMouseEvent *mouseEvent); /** * @brief called when key occurred * * due to some limitations, we doesn't support intercept key event, * event dispatch logic depends on implementation, * you may use native view to achieve if necessary\n * \n * by default, this method would call #viewEventOnKeyEventResolveFocus to achieve focus move, * you may override without call super's method, to override the event\n * the event would be dispatched from child to parent, * util it's resolved */ virtual void viewEventOnKeyEvent(ZF_IN ZFUIKeyEvent *keyEvent); /** * @brief called by #viewEventOnKeyEvent to resolve focus move key event * * this method would call #ZFUIViewFocusResolveKeyEvent to achieve focus move, * you may override without call super's method, to override the event */ virtual void viewEventOnKeyEventResolveFocus(ZF_IN ZFUIKeyEvent *keyEvent); /** * @brief called when wheel event occurred * * due to some limitations, we doesn't support intercept wheel event, * event dispatch logic depends on implementation, * you may use native view to achieve if necessary\n * \n * the event would be dispatched from child to parent, * util it's resolved */ virtual void viewEventOnWheelEvent(ZF_IN ZFUIWheelEvent *wheelEvent); // ============================================================ // override protected: /** * @brief for a view, copy style would also copy all of it's children */ zfoverride virtual void styleableOnCopyFrom(ZF_IN ZFStyleable *anotherStyleable); protected: zfoverride virtual void observerOnAdd(ZF_IN zfidentity eventId); zfoverride virtual void observerOnRemove(ZF_IN zfidentity eventId); private: _ZFP_ZFUIViewPrivate *d; friend zfclassFwd _ZFP_ZFUIViewPrivate; }; ZF_NAMESPACE_GLOBAL_END #endif // #ifndef _ZFI_ZFUIView_h_
[ "z@zsaber.com" ]
z@zsaber.com
51d7685f6104f235b3768dc86409ebe4eb2c94cb
77a08ec51aa16191986a739267fd9d4379bbb208
/sycoj/1169.cpp
4b9e04d30bcf2f1bed98e72f6bc9b7a989d85b5b
[]
no_license
cenariusxz/ACM-Coding
8f698203db802f79578921b311b38346950ef0ca
dc09ac9adfb4b80d463bdc93f52b479a957154e6
refs/heads/master
2023-06-24T13:12:13.279255
2021-07-26T01:24:36
2021-07-26T01:24:36
185,567,471
0
0
null
null
null
null
UTF-8
C++
false
false
795
cpp
#include <bits/stdc++.h> using namespace std; #define PB push_back #define MP make_pair typedef long long ll; const int maxn = 1e5 + 5; const int INF = 0x3f3f3f3f; const int mod = 1e9 + 7; const double eps = 1e-8; struct node{ int x,t; }; int num[maxn],vis[maxn],n; void bfs(int a,int b){ queue<node>q; vis[a] = 1; q.push(node{a,0}); while(!q.empty()){ node u = q.front();q.pop(); if(u.x == b){ printf("%d\n",u.t); return; } int dx = u.x + num[u.x]; if(dx <= n && !vis[dx]){ vis[dx] = 1; q.push(node{dx,u.t+1}); } dx = u.x - num[u.x]; if(dx >= 1 && !vis[dx]){ vis[dx] = 1; q.push(node{dx,u.t+1}); } } printf("-1\n"); } int main(){ int a,b; scanf("%d%d%d",&n,&a,&b); for(int i = 1 ; i <= n ; ++ i)scanf("%d",&num[i]); bfs(a,b); return 0; }
[ "810988849@qq.com" ]
810988849@qq.com
a9bd81e57ab2f44d9c675463a400b8c3ac56d824
6ea50d800eaf5690de87eea3f99839f07c662c8b
/ver.0.15.0.1/FlowerPotBlockEntity.h
78848d3043d0e2ef93e6fa4348fbbbf1763166c0
[]
no_license
Toku555/MCPE-Headers
73eefeab8754a9ce9db2545fb0ea437328cade9e
b0806aebd8c3f4638a1972199623d1bf686e6497
refs/heads/master
2021-01-15T20:53:23.115576
2016-09-01T15:38:27
2016-09-01T15:38:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
649
h
#pragma once class FlowerPotBlockEntity{ public: FlowerPotBlockEntity(BlockPos const&); FlowerPotBlockEntity(BlockPos const&); void getItemData(void); void getItemData(void); void getPlantItem(void); void getPlantItem(void); void getUpdatePacket(BlockSource &); void getUpdatePacket(BlockSource &); void load(CompoundTag const&); void load(CompoundTag const&); void onUpdatePacket(CompoundTag &); void onUpdatePacket(CompoundTag &); void save(CompoundTag &); void save(CompoundTag &); void setPlantItem(Block *,int); void setPlantItem(Block *,int); void ~FlowerPotBlockEntity(); void ~FlowerPotBlockEntity(); };
[ "sinigami3427@gmail.com" ]
sinigami3427@gmail.com
cf8a31b25d1150128a8e73ce8c1d89acc82751fc
e86573147478c3279ade2e18897de4fac60457bd
/freshmen-second-semeter/数据测试___debug/1/对拍.cpp
4fa86485176c4eb1d51abb2e316afbbdc5706e16
[]
no_license
c2909371614/my_acm_documents
aded54a6153cf2fb24ac92bd271c344e74cfec89
58adca644a13cd472c09ec22ac85995d85c4ce6a
refs/heads/master
2022-03-11T14:37:06.758870
2019-09-11T15:24:54
2019-09-11T15:24:54
197,711,530
1
0
null
null
null
null
GB18030
C++
false
false
997
cpp
#include<cstdlib> #include<cstdio> #include<ctime> #include<iostream> #include<fstream> #include<iomanip> #include<string> #include <process.h> using namespace std; int run_time = 100;//运行次数 string rand_exe = "随机字符.exe"; string test_exe = "11-D_test.exe"; string AC_exe = "11_D_AC_code.exe"; string AC_out = "AC_data.out"; string my_out = "my_data.out"; int main() { //system("comp"); for(int i = 1; i <= run_time; i++){ //路径 //system("comp"); system(rand_exe.c_str()); double now_t = clock();//当前cup运行时间 system(test_exe.c_str());//运行我的程序 double end_t = clock();//我的时间 system(AC_exe.c_str());//运行AC的程序 //system("pause"); string command; command = (string)"fc "+ AC_out + (string)" " + my_out;//调用fc命令 if(system(command.c_str())) { cout << "Wrong ans" << endl; return 0; } else cout <<"Accepted,测试点#" << i <<",用时" << setprecision(2)<<end_t - now_t << "ms" <<endl; } }
[ "2909371614@qq.com" ]
2909371614@qq.com
5ccc7d418d51d4060a318f98c2ec5be66c5a32b3
16d6efcdd741659deeb5bf3cd4818a9b11f49646
/ZQ_PoissonEditing3D/main.cpp
9481a307474411637a5ccd136bbb006c17399039
[]
no_license
tianxingyzxq/ZQ_SmokeSimulation
4b050a71c84160bc9a9011e425fc11a5ad552f05
4ca6d8b6f4c7212a862009e77b5b3a1ef24f4b11
refs/heads/master
2020-03-19T07:37:45.413844
2018-06-05T03:01:20
2018-06-05T03:01:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,171
cpp
#include "ZQ_DoubleImage.h" #include "ZQ_DoubleImage3D.h" #include "ZQ_ImageIO.h" #include "ZQ_PoissonEditing.h" #include "ZQ_PoissonEditing3D.h" #include <vector> #include <stdio.h> #include <string.h> using namespace ZQ; typedef float BaseType; typedef ZQ_DImage<BaseType> DImage; typedef ZQ_DImage3D<BaseType> DImage3D; void main(const int argc, const char** argv) { if(argc != 8) { printf(" args error\n"); return; } int num = atoi(argv[1]); const char* input_fold = argv[2]; const char* input_prefix = ""; const char* input_suffix = argv[3]; const char* copyin_fold = argv[4]; const char* copyin_prefix = ""; const char* copyin_suffix = argv[5]; const char* mask_file = argv[6]; const char* output_fold = argv[7]; std::vector<DImage> input_images; std::vector<DImage> copyin_images; DImage mask; char buf[500]; for(int i = 0;i < num;i++) { DImage tmp; sprintf(buf,"%s\\%s%d.%s",input_fold,input_prefix,i,input_suffix); if(!ZQ_ImageIO::loadImage(tmp,buf,0)) { printf("failed to load %s\n",buf); return; } input_images.push_back(tmp); } for(int i = 0;i < num;i++) { DImage tmp; sprintf(buf,"%s\\%s%d.%s",copyin_fold,copyin_prefix,i,copyin_suffix); if(!ZQ_ImageIO::loadImage(tmp,buf,0)) { printf("failed to load %s\n",buf); return; } copyin_images.push_back(tmp); } if(!ZQ_ImageIO::loadImage(mask,mask_file,0)) { printf("failed to load %s\n",mask_file); return; } ZQ_PoissonEditingOptions opt; opt.type = ZQ_PoissonEditingOptions::METHOD_NAIVE; opt.grad_scale = 1; opt.nSORIteration = 500; opt.display = true; DImage tmp_output; ZQ_PoissonEditing::PoissonEditing(mask,copyin_images[0],input_images[0],tmp_output,opt); input_images[0] = tmp_output; ZQ_PoissonEditing::PoissonEditing(mask,copyin_images[num-1],input_images[num-1],tmp_output,opt); input_images[num-1] = tmp_output; int width = mask.width(); int height = mask.height(); DImage3D input3D(width,height,num); DImage3D copyin3D(width,height,num); DImage3D output3D(width,height,num); DImage3D mask3D(width,height,num); BaseType*& input3D_data = input3D.data(); BaseType*& copyin3D_data = copyin3D.data(); BaseType*& mask3D_data = mask3D.data(); for(int i = 0;i < num;i++) { for(int pp = 0;pp < width*height;pp++) { input3D_data[i*width*height+pp] = input_images[i].data()[pp]; copyin3D_data[i*width*height+pp] = copyin_images[i].data()[pp]; } } for(int i = 1;i < num-1;i++) { for(int pp = 0;pp < width*height;pp++) { mask3D_data[i*width*height+pp] = mask.data()[pp]; } } ZQ_PoissonEditing3DOptions opt3d; opt3d.nSORIteration = 5000; opt3d.display = true; opt3d.grad_scale = 1; if(!ZQ_PoissonEditing3D::PoissonEditing(mask3D,copyin3D,input3D,output3D,opt3d)) { printf("poisson edting 3d fail\n"); return; } BaseType*& output_data = output3D.data(); for(int i = 0;i < num;i++) { DImage tmp(width,height); for(int pp = 0;pp < width*height;pp++) tmp.data()[pp] = output_data[i*width*height+pp]; sprintf(buf,"%s\\%s%d.%s",output_fold,input_prefix,i,input_suffix); if(!ZQ_ImageIO::saveImage(tmp,buf)) { printf("failed to save %s\n",buf); } } return; }
[ "zuoqing1988@aliyun.com" ]
zuoqing1988@aliyun.com
a75c0f20948ff76299f94bb091028cd74f13947b
7ef60646f13ef6dcd56ea81941798d54c058ab07
/src/RBD_SerialManager.cpp
9c884c3e984eb08975253696bd9ec9a1e5f5fb41
[ "MIT" ]
permissive
alextaujenis/RBD_SerialManager
54b2f682fb880dbd313ff2abc2d496a3108beca9
28abbc7602bead007a6ab850d3e21d048d2ad5b4
refs/heads/master
2021-05-04T10:47:26.397692
2020-06-08T19:59:46
2020-06-08T19:59:46
46,815,340
20
7
null
2018-05-22T12:55:39
2015-11-24T20:00:26
C++
UTF-8
C++
false
false
1,536
cpp
// Arduino RBD Serial Manager Library v1.0.0 - A simple interface for serial communication. // https://github.com/alextaujenis/RBD_SerialManager // Copyright (c) 2015 Alex Taujenis - MIT License #include <Arduino.h> #include <RBD_SerialManager.h> // https://github.com/alextaujenis/RBD_SerialManager namespace RBD { SerialManager::SerialManager() {} void SerialManager::start() { Serial.begin(115200); } bool SerialManager::onReceive() { if(Serial.available()) { _char = char(Serial.read()); if(_char == _flag) { _value = _buffer; _buffer = ""; return true; } else { _buffer += _char; return false; } } else { return false; } } String SerialManager::getValue() { return _value; } void SerialManager::setFlag(char value) { _flag = value; } void SerialManager::setDelimiter(char value) { _delimiter = value; } String SerialManager::getCmd() { _position = getValue().indexOf(_delimiter); if(_position > -1) { return _value.substring(0, _position); } else { return getValue(); } } String SerialManager::getParam() { _position = getValue().indexOf(_delimiter); if(_position > -1) { return _value.substring(_position + 1, _value.length()); } else { return ""; } } bool SerialManager::isCmd(String value) { return getCmd() == value; } bool SerialManager::isParam(String value) { return getParam() == value; } }
[ "alex.taujenis@gmail.com" ]
alex.taujenis@gmail.com
b88a6506e7216d498465c55287c0649377e2ed47
95028ab82444e13af69c334f3ba2dacea7f11b61
/src/desktop/MockData/AnalogTriggerDataInternal.h
b6053bd09181e2ac3d97f09ed39ed6f448c1d3af
[]
no_license
ThadHouse/MockHalTesting
5f5f833f07cb567bf04b8ffba817057d7a91efd0
a6791046dc708a76cbf01cbdf16db77087494f6d
refs/heads/master
2020-05-21T20:55:19.678899
2017-05-28T06:02:43
2017-05-28T06:02:43
60,224,833
2
0
null
null
null
null
UTF-8
C++
false
false
2,059
h
#pragma once #include <atomic> #include <memory> #include "MockData/AnalogTriggerData.h" #include "MockData/NotifyListenerVector.h" namespace hal { class AnalogTriggerData { public: int32_t RegisterInitializedCallback(HAL_NotifyCallback callback, void* param, HAL_Bool initialNotify); void CancelInitializedCallback(int32_t uid); void InvokeInitializedCallback(HAL_Value value); HAL_Bool GetInitialized(); void SetInitialized(HAL_Bool initialized); int32_t RegisterTriggerLowerBoundCallback(HAL_NotifyCallback callback, void* param, HAL_Bool initialNotify); void CancelTriggerLowerBoundCallback(int32_t uid); void InvokeTriggerLowerBoundCallback(HAL_Value value); double GetTriggerLowerBound(); void SetTriggerLowerBound(double triggerLowerBound); int32_t RegisterTriggerUpperBoundCallback(HAL_NotifyCallback callback, void* param, HAL_Bool initialNotify); void CancelTriggerUpperBoundCallback(int32_t uid); void InvokeTriggerUpperBoundCallback(HAL_Value value); double GetTriggerUpperBound(); void SetTriggerUpperBound(double triggerUpperBound); int32_t RegisterTriggerModeCallback(HAL_NotifyCallback callback, void* param, HAL_Bool initialNotify); void CancelTriggerModeCallback(int32_t uid); void InvokeTriggerModeCallback(HAL_Value value); HALSIM_AnalogTriggerMode GetTriggerMode(); void SetTriggerMode(HALSIM_AnalogTriggerMode triggerMode); virtual void ResetData(); private: std::mutex m_registerMutex; std::atomic<HAL_Bool> m_initialized {0}; std::shared_ptr<NotifyListenerVector> m_initializedCallbacks = nullptr; std::atomic<double> m_triggerLowerBound {0}; std::shared_ptr<NotifyListenerVector> m_triggerLowerBoundCallbacks = nullptr; std::atomic<double> m_triggerUpperBound {0}; std::shared_ptr<NotifyListenerVector> m_triggerUpperBoundCallbacks = nullptr; std::atomic<HALSIM_AnalogTriggerMode> m_triggerMode {static_cast<HALSIM_AnalogTriggerMode>(0)}; std::shared_ptr<NotifyListenerVector> m_triggerModeCallbacks = nullptr; }; extern AnalogTriggerData SimAnalogTriggerData[]; }
[ "thadhouse1@gmail.com" ]
thadhouse1@gmail.com
e16a024bb9c7f101d8b173471972a61a15cc1f2b
38f3e564c277e9ab45d5ce3db3ff6465bf746ce0
/Week 3/ForLab3/Lab 5 Strings/o.last_letter.cpp
fec53b3263fa27207f2416f18d84c026840ab0aa
[]
no_license
tdinaraa/PP2
149e4c230b1c45daa0ef8b5c55853ece5eac65a3
f050e5c46d629367b977a2ccc853a0b03484cc91
refs/heads/master
2020-04-19T09:10:41.180996
2019-04-23T04:14:52
2019-04-23T04:14:52
168,102,250
0
0
null
null
null
null
UTF-8
C++
false
false
271
cpp
#include<iostream> #include<algorithm> using namespace std; int main() { string s; char max=s[0]; cin>>s; for (int i=1; i<s.size(); i++) { if (s[i]>max) { max=s[i]; } } cout << max<< endl; return 0; }
[ "45028995+tdinaraa@users.noreply.github.com" ]
45028995+tdinaraa@users.noreply.github.com
abb25c6ea94f1508467555d2f4aa4c4b1a7494cb
60dbb8d07b04e581264e7686caa785710458479c
/client/src/Block_test.cpp
65e1796ecd9cfe17d72dbe274b6558c5e0d6c149
[]
no_license
Jereq/PongOut
15f4cf662a3d27ce8b381e0c75bcb7adaaa95505
46b8b9af38aa89aaa0be037fc2cd93809e692c09
refs/heads/master
2016-09-06T05:32:02.906945
2013-10-28T10:26:17
2013-10-28T10:26:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
52
cpp
/* * Block_test.cpp * * */ #include "Block.h"
[ "spigoe@hotmail.com" ]
spigoe@hotmail.com
321924eee90d2ec1829a9a3906dd47dc8b87df94
d0b5a4a823ce715fd4f25258396ece4b792318ef
/private_join_and_compute/util/status_matchers.h
401b47d4fec630566fcda21dde191412d345b44a
[ "Apache-2.0" ]
permissive
zhu1971/private-join-and-compute
d947fc2b8aa494fdb3a3b5025abb009815f37833
505ba981d66c9e5e73e18cfa647b4685f74784cb
refs/heads/master
2023-08-11T01:43:42.769101
2021-09-29T19:13:29
2021-09-29T19:13:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,052
h
/* * Copyright 2019 Google LLC. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef PRIVATE_JOIN_AND_COMPUTE_UTIL_STATUS_MATCHERS_H_ #define PRIVATE_JOIN_AND_COMPUTE_UTIL_STATUS_MATCHERS_H_ #include <gmock/gmock.h> #include "private_join_and_compute/util/status.inc" namespace private_join_and_compute { namespace testing { #ifdef GTEST_HAS_STATUS_MATCHERS using ::testing::status::IsOk; using ::testing::status::IsOkAndHolds; using ::testing::status::StatusIs; #else // GTEST_HAS_STATUS_MATCHERS namespace internal { // This function and its overload allow the same matcher to be used for Status // and StatusOr tests. inline Status GetStatus(const Status& status) { return status; } template <typename T> inline Status GetStatus(const StatusOr<T>& statusor) { return statusor.status(); } template <typename StatusType> class StatusIsImpl : public ::testing::MatcherInterface<StatusType> { public: StatusIsImpl(const ::testing::Matcher<StatusCode>& code, const ::testing::Matcher<const std::string&>& message) : code_(code), message_(message) {} bool MatchAndExplain( StatusType status, ::testing::MatchResultListener* listener) const override { ::testing::StringMatchResultListener str_listener; Status real_status = GetStatus(status); if (!code_.MatchAndExplain(real_status.code(), &str_listener)) { *listener << str_listener.str(); return false; } if (!message_.MatchAndExplain( static_cast<std::string>(real_status.message()), &str_listener)) { *listener << str_listener.str(); return false; } return true; } void DescribeTo(std::ostream* os) const override { *os << "has a status code that "; code_.DescribeTo(os); *os << " and a message that "; message_.DescribeTo(os); } void DescribeNegationTo(std::ostream* os) const override { *os << "has a status code that "; code_.DescribeNegationTo(os); *os << " and a message that "; message_.DescribeNegationTo(os); } private: ::testing::Matcher<StatusCode> code_; ::testing::Matcher<const std::string&> message_; }; class StatusIsPoly { public: StatusIsPoly(::testing::Matcher<StatusCode>&& code, ::testing::Matcher<const std::string&>&& message) : code_(code), message_(message) {} // Converts this polymorphic matcher to a monomorphic matcher. template <typename StatusType> operator ::testing::Matcher<StatusType>() const { return ::testing::Matcher<StatusType>( new StatusIsImpl<StatusType>(code_, message_)); } private: ::testing::Matcher<StatusCode> code_; ::testing::Matcher<const std::string&> message_; }; } // namespace internal // This function allows us to avoid a template parameter when writing tests, so // that we can transparently test both Status and StatusOr returns. inline internal::StatusIsPoly StatusIs( ::testing::Matcher<StatusCode>&& code, ::testing::Matcher<const std::string&>&& message) { return internal::StatusIsPoly( std::forward< ::testing::Matcher<StatusCode> >(code), std::forward< ::testing::Matcher<const std::string&> >(message)); } // Monomorphic implementation of matcher IsOkAndHolds(m). StatusOrType is a // reference to StatusOr<T>. template <typename StatusOrType> class IsOkAndHoldsMatcherImpl : public ::testing::MatcherInterface<StatusOrType> { public: typedef typename std::remove_reference<StatusOrType>::type::value_type value_type; template <typename InnerMatcher> explicit IsOkAndHoldsMatcherImpl(InnerMatcher&& inner_matcher) : inner_matcher_(::testing::SafeMatcherCast<const value_type&>( std::forward<InnerMatcher>(inner_matcher))) {} void DescribeTo(std::ostream* os) const override { *os << "is OK and has a value that "; inner_matcher_.DescribeTo(os); } void DescribeNegationTo(std::ostream* os) const override { *os << "isn't OK or has a value that "; inner_matcher_.DescribeNegationTo(os); } bool MatchAndExplain( StatusOrType actual_value, ::testing::MatchResultListener* result_listener) const override { if (!actual_value.ok()) { *result_listener << "which has status " << actual_value.status(); return false; } ::testing::StringMatchResultListener inner_listener; const bool matches = inner_matcher_.MatchAndExplain(*actual_value, &inner_listener); const std::string inner_explanation = inner_listener.str(); if (!inner_explanation.empty()) { *result_listener << "which contains value " << ::testing::PrintToString(*actual_value) << ", " << inner_explanation; } return matches; } private: const ::testing::Matcher<const value_type&> inner_matcher_; }; // Implements IsOkAndHolds(m) as a polymorphic matcher. template <typename InnerMatcher> class IsOkAndHoldsMatcher { public: explicit IsOkAndHoldsMatcher(InnerMatcher inner_matcher) : inner_matcher_(std::move(inner_matcher)) {} // Converts this polymorphic matcher to a monomorphic matcher of the // given type. StatusOrType can be either StatusOr<T> or a // reference to StatusOr<T>. template <typename StatusOrType> operator ::testing::Matcher<StatusOrType>() const { // NOLINT return ::testing::Matcher<StatusOrType>( new IsOkAndHoldsMatcherImpl<const StatusOrType&>(inner_matcher_)); } private: const InnerMatcher inner_matcher_; }; // Monomorphic implementation of matcher IsOk() for a given type T. // T can be Status, StatusOr<>, or a reference to either of them. template <typename T> class MonoIsOkMatcherImpl : public ::testing::MatcherInterface<T> { public: void DescribeTo(std::ostream* os) const override { *os << "is OK"; } void DescribeNegationTo(std::ostream* os) const override { *os << "is not OK"; } bool MatchAndExplain(T actual_value, ::testing::MatchResultListener*) const override { return GetStatus(actual_value).ok(); } }; // Implements IsOk() as a polymorphic matcher. class IsOkMatcher { public: template <typename T> operator ::testing::Matcher<T>() const { // NOLINT return ::testing::Matcher<T>(new MonoIsOkMatcherImpl<T>()); } }; // Returns a gMock matcher that matches a StatusOr<> whose status is // OK and whose value matches the inner matcher. template <typename InnerMatcher> IsOkAndHoldsMatcher<typename std::decay<InnerMatcher>::type> IsOkAndHolds( InnerMatcher&& inner_matcher) { return IsOkAndHoldsMatcher<typename std::decay<InnerMatcher>::type>( std::forward<InnerMatcher>(inner_matcher)); } // Returns a gMock matcher that matches a Status or StatusOr<> which is OK. inline IsOkMatcher IsOk() { return IsOkMatcher(); } #endif // GTEST_HAS_STATUS_MATCHERS } // namespace testing } // namespace private_join_and_compute #endif // PRIVATE_JOIN_AND_COMPUTE_UTIL_STATUS_MATCHERS_H_
[ "karn@google.com" ]
karn@google.com
8bf0592c4d863638a58bd64e533d846f73d22c8f
1e9fbdb90fa4fd3d2c97fc8a45541461ce8ec67f
/src/2016.XO/Sushko_Andriy/TIC-TAC-TOE/HightScoresView.h
feb023cafe3565b3a208a1f1cf95a36f783b6534
[]
no_license
vnobis-univ/sonarcube-test
715168684fdd3547240db032d8ccc4d9680fff6f
f917ef2722144107cb12435021dd02574d149e39
refs/heads/master
2020-03-29T11:49:25.879413
2018-09-24T12:29:56
2018-09-24T12:29:56
149,872,507
0
0
null
null
null
null
UTF-8
C++
false
false
248
h
#pragma once #include "View.h" #include "scores.h" #include <fstream> class HightScoresView :public View { vector<hightScore> vec; void readScores(); public: HightScoresView(); virtual void draw(); virtual View* handle(); };
[ "nobisvitaliy@gmail.com" ]
nobisvitaliy@gmail.com
68855fd00662c8a0e24127689a991c9e66badc0d
d678a380ad8db03eaf785a6f490f60a11e90c036
/GeoFeatures/Internal/boost/mpl/vector/aux_/preprocessed/plain/vector10.hpp
1bb04a91b2882e2c30a7510855d31a7bbbfb6089
[ "BSL-1.0", "Apache-2.0" ]
permissive
Niko-r/geofeatures
0eaa09c65bd9c7e47c3da7bb69e2f20776ba557c
b3b1311f7836b700d47064490e3d7533b8d574ee
refs/heads/master
2020-05-29T11:07:11.474367
2016-07-16T01:43:36
2016-07-16T01:43:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
18,629
hpp
// Copyright Aleksey Gurtovoy 2000-2004 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // Preprocessed version of "boost/mpl/vector/vector10.hpp" header // -- DO NOT modify by hand! namespace geofeatures_boost {} namespace boost = geofeatures_boost; namespace geofeatures_boost { namespace mpl { template< typename V > struct v_at< V,0 > { typedef typename V::item0 type; }; template< typename T0 > struct vector1 { typedef aux::vector_tag<1> tag; typedef vector1 type; typedef T0 item0; typedef void_ item1; typedef T0 back; typedef v_iter< type,0 > begin; typedef v_iter< type,1 > end; }; template<> struct push_front_impl< aux::vector_tag<0> > { template< typename Vector, typename T > struct apply { typedef vector1< T > type; }; }; template<> struct pop_front_impl< aux::vector_tag<1> > { template< typename Vector > struct apply { typedef vector0< > type; }; }; template<> struct push_back_impl< aux::vector_tag<0> > { template< typename Vector, typename T > struct apply { typedef vector1< T > type; }; }; template<> struct pop_back_impl< aux::vector_tag<1> > { template< typename Vector > struct apply { typedef vector0< > type; }; }; template< typename V > struct v_at< V,1 > { typedef typename V::item1 type; }; template< typename T0, typename T1 > struct vector2 { typedef aux::vector_tag<2> tag; typedef vector2 type; typedef T0 item0; typedef T1 item1; typedef void_ item2; typedef T1 back; typedef v_iter< type,0 > begin; typedef v_iter< type,2 > end; }; template<> struct push_front_impl< aux::vector_tag<1> > { template< typename Vector, typename T > struct apply { typedef vector2< T , typename Vector::item0 > type; }; }; template<> struct pop_front_impl< aux::vector_tag<2> > { template< typename Vector > struct apply { typedef vector1< typename Vector::item1 > type; }; }; template<> struct push_back_impl< aux::vector_tag<1> > { template< typename Vector, typename T > struct apply { typedef vector2< typename Vector::item0 , T > type; }; }; template<> struct pop_back_impl< aux::vector_tag<2> > { template< typename Vector > struct apply { typedef vector1< typename Vector::item0 > type; }; }; template< typename V > struct v_at< V,2 > { typedef typename V::item2 type; }; template< typename T0, typename T1, typename T2 > struct vector3 { typedef aux::vector_tag<3> tag; typedef vector3 type; typedef T0 item0; typedef T1 item1; typedef T2 item2; typedef void_ item3; typedef T2 back; typedef v_iter< type,0 > begin; typedef v_iter< type,3 > end; }; template<> struct push_front_impl< aux::vector_tag<2> > { template< typename Vector, typename T > struct apply { typedef vector3< T , typename Vector::item0, typename Vector::item1 > type; }; }; template<> struct pop_front_impl< aux::vector_tag<3> > { template< typename Vector > struct apply { typedef vector2< typename Vector::item1, typename Vector::item2 > type; }; }; template<> struct push_back_impl< aux::vector_tag<2> > { template< typename Vector, typename T > struct apply { typedef vector3< typename Vector::item0, typename Vector::item1 , T > type; }; }; template<> struct pop_back_impl< aux::vector_tag<3> > { template< typename Vector > struct apply { typedef vector2< typename Vector::item0, typename Vector::item1 > type; }; }; template< typename V > struct v_at< V,3 > { typedef typename V::item3 type; }; template< typename T0, typename T1, typename T2, typename T3 > struct vector4 { typedef aux::vector_tag<4> tag; typedef vector4 type; typedef T0 item0; typedef T1 item1; typedef T2 item2; typedef T3 item3; typedef void_ item4; typedef T3 back; typedef v_iter< type,0 > begin; typedef v_iter< type,4 > end; }; template<> struct push_front_impl< aux::vector_tag<3> > { template< typename Vector, typename T > struct apply { typedef vector4< T , typename Vector::item0, typename Vector::item1 , typename Vector::item2 > type; }; }; template<> struct pop_front_impl< aux::vector_tag<4> > { template< typename Vector > struct apply { typedef vector3< typename Vector::item1, typename Vector::item2 , typename Vector::item3 > type; }; }; template<> struct push_back_impl< aux::vector_tag<3> > { template< typename Vector, typename T > struct apply { typedef vector4< typename Vector::item0, typename Vector::item1 , typename Vector::item2 , T > type; }; }; template<> struct pop_back_impl< aux::vector_tag<4> > { template< typename Vector > struct apply { typedef vector3< typename Vector::item0, typename Vector::item1 , typename Vector::item2 > type; }; }; template< typename V > struct v_at< V,4 > { typedef typename V::item4 type; }; template< typename T0, typename T1, typename T2, typename T3, typename T4 > struct vector5 { typedef aux::vector_tag<5> tag; typedef vector5 type; typedef T0 item0; typedef T1 item1; typedef T2 item2; typedef T3 item3; typedef T4 item4; typedef void_ item5; typedef T4 back; typedef v_iter< type,0 > begin; typedef v_iter< type,5 > end; }; template<> struct push_front_impl< aux::vector_tag<4> > { template< typename Vector, typename T > struct apply { typedef vector5< T , typename Vector::item0, typename Vector::item1 , typename Vector::item2, typename Vector::item3 > type; }; }; template<> struct pop_front_impl< aux::vector_tag<5> > { template< typename Vector > struct apply { typedef vector4< typename Vector::item1, typename Vector::item2 , typename Vector::item3, typename Vector::item4 > type; }; }; template<> struct push_back_impl< aux::vector_tag<4> > { template< typename Vector, typename T > struct apply { typedef vector5< typename Vector::item0, typename Vector::item1 , typename Vector::item2, typename Vector::item3 , T > type; }; }; template<> struct pop_back_impl< aux::vector_tag<5> > { template< typename Vector > struct apply { typedef vector4< typename Vector::item0, typename Vector::item1 , typename Vector::item2, typename Vector::item3 > type; }; }; template< typename V > struct v_at< V,5 > { typedef typename V::item5 type; }; template< typename T0, typename T1, typename T2, typename T3, typename T4 , typename T5 > struct vector6 { typedef aux::vector_tag<6> tag; typedef vector6 type; typedef T0 item0; typedef T1 item1; typedef T2 item2; typedef T3 item3; typedef T4 item4; typedef T5 item5; typedef void_ item6; typedef T5 back; typedef v_iter< type,0 > begin; typedef v_iter< type,6 > end; }; template<> struct push_front_impl< aux::vector_tag<5> > { template< typename Vector, typename T > struct apply { typedef vector6< T , typename Vector::item0, typename Vector::item1 , typename Vector::item2, typename Vector::item3 , typename Vector::item4 > type; }; }; template<> struct pop_front_impl< aux::vector_tag<6> > { template< typename Vector > struct apply { typedef vector5< typename Vector::item1, typename Vector::item2 , typename Vector::item3, typename Vector::item4 , typename Vector::item5 > type; }; }; template<> struct push_back_impl< aux::vector_tag<5> > { template< typename Vector, typename T > struct apply { typedef vector6< typename Vector::item0, typename Vector::item1 , typename Vector::item2, typename Vector::item3 , typename Vector::item4 , T > type; }; }; template<> struct pop_back_impl< aux::vector_tag<6> > { template< typename Vector > struct apply { typedef vector5< typename Vector::item0, typename Vector::item1 , typename Vector::item2, typename Vector::item3 , typename Vector::item4 > type; }; }; template< typename V > struct v_at< V,6 > { typedef typename V::item6 type; }; template< typename T0, typename T1, typename T2, typename T3, typename T4 , typename T5, typename T6 > struct vector7 { typedef aux::vector_tag<7> tag; typedef vector7 type; typedef T0 item0; typedef T1 item1; typedef T2 item2; typedef T3 item3; typedef T4 item4; typedef T5 item5; typedef T6 item6; typedef void_ item7; typedef T6 back; typedef v_iter< type,0 > begin; typedef v_iter< type,7 > end; }; template<> struct push_front_impl< aux::vector_tag<6> > { template< typename Vector, typename T > struct apply { typedef vector7< T , typename Vector::item0, typename Vector::item1 , typename Vector::item2, typename Vector::item3 , typename Vector::item4, typename Vector::item5 > type; }; }; template<> struct pop_front_impl< aux::vector_tag<7> > { template< typename Vector > struct apply { typedef vector6< typename Vector::item1, typename Vector::item2 , typename Vector::item3, typename Vector::item4 , typename Vector::item5, typename Vector::item6 > type; }; }; template<> struct push_back_impl< aux::vector_tag<6> > { template< typename Vector, typename T > struct apply { typedef vector7< typename Vector::item0, typename Vector::item1 , typename Vector::item2, typename Vector::item3 , typename Vector::item4, typename Vector::item5 , T > type; }; }; template<> struct pop_back_impl< aux::vector_tag<7> > { template< typename Vector > struct apply { typedef vector6< typename Vector::item0, typename Vector::item1 , typename Vector::item2, typename Vector::item3 , typename Vector::item4, typename Vector::item5 > type; }; }; template< typename V > struct v_at< V,7 > { typedef typename V::item7 type; }; template< typename T0, typename T1, typename T2, typename T3, typename T4 , typename T5, typename T6, typename T7 > struct vector8 { typedef aux::vector_tag<8> tag; typedef vector8 type; typedef T0 item0; typedef T1 item1; typedef T2 item2; typedef T3 item3; typedef T4 item4; typedef T5 item5; typedef T6 item6; typedef T7 item7; typedef void_ item8; typedef T7 back; typedef v_iter< type,0 > begin; typedef v_iter< type,8 > end; }; template<> struct push_front_impl< aux::vector_tag<7> > { template< typename Vector, typename T > struct apply { typedef vector8< T , typename Vector::item0, typename Vector::item1 , typename Vector::item2, typename Vector::item3 , typename Vector::item4, typename Vector::item5 , typename Vector::item6 > type; }; }; template<> struct pop_front_impl< aux::vector_tag<8> > { template< typename Vector > struct apply { typedef vector7< typename Vector::item1, typename Vector::item2 , typename Vector::item3, typename Vector::item4 , typename Vector::item5, typename Vector::item6 , typename Vector::item7 > type; }; }; template<> struct push_back_impl< aux::vector_tag<7> > { template< typename Vector, typename T > struct apply { typedef vector8< typename Vector::item0, typename Vector::item1 , typename Vector::item2, typename Vector::item3 , typename Vector::item4, typename Vector::item5 , typename Vector::item6 , T > type; }; }; template<> struct pop_back_impl< aux::vector_tag<8> > { template< typename Vector > struct apply { typedef vector7< typename Vector::item0, typename Vector::item1 , typename Vector::item2, typename Vector::item3 , typename Vector::item4, typename Vector::item5 , typename Vector::item6 > type; }; }; template< typename V > struct v_at< V,8 > { typedef typename V::item8 type; }; template< typename T0, typename T1, typename T2, typename T3, typename T4 , typename T5, typename T6, typename T7, typename T8 > struct vector9 { typedef aux::vector_tag<9> tag; typedef vector9 type; typedef T0 item0; typedef T1 item1; typedef T2 item2; typedef T3 item3; typedef T4 item4; typedef T5 item5; typedef T6 item6; typedef T7 item7; typedef T8 item8; typedef void_ item9; typedef T8 back; typedef v_iter< type,0 > begin; typedef v_iter< type,9 > end; }; template<> struct push_front_impl< aux::vector_tag<8> > { template< typename Vector, typename T > struct apply { typedef vector9< T , typename Vector::item0, typename Vector::item1 , typename Vector::item2, typename Vector::item3 , typename Vector::item4, typename Vector::item5 , typename Vector::item6, typename Vector::item7 > type; }; }; template<> struct pop_front_impl< aux::vector_tag<9> > { template< typename Vector > struct apply { typedef vector8< typename Vector::item1, typename Vector::item2 , typename Vector::item3, typename Vector::item4 , typename Vector::item5, typename Vector::item6 , typename Vector::item7, typename Vector::item8 > type; }; }; template<> struct push_back_impl< aux::vector_tag<8> > { template< typename Vector, typename T > struct apply { typedef vector9< typename Vector::item0, typename Vector::item1 , typename Vector::item2, typename Vector::item3 , typename Vector::item4, typename Vector::item5 , typename Vector::item6, typename Vector::item7 , T > type; }; }; template<> struct pop_back_impl< aux::vector_tag<9> > { template< typename Vector > struct apply { typedef vector8< typename Vector::item0, typename Vector::item1 , typename Vector::item2, typename Vector::item3 , typename Vector::item4, typename Vector::item5 , typename Vector::item6, typename Vector::item7 > type; }; }; template< typename V > struct v_at< V,9 > { typedef typename V::item9 type; }; template< typename T0, typename T1, typename T2, typename T3, typename T4 , typename T5, typename T6, typename T7, typename T8, typename T9 > struct vector10 { typedef aux::vector_tag<10> tag; typedef vector10 type; typedef T0 item0; typedef T1 item1; typedef T2 item2; typedef T3 item3; typedef T4 item4; typedef T5 item5; typedef T6 item6; typedef T7 item7; typedef T8 item8; typedef T9 item9; typedef void_ item10; typedef T9 back; typedef v_iter< type,0 > begin; typedef v_iter< type,10 > end; }; template<> struct push_front_impl< aux::vector_tag<9> > { template< typename Vector, typename T > struct apply { typedef vector10< T , typename Vector::item0, typename Vector::item1 , typename Vector::item2, typename Vector::item3 , typename Vector::item4, typename Vector::item5 , typename Vector::item6, typename Vector::item7 , typename Vector::item8 > type; }; }; template<> struct pop_front_impl< aux::vector_tag<10> > { template< typename Vector > struct apply { typedef vector9< typename Vector::item1, typename Vector::item2 , typename Vector::item3, typename Vector::item4 , typename Vector::item5, typename Vector::item6 , typename Vector::item7, typename Vector::item8 , typename Vector::item9 > type; }; }; template<> struct push_back_impl< aux::vector_tag<9> > { template< typename Vector, typename T > struct apply { typedef vector10< typename Vector::item0, typename Vector::item1 , typename Vector::item2, typename Vector::item3 , typename Vector::item4, typename Vector::item5 , typename Vector::item6, typename Vector::item7 , typename Vector::item8 , T > type; }; }; template<> struct pop_back_impl< aux::vector_tag<10> > { template< typename Vector > struct apply { typedef vector9< typename Vector::item0, typename Vector::item1 , typename Vector::item2, typename Vector::item3 , typename Vector::item4, typename Vector::item5 , typename Vector::item6, typename Vector::item7 , typename Vector::item8 > type; }; }; template< typename V > struct v_at< V,10 > { typedef typename V::item10 type; }; }}
[ "tony@mobilegridinc.com" ]
tony@mobilegridinc.com
6d8b7dee885c50ef67a06935027d8f95a25c6e3b
f9ba40591239d2b112803db74d5d11a4e993f96c
/moses/src/ChartTranslationOptionList.h
5764392279375a179ed65e1c66b9f65a3590f309
[]
no_license
obo/Moses-Extensions-at-UFAL
388721f8ed54ee017aec42523fcc0ed292d17c37
24df6160d2ebcd436daec0264475b507969339bd
refs/heads/master
2020-05-02T22:25:24.457442
2011-02-03T09:11:27
2011-02-03T09:11:27
494,934
1
0
null
null
null
null
UTF-8
C++
false
false
3,113
h
// $Id$ /*********************************************************************** Moses - factored phrase-based language decoder Copyright (C) 2006 University of Edinburgh 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; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 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 Street, Fifth Floor, Boston, MA 02110-1301 USA ***********************************************************************/ #pragma once #include <queue> #include <vector> #include <list> #include <set> #include "ChartTranslationOption.h" #include "TargetPhrase.h" #include "Util.h" #include "TargetPhraseCollection.h" #include "ObjectPool.h" namespace Moses { //! a list of target phrases that is trsnalated from the same source phrase class ChartTranslationOptionList { friend std::ostream& operator<<(std::ostream&, const ChartTranslationOptionList&); protected: #ifdef USE_HYPO_POOL static ObjectPool<ChartTranslationOptionList> s_objectPool; #endif typedef std::vector<ChartTranslationOption*> CollType; CollType m_collection; float m_scoreThreshold; Moses::WordsRange m_range; public: // iters typedef CollType::iterator iterator; typedef CollType::const_iterator const_iterator; iterator begin() { return m_collection.begin(); } iterator end() { return m_collection.end(); } const_iterator begin() const { return m_collection.begin(); } const_iterator end() const { return m_collection.end(); } #ifdef USE_HYPO_POOL void *operator new(size_t num_bytes) { void *ptr = s_objectPool.getPtr(); return ptr; } static void Delete(ChartTranslationOptionList *obj) { s_objectPool.freeObject(obj); } #else static void Delete(ChartTranslationOptionList *obj) { delete obj; } #endif ChartTranslationOptionList(const WordsRange &range); ~ChartTranslationOptionList(); const ChartTranslationOption &Get(size_t ind) const { return *m_collection[ind]; } //! divide collection into 2 buckets using std::nth_element, the top & bottom according to table limit // void Sort(size_t tableLimit); //! number of target phrases in this collection size_t GetSize() const { return m_collection.size(); } //! wether collection has any phrases bool IsEmpty() const { return m_collection.empty(); } void Add(const Moses::TargetPhraseCollection &targetPhraseCollection , const WordConsumed &wordConsumed , bool ruleLimit , size_t tableLimit); void Add(ChartTranslationOption *transOpt); void CreateChartRules(size_t ruleLimit); const Moses::WordsRange &GetSourceRange() const { return m_range; } void Sort(); }; }
[ "bojar@ufal.mff.cuni.cz" ]
bojar@ufal.mff.cuni.cz
2bfa16edc4fd0fc9ed6d943e2540fe49b5245746
ac0d3dc1867eaebe756642b9e29ac8a89e59309b
/Agora/Private/Abilities/Shared/AgoraGameplayTags.cpp
6224bfed24a9b2f7b57e8d99d8d5713e3747ed75
[]
no_license
lineCode/MobaGame
e58a9caf289f067d6708598ead35ddcfe9d2a806
1c26b527a19e5ec3bfaaa6fbe6869510cfecfa50
refs/heads/main
2023-03-25T22:17:11.179350
2021-03-29T22:43:06
2021-03-29T22:43:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
210
cpp
// Copyright (C) 2019 Kevin Ossia, Joe Finley, and Nicholas Arthur. Unauthorized copying of this file via any medium is strictly prohibited. #include "AgoraGameplayTags.h" #include "GameplayTagContainer.h"
[ "joefinleybusiness@gmail.com" ]
joefinleybusiness@gmail.com
df3aa244ea8186fe3b52ab4626a0a68cee11219b
fb6251837c15a0ee0b28b15d214599165e11de83
/LightOJ/Breadth First Search-Depth First Search/1238 - Power Puff Girls.cpp
a7634b4a0b26515c55ad5e2d48dc28ff7b8c365b
[]
no_license
CDPS/Competitive-Programming
de72288b8dc02ca2a45ed40491ce1839e983b765
24c046cbde7fea04a6c0f22518a688faf7521e2e
refs/heads/master
2023-08-09T09:57:15.368959
2023-08-05T00:44:41
2023-08-05T00:44:41
104,966,014
0
0
null
null
null
null
UTF-8
C++
false
false
2,312
cpp
#include <bits/stdc++.h> using namespace std; char g[20][20]; bool v[20][20]; int l[20][20]; int x[4]={1,-1,0,0}; int y[4]={0,0,1,-1}; int n,m; bool isValid(int i,int j){ if( (i>=0 && i<n) && (j>=0 && j<m) ){ if(g[i][j]=='.'){ return 1; } } return 0; } int bfs(int i,int j, int it, int jt){ queue< pair<int,int> > q; q.push(make_pair(i,j)); v[i][j]=1; l[i][j]=0; while(!q.empty()){ int ux = q.front().first; int uy= q.front().second; q.pop(); if(ux==it && uy==jt) return l[ux][uy]; for(int i=0;i<4;i++){ int vx=ux+ x[i]; int vy= uy +y[i]; if( isValid(vx,vy)){ if(!v[vx][vy]){ q.push(make_pair(vx,vy)); l[vx][vy]=l[ux][uy]+1; v[vx][vy]=1; } } } } return -1; } int main(){ int t,caseno=1; scanf("%d",&t); while(t--){ scanf("%d %d",&n,&m); pair<int,int> blossom,bubbles,buttercup,home; for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ scanf(" %c",&g[i][j]); if(g[i][j]=='a'){ blossom= make_pair(i,j); g[i][j]='.'; } if(g[i][j]=='b'){ bubbles=make_pair(i,j); g[i][j]='.'; } if(g[i][j]=='c'){ buttercup=make_pair(i,j); g[i][j]='.'; } if(g[i][j]=='h'){ home= make_pair(i,j); g[i][j]='.'; } } } int disBlossom= bfs(blossom.first,blossom.second,home.first,home.second); memset(v,0,sizeof v); memset(l,0,sizeof l); int disBubble = bfs(bubbles.first,bubbles.second,home.first,home.second); memset(v,0,sizeof v); memset(l,0,sizeof l); int disButtercup= bfs(buttercup.first,buttercup.second,home.first,home.second); memset(v,0,sizeof v); memset(l,0,sizeof l); printf("Case %d: %d\n",caseno++,max(disBlossom,max(disButtercup,disBubble))); } return 0; }
[ "crispale07@gmail.com" ]
crispale07@gmail.com
64d5fa0df03dd58380ecc317e9a3be4fec139d06
15098e674df8cc889872012748f602fa43fc3713
/cpp/open3d/t/io/sensor/realsense/RSBagReader.cpp
9a3108388b92c184cc200db072f661957e694367
[ "MIT" ]
permissive
TileDB-Inc/Open3D
4606ae77a1f5113c16f41ed3b78e12dc5a60e9fa
6c4080d2aec2c0df95e2e37ed75fc0911f14dbe9
refs/heads/master
2023-07-06T04:55:59.245294
2021-07-22T15:53:22
2021-07-22T15:53:22
388,842,109
0
0
NOASSERTION
2021-07-23T15:15:04
2021-07-23T15:15:03
null
UTF-8
C++
false
false
9,427
cpp
// ---------------------------------------------------------------------------- // - Open3D: www.open3d.org - // ---------------------------------------------------------------------------- // The MIT License (MIT) // // Copyright (c) 2018-2021 www.open3d.org // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // ---------------------------------------------------------------------------- #include "open3d/t/io/sensor/realsense/RSBagReader.h" #include <json/json.h> #include <chrono> #include <iomanip> #include <iostream> #include <mutex> #include <sstream> #include <tuple> #include "open3d/t/io/sensor/realsense/RealSensePrivate.h" #include "open3d/t/io/sensor/realsense/RealSenseSensorConfig.h" namespace open3d { namespace t { namespace io { // If DEFAULT_BUFFER_SIZE is odr-uses, a definition is required. // For Fedora33, GCC10, CUDA11.2: // Fix undefined symble error in pybind-*-linux-gnu.so. // See: https://github.com/intel-isl/Open3D/issues/3141 const size_t RSBagReader::DEFAULT_BUFFER_SIZE; RSBagReader::RSBagReader(size_t buffer_size) : frame_buffer_(buffer_size), frame_position_us_(buffer_size), pipe_(nullptr) {} RSBagReader::~RSBagReader() { if (IsOpened()) Close(); } bool RSBagReader::Open(const std::string &filename) { if (IsOpened()) { Close(); } try { rs2::config cfg; cfg.enable_device_from_file(filename, false); // Do not repeat playback cfg.disable_all_streams(); cfg.enable_stream(RS2_STREAM_DEPTH); cfg.enable_stream(RS2_STREAM_COLOR); pipe_.reset(new rs2::pipeline); auto profile = pipe_->start(cfg); // Open file in read mode // do not drop frames: Causes deadlock after 4 frames on macOS/Linux // https://github.com/IntelRealSense/librealsense/issues/7547#issuecomment-706984376 /* profile.get_device().as<rs2::playback>().set_real_time(false); */ metadata_.ConvertFromJsonValue( RealSenseSensorConfig::GetMetadataJson(profile)); RealSenseSensorConfig::GetPixelDtypes(profile, metadata_); if (seek_to_ == UINT64_MAX) { utility::LogInfo("File {} opened", filename); } } catch (const rs2::error &) { utility::LogWarning("Unable to open file {}", filename); return false; } filename_ = filename; is_eof_ = false; is_opened_ = true; // Launch thread to keep frame_buffer full frame_reader_thread_ = std::thread{&RSBagReader::fill_frame_buffer, this}; return true; } void RSBagReader::Close() { is_opened_ = false; need_frames_.notify_one(); frame_reader_thread_.join(); pipe_->stop(); } void RSBagReader::fill_frame_buffer() try { std::mutex frame_buffer_mutex; std::unique_lock<std::mutex> lock(frame_buffer_mutex); const unsigned int RS2_PLAYBACK_TIMEOUT_MS = static_cast<unsigned int>(10 * 1000.0 / metadata_.fps_); rs2::frameset frames; rs2::playback rs_device = pipe_->get_active_profile().get_device().as<rs2::playback>(); rs2::align align_to_color(rs2_stream::RS2_STREAM_COLOR); head_fid_ = 0; tail_fid_ = 0; uint64_t next_dev_color_fid = 0; uint64_t dev_color_fid = 0; while (is_opened_) { rs_device.resume(); utility::LogDebug( "frame_reader_thread_ start reading tail_fid_={}, " "head_fid_={}.", tail_fid_, head_fid_); while (!is_eof_ && head_fid_ < tail_fid_ + frame_buffer_.size()) { if (seek_to_ < UINT64_MAX) { utility::LogDebug("frame_reader_thread_ seek to {}us", seek_to_); rs_device.seek(std::chrono::microseconds(seek_to_)); tail_fid_.store( head_fid_.load()); // atomic: Invalidate buffer. next_dev_color_fid = dev_color_fid = 0; seek_to_ = UINT64_MAX; } // Ensure next frameset is not a repeat while (next_dev_color_fid == dev_color_fid && pipe_->try_wait_for_frames(&frames, RS2_PLAYBACK_TIMEOUT_MS)) { next_dev_color_fid = frames.get_color_frame().get_frame_number(); } if (next_dev_color_fid != dev_color_fid) { dev_color_fid = next_dev_color_fid; auto &current_frame = frame_buffer_[head_fid_ % frame_buffer_.size()]; frames = align_to_color.process(frames); const auto &color_frame = frames.get_color_frame(); // Copy frame data to Tensors current_frame.color_ = core::Tensor( static_cast<const uint8_t *>(color_frame.get_data()), {color_frame.get_height(), color_frame.get_width(), metadata_.color_channels_}, metadata_.color_dt_); const auto &depth_frame = frames.get_depth_frame(); current_frame.depth_ = core::Tensor( static_cast<const uint16_t *>(depth_frame.get_data()), {depth_frame.get_height(), depth_frame.get_width()}, metadata_.depth_dt_); frame_position_us_[head_fid_ % frame_buffer_.size()] = rs_device.get_position() / 1000; // Convert nanoseconds -> microseconds ++head_fid_; // atomic } else { utility::LogDebug("frame_reader_thread EOF. Join."); is_eof_ = true; return; } if (!is_opened_) break; // exit if Close() } rs_device.pause(); // Pause playback to prevent frame drops utility::LogDebug( "frame_reader_thread pause reading tail_fid_={}, head_fid_={}", tail_fid_, head_fid_); need_frames_.wait(lock, [this] { return !is_opened_ || head_fid_ < tail_fid_ + frame_buffer_.size() / BUFFER_REFILL_FACTOR; }); } } catch (const rs2::error &e) { utility::LogError("Realsense error: {}: {}", rs2_exception_type_to_string(e.get_type()), e.what()); } catch (const std::exception &e) { utility::LogError("Error in reading RealSense bag file: {}", e.what()); } bool RSBagReader::IsEOF() const { return is_eof_ && tail_fid_ == head_fid_; } t::geometry::RGBDImage RSBagReader::NextFrame() { if (!IsOpened()) { utility::LogError("Null file handler. Please call Open()."); } if (!is_eof_ && head_fid_ < tail_fid_ + frame_buffer_.size() / BUFFER_REFILL_FACTOR) need_frames_.notify_one(); while (!is_eof_ && tail_fid_ == head_fid_) { // (rare) spin wait for frame_reader_thread_ std::this_thread::sleep_for( std::chrono::duration<double>(1 / metadata_.fps_)); } if (is_eof_ && tail_fid_ == head_fid_) { // no more frames utility::LogInfo("EOF reached"); return t::geometry::RGBDImage(); } else { return frame_buffer_[(tail_fid_++) % // atomic frame_buffer_.size()]; } } bool RSBagReader::SeekTimestamp(uint64_t timestamp) { if (!IsOpened()) { utility::LogWarning("Null file handler. Please call Open()."); return false; } if (timestamp >= metadata_.stream_length_usec_) { utility::LogWarning("Timestamp {} exceeds maximum {} (us).", timestamp, metadata_.stream_length_usec_); return false; } seek_to_ = timestamp; // atomic if (is_eof_) { Open(filename_); // EOF requires restarting pipeline. } else { need_frames_.notify_one(); } return true; } uint64_t RSBagReader::GetTimestamp() const { if (!IsOpened()) { utility::LogWarning("Null file handler. Please call Open()."); return UINT64_MAX; } return tail_fid_ == 0 ? 0 : frame_position_us_[(tail_fid_ - 1) % frame_buffer_.size()]; } } // namespace io } // namespace t } // namespace open3d
[ "noreply@github.com" ]
noreply@github.com
71b3bdb108b275159f8f2ac78743e4f9cf48ed5d
5691f5072faff744fc3cb923a0a9def53348f4e2
/Product.h
d9e9100d84f3e5fbbd9afe35be3333c7c7042135
[]
no_license
Abdul-Sen/Aid-Management-Application
f4fc3450dd23b8e42eeabceca758ef7358a1a674
2981de404c700099923913737a83632bf0fe3547
refs/heads/master
2020-04-08T12:55:19.746291
2018-11-27T16:40:55
2018-11-27T16:40:55
159,367,287
0
0
null
null
null
null
UTF-8
C++
false
false
2,658
h
// Milestone 3 - Product Class // File Prodcut.h // Date 2018/07/18 // Name: Abdul Rehman Jahangir // Description // This file contains the class definition for Prodcut class and the helper function declaration. ///////////////////////////////////////////////////// #ifndef AMA_PRODUCT_H #define AMA_PRODUCT_H #include "ErrorState.h" #include "iProduct.h" namespace AMA { const int max_sku_length = 7; const int max_unit_length = 10; const int max_name_length = 75; const double CURR_TAX_RATE = 0.13;//or 0.13? class Product :public iProduct { char product_type;//tells product type char product_sku[max_sku_length]; char product_unit[max_unit_length]; char* p_name;//stores product name in dynamic mem int quantity_available; int quantity_needed; double product_price;//holds price of 1 unit bool tax_status;// true if product is taxable ErrorState product_error;//Is this correct? protected: void name(const char*); //takes name of the product and sets it up dynamically const char* name() const; // returns address of name string const char* sku() const; //returns address of sku string const char* unit() const; // returns address of unit string bool taxed() const; //returns tax status double price() const; // return cost of 1 item double cost() const; // return cost of 1 item + tax void message(const char*); // takes message and add it to error state of the class bool isClear() const; //checks if errorstate is clear public: //default constructor Product(char = 'N');//default constructor Product(const char* ui_sku, const char* ui_p_name, const char* ui_unit, int ui_qty_available= 0,bool ui_tax_status = true, double ui_price = 0,int ui_qty_needed = 0); Product(const Product&);//build = operator first Product& operator=(const Product&);//copy assignment operator ~Product(); std::fstream& store(std::fstream& file, bool newLine = true) const; std::fstream& load(std::fstream& file); std::ostream& write(std::ostream& os, bool linear) const; std::istream& read(std::istream& is); //OVERLOADS bool operator==(const char*) const; double total_cost() const; void quantity(int); //changes quntity avail to whatever you input bool isEmpty() const; //checks if obj is in safe empty state int qtyNeeded() const; int quantity() const;// bool operator>(const char*) const; bool operator>(const iProduct&) const; int operator+=(int);//adds that much amount to quantity }; std::ostream& operator<<(std::ostream&, const iProduct&); std::istream& operator>>(std::istream&, iProduct&); double operator+=(double&, const iProduct&); } #endif // !AMA_PRODUCT_H
[ "abdul-rehman@myseneca.ca" ]
abdul-rehman@myseneca.ca
689d764c72c1bce0b7bb57c48c454e7e56388434
d55bbde7f9b252b47f072f74b02f65640807ddeb
/RegistrationStatistics.h
8dc86de4a0606fe90e9d26f06b7b5f48b018e2bc
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-warranty-disclaimer", "TCL", "LicenseRef-scancode-newlib-historical", "LicenseRef-scancode-x11-opengl", "LicenseRef-scancode-mit-old-style" ]
permissive
caomw/scanalyze
542b4fcccec83e27d74a51ac8a9dbcf9a5688baf
f9c0f08c89586715df62f98d5997a79a5b527428
refs/heads/master
2020-02-26T16:52:43.178708
2014-07-18T15:31:48
2014-07-18T15:31:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,981
h
//############################################################### // RegistationStatistics.h // Laurent MEUNIER // $date // // structure for registration quality related features // computed in ICP.h //############################################################### #ifndef REGISTRATION_STATISTICS_H #define REGISTRATION_STATISTICS_H extern void fitPnt3Plane(const vector<Pnt3> &, Pnt3 &, float &, Pnt3 &); class RegistrationStatistics { public: enum { PERCENTAGE_OVERLAPPING = 1, AVG_MOTION = 2, CONDITION_NUMBER = 3, PAIR_STABILITY = 4, RMS_POINT_TO_PLANE_ERROR = 5, RMS_POINT_TO_POINT_ERROR = 6 }; bool discarded; float percentageOverlapping; float percentageKept; float avgConfidence; float avgMotion; float conditionNumber; float RMSPointToPointError; float AVGPointToPointError; float pointToPointDeviation; float RMSPointToPlaneError; float AVGPointToPlaneError; float pointToPlaneDeviation; float mainDirProjections[8]; // init everything RegistrationStatistics() { discarded = false; percentageOverlapping = 0.0; percentageKept = 0.0; avgConfidence = 0.0; avgMotion = 0.0; conditionNumber = 0.0; RMSPointToPointError = 0.0; AVGPointToPointError = 0.0; pointToPointDeviation = 0.0; RMSPointToPlaneError = 0.0; AVGPointToPlaneError = 0.0; pointToPlaneDeviation = 0.0; for (int i = 0; i < 8; i++) mainDirProjections[i] = 0.0; } bool test(RegistrationStatistics t) { return ((percentageOverlapping > t.percentageOverlapping) && (percentageKept > t.percentageKept) && (avgMotion < t.avgMotion) && (RMSPointToPlaneError < t.RMSPointToPlaneError) && (RMSPointToPointError < t.RMSPointToPointError)); } float getResult(int resultType) { switch (resultType) { case PERCENTAGE_OVERLAPPING: return percentageOverlapping; case PAIR_STABILITY: return percentageKept; case AVG_MOTION: return -avgMotion; case CONDITION_NUMBER: return -conditionNumber; case RMS_POINT_TO_PLANE_ERROR: return -RMSPointToPlaneError; case RMS_POINT_TO_POINT_ERROR: return -RMSPointToPointError; } return 0; } // print everything void print() { if (discarded) { cout << "this pairing was discarded (overlapping area is to " "small)\n"; return; } cout << "overlapping = " << percentageOverlapping << "%\n"; cout << "kept = " << percentageKept << "%\n"; cout << "avg confidence = " << avgConfidence << "\n"; cout << "avg motion = " << avgMotion << "mm\n"; cout << "condition number = " << conditionNumber << "\n"; cout << "point to point: avg = " << AVGPointToPointError << "mm, rms = " << RMSPointToPointError << "mm, deviation = " << pointToPointDeviation << "mm\n"; cout << "point to plane: avg = " << AVGPointToPlaneError << "mm, rms = " << RMSPointToPlaneError << "mm, deviation = " << pointToPlaneDeviation << "mm\n"; char str1[80], str2[80], str3[80]; sprintf(str1, "projections: %9.3f %9.3f %9.3f\n", mainDirProjections[3], mainDirProjections[2], mainDirProjections[1]); sprintf(str2, " %9.3f %9.3f\n", mainDirProjections[4], mainDirProjections[0]); sprintf(str3, " %9.3f %9.3f %9.3f\n", mainDirProjections[5], mainDirProjections[6], mainDirProjections[7]); cout << str1 << str2 << str3 << "\n" << flush; } static void computeMainDirections(vector<Pnt3> pts, Pnt3 *directions, Pnt3 &centroid) { Pnt3 norm; float d; fitPnt3Plane(pts, norm, d, centroid); Pnt3 u = cross(norm, Pnt3(1, 0, 0)); norm.normalize(); float lu = u.norm(); if (lu == 0.0) u = cross(norm, Pnt3(0, 1, 0)); u.normalize(); Pnt3 v = cross(norm, u); v.normalize(); directions[0] = u; directions[1] = (u + v).normalize(); directions[2] = v; directions[3] = (u * (-1) + v).normalize(); directions[4] = u * (-1); directions[5] = (u * (-1) + v * (-1)).normalize(); directions[6] = v * (-1); directions[7] = (u + v * (-1)).normalize(); } static float projection(vector<Pnt3> pts, Pnt3 centroid, Pnt3 direction) { float sum = 0; for (int i = 0; i < pts.size(); i++) { float d = dot(pts[i] - centroid, direction); sum += (d > 0) ? d : 0.0; } return sum / pts.size(); } }; #endif
[ "daniel.thul@gmail.com" ]
daniel.thul@gmail.com
73ac344076355d920593ee6f5688cc342b0e312d
cc94542e78e38567f9f0f891f8fa31996ea169cb
/MiniSlamGraphLib/VariableLengthVector.h
351946fba27658d0d6cf3106ad6aad1ca7fb398c
[]
no_license
WSX741405/ITM
725700e57ff4d1e7cfe784b85c12f25597df87b2
78ad22bc19211d16d1a1db6b9df22b72600ffea1
refs/heads/master
2021-04-09T16:36:54.226544
2018-03-20T13:03:39
2018-03-20T13:03:39
125,861,673
0
0
null
null
null
null
UTF-8
C++
false
false
698
h
// Copyright 2014-2017 Oxford University Innovation Limited and the authors of ITM #pragma once namespace MiniSlamGraph { class VariableLengthVector { public: typedef std::vector<double> InternalStorage; void addData(int pos, int size, double *data) { int minSizeNeeded = pos + size; if (mData.size() < (unsigned)minSizeNeeded) mData.resize(minSizeNeeded, 0.0f); for (int i = 0; i < size; ++i) mData[i + pos] += data[i]; } void setOverallSize(int size) { mData.resize(size, 0.0f); } int getOverallSize(void) const { return (int)mData.size(); } const double* getData(void) const { return &(mData[0]); } private: InternalStorage mData; }; }
[ "wsx741405@gmail.com" ]
wsx741405@gmail.com
2c8b7b1c34785a15426bd40907f2d790cfcb48ea
75a1623e624d1140dc9f64a38a0e6b9533c5d784
/questao7/main7.cpp
9c7c8f03e099c2dbd8cad40bef20b6186764d2d6
[]
no_license
sustavos/lista3
802c7f84be1e2f0fc8a0def323037a47a5968080
3b8ee06f3a28bf9f5c80b5162703ae991fb60a81
refs/heads/master
2020-08-27T09:25:07.229910
2019-11-07T01:33:06
2019-11-07T01:33:06
217,316,224
0
0
null
null
null
null
UTF-8
C++
false
false
390
cpp
#include <iostream> #include <vector> #include <fstream> #include <algorithm> #include "dadosSensor.h" #include "metodos.h" using namespace std; int main(){ vector <DadosSensor> vetor; vector <int> valor; arquivo("../questao2/arquivo.txt", valor); sort(valor.begin(), valor.end()); // ordena o vetor criarObjetos(vetor, valor); show(vetor); return 0; }
[ "noreply@github.com" ]
noreply@github.com
b5dcf3d999b819742dc4847ecca3fe7119eeb2e7
7fb3d724b38f956ea549fd9c250eb2fd5b2b8a23
/src/libtiled/properties.h
92cec8a6192f5ddb1f15364234274d9201022507
[]
no_license
chenzujiang/tiled-map-editor
b355bdde79d836f1af669891612a9b5275ecb3bd
28dc164c625bbfdb0e39f6e6b4bdc5aac70ae3dc
refs/heads/master
2021-04-14T07:46:58.014886
2020-03-22T15:50:12
2020-03-22T15:50:12
249,216,650
1
0
null
null
null
null
GB18030
C++
false
false
3,667
h
/* * properties.h * Copyright 2010, Thorbj酶rn Lindeijer <thorbjorn@lindeijer.nl> * * This file is part of libtiled. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE 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 CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once #include "tiled_global.h" #include <QJsonArray> #include <QMap> #include <QString> #include <QUrl> #include <QVariant> class QDir; namespace Tiled { struct FilePath { QUrl url; }; /**属性的集合和它们的值。 * Collection of properties and their values. */ class TILEDSHARED_EXPORT Properties : public QMap<QString,QVariant> { public: void merge(const Properties &other); QJsonArray toJson() const; static Properties fromJson(const QJsonArray &json); }; class TILEDSHARED_EXPORT AggregatedPropertyData { public: AggregatedPropertyData() : mPresenceCount(0) , mValueConsistent(true) {} explicit AggregatedPropertyData(const QVariant &value) : mValue(value) , mPresenceCount(1) , mValueConsistent(true) {} void aggregate(const QVariant &value) { mValueConsistent &= value == mValue; mPresenceCount += 1; } const QVariant &value() const { return mValue; } int presenceCount() const { return mPresenceCount; } bool valueConsistent() const { return mValueConsistent; } bool operator==(const AggregatedPropertyData &other) const { return mValue == other.mValue && mPresenceCount == other.mPresenceCount && mValueConsistent == other.mValueConsistent; } private: QVariant mValue; int mPresenceCount; bool mValueConsistent; }; /** * Collection of properties with information about the consistency of their * presence and value over several property collections. */ class TILEDSHARED_EXPORT AggregatedProperties : public QMap<QString, AggregatedPropertyData> { public: void aggregate(const Properties &properties); }; TILEDSHARED_EXPORT int filePathTypeId(); TILEDSHARED_EXPORT QString typeToName(int type); TILEDSHARED_EXPORT int nameToType(const QString &name); TILEDSHARED_EXPORT QVariant toExportValue(const QVariant &value); TILEDSHARED_EXPORT QVariant fromExportValue(const QVariant &value, int type); TILEDSHARED_EXPORT QVariant toExportValue(const QVariant &value, const QDir &dir); TILEDSHARED_EXPORT QVariant fromExportValue(const QVariant &value, int type, const QDir &dir); } // namespace Tiled Q_DECLARE_METATYPE(Tiled::FilePath)
[ "atk_develop@163.com" ]
atk_develop@163.com
c2b685c5e85e958e57228c68e3fd65ef06311ae9
bbf709d16d0552d4dd2e680b0dc39848c1a576ee
/test/ast_test/tokenizer_for_doc.cc
7b3260886d566e559e1be451db6717093a337890
[ "MIT" ]
permissive
huntzhan/clidoc
093aae92fb089dc740cc7843e335a728e5003187
5587233558a40faafea5b4865732a261568e8428
refs/heads/master
2021-01-18T01:08:36.975837
2015-06-08T07:30:27
2015-06-08T07:30:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,393
cc
#include <string> #include <vector> #include <sstream> #include "clidoc/ast/ast_node_interface.h" #include "clidoc/ast/generated_scanner.h" #include "shared/tokenizer.h" using std::string; using std::vector; using std::istringstream; using std::ostringstream; // I know this is ugly. Fix it if you have a better plan. #define TokenTypeMapping(name) \ case TypeID::name: \ return TerminalType::name \ // facilitate usage. using Type = clidoc::BisonGeneratedParser::token_type; using TypeID = clidoc::BisonGeneratedParser::token; namespace clidoc { TerminalType ToTerminalType(const Type &type_id) { switch (type_id) { TokenTypeMapping(K_OPTIONS); TokenTypeMapping(K_DOUBLE_HYPHEN); TokenTypeMapping(POSIX_OPTION); TokenTypeMapping(GROUPED_OPTIONS); TokenTypeMapping(GNU_OPTION); TokenTypeMapping(ARGUMENT); TokenTypeMapping(DEFAULT_VALUE); TokenTypeMapping(COMMAND); TokenTypeMapping(GENERAL_ELEMENT); default: return TerminalType::OTHER; } } bool TokenHasValue(const TerminalType &type) { switch (type) { case TerminalType::POSIX_OPTION: case TerminalType::GROUPED_OPTIONS: case TerminalType::GNU_OPTION: case TerminalType::ARGUMENT: case TerminalType::DEFAULT_VALUE: case TerminalType::COMMAND: case TerminalType::GENERAL_ELEMENT: return true; default: return false; } } vector<Token> FromString(const string &text) { // TODO(huntzhan): handle invalid input. istringstream input_stream(text); ostringstream null_ostream; // Since `FlexGeneratedScanner` accepts istream as argument, // lexer->lex() would always return a token with TypeID::END when finished // processing `text`. FlexGeneratedScanner lexer(&input_stream, &null_ostream); vector<Token> tokens; while (true) { auto item = lexer.lex(); auto type_id = item.token(); auto terminal_type = ToTerminalType(type_id); if (type_id == TypeID::END) { // finish. break; } if (terminal_type == TerminalType::OTHER) { // terminals that would not be instaniation. continue; } // add token. if (TokenHasValue(terminal_type)) { const string &value = item.value.as<string>(); tokens.emplace_back(terminal_type, value); } else { tokens.emplace_back(terminal_type); } } return tokens; } } // namespace clidoc
[ "programmer.zhx@gmail.com" ]
programmer.zhx@gmail.com
92ca4fe41ab0ff3e9e50f1e6440d46149148f619
49576748e4106e0851c6af249e197179b52d656f
/src/node/connection_types.h
4eda07fc748b90b84708ba6811e0261e89cf11b6
[ "MIT" ]
permissive
umkoin/umkoin
6a0df0e8311f1d4f4326544615b692a4e294c038
56e5961d0c14b1ca1e615bca14d1eb2caa847ae3
refs/heads/master
2023-07-09T22:38:32.225678
2023-07-01T11:18:17
2023-07-01T11:18:17
112,662,902
7
6
MIT
2020-04-11T20:07:40
2017-11-30T21:34:13
C++
UTF-8
C++
false
false
3,514
h
// Copyright (c) 2022 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef UMKOIN_NODE_CONNECTION_TYPES_H #define UMKOIN_NODE_CONNECTION_TYPES_H #include <string> /** Different types of connections to a peer. This enum encapsulates the * information we have available at the time of opening or accepting the * connection. Aside from INBOUND, all types are initiated by us. * * If adding or removing types, please update CONNECTION_TYPE_DOC in * src/rpc/net.cpp and src/qt/rpcconsole.cpp, as well as the descriptions in * src/qt/guiutil.cpp and src/umkoin-cli.cpp::NetinfoRequestHandler. */ enum class ConnectionType { /** * Inbound connections are those initiated by a peer. This is the only * property we know at the time of connection, until P2P messages are * exchanged. */ INBOUND, /** * These are the default connections that we use to connect with the * network. There is no restriction on what is relayed; by default we relay * blocks, addresses & transactions. We automatically attempt to open * MAX_OUTBOUND_FULL_RELAY_CONNECTIONS using addresses from our AddrMan. */ OUTBOUND_FULL_RELAY, /** * We open manual connections to addresses that users explicitly requested * via the addnode RPC or the -addnode/-connect configuration options. Even if a * manual connection is misbehaving, we do not automatically disconnect or * add it to our discouragement filter. */ MANUAL, /** * Feeler connections are short-lived connections made to check that a node * is alive. They can be useful for: * - test-before-evict: if one of the peers is considered for eviction from * our AddrMan because another peer is mapped to the same slot in the tried table, * evict only if this longer-known peer is offline. * - move node addresses from New to Tried table, so that we have more * connectable addresses in our AddrMan. * Note that in the literature ("Eclipse Attacks on Umkoin’s Peer-to-Peer Network") * only the latter feature is referred to as "feeler connections", * although in our codebase feeler connections encompass test-before-evict as well. * We make these connections approximately every FEELER_INTERVAL: * first we resolve previously found collisions if they exist (test-before-evict), * otherwise we connect to a node from the new table. */ FEELER, /** * We use block-relay-only connections to help prevent against partition * attacks. By not relaying transactions or addresses, these connections * are harder to detect by a third party, thus helping obfuscate the * network topology. We automatically attempt to open * MAX_BLOCK_RELAY_ONLY_ANCHORS using addresses from our anchors.dat. Then * addresses from our AddrMan if MAX_BLOCK_RELAY_ONLY_CONNECTIONS * isn't reached yet. */ BLOCK_RELAY, /** * AddrFetch connections are short lived connections used to solicit * addresses from peers. These are initiated to addresses submitted via the * -seednode command line argument, or under certain conditions when the * AddrMan is empty. */ ADDR_FETCH, }; /** Convert ConnectionType enum to a string value */ std::string ConnectionTypeAsString(ConnectionType conn_type); #endif // UMKOIN_NODE_CONNECTION_TYPES_H
[ "vmta@yahoo.com" ]
vmta@yahoo.com
015cf0af87c7bde23771679cd3e8d104b1b93fb4
a12546f4f3ebeaeb142160ff5384be1f9c5c349f
/tests/unit_tests/test_tx_utils.cpp
55c76c3b6cd6da4379f8494d767be00dba1b8f17
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
FourtyTwo/42
851f171719ea74fcf63449949d9af0599f205a66
014e76d44803fbe32de2b219e0eb825c8626401f
refs/heads/master
2020-03-23T05:39:11.951950
2019-01-30T01:04:23
2019-01-30T01:04:23
141,158,382
4
4
NOASSERTION
2019-07-24T14:05:29
2018-07-16T15:33:04
C++
UTF-8
C++
false
false
11,748
cpp
// Copyright (c) 2014-2018, The Monero Project // // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are // permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other // materials provided with the distribution. // // 3. Neither the name of the copyright holder 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers #include "gtest/gtest.h" #include <vector> #include "common/util.h" #include "cryptonote_basic/cryptonote_basic.h" #include "cryptonote_basic/tx_extra.h" #include "cryptonote_core/cryptonote_tx_utils.h" namespace { uint64_t const TEST_FEE = 5000000000; // 5 * 10^9 } TEST(parse_tx_extra, handles_empty_extra) { std::vector<uint8_t> extra;; std::vector<cryptonote::tx_extra_field> tx_extra_fields; ASSERT_TRUE(cryptonote::parse_tx_extra(extra, tx_extra_fields)); ASSERT_TRUE(tx_extra_fields.empty()); } TEST(parse_tx_extra, handles_padding_only_size_1) { const uint8_t extra_arr[] = {0}; std::vector<uint8_t> extra(&extra_arr[0], &extra_arr[0] + sizeof(extra_arr)); std::vector<cryptonote::tx_extra_field> tx_extra_fields; ASSERT_TRUE(cryptonote::parse_tx_extra(extra, tx_extra_fields)); ASSERT_EQ(1, tx_extra_fields.size()); ASSERT_EQ(typeid(cryptonote::tx_extra_padding), tx_extra_fields[0].type()); ASSERT_EQ(1, boost::get<cryptonote::tx_extra_padding>(tx_extra_fields[0]).size); } TEST(parse_tx_extra, handles_padding_only_size_2) { const uint8_t extra_arr[] = {0, 0}; std::vector<uint8_t> extra(&extra_arr[0], &extra_arr[0] + sizeof(extra_arr)); std::vector<cryptonote::tx_extra_field> tx_extra_fields; ASSERT_TRUE(cryptonote::parse_tx_extra(extra, tx_extra_fields)); ASSERT_EQ(1, tx_extra_fields.size()); ASSERT_EQ(typeid(cryptonote::tx_extra_padding), tx_extra_fields[0].type()); ASSERT_EQ(2, boost::get<cryptonote::tx_extra_padding>(tx_extra_fields[0]).size); } TEST(parse_tx_extra, handles_padding_only_max_size) { std::vector<uint8_t> extra(TX_EXTRA_NONCE_MAX_COUNT, 0); std::vector<cryptonote::tx_extra_field> tx_extra_fields; ASSERT_TRUE(cryptonote::parse_tx_extra(extra, tx_extra_fields)); ASSERT_EQ(1, tx_extra_fields.size()); ASSERT_EQ(typeid(cryptonote::tx_extra_padding), tx_extra_fields[0].type()); ASSERT_EQ(TX_EXTRA_NONCE_MAX_COUNT, boost::get<cryptonote::tx_extra_padding>(tx_extra_fields[0]).size); } TEST(parse_tx_extra, handles_padding_only_exceed_max_size) { std::vector<uint8_t> extra(TX_EXTRA_NONCE_MAX_COUNT + 1, 0); std::vector<cryptonote::tx_extra_field> tx_extra_fields; ASSERT_FALSE(cryptonote::parse_tx_extra(extra, tx_extra_fields)); } TEST(parse_tx_extra, handles_invalid_padding_only) { std::vector<uint8_t> extra(2, 0); extra[1] = 42; std::vector<cryptonote::tx_extra_field> tx_extra_fields; ASSERT_FALSE(cryptonote::parse_tx_extra(extra, tx_extra_fields)); } TEST(parse_tx_extra, handles_pub_key_only) { const uint8_t extra_arr[] = {1, 30, 208, 98, 162, 133, 64, 85, 83, 112, 91, 188, 89, 211, 24, 131, 39, 154, 22, 228, 80, 63, 198, 141, 173, 111, 244, 183, 4, 149, 186, 140, 230}; std::vector<uint8_t> extra(&extra_arr[0], &extra_arr[0] + sizeof(extra_arr)); std::vector<cryptonote::tx_extra_field> tx_extra_fields; ASSERT_TRUE(cryptonote::parse_tx_extra(extra, tx_extra_fields)); ASSERT_EQ(1, tx_extra_fields.size()); ASSERT_EQ(typeid(cryptonote::tx_extra_pub_key), tx_extra_fields[0].type()); } TEST(parse_tx_extra, handles_extra_nonce_only) { const uint8_t extra_arr[] = {2, 1, 42}; std::vector<uint8_t> extra(&extra_arr[0], &extra_arr[0] + sizeof(extra_arr)); std::vector<cryptonote::tx_extra_field> tx_extra_fields; ASSERT_TRUE(cryptonote::parse_tx_extra(extra, tx_extra_fields)); ASSERT_EQ(1, tx_extra_fields.size()); ASSERT_EQ(typeid(cryptonote::tx_extra_nonce), tx_extra_fields[0].type()); cryptonote::tx_extra_nonce extra_nonce = boost::get<cryptonote::tx_extra_nonce>(tx_extra_fields[0]); ASSERT_EQ(1, extra_nonce.nonce.size()); ASSERT_EQ(42, extra_nonce.nonce[0]); } TEST(parse_tx_extra, handles_pub_key_and_padding) { const uint8_t extra_arr[] = {1, 30, 208, 98, 162, 133, 64, 85, 83, 112, 91, 188, 89, 211, 24, 131, 39, 154, 22, 228, 80, 63, 198, 141, 173, 111, 244, 183, 4, 149, 186, 140, 230, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; std::vector<uint8_t> extra(&extra_arr[0], &extra_arr[0] + sizeof(extra_arr)); std::vector<cryptonote::tx_extra_field> tx_extra_fields; ASSERT_TRUE(cryptonote::parse_tx_extra(extra, tx_extra_fields)); ASSERT_EQ(2, tx_extra_fields.size()); ASSERT_EQ(typeid(cryptonote::tx_extra_pub_key), tx_extra_fields[0].type()); ASSERT_EQ(typeid(cryptonote::tx_extra_padding), tx_extra_fields[1].type()); } TEST(parse_and_validate_tx_extra, is_valid_tx_extra_parsed) { cryptonote::transaction tx = AUTO_VAL_INIT(tx); cryptonote::account_base acc; acc.generate(); cryptonote::blobdata b = "dsdsdfsdfsf"; ASSERT_TRUE(cryptonote::construct_miner_tx(0, 0, 10000000000000, 1000, TEST_FEE, acc.get_keys().m_account_address, tx, b, 1)); crypto::public_key tx_pub_key = cryptonote::get_tx_pub_key_from_extra(tx); ASSERT_NE(tx_pub_key, crypto::null_pkey); } TEST(parse_and_validate_tx_extra, fails_on_big_extra_nonce) { cryptonote::transaction tx = AUTO_VAL_INIT(tx); cryptonote::account_base acc; acc.generate(); cryptonote::blobdata b(TX_EXTRA_NONCE_MAX_COUNT + 1, 0); ASSERT_FALSE(cryptonote::construct_miner_tx(0, 0, 10000000000000, 1000, TEST_FEE, acc.get_keys().m_account_address, tx, b, 1)); } TEST(parse_and_validate_tx_extra, fails_on_wrong_size_in_extra_nonce) { cryptonote::transaction tx = AUTO_VAL_INIT(tx); tx.extra.resize(20, 0); tx.extra[0] = TX_EXTRA_NONCE; tx.extra[1] = 255; std::vector<cryptonote::tx_extra_field> tx_extra_fields; ASSERT_FALSE(cryptonote::parse_tx_extra(tx.extra, tx_extra_fields)); } TEST(validate_parse_amount_case, validate_parse_amount) { uint64_t res = 0; bool r = cryptonote::parse_amount(res, "0.0001"); ASSERT_TRUE(r); ASSERT_EQ(res, 100000000); r = cryptonote::parse_amount(res, "100.0001"); ASSERT_TRUE(r); ASSERT_EQ(res, 100000100000000); r = cryptonote::parse_amount(res, "000.0000"); ASSERT_TRUE(r); ASSERT_EQ(res, 0); r = cryptonote::parse_amount(res, "0"); ASSERT_TRUE(r); ASSERT_EQ(res, 0); r = cryptonote::parse_amount(res, " 100.0001 "); ASSERT_TRUE(r); ASSERT_EQ(res, 100000100000000); r = cryptonote::parse_amount(res, " 100.0000 "); ASSERT_TRUE(r); ASSERT_EQ(res, 100000000000000); r = cryptonote::parse_amount(res, " 100. 0000 "); ASSERT_FALSE(r); r = cryptonote::parse_amount(res, "100. 0000"); ASSERT_FALSE(r); r = cryptonote::parse_amount(res, "100 . 0000"); ASSERT_FALSE(r); r = cryptonote::parse_amount(res, "100.00 00"); ASSERT_FALSE(r); r = cryptonote::parse_amount(res, "1 00.00 00"); ASSERT_FALSE(r); } TEST(sort_tx_extra, empty) { std::vector<uint8_t> extra, sorted; ASSERT_TRUE(cryptonote::sort_tx_extra(extra, sorted)); ASSERT_EQ(extra, sorted); } TEST(sort_tx_extra, pubkey) { std::vector<uint8_t> sorted; const uint8_t extra_arr[] = {1, 30, 208, 98, 162, 133, 64, 85, 83, 112, 91, 188, 89, 211, 24, 131, 39, 154, 22, 228, 80, 63, 198, 141, 173, 111, 244, 183, 4, 149, 186, 140, 230}; std::vector<uint8_t> extra(&extra_arr[0], &extra_arr[0] + sizeof(extra_arr)); ASSERT_TRUE(cryptonote::sort_tx_extra(extra, sorted)); ASSERT_EQ(extra, sorted); } TEST(sort_tx_extra, two_pubkeys) { std::vector<uint8_t> sorted; const uint8_t extra_arr[] = {1, 30, 208, 98, 162, 133, 64, 85, 83, 112, 91, 188, 89, 211, 24, 131, 39, 154, 22, 228, 80, 63, 198, 141, 173, 111, 244, 183, 4, 149, 186, 140, 230, 1, 30, 208, 98, 162, 133, 64, 85, 83, 112, 91, 188, 89, 211, 24, 131, 39, 154, 22, 228, 80, 63, 198, 141, 173, 111, 244, 183, 4, 149, 186, 140, 230}; std::vector<uint8_t> extra(&extra_arr[0], &extra_arr[0] + sizeof(extra_arr)); ASSERT_TRUE(cryptonote::sort_tx_extra(extra, sorted)); ASSERT_EQ(extra, sorted); } TEST(sort_tx_extra, keep_order) { std::vector<uint8_t> sorted; const uint8_t extra_arr[] = {1, 30, 208, 98, 162, 133, 64, 85, 83, 112, 91, 188, 89, 211, 24, 131, 39, 154, 22, 228, 80, 63, 198, 141, 173, 111, 244, 183, 4, 149, 186, 140, 230, 2, 9, 1, 0, 0, 0, 0, 0, 0, 0, 0}; std::vector<uint8_t> extra(&extra_arr[0], &extra_arr[0] + sizeof(extra_arr)); ASSERT_TRUE(cryptonote::sort_tx_extra(extra, sorted)); ASSERT_EQ(extra, sorted); } TEST(sort_tx_extra, switch_order) { std::vector<uint8_t> sorted; const uint8_t extra_arr[] = {2, 9, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 30, 208, 98, 162, 133, 64, 85, 83, 112, 91, 188, 89, 211, 24, 131, 39, 154, 22, 228, 80, 63, 198, 141, 173, 111, 244, 183, 4, 149, 186, 140, 230}; const uint8_t expected_arr[] = {1, 30, 208, 98, 162, 133, 64, 85, 83, 112, 91, 188, 89, 211, 24, 131, 39, 154, 22, 228, 80, 63, 198, 141, 173, 111, 244, 183, 4, 149, 186, 140, 230, 2, 9, 1, 0, 0, 0, 0, 0, 0, 0, 0}; std::vector<uint8_t> extra(&extra_arr[0], &extra_arr[0] + sizeof(extra_arr)); ASSERT_TRUE(cryptonote::sort_tx_extra(extra, sorted)); std::vector<uint8_t> expected(&expected_arr[0], &expected_arr[0] + sizeof(expected_arr)); ASSERT_EQ(expected, sorted); } TEST(sort_tx_extra, invalid) { std::vector<uint8_t> sorted; const uint8_t extra_arr[] = {1}; std::vector<uint8_t> extra(&extra_arr[0], &extra_arr[0] + sizeof(extra_arr)); ASSERT_FALSE(cryptonote::sort_tx_extra(extra, sorted)); } TEST(sort_tx_extra, invalid_suffix_strict) { std::vector<uint8_t> sorted; const uint8_t extra_arr[] = {2, 9, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1}; std::vector<uint8_t> extra(&extra_arr[0], &extra_arr[0] + sizeof(extra_arr)); ASSERT_FALSE(cryptonote::sort_tx_extra(extra, sorted)); } TEST(sort_tx_extra, invalid_suffix_partial) { std::vector<uint8_t> sorted; const uint8_t extra_arr[] = {2, 9, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1}; const uint8_t expected_arr[] = {2, 9, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1}; std::vector<uint8_t> extra(&extra_arr[0], &extra_arr[0] + sizeof(extra_arr)); ASSERT_TRUE(cryptonote::sort_tx_extra(extra, sorted, true)); std::vector<uint8_t> expected(&expected_arr[0], &expected_arr[0] + sizeof(expected_arr)); ASSERT_EQ(sorted, expected); }
[ "33090942+System96@users.noreply.github.com" ]
33090942+System96@users.noreply.github.com
2684f9c7f8b1d2bb90238def157dd7620cbc5908
ebb8d7c5181d6b2119b3116497d4167390bd09ca
/scalar/include/cuda_timing.h
eb182c14155c8ba9071d08bedd8eaece449fe1a8
[ "BSD-3-Clause" ]
permissive
TobyFlynn/tridsolver
1cd83096c064ee21a3ede05001c7aeb574e8e60e
234eab0917f256cd2f8b6215cd588d5aa52b9f3f
refs/heads/master
2020-12-20T00:21:49.912322
2020-08-17T07:50:22
2020-08-17T07:50:22
235,896,697
0
0
null
2020-01-23T22:09:42
2020-01-23T22:09:41
null
UTF-8
C++
false
false
2,794
h
#ifndef CUDA_TIMING_H_INCLUDED #define CUDA_TIMING_H_INCLUDED // Written by Gabor Daniel Balogh, Pazmany Peter Catholic University 2020 // TODO merge with timing.h #include <chrono> #include <map> #include <vector> #include <iostream> #include "cutil_inline.h" #include <nvToolsExt.h> class Timing { using clock = std::chrono::high_resolution_clock; using time_point = clock::time_point; struct LoopData { int index = 0; int parent = 0; double time = 0.0; time_point current; std::vector<cudaEvent_t> event_pairs; }; std::string name; static std::map<std::string, LoopData> loops; static std::vector<int> stack; static int counter; static void sumCudaEvents(); static void reportWithParent(int parent, const std::string &indentation); public: explicit Timing(std::string &&name_p) : name(std::move(name_p)) { startTimer(name); } ~Timing() { stopTimer(name); } static void startTimer(const std::string &_name); static void stopTimer(const std::string &_name); static void startTimerCUDA(const std::string &_name, cudaStream_t stream); static void stopTimerCUDA(const std::string &_name, cudaStream_t stream); static void pushRange(const std::string &_name); static void popRange(); static void markStart(const std::string &_name); static void report(); }; #if PROFILING # define BEGIN_PROFILING(name) Timing::startTimer(name) # define END_PROFILING(name) Timing::stopTimer(name) # define BEGIN_PROFILING_CUDA(name,stream) Timing::startTimerCUDA(name,stream) # define END_PROFILING_CUDA(name,stream) Timing::stopTimerCUDA(name,stream) # define PROFILE_SCOPE(name) Timing timer##__LINE__(name) # define PROFILE_FUNCTION() PROFILE_SCOPE(__FUNCTION__) # define PROFILE_REPORT() Timing::report() # if PROFILING > 1 # define BEGIN_PROFILING2(name) BEGIN_PROFILING(name) # define END_PROFILING2(name) END_PROFILING(name) # define BEGIN_PROFILING_CUDA2(name,stream) BEGIN_PROFILING_CUDA(name,stream) # define END_PROFILING_CUDA2(name,stream) END_PROFILING_CUDA(name,stream) # else # define BEGIN_PROFILING2(name) Timing::pushRange(name) # define END_PROFILING2(name) Timing::popRange() # define BEGIN_PROFILING_CUDA2(name,stream) Timing::markStart(name) # define END_PROFILING_CUDA2(name,stream) # endif #else # define BEGIN_PROFILING(name) # define END_PROFILING(name) # define BEGIN_PROFILING_CUDA(name,stream) # define END_PROFILING_CUDA(name,stream) # define BEGIN_PROFILING2(name) # define END_PROFILING2(name) # define BEGIN_PROFILING_CUDA2(name,stream) # define END_PROFILING_CUDA2(name,stream) # define PROFILE_SCOPE(name) # define PROFILE_FUNCTION() # define PROFILE_REPORT() #endif #endif /* ifndef CUDA_TIMING_H_INCLUDED */
[ "regulyistvan@gmail.com" ]
regulyistvan@gmail.com
0902603a6116199a8c972d8f11b7538ae5082cd0
34787af69dac9a8df1ec2d94eadf2e74cfb24607
/src/learning/concept-check/src/impl/VOID.hpp
48d5bfa18b2bead2a9d192f0994f420e197441e4
[ "MIT" ]
permissive
NobodyXu/snippet
edd5cfbbe586d5e1409a8375db235265d8b09370
8f0308e48dab1d166dc9e5ff43b00db2d35b616b
refs/heads/master
2021-07-11T11:14:51.870194
2020-05-28T01:42:41
2020-05-28T01:42:41
134,259,240
1
0
null
null
null
null
UTF-8
C++
false
false
143
hpp
#ifndef __concept_check_VOID_HPP__ #define __concept_check_VOID_HPP__ namespace concept_check { struct VOID; }//namespace concept_check #endif
[ "johnxujiahao2000@gmail.com" ]
johnxujiahao2000@gmail.com
c0e498048eadf9eb8cea87ecac2af9e65c8a5796
ccf5cd20ab4f6a0a8faad23ecb877101355737a5
/cxx-cloth-simulation/CameraController.h
4d48f4d661b93494083c442559ffb80ec56c5f67
[]
no_license
creizyz/cxx-cloth-simulation-old
7f9a364428793664a79fce3f4d851f8d6b73042a
da4aa3ae1312b5d405fe451b020725cd8dec40ad
refs/heads/master
2020-06-28T19:22:59.333967
2019-08-03T02:27:12
2019-08-03T02:27:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,177
h
#pragma once #include "Camera.h" typedef enum { MOVE_UP = 0, MOVE_DOWN = 1, MOVE_LEFT = 2, MOVE_RIGHT = 3, MOVE_FORWARD = 4, MOVE_BACKWARD = 5, ZOOM_IN = 6, ZOOM_OUT = 7, ROTATION_X_CW = 8, ROTATION_Y_CW = 9, ROTATION_X_CCW = 10, ROTATION_Y_CCW = 11, CENTER_VIEW = 12 } CAMERA_ACTION; #define COUNT_CAMERA_ACTIONS 13 class CameraController { public: CameraController(Camera3D & c) : camera(c) { clear_logs(); actionkey[MOVE_FORWARD] = GLFW_KEY_W; actionkey[MOVE_BACKWARD] = GLFW_KEY_S; actionkey[MOVE_LEFT] = GLFW_KEY_A; actionkey[MOVE_RIGHT] = GLFW_KEY_D; actionkey[MOVE_UP] = GLFW_KEY_R; actionkey[MOVE_DOWN] = GLFW_KEY_F; actionkey[ROTATION_Y_CCW] = GLFW_KEY_LEFT; actionkey[ROTATION_Y_CW] = GLFW_KEY_RIGHT; actionkey[ROTATION_X_CCW] = GLFW_KEY_DOWN; actionkey[ROTATION_X_CW] = GLFW_KEY_UP; actionkey[CENTER_VIEW] = GLFW_KEY_SPACE; actionkey[ZOOM_IN] = GLFW_KEY_1; actionkey[ZOOM_OUT] = GLFW_KEY_2; } void init_speeds(float Ts, float Rs, float Zs) { T_speed = Ts; R_speed = Rs; Z_speed = Zs; } void init_camera(float fov, float aspect, float near, float far) { camera.set_fieldOfView(fov); camera.set_nearAndFarPlane(near, far); camera.set_viewportAspect(aspect); } void log_action(CAMERA_ACTION a) { log[a] = true; } void unlog_action(CAMERA_ACTION a) { log[a] = false; } void clear_logs() { for (int i = 0; i < COUNT_CAMERA_ACTIONS; i++) log[i] = false; } void update_camera(float dT) { // TRANSLATION math::vec3 T_res(0.f, 0.f, 0.f); if (log[MOVE_UP] && !log[MOVE_DOWN]) T_res += math::vec3(0.f, -1.f, 0.f); else if (log[MOVE_DOWN]) T_res += math::vec3(0.f, 1.f, 0.f); if (log[MOVE_LEFT] && !log[MOVE_RIGHT]) T_res += math::vec3(-1.f, 0.f, 0.f); else if (log[MOVE_RIGHT]) T_res += math::vec3(1.f, 0.f, 0.f); if (log[MOVE_FORWARD] && !log[MOVE_BACKWARD]) T_res += math::vec3(0.f, 0.f, -1.f); else if (log[MOVE_BACKWARD]) T_res += math::vec3(0.f, 0.f, 1.f); camera.translate(T_res * (T_speed * dT)); // ZOOM if (log[ZOOM_IN] && !log[ZOOM_OUT]) camera.increase_fieldOfView(Z_speed * dT); else if (log[ZOOM_OUT]) camera.increase_fieldOfView(-Z_speed * dT); // ROTATION float rX = 0.f; if (log[ROTATION_X_CW] && !log[ROTATION_X_CCW]) rX += R_speed * dT; else if (log[ROTATION_X_CCW]) rX -= R_speed * dT; float rY = 0.f; if (log[ROTATION_Y_CW] && !log[ROTATION_Y_CCW]) rY += R_speed * dT; else if (log[ROTATION_Y_CCW]) rY -= R_speed * dT; camera.rotate(rX, rY); // CENTER VIEW if (log[CENTER_VIEW]) camera.look_at(math::vec3(0.f, 0.f, 0.f)); } int actionkey[COUNT_CAMERA_ACTIONS]; private: Camera3D & camera; float T_speed; float R_speed; float Z_speed; bool log[COUNT_CAMERA_ACTIONS]; };
[ "remilaot@gmail.com" ]
remilaot@gmail.com
055c97b703560d6c8f67659d78170abfbc66fabd
dda4531ec8bc9a0f34a16b66e0540504578b4385
/hammer/mapcheckdlg.cpp
1837587a4d4df1804f5734e5d7cadba4cba2226f
[]
no_license
Smaedd/sdk-2013-hammer
0159d5548e36c268fb3c769e784e050062ff3362
944d9be016476e0574aa3b7e0d6f9128a395fe4c
refs/heads/master
2022-12-07T05:27:11.526994
2020-08-18T10:43:22
2020-08-18T10:43:22
287,728,916
0
0
null
2020-08-15T10:55:05
2020-08-15T10:55:04
null
WINDOWS-1252
C++
false
false
44,771
cpp
//========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============// // // Purpose: // //=============================================================================// #include "stdafx.h" #include "GameConfig.h" #include "GlobalFunctions.h" #include "History.h" #include "MainFrm.h" #include "MapCheckDlg.h" #include "MapDoc.h" #include "MapEntity.h" #include "MapSolid.h" #include "MapWorld.h" #include "Options.h" #include "ToolManager.h" #include "VisGroup.h" #include "hammer.h" #include "MapOverlay.h" #include "Selection.h" // memdbgon must be the last include file in a .cpp file!!! #include <tier0/memdbgon.h> // ******** // NOTE: Make sure the order matches g_MapErrorStringIDs below! // ******** typedef enum { ErrorNoPlayerStart, ErrorMixedFace, ErrorDuplicatePlanes, ErrorMissingTarget, ErrorInvalidTexture, ErrorSolidStructure, ErrorUnusedKeyvalues, ErrorEmptyEntity, ErrorDuplicateKeys, ErrorInvalidTextureAxes, ErrorDuplicateFaceIDs, ErrorDuplicateNodeIDs, ErrorBadConnections, ErrorHiddenGroupHiddenChildren, ErrorHiddenGroupVisibleChildren, ErrorHiddenGroupMixedChildren, ErrorHiddenObjectNoVisGroup, ErrorHiddenChildOfEntity, ErrorIllegallyHiddenObject, ErrorKillInputRaceCondition, ErrorOverlayFaceList, } MapErrorType; // ******** // NOTE: Make sure the order matches MapErrorType above! // ******** struct { int m_StrResourceID; int m_DescriptionResourceID; } g_MapErrorStrings[] = { {IDS_NOPLAYERSTART, IDS_NOPLAYERSTART_DESC}, {IDS_MIXEDFACES, IDS_MIXEDFACES_DESC}, {IDS_DUPLICATEPLANES, IDS_DUPLICATEPLANES_DESC}, {IDS_UNMATCHEDTARGET, IDS_UNMATCHEDTARGET_DESC}, {IDS_INVALIDTEXTURE, IDS_INVALIDTEXTURE_DESC}, {IDS_SOLIDSTRUCTURE, IDS_SOLIDSTRUCTURE_DESC}, {IDS_UNUSEDKEYVALUES, IDS_UNUSEDKEYVALUES_DESC}, {IDS_EMPTYENTITY, IDS_EMPTYENTITY_DESC}, {IDS_DUPLICATEKEYS, IDS_DUPLICATEKEYS_DESC}, {IDS_SOLIDCONTENT, IDS_SOLIDCONTENT_DESC}, {IDS_INVALIDTEXTUREAXES, IDS_INVALIDTEXTUREAXES_DESC}, {IDS_DUPLICATEFACEID, IDS_DUPLICATEFACEID_DESC}, {IDS_DUPLICATE_NODE_ID, IDS_DUPLICATE_NODE_ID_DESC}, {IDS_BAD_CONNECTIONS, IDS_BAD_CONNECTIONS_DESC}, {IDS_HIDDEN_GROUP_HIDDEN_CHILDREN, IDS_HIDDEN_GROUP_HIDDEN_CHILDREN_DESC}, {IDS_HIDDEN_GROUP_VISIBLE_CHILDREN, IDS_HIDDEN_GROUP_VISIBLE_CHILDREN_DESC}, {IDS_HIDDEN_GROUP_MIXED_CHILDREN, IDS_HIDDEN_GROUP_MIXED_CHILDREN_DESC}, {IDS_HIDDEN_NO_VISGROUP, IDS_HIDDEN_NO_VISGROUP_DESC}, {IDS_HIDDEN_CHILD_OF_ENTITY, IDS_HIDDEN_CHILD_OF_ENTITY_DESC}, {IDS_HIDDEN_ILLEGALLY, IDS_HIDDEN_ILLEGALLY_DESC}, {IDS_KILL_INPUT_RACE_CONDITION, IDS_KILL_INPUT_RACE_CONDITION_DESC}, {IDS_BAD_OVERLAY, IDS_DAB_OVERLAY_DESC} }; typedef enum { CantFix, NeedsFix, Fixed, } FIXCODE; struct MapError { CMapClass *pObjects[3]; MapErrorType Type; DWORD dwExtra; FIXCODE Fix; }; // // Fix functions. // static void FixDuplicatePlanes(MapError *pError); static void FixSolidStructure(MapError *pError); static void FixInvalidTexture(MapError *pError); static void FixInvalidTextureAxes(MapError *pError); static void FixUnusedKeyvalues(MapError *pError); static void FixEmptyEntity(MapError *pError); static void FixBadConnections(MapError *pError); static void FixDuplicateFaceIDs(MapError *pError); static void FixDuplicateNodeIDs(MapError *pError); static void FixMissingTarget(MapError *pError); void FixHiddenObject(MapError *pError); static void FixKillInputRaceCondition(MapError *pError); static void FixOverlayFaceList(MapError *pError); CMapCheckDlg *s_pDlg = NULL; BEGIN_MESSAGE_MAP(CMapCheckDlg, CDialog) //{{AFX_MSG_MAP(CMapCheckDlg) ON_BN_CLICKED(IDC_GO, OnGo) ON_LBN_SELCHANGE(IDC_ERRORS, OnSelchangeErrors) ON_LBN_DBLCLK(IDC_ERRORS, OnDblClkErrors) ON_WM_PAINT() ON_BN_CLICKED(IDC_FIX, OnFix) ON_BN_CLICKED(IDC_FIXALL, OnFixall) ON_WM_DESTROY() ON_WM_CLOSE() ON_BN_CLICKED(IDC_CHECK_VISIBLE_ONLY, OnCheckVisibleOnly) //}}AFX_MSG_MAP END_MESSAGE_MAP() //----------------------------------------------------------------------------- // Visibility check //----------------------------------------------------------------------------- inline bool IsCheckVisible( CMapClass *pClass ) { return (Options.general.bCheckVisibleMapErrors == FALSE) || pClass->IsVisible(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CMapCheckDlg::CheckForProblems(CWnd *pwndParent) { if (!s_pDlg) { s_pDlg = new CMapCheckDlg; s_pDlg->Create(IDD, pwndParent); } if (!s_pDlg->DoCheck()) { // Found problems. s_pDlg->ShowWindow(SW_SHOW); } } //----------------------------------------------------------------------------- // Purpose: // Input : pParent - //----------------------------------------------------------------------------- CMapCheckDlg::CMapCheckDlg(CWnd *pParent) : CDialog(CMapCheckDlg::IDD, pParent) { //{{AFX_DATA_INIT(CMapCheckDlg) m_bCheckVisible = FALSE; //}}AFX_DATA_INIT m_bCheckVisible = Options.general.bCheckVisibleMapErrors; } //----------------------------------------------------------------------------- // Purpose: // Input : pDX - //----------------------------------------------------------------------------- void CMapCheckDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CMapCheckDlg) DDX_Control(pDX, IDC_FIXALL, m_cFixAll); DDX_Control(pDX, IDC_FIX, m_Fix); DDX_Control(pDX, IDC_GO, m_Go); DDX_Control(pDX, IDC_DESCRIPTION, m_Description); DDX_Control(pDX, IDC_ERRORS, m_Errors); DDX_Check(pDX, IDC_CHECK_VISIBLE_ONLY, m_bCheckVisible); //}}AFX_DATA_MAP if ( pDX->m_bSaveAndValidate ) { Options.general.bCheckVisibleMapErrors = m_bCheckVisible; } } //----------------------------------------------------------------------------- // Checkbox indicating whether we should check visible errors //----------------------------------------------------------------------------- void CMapCheckDlg::OnCheckVisibleOnly() { UpdateData( TRUE ); DoCheck(); } //----------------------------------------------------------------------------- // Purpose: Selects the current error objects and centers the views on it. //----------------------------------------------------------------------------- void CMapCheckDlg::OnGo() { GotoSelectedErrors(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CMapCheckDlg::GotoSelectedErrors() { int iSel = m_Errors.GetCurSel(); if (iSel == LB_ERR) { return; } ToolManager()->SetTool(TOOL_POINTER); CMapObjectList Objects; for (int i = 0; i < m_Errors.GetCount(); i++) { if (m_Errors.GetSel(i) > 0) { MapError *pError = (MapError *)m_Errors.GetItemDataPtr(i); if (pError) { Objects.AddToTail(pError->pObjects[0]); } } } CMapDoc *pDoc = CMapDoc::GetActiveMapDoc(); pDoc->SelectObjectList(&Objects); pDoc->CenterViewsOnSelection(); } //----------------------------------------------------------------------------- // Purpose: Fixes all the selected errors. //----------------------------------------------------------------------------- void CMapCheckDlg::OnFix() { int iSel = m_Errors.GetCurSel(); if (iSel == LB_ERR) { return; } UpdateBox ub; CMapObjectList Objects; ub.Objects = &Objects; for (int i = 0; i < m_Errors.GetCount(); i++) { if (m_Errors.GetSel(i) > 0) { MapError *pError = (MapError *)m_Errors.GetItemDataPtr(i); if (pError) { Fix(pError, ub); } } } OnSelchangeErrors(); CMapDoc::GetActiveMapDoc()->UpdateAllViews( MAPVIEW_UPDATE_OBJECTS ); } //----------------------------------------------------------------------------- // Purpose: // Input : pError - // ub - //----------------------------------------------------------------------------- void CMapCheckDlg::Fix(MapError *pError, UpdateBox &ub) { CMapDoc::GetActiveMapDoc()->SetModifiedFlag(); if (pError->Fix != NeedsFix) { // should never get here because this button is supposed // to be disabled if the error cannot be fixed return; } // // Expand the bounds of the update region to include the broken objects. // for (int i = 0; i < 2; i++) { if (!pError->pObjects[i]) { continue; } ub.Objects->AddToTail(pError->pObjects[i]); Vector mins; Vector maxs; pError->pObjects[i]->GetRender2DBox(mins, maxs); ub.Box.UpdateBounds(mins, maxs); } // // Perform the fix. // switch (pError->Type) { case ErrorDuplicatePlanes: { FixDuplicatePlanes(pError); break; } case ErrorDuplicateFaceIDs: { FixDuplicatePlanes(pError); break; } case ErrorDuplicateNodeIDs: { FixDuplicateNodeIDs(pError); break; } case ErrorMissingTarget: { FixMissingTarget(pError); break; } case ErrorSolidStructure: { FixSolidStructure(pError); break; } case ErrorInvalidTexture: { FixInvalidTexture(pError); break; } case ErrorInvalidTextureAxes: { FixInvalidTextureAxes(pError); break; } case ErrorUnusedKeyvalues: { FixUnusedKeyvalues(pError); break; } case ErrorBadConnections: { FixBadConnections(pError); break; } case ErrorEmptyEntity: { FixEmptyEntity(pError); break; } case ErrorHiddenGroupVisibleChildren: case ErrorHiddenGroupMixedChildren: case ErrorHiddenGroupHiddenChildren: case ErrorHiddenObjectNoVisGroup: case ErrorHiddenChildOfEntity: case ErrorIllegallyHiddenObject: { FixHiddenObject(pError); break; } case ErrorKillInputRaceCondition: { FixKillInputRaceCondition(pError); break; } case ErrorOverlayFaceList: { FixOverlayFaceList( pError ); break; } } pError->Fix = Fixed; // // Expand the bounds of the update region to include the fixed objects. // for (int i = 0; i < 2; i++) { if (!pError->pObjects[i]) { continue; } Vector mins; Vector maxs; pError->pObjects[i]->GetRender2DBox(mins, maxs); ub.Box.UpdateBounds(mins, maxs); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CMapCheckDlg::OnFixall() { int iSel = m_Errors.GetCurSel(); if (iSel == LB_ERR) { return; } MapError *pError = (MapError *) m_Errors.GetItemDataPtr(iSel); if (pError->Fix == CantFix) { // should never get here because this button is supposed // to be disabled if the error cannot be fixed return; } UpdateBox ub; CMapObjectList Objects; ub.Objects = &Objects; // For every selected error... for (int i = 0; i < m_Errors.GetCount(); i++) { if (m_Errors.GetSel(i) > 0) { MapError *pError = (MapError *)m_Errors.GetItemDataPtr(i); if ((pError) && (pError->Fix == NeedsFix)) { // Find and fix every error of the same type. for (int j = 0; j < m_Errors.GetCount(); j++) { MapError *pError2 = (MapError *)m_Errors.GetItemDataPtr(j); if ((pError2->Type != pError->Type) || (pError2->Fix != NeedsFix)) { continue; } Fix(pError2, ub); } } } } OnSelchangeErrors(); CMapDoc::GetActiveMapDoc()->UpdateAllViews( MAPVIEW_UPDATE_OBJECTS ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CMapCheckDlg::OnSelchangeErrors() { // change description to match error int iSel = m_Errors.GetCurSel(); if(iSel == LB_ERR) { m_Fix.EnableWindow(FALSE); m_cFixAll.EnableWindow(FALSE); m_Go.EnableWindow(FALSE); } CString str; MapError *pError; pError = (MapError*) m_Errors.GetItemDataPtr(iSel); // Figure out which error string we're using. int iErrorStr = (int)pError->Type; iErrorStr = clamp( iErrorStr, 0, ARRAYSIZE( g_MapErrorStrings ) - 1 ); Assert( iErrorStr == (int)pError->Type ); str.LoadString(g_MapErrorStrings[iErrorStr].m_DescriptionResourceID); m_Description.SetWindowText(str); m_Go.EnableWindow(pError->pObjects[0] != NULL); // set state of fix button m_Fix.EnableWindow(pError->Fix == NeedsFix); m_cFixAll.EnableWindow(pError->Fix != CantFix); // set text of fix button switch (pError->Fix) { case NeedsFix: m_Fix.SetWindowText("&Fix"); break; case CantFix: m_Fix.SetWindowText("Can't fix"); break; case Fixed: m_Fix.SetWindowText("(fixed)"); break; } CMapDoc *pDoc = CMapDoc::GetActiveMapDoc(); pDoc->GetSelection()->SetMode(selectObjects); if (pError->pObjects[0]) { pDoc->SelectObject(pError->pObjects[0], scClear|scSelect|scSaveChanges ); } else { pDoc->SelectObject(NULL, scClear|scSaveChanges ); } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CMapCheckDlg::OnDblClkErrors() { GotoSelectedErrors(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CMapCheckDlg::OnPaint() { CPaintDC dc(this); // device context for painting } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CMapCheckDlg::KillErrorList() { // delete items in list.. their data ptrs are allocated objects int iSize = m_Errors.GetCount(); for(int i = 0; i < iSize; i++) { MapError *pError = (MapError*) m_Errors.GetItemDataPtr(i); delete pError; } m_Errors.ResetContent(); } //----------------------------------------------------------------------------- // Purpose: Builds the listbox string for the given error and adds it to the list. //----------------------------------------------------------------------------- static void AddErrorToListBox(CListBox *pList, MapError *pError) { CString str; // Figure out which error string we're using. int iErrorStr = (int)pError->Type; iErrorStr = clamp( iErrorStr, 0, ARRAYSIZE( g_MapErrorStrings ) - 1 ); Assert( iErrorStr == (int)pError->Type ); str.LoadString(g_MapErrorStrings[iErrorStr].m_StrResourceID); if (str.Find('%') != -1) { if (pError->Type == ErrorUnusedKeyvalues) { // dwExtra has the name of the string in it CString str2 = str; CMapEntity *pEntity = (CMapEntity *)pError->pObjects[0]; str.Format(str2, pEntity->GetClassName(), pError->dwExtra); } else { CString str2 = str; str.Format(str2, pError->dwExtra); } } int iIndex = pList->AddString(str); pList->SetItemDataPtr(iIndex, (PVOID)pError); } //----------------------------------------------------------------------------- // Purpose: // Input : pList - // Type - // dwExtra - // ... - //----------------------------------------------------------------------------- static void AddError(CListBox *pList, MapErrorType Type, DWORD dwExtra, ...) { MapError *pError = new MapError; memset(pError, 0, sizeof(MapError)); pError->Type = Type; pError->dwExtra = dwExtra; pError->Fix = CantFix; va_list vl; va_start(vl, dwExtra); // // Get the object pointer from the variable argument list. // switch (Type) { case ErrorNoPlayerStart: { // no objects. break; } case ErrorMixedFace: case ErrorMissingTarget: case ErrorDuplicatePlanes: case ErrorDuplicateFaceIDs: case ErrorDuplicateNodeIDs: case ErrorSolidStructure: case ErrorInvalidTexture: case ErrorUnusedKeyvalues: case ErrorBadConnections: case ErrorEmptyEntity: case ErrorDuplicateKeys: case ErrorInvalidTextureAxes: case ErrorHiddenGroupHiddenChildren: case ErrorHiddenGroupVisibleChildren: case ErrorHiddenGroupMixedChildren: case ErrorHiddenObjectNoVisGroup: case ErrorHiddenChildOfEntity: case ErrorIllegallyHiddenObject: case ErrorOverlayFaceList: { pError->pObjects[0] = va_arg(vl, CMapClass *); break; } case ErrorKillInputRaceCondition: { pError->pObjects[0] = va_arg(vl, CMapClass *); pError->dwExtra = (DWORD)va_arg(vl, CEntityConnection *); break; } } // // Set the can fix flag. // switch (Type) { case ErrorDuplicatePlanes: case ErrorDuplicateFaceIDs: case ErrorDuplicateNodeIDs: case ErrorSolidStructure: case ErrorInvalidTexture: case ErrorUnusedKeyvalues: case ErrorMissingTarget: case ErrorBadConnections: case ErrorEmptyEntity: case ErrorDuplicateKeys: case ErrorInvalidTextureAxes: case ErrorHiddenGroupHiddenChildren: case ErrorHiddenGroupVisibleChildren: case ErrorHiddenGroupMixedChildren: case ErrorHiddenObjectNoVisGroup: case ErrorHiddenChildOfEntity: case ErrorIllegallyHiddenObject: case ErrorKillInputRaceCondition: case ErrorOverlayFaceList: { pError->Fix = NeedsFix; break; } } va_end(vl); AddErrorToListBox(pList, pError); } //----------------------------------------------------------------------------- // Purpose: // Input : pObject - // DWORD - // Output : //----------------------------------------------------------------------------- static BOOL FindPlayer(CMapEntity *pObject, DWORD*) { if ( !IsCheckVisible( pObject ) ) return TRUE; if (pObject->IsPlaceholder() && pObject->IsClass("info_player_start")) { return(FALSE); } return(TRUE); } //----------------------------------------------------------------------------- // Purpose: // Input : pList - // pWorld - //----------------------------------------------------------------------------- static void CheckRequirements(CListBox *pList, CMapWorld *pWorld) { // ensure there's a player start .. if (pWorld->EnumChildren(FindPlayer, (DWORD*)NULL, MAPCLASS_TYPE(CMapEntity))) { // if rvl is !0, it was not stopped prematurely.. which means there is // NO player start. AddError(pList, ErrorNoPlayerStart, 0); } } //----------------------------------------------------------------------------- // Purpose: // Input : pSolid - // pList - // Output : //----------------------------------------------------------------------------- static BOOL _CheckMixedFaces(CMapSolid *pSolid, CListBox *pList) { if ( !IsCheckVisible( pSolid ) ) return TRUE; // run thru faces.. int iFaces = pSolid->GetFaceCount(); int iSolid = 2; // start off ambivalent int i; for(i = 0; i < iFaces; i++) { CMapFace *pFace = pSolid->GetFace(i); char ch = pFace->texture.texture[0]; if((ch == '*' && iSolid == 1) || (ch != '*' && iSolid == 0)) { break; } else iSolid = (ch == '*') ? 0 : 1; } if(i == iFaces) // all ok return TRUE; // NOT ok AddError(pList, ErrorMixedFace, 0, pSolid); return TRUE; } static void CheckMixedFaces(CListBox *pList, CMapWorld *pWorld) { pWorld->EnumChildren(_CheckMixedFaces, pList, MAPCLASS_TYPE(CMapSolid)); } //----------------------------------------------------------------------------- // Purpose: Returns true if there is another node entity in the world with the // same node ID as the given entity. // Input : pNode - // pWorld - //----------------------------------------------------------------------------- bool FindDuplicateNodeID(CMapEntity *pNode, CMapWorld *pWorld) { if ( !IsCheckVisible( pNode ) ) return false; EnumChildrenPos_t pos; CMapClass *pChild = pWorld->GetFirstDescendent(pos); while (pChild != NULL) { CMapEntity *pEntity = dynamic_cast<CMapEntity *>(pChild); if (pEntity && IsCheckVisible( pEntity ) && (pEntity != pNode) && pEntity->IsNodeClass()) { int nNodeID1 = pNode->GetNodeID(); int nNodeID2 = pEntity->GetNodeID(); if ((nNodeID1 != 0) && (nNodeID2 != 0) && (nNodeID1 == nNodeID2)) { return true; } } pChild = pWorld->GetNextDescendent(pos); } return false; } //----------------------------------------------------------------------------- // Purpose: Checks for node entities with the same node ID. //----------------------------------------------------------------------------- static void CheckDuplicateNodeIDs(CListBox *pList, CMapWorld *pWorld) { EnumChildrenPos_t pos; CMapClass *pChild = pWorld->GetFirstDescendent(pos); while (pChild != NULL) { CMapEntity *pEntity = dynamic_cast<CMapEntity *>(pChild); if (pEntity && pEntity->IsNodeClass()) { if (FindDuplicateNodeID(pEntity, pWorld)) { AddError(pList, ErrorDuplicateNodeIDs, (DWORD)pWorld, pEntity); } } pChild = pWorld->GetNextDescendent(pos); } } //----------------------------------------------------------------------------- // Purpose: Checks for faces with identical face normals in this solid object. // Input : pSolid - Solid to check for duplicate faces. // Output : Returns TRUE if the face contains at least one duplicate face, // FALSE if the solid contains no duplicate faces. //----------------------------------------------------------------------------- BOOL DoesContainDuplicates(CMapSolid *pSolid) { int iFaces = pSolid->GetFaceCount(); for (int i = 0; i < iFaces; i++) { CMapFace *pFace = pSolid->GetFace(i); Vector& pts1 = pFace->plane.normal; for (int j = 0; j < iFaces; j++) { // Don't check self. if (j == i) { continue; } CMapFace *pFace2 = pSolid->GetFace(j); Vector& pts2 = pFace2->plane.normal; if (pts1 == pts2) { return(TRUE); } } } return(FALSE); } //----------------------------------------------------------------------------- // Purpose: // Input : pSolid - // pList - // Output : //----------------------------------------------------------------------------- static BOOL _CheckDuplicatePlanes(CMapSolid *pSolid, CListBox *pList) { if ( !IsCheckVisible( pSolid ) ) return TRUE; if (DoesContainDuplicates(pSolid)) { AddError(pList, ErrorDuplicatePlanes, 0, pSolid); } return(TRUE); } static void CheckDuplicatePlanes(CListBox *pList, CMapWorld *pWorld) { pWorld->EnumChildren(_CheckDuplicatePlanes, pList, MAPCLASS_TYPE(CMapSolid)); } struct FindDuplicateFaceIDs_t { CMapFaceList All; // Collects all the face IDs in this map. CMapFaceList Duplicates; // Collects the duplicate face IDs in this map. }; //----------------------------------------------------------------------------- // Purpose: // Input : pSolid - // pData - // Output : Returns TRUE to continue enumerating. //----------------------------------------------------------------------------- static BOOL _CheckDuplicateFaceIDs(CMapSolid *pSolid, FindDuplicateFaceIDs_t *pData) { if ( !IsCheckVisible( pSolid ) ) return TRUE; int nFaceCount = pSolid->GetFaceCount(); for (int i = 0; i < nFaceCount; i++) { CMapFace *pFace = pSolid->GetFace(i); if (pData->All.FindFaceID(pFace->GetFaceID()) != -1) { if (pData->Duplicates.FindFaceID(pFace->GetFaceID()) != -1) { pData->Duplicates.AddToTail(pFace); } } else { pData->All.AddToTail(pFace); } } return(TRUE); } //----------------------------------------------------------------------------- // Purpose: Reports errors for all faces with duplicate face IDs. // Input : pList - // pWorld - //----------------------------------------------------------------------------- static void CheckDuplicateFaceIDs(CListBox *pList, CMapWorld *pWorld) { FindDuplicateFaceIDs_t Lists; Lists.All.SetGrowSize(128); Lists.Duplicates.SetGrowSize(128); pWorld->EnumChildren(_CheckDuplicateFaceIDs, &Lists, MAPCLASS_TYPE(CMapSolid)); for (int i = 0; i < Lists.Duplicates.Count(); i++) { CMapFace *pFace = Lists.Duplicates.Element(i); AddError(pList, ErrorDuplicateFaceIDs, (DWORD)pFace, (CMapSolid *)pFace->GetParent()); } } //----------------------------------------------------------------------------- // Checks if a particular target is valid. //----------------------------------------------------------------------------- static void CheckValidTarget(CMapEntity *pEntity, const char *pFieldName, const char *pTargetName, CListBox *pList, bool bCheckClassNames) { if (!pTargetName) return; // These procedural names are always assumed to exist. if (!stricmp(pTargetName, "!activator") || !stricmp(pTargetName, "!caller") || !stricmp(pTargetName, "!player") || !stricmp(pTargetName, "!self")) return; CMapDoc *pDoc = CMapDoc::GetActiveMapDoc(); // Search by name first. CMapEntityList Found; bool bFound = pDoc->FindEntitiesByName(Found, pTargetName, (Options.general.bCheckVisibleMapErrors == TRUE)); if (!bFound && bCheckClassNames) { // Not found, search by classname. bFound = pDoc->FindEntitiesByClassName(Found, pTargetName, (Options.general.bCheckVisibleMapErrors == TRUE)); } if (!bFound) { // No dice, flag it as an error. AddError(pList, ErrorMissingTarget, (DWORD)pFieldName, pEntity); } } //----------------------------------------------------------------------------- // Purpose: Checks the given entity for references by name to nonexistent entities. // Input : pEntity - // pList - // Output : Returns TRUE to keep enumerating. //----------------------------------------------------------------------------- static BOOL _CheckMissingTargets(CMapEntity *pEntity, CListBox *pList) { if ( !IsCheckVisible( pEntity ) ) return TRUE; GDclass *pClass = pEntity->GetClass(); if (!pClass) { // Unknown class -- just check for target references. static char *pszTarget = "target"; const char *pszValue = pEntity->GetKeyValue(pszTarget); CheckValidTarget(pEntity, pszTarget, pszValue, pList, false); } else { // Known class -- check all target_destination and target_name_or_class keyvalues. for (int i = 0; i < pClass->GetVariableCount(); i++) { GDinputvariable *pVar = pClass->GetVariableAt(i); if ((pVar->GetType() != ivTargetDest) && (pVar->GetType() != ivTargetNameOrClass)) continue; const char *pszValue = pEntity->GetKeyValue(pVar->GetName()); CheckValidTarget(pEntity, pVar->GetName(), pszValue, pList, (pVar->GetType() == ivTargetNameOrClass)); } } return TRUE; } static void CheckMissingTargets(CListBox *pList, CMapWorld *pWorld) { pWorld->EnumChildren(_CheckMissingTargets, pList, MAPCLASS_TYPE(CMapEntity)); } //----------------------------------------------------------------------------- // Purpose: Determines whether a solid is good or bad. // Input : pSolid - Solid to check. // pList - List box into which to place errors. // Output : Always returns TRUE to continue enumerating. //----------------------------------------------------------------------------- static BOOL _CheckSolidIntegrity(CMapSolid *pSolid, CListBox *pList) { if ( !IsCheckVisible( pSolid ) ) return TRUE; CCheckFaceInfo cfi; int nFaces = pSolid->GetFaceCount(); for (int i = 0; i < nFaces; i++) { CMapFace *pFace = pSolid->GetFace(i); // // Reset the iPoint member so results from previous faces don't carry over. // cfi.iPoint = -1; // // Check the face. // if (!pFace->CheckFace(&cfi)) { AddError(pList, ErrorSolidStructure, 0, pSolid); break; } } return(TRUE); } static void CheckSolidIntegrity(CListBox *pList, CMapWorld *pWorld) { pWorld->EnumChildren(_CheckSolidIntegrity, pList, MAPCLASS_TYPE(CMapSolid)); } //----------------------------------------------------------------------------- // Purpose: Determines if there are any invalid textures or texture axes on any // face of this solid. Adds an error message to the list box for each // error found. // Input : pSolid - Solid to check. // pList - Pointer to the error list box. // Output : Returns TRUE. //----------------------------------------------------------------------------- static BOOL _CheckInvalidTextures(CMapSolid *pSolid, CListBox *pList) { if ( !IsCheckVisible( pSolid ) ) return TRUE; int nFaces = pSolid->GetFaceCount(); for(int i = 0; i < nFaces; i++) { const CMapFace *pFace = pSolid->GetFace(i); IEditorTexture *pTex = pFace->GetTexture(); if (pTex->IsDummy()) { AddError(pList, ErrorInvalidTexture, (DWORD)pFace->texture.texture, pSolid); return TRUE; } if (!pFace->IsTextureAxisValid()) { AddError(pList, ErrorInvalidTextureAxes, i, pSolid); return(TRUE); } } return(TRUE); } static void CheckInvalidTextures(CListBox *pList, CMapWorld *pWorld) { pWorld->EnumChildren(_CheckInvalidTextures, pList, MAPCLASS_TYPE(CMapSolid)); } //----------------------------------------------------------------------------- // Purpose: // Input : pEntity - // pList - // Output : //----------------------------------------------------------------------------- static BOOL _CheckUnusedKeyvalues(CMapEntity *pEntity, CListBox *pList) { if ( !IsCheckVisible( pEntity ) ) return TRUE; if (!pEntity->IsClass() || pEntity->IsClass("multi_manager")) { return(TRUE); // can't check if no class associated } GDclass *pClass = pEntity->GetClass(); for (int i = pEntity->GetFirstKeyValue(); i != pEntity->GetInvalidKeyValue(); i=pEntity->GetNextKeyValue( i ) ) { if (pClass->VarForName(pEntity->GetKey(i)) == NULL) { AddError(pList, ErrorUnusedKeyvalues, (DWORD)pEntity->GetKey(i), pEntity); return(TRUE); } } return(TRUE); } static void CheckUnusedKeyvalues(CListBox *pList, CMapWorld *pWorld) { pWorld->EnumChildren(_CheckUnusedKeyvalues, pList, MAPCLASS_TYPE(CMapEntity)); } //----------------------------------------------------------------------------- // Purpose: // Input : pEntity - // pList - // Output : //----------------------------------------------------------------------------- static BOOL _CheckEmptyEntities(CMapEntity *pEntity, CListBox *pList) { if ( !IsCheckVisible( pEntity ) ) return TRUE; if(!pEntity->IsPlaceholder() && !pEntity->GetChildCount()) { AddError(pList, ErrorEmptyEntity, (DWORD)pEntity->GetClassName(), pEntity); } return(TRUE); } static void CheckEmptyEntities(CListBox *pList, CMapWorld *pWorld) { pWorld->EnumChildren(_CheckEmptyEntities, pList, MAPCLASS_TYPE(CMapEntity)); } //----------------------------------------------------------------------------- // Purpose: Checks the entity for bad I/O connections. // Input : pEntity - the entity to check // pList - list box that tracks the errors // Output : Returns TRUE to keep enumerating. //----------------------------------------------------------------------------- static BOOL _CheckBadConnections(CMapEntity *pEntity, CListBox *pList) { if ( !IsCheckVisible( pEntity ) ) return TRUE; if (CEntityConnection::ValidateOutputConnections(pEntity, (Options.general.bCheckVisibleMapErrors == TRUE)) == CONNECTION_BAD) { AddError(pList, ErrorBadConnections, (DWORD)pEntity->GetClassName(), pEntity); } // TODO: Check for a "Kill" input with the same output, target, and delay as another input. This // creates a race condition in the game where the order of arrival is not guaranteed //int nConnCount = pEntity->Connections_GetCount(); //for (int i = 0; i < nConnCount; i++) //{ // CEntityConnection *pConn = pEntity->Connections_Get(i); // if (!stricmp(pConn->GetInputName(), "kill")) // { // } //} return TRUE; } static void CheckBadConnections(CListBox *pList, CMapWorld *pWorld) { pWorld->EnumChildren(_CheckBadConnections, pList, MAPCLASS_TYPE(CMapEntity)); } static bool HasVisGroupHiddenChildren(CMapClass *pObject) { const CMapObjectList *pChildren = pObject->GetChildren(); FOR_EACH_OBJ( *pChildren, pos ) { if (!pChildren->Element(pos)->IsVisGroupShown()) return true; } return false; } static bool HasVisGroupShownChildren(CMapClass *pObject) { const CMapObjectList *pChildren = pObject->GetChildren(); FOR_EACH_OBJ( *pChildren, pos ) { if (pChildren->Element(pos)->IsVisGroupShown()) return true; } return false; } //----------------------------------------------------------------------------- // Purpose: Makes sure that the visgroup assignments are valid. //----------------------------------------------------------------------------- static BOOL _CheckVisGroups(CMapClass *pObject, CListBox *pList) { CMapDoc *pDoc = CMapDoc::GetActiveMapDoc(); // dvs: FIXME: not working yet, revisit // Entities cannot have hidden children. //CMapEntity *pEntity = dynamic_cast<CMapEntity *>(pObject); //if (pEntity && HasVisGroupHiddenChildren(pEntity)) //{ // AddError(pList, ErrorHiddenChildOfEntity, 0, pEntity); // return TRUE; //} // Check the validity of any object that claims to be hidden by visgroups. if (!pObject->IsVisGroupShown()) { // Groups cannot be hidden by visgroups. if (pObject->IsGroup()) { bool bHidden = HasVisGroupHiddenChildren(pObject); bool bVisible = HasVisGroupShownChildren(pObject); if (bHidden && !bVisible) { AddError(pList, ErrorHiddenGroupHiddenChildren, 0, pObject); } else if (!bHidden && bVisible) { AddError(pList, ErrorHiddenGroupVisibleChildren, 0, pObject); } else { AddError(pList, ErrorHiddenGroupMixedChildren, 0, pObject); } return TRUE; } // Check for unanticipated objects that are hidden but forbidden from visgroup membership. if (!pDoc->VisGroups_ObjectCanBelongToVisGroup(pObject)) { AddError(pList, ErrorIllegallyHiddenObject, 0, pObject); return TRUE; } // Hidden objects must belong to at least one visgroup. if (pObject->GetVisGroupCount() == 0) { AddError(pList, ErrorHiddenObjectNoVisGroup, 0, pObject); return TRUE; } } return TRUE; } static void CheckVisGroups(CListBox *pList, CMapWorld *pWorld) { pWorld->EnumChildrenRecurseGroupsOnly(_CheckVisGroups, pList); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- static BOOL _CheckOverlayFaceList( CMapEntity *pEntity, CListBox *pList ) { if ( !IsCheckVisible( pEntity ) ) return TRUE; const CMapObjectList *pChildren = pEntity->GetChildren(); FOR_EACH_OBJ( *pChildren, pos ) { CMapOverlay *pOverlay = dynamic_cast<CMapOverlay*>( pChildren->Element(pos) ); if ( pOverlay ) { // Check to see if the overlay has assigned faces. if ( pOverlay->GetFaceCount() <= 0 ) { AddError( pList, ErrorOverlayFaceList, 0, pEntity ); return TRUE; } } } return TRUE; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- static void CheckOverlayFaceList( CListBox *pList, CMapWorld *pWorld ) { pWorld->EnumChildren( _CheckOverlayFaceList, pList, MAPCLASS_TYPE( CMapEntity )); } // // ** FIX FUNCTIONS // static void FixDuplicatePlanes(MapError *pError) { // duplicate planes in pObjects[0] // run thru faces.. CMapSolid *pSolid = (CMapSolid*) pError->pObjects[0]; ReStart: int iFaces = pSolid->GetFaceCount(); for(int i = 0; i < iFaces; i++) { CMapFace *pFace = pSolid->GetFace(i); Vector& pts1 = pFace->plane.normal; for (int j = 0; j < iFaces; j++) { // Don't check self if (j == i) { continue; } CMapFace *pFace2 = pSolid->GetFace(j); Vector& pts2 = pFace2->plane.normal; if (pts1 == pts2) { pSolid->DeleteFace(j); goto ReStart; } } } } //----------------------------------------------------------------------------- // Purpose: Repairs an invalid solid. // Input : pError - Contains information about the error. //----------------------------------------------------------------------------- static void FixSolidStructure(MapError *pError) { CMapSolid *pSolid = (CMapSolid *)pError->pObjects[0]; // // First make sure all the faces are good. // int nFaces = pSolid->GetFaceCount(); for (int i = nFaces - 1; i >= 0; i--) { CMapFace *pFace = pSolid->GetFace(i); if (!pFace->CheckFace(NULL)) { pFace->Fix(); } // // If the face has no points, just remove it from the solid. // if (pFace->GetPointCount() == 0) { pSolid->DeleteFace(i); } } // // Rebuild the solid from the planes. // pSolid->CreateFromPlanes(); pSolid->PostUpdate(Notify_Changed); } LPCTSTR GetDefaultTextureName(); // dvs: BAD! //----------------------------------------------------------------------------- // Purpose: Replaces any missing textures with the default texture. // Input : pError - //----------------------------------------------------------------------------- static void FixInvalidTexture(MapError *pError) { CMapSolid *pSolid = (CMapSolid *)pError->pObjects[0]; int nFaces = pSolid->GetFaceCount(); for (int i = 0; i < nFaces; i++) { CMapFace *pFace = pSolid->GetFace(i); if (pFace != NULL) { IEditorTexture *pTex = pFace->GetTexture(); if (pTex != NULL) { if (pTex->IsDummy()) { pFace->SetTexture(GetDefaultTextureName()); } } } } } static void FixInvalidTextureAxes(MapError *pError) { CMapSolid *pSolid = (CMapSolid *)pError->pObjects[0]; int nFaces = pSolid->GetFaceCount(); for (int i = 0; i < nFaces; i++) { CMapFace *pFace = pSolid->GetFace(i); if (!pFace->IsTextureAxisValid()) { pFace->InitializeTextureAxes(Options.GetTextureAlignment(), INIT_TEXTURE_FORCE | INIT_TEXTURE_AXES); } } } //----------------------------------------------------------------------------- // Purpose: Fixes duplicate face IDs by assigning the face a unique ID within // the world. // Input : pError - Holds the world and the face that is in error. //----------------------------------------------------------------------------- static void FixDuplicateFaceIDs(MapError *pError) { CMapWorld *pWorld = (CMapWorld *)pError->pObjects[0]; CMapFace *pFace = (CMapFace *)pError->dwExtra; pFace->SetFaceID(pWorld->FaceID_GetNext()); } //----------------------------------------------------------------------------- // Purpose: // Input : pError - //----------------------------------------------------------------------------- static void FixUnusedKeyvalues(MapError *pError) { CMapEntity *pEntity = (CMapEntity*) pError->pObjects[0]; GDclass *pClass = pEntity->GetClass(); if (!pClass) { return; } int iNext; for ( int i=pEntity->GetFirstKeyValue(); i != pEntity->GetInvalidKeyValue(); i = iNext ) { iNext = pEntity->GetNextKeyValue( i ); if (pClass->VarForName(pEntity->GetKey(i)) == NULL) { pEntity->DeleteKeyValue(pEntity->GetKey(i)); } } } //----------------------------------------------------------------------------- // Purpose: Removes any bad connections from the entity associated with the error. // Input : pError - //----------------------------------------------------------------------------- static void FixBadConnections(MapError *pError) { CMapEntity *pEntity = (CMapEntity *)pError->pObjects[0]; CEntityConnection::FixBadConnections(pEntity, (Options.general.bCheckVisibleMapErrors == TRUE)); } //----------------------------------------------------------------------------- // Purpose: Fixes a race condition caused by a Kill input being triggered at the // same instant as another input. // Input : pError - //----------------------------------------------------------------------------- static void FixKillInputRaceCondition(MapError *pError) { CEntityConnection *pConn = (CEntityConnection *)pError->pObjects[1]; // Delay the Kill command so that it arrives after the other command, // solving the race condition. pConn->SetDelay(pConn->GetDelay() + 0.01); } //----------------------------------------------------------------------------- // Purpose: // Input : pError - //----------------------------------------------------------------------------- static void FixOverlayFaceList( MapError *pError ) { CMapEntity *pEntity = static_cast<CMapEntity*>( pError->pObjects[0] ); if ( !pEntity ) return; const CMapObjectList *pChildren = pEntity->GetChildren(); FOR_EACH_OBJ( *pChildren, pos ) { CMapOverlay *pOverlay = dynamic_cast<CMapOverlay*>( pChildren->Element(pos) ); if ( pOverlay ) { // Destroy itself. CMapDoc *pDoc = CMapDoc::GetActiveMapDoc(); pDoc->RemoveObjectFromWorld( pEntity, true ); GetHistory()->KeepForDestruction( pEntity ); return; } } } //----------------------------------------------------------------------------- // Purpose: // Input : pError - //----------------------------------------------------------------------------- static void FixEmptyEntity(MapError *pError) { CMapClass *pKillMe = pError->pObjects[0]; if (pKillMe->GetParent() != NULL) { GetHistory()->KeepForDestruction(pKillMe); pKillMe->GetParent()->RemoveChild(pKillMe); } } //----------------------------------------------------------------------------- // Purpose: Fixes duplicate node IDs by assigning the entity a unique node ID. // Input : pError - Holds the world and the entity that is in error. //----------------------------------------------------------------------------- static void FixDuplicateNodeIDs(MapError *pError) { CMapEntity *pEntity = (CMapEntity *)pError->pObjects[0]; pEntity->AssignNodeID(); } //----------------------------------------------------------------------------- // Purpose: Clears a bad target reference from the given entity. // Input : pError - //----------------------------------------------------------------------------- static void FixMissingTarget(MapError *pError) { CMapEntity *pEntity = (CMapEntity *)pError->pObjects[0]; const char *pszKey = (const char *)pError->dwExtra; pEntity->SetKeyValue(pszKey, NULL); } //----------------------------------------------------------------------------- // Purpose: Fix a an invalid visgroup state. This is either: // 1) A group that is hidden // 2) An object that is hidden but not in any visgroups //----------------------------------------------------------------------------- void FixHiddenObject(MapError *pError) { CMapClass *pObject = pError->pObjects[0]; // Tweak the object's visgroup state directly to avoid changing the // hidden/shown state of the object's children. pObject->m_bVisGroupShown = true; pObject->m_bVisGroupAutoShown = true; pObject->m_VisGroups.RemoveAll(); // Create a new visgroup to out the objects in (for hiding or inspection/deletion). CMapObjectList Objects; Objects.AddToTail(pObject); CMapDoc *pDoc = CMapDoc::GetActiveMapDoc(); if ((pError->Type == ErrorHiddenGroupHiddenChildren) || (pError->Type == ErrorHiddenObjectNoVisGroup)) { // The objects aren't in the compile, so just hide them. pDoc->VisGroups_CreateNamedVisGroup(Objects, "_hidden by Check for Problems", true, false); } else if (pError->Type == ErrorIllegallyHiddenObject) { // Do nothing, the object is now shown. } else { // ErrorHiddenGroupVisibleChildren // ErrorHiddenGroupMixedChildren // ErrorHiddenChildOfEntity // The objects either ARE in the compile, or they can't be hidden in a visgroup. // Don't hide them, just stick them in a visgroup for inspection pDoc->VisGroups_CreateNamedVisGroup(Objects, "found by Check for Problems", false, false); } } //----------------------------------------------------------------------------- // Purpose: Checks the map for problems. Returns true if the map is okay, // false if problems were found. //----------------------------------------------------------------------------- bool CMapCheckDlg::DoCheck(void) { CMapWorld *pWorld = GetActiveWorld(); // Clear error list KillErrorList(); // Map validation CheckRequirements(&m_Errors, pWorld); // Solid validation CheckMixedFaces(&m_Errors, pWorld); //CheckDuplicatePlanes(&m_Errors, pWorld); CheckDuplicateFaceIDs(&m_Errors, pWorld); CheckDuplicateNodeIDs(&m_Errors, pWorld); CheckSolidIntegrity(&m_Errors, pWorld); CheckInvalidTextures(&m_Errors, pWorld); // Entity validation CheckUnusedKeyvalues(&m_Errors, pWorld); CheckEmptyEntities(&m_Errors, pWorld); CheckMissingTargets(&m_Errors, pWorld); CheckBadConnections(&m_Errors, pWorld); CheckVisGroups(&m_Errors, pWorld); CheckOverlayFaceList(&m_Errors, pWorld); if (!m_Errors.GetCount()) { AfxMessageBox("No errors were found."); EndDialog(IDOK); return true; } return false; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CMapCheckDlg::OnOK() { DestroyWindow(); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void CMapCheckDlg::OnClose() { DestroyWindow(); } //----------------------------------------------------------------------------- // Purpose: Called when our window is being destroyed. //----------------------------------------------------------------------------- void CMapCheckDlg::OnDestroy() { delete this; s_pDlg = NULL; }
[ "kubci.rusnk645@gmail.com" ]
kubci.rusnk645@gmail.com
b32410fdc19cf3ca057ab28531bf5dddfd4c4851
938f5e3fca328e0a2f2c28069aa4157892de2015
/Targets/Target_Code.ino
cadf9ecc148fe9cfb17aae13995543e5842021f9
[]
no_license
colincolt/STARS
e430dcd85ce97cf0370b69af3a586430336d6424
b7cc901c3f962260bb375caa3386ad022a75936f
refs/heads/master
2020-04-09T15:08:43.608197
2019-04-05T14:35:57
2019-04-05T14:35:57
160,416,928
0
4
null
2019-01-21T19:09:29
2018-12-04T20:47:56
Python
UTF-8
C++
false
false
9,041
ino
#include <SPI.h> #include <Wire.h> #include <IRremote.h> #define PIN_IR 9 #define SENSORPIN1 2 //Sensor 1 is on the front plane #define SENSORPIN2 3 //Sensor 2 is on the back plane //#define SENSORPIN3 12 //Sensor 3 is on the front top //#define SENSORPIN4 8 //Sensor 4 is on the back top #define REDPIN 4 #define GREENPIN 5 #define BLUEPIN 6 IRsend irsend; volatile unsigned long Plane1_Break_Time = 0; // When plane 1 is triggered volatile unsigned long Plane2_Break_Time = 0; // When plane 1 is triggered volatile unsigned long Elapsed_Time = 0; // Time it takes for ball to cross both planes float ball_speed1 = 0.0; // Speed calculated float ball_speed2 = 0.0; // Speed calculated int Difficulty = 0; long Base_Drill_Time = 10000; // Base time for a drill (5 seconds) long Drill_Time; // Total drill time which is a multiple of the base time long Drill_Start_Time; //long Drill_End_Time; // nRF24L01 radio transceiver external libraries //#include <SPI.h> #include <RF24.h> #include <nRF24L01.h> #include <printf.h> // chip select and RF24 radio setup pins #define CE_PIN 7 #define CSN_PIN 10 RF24 radio(CE_PIN,CSN_PIN); // set this to appropriate slave device number minus 1 (e.g. 0 for device 1) #define NODE_ID 0 // setup radio pipe addresses for each sensor node const byte nodeAddresses[5][5] = { {'N','O','D','E','1'}, {'N','O','D','E','2'}, {'N','O','D','E','3'}, {'N','O','D','E','4'}, {'N','O','D','E','5'}, }; // simple integer array for each remote node data, in the form [node_id, returned_count] //int remoteNodeData[3][2] = {{1, 1,}, {2, 1}, {3, 1}}; float remoteNodeData[4]; // integer to store count of successful transmissions int Difficulty = 0; float reset_data = -1.0; int speed_poll = 0; void setup() { // setup serial communications for basic program display Serial.begin(9600); Serial.println("[*][*][*] Beginning nRF24L01+ ack-payload slave device program [*][*][*]"); // ----------------------------- RADIO SETUP CONFIGURATION AND SETTINGS -------------------------// radio.begin(); // set power level of the radio radio.setPALevel(RF24_PA_LOW); // set RF datarate radio.setDataRate(RF24_250KBPS); // set radio channel to use - ensure it matches the target host radio.setChannel(0x76); // open a reading pipe on the chosen address for selected node radio.openReadingPipe(1, nodeAddress[NODE_ID]); radio.setAutoAck(false); // enable ack payload - slave reply with data using this feature // radio.enableAckPayload(); // preload the payload with initial data - sent after an incoming message is read // radio.writeAckPayload(1, &remoteNodeData[NODE_ID], sizeof(remoteNodeData[NODE_ID])); // print radio config details to console printf_begin(); radio.printDetails(); // start listening on radio // radio.startListening(); // --------------------------------------------------------------------------------------------// pinMode(REDPIN, OUTPUT); pinMode(GREENPIN, OUTPUT); pinMode(BLUEPIN, OUTPUT); pinMode(SENSORPIN1, INPUT); // Sensor 1 as input // digitalWrite(SENSORPIN1, HIGH); // Turn on the pullup pinMode(SENSORPIN2, INPUT); // Sensor 2 as input // digitalWrite(SENSORPIN2, HIGH); // Turn on the pullup pinMode(SENSORPIN3, INPUT); // Sensor 2 as input pinMode(SENSORPIN4, INPUT); // Sensor 2 as input // Serial.begin(9600); // while (! Serial); Serial.println("Target 1 = 1; Target 2 = 2"); irsend.enableIROut(38); irsend.mark(0); } void loop() { radio.startListening(); // wait for an initialization signal from the master while (Difficulty == 0){ radioInitialize(); } Drill_Start_Time = millis(); Drill_Time = (Base_Drill_Time) - (Difficulty)*(1000); //Initialize the target Initialize(); //Wait for ball to be detected and then buffer the speed value while (Difficulty > 0){ if (plane2_break_time > 0) { Ball_Speed(); radio.writeAckPayload(1, &ball_speed1, sizeof(ball_speed1)); while(ball_speed1 > 0.0) { Wireless(); } delay(2000); // deactivate target (RED) digitalWrite(REDPIN, HIGH); digitalWrite(GREENPIN, LOW); digitalWrite(BLUEPIN, LOW); } else{ if ((millis()-Drill_Start_Time)>= Drill_Time){ Reset(); } else{ } } Reset(); } } // Function to determine speed void Ball_Speed() { // subtract end time from start time to get total time Elapsed_Time = (Plane2_Break_Time - Plane1_Break_Time); // activate target (GREEN) digitalWrite(REDPIN, LOW); digitalWrite(GREENPIN, HIGH); digitalWrite(BLUEPIN, LOW); // convert mm/s to m/s ball_speed1 = ((224000.00 / Elapsed_Time)); ball_speed2 = ball_speed1*3.6; Serial.println("GOAL!"); Serial.print("Ball Speed (m/s) = "); Serial.println(ball_speed1); Serial.print("Ball Speed (km/h) = "); Serial.println(ball_speed2); Serial.println(); } void Initialize() { EIFR |= (1 << INTF0); // clear any outstanding interrupt 0 EIFR |= (1 << INTF1); // clear any outstanding interrupt 1 // attach interrupts attachInterrupt(digitalPinToInterrupt(SENSORPIN_1), Plane1_Break_Time_ISR, RISING); attachInterrupt(digitalPinToInterrupt(SENSORPIN_2), Plane2_Break_Time_ISR, RISING); // activate target (BLUE) digitalWrite(REDPIN, LOW); digitalWrite(GREENPIN, LOW); digitalWrite(BLUEPIN, HIGH); // set autoack True radio.setAutoAck(true); // enable ack payload - slave reply with data using this feature radio.enableAckPayload(); } void Reset() { // detach interrupts detachInterrupt(digitalPinToInterrupt(SENSORPIN_1)); detachInterrupt(digitalPinToInterrupt(SENSORPIN_2)); // deactivate target (RED) digitalWrite(REDPIN, HIGH); digitalWrite(GREENPIN, LOW); digitalWrite(BLUEPIN, LOW); // set autoack(false) radio.setAutoAck(false); // Reset variables Difficulty = 0; Plane1_Break_Time = 0; Plane2_Break_Time = 0; ball_speed1 = 0.0; ball_speed2 = 0.0; // Elapsed_Time = 0; } /* Function: loop * main loop program for the slave node - repeats continuously during system operation */ void Wireless() { // transmit current preloaded data to master device if message request received radioCheckAndReply(); } /* Function: updateNodeData * updates the count variable for the node and stores it in the nRF24L01+ radio * preloaded ack payload ready for sending on next received message */ void updateNodeData(void) { // // increment node count - reset to 1 if exceeds 500 // if (remoteNodeData[NODE_ID][1] < 500) { // remoteNodeData[NODE_ID][1]++; // } else { // remoteNodeData[NODE_ID][1] = 1; // } // set the ack payload ready for next request from the master device radio.writeAckPayload(1, &reset_data, sizeof(reset_data)); } /* Function: radioCheckAndReply * sends the preloaded node data over the nrf24l01+ radio when * a message is received by the master */ void radioCheckAndReply(void) { // check for radio message and send sensor data using auto-ack if ( radio.available() ) { radio.read( &speed_poll, sizeof(speed_poll)); Serial.println("Received request from master - sending preloaded data."); Serial.print("The received signal from the master was: "); Serial.println(speed_poll); Serial.println("--------------------------------------------------------"); radio.stopListening(); // update the node count after sending ack payload - provides continually changing data // Difficulty = 0; // update the node count after sending ack payload - provides continually changing data // updateNodeData(); } } void radioInitialize(void) { // check for radio message and send sensor data using auto-ack if ( radio.available() ) { radio.read( &Difficulty, sizeof(Difficulty) ); Serial.println("Received request from master - sending preloaded data."); Serial.print("The received signal from the master was: "); Serial.println(Difficulty); Serial.println("--------------------------------------------------------"); // // radio.stopListening(); // // update the node count after sending ack payload - provides continually changing data // // Difficulty = 0; // // // update the node count after sending ack payload - provides continually changing data // updateNodeData(); } } void Plane1_Break_Time_ISR() { Plane1_Break_Time = micros(); } void Plane2_Break_Time_ISR() { Plane2_Break_Time = micros(); }
[ "noreply@github.com" ]
noreply@github.com
09a4b784138d80ef983f240c0477fb5062e9ca14
430a34770d0fe50c9629760d36fbf1d0c023e98a
/application/src/TerminalInterface.h
b2609889cec9339dae31dd0a6c2b5b1c4fac85c1
[ "MIT" ]
permissive
pawel-jakubowski/arduino-terminal
1e111cbeb28b3f94728f5abc5b32abca6e57f77b
78a8af192be6d09c1b66cd8a5a47b8751c55778b
refs/heads/master
2021-01-01T06:11:07.952060
2015-01-24T22:09:08
2015-01-24T22:09:08
29,424,266
1
0
null
null
null
null
UTF-8
C++
false
false
305
h
/* * TerminalInterface.h * * Created on: 22 sty 2015 * Author: Pawel Jakubowski */ #ifndef TERMINALINTERFACE_H_ #define TERMINALINTERFACE_H_ #include <string> class TerminalInterface { public: virtual void run() = 0; virtual ~TerminalInterface() {} }; #endif /* TERMINALINTERFACE_H_ */
[ "pawel-jakubowski@hotmail.com" ]
pawel-jakubowski@hotmail.com