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
5ddfbfdfc22c7ee2ef5009b9d2959433133a12e4
f72953e6e45acba00fd09a245004dce9bdbd49ac
/problems/70_Climbing_Stairs.cpp
2c5b3f49c5dac1800d386039e52d8a512fad14d1
[]
no_license
guravtushar/LeetCode
bcb686d22d09de0f1d9391424e700062fd491719
fdcb3619b921f3c812a3be45421105075b369b5b
refs/heads/master
2022-11-25T00:01:38.475122
2020-07-26T18:38:28
2020-07-26T18:38:28
261,482,972
0
0
null
null
null
null
UTF-8
C++
false
false
781
cpp
/* https://leetcode.com/problems/climbing-stairs/ You are climbing a stair case. It takes n steps to reach to the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? Note: Given n will be a positive integer. Example 1: Input: 2 Output: 2 Explanation: There are two ways to climb to the top. 1. 1 step + 1 step 2. 2 steps Example 2: Input: 3 Output: 3 Explanation: There are three ways to climb to the top. 1. 1 step + 1 step + 1 step 2. 1 step + 2 steps 3. 2 steps + 1 step */ class Solution { public: int climbStairs(int n) { int dp[n+1]; memset(dp,0,sizeof(dp)); dp[0]=1; dp[1]=1; for(int i=2;i<=n;i++){ dp[i]=dp[i-1]+dp[i-2]; } return dp[n]; } };
[ "tushar.gurav25@gmail.com" ]
tushar.gurav25@gmail.com
73bfc5252cd103cb7e320d4927f363b54f2dbe0d
54c4a6f4c05ac93257f65a571171287a3d9ad5f4
/Brute-force/3085/naive.cpp
7adbb3eab0c48dbb9585258ee273f08bed25ffc8
[]
no_license
DaeHwanGi/BAEKJOON_solution
747d202117d642268d2a80932a763544d879266e
bdf823d196d336ca509931638e843fd36716f0bf
refs/heads/master
2020-04-26T08:29:34.725920
2019-03-11T13:02:07
2019-03-11T13:02:07
173,424,591
0
0
null
null
null
null
UTF-8
C++
false
false
2,532
cpp
#include <iostream> #include <vector> #include <algorithm> using namespace std; int change_with_down(char **arr, int row, int col) { char temp = arr[row][col]; arr[row][col] = arr[row + 1][col]; arr[row + 1][col] = temp; return 0; } int change_with_right(char **arr, int row, int col) { char temp = arr[row][col]; arr[row][col] = arr[row][col+1]; arr[row][col+1] = temp; return 0; } int find_max_in_row(char **arr, int N, int row) { vector<char> v; int ret = 0; for (int i = 0; i < N; i++) { if (!v.empty()) { if (v.back() != arr[row][i]) { v.clear(); v.push_back(arr[row][i]); } else { v.push_back(arr[row][i]); } } else { v.push_back(arr[row][i]); } ret = ret > v.size() ? ret : v.size(); } return ret; } int find_max_in_col(char **arr, int N, int col) { vector<char> v; int ret = 0; for (int i = 0; i < N; i++) { if (!v.empty()) { if (v.back() != arr[i][col]) { v.clear(); v.push_back(arr[i][col]); } else { v.push_back(arr[i][col]); } } else { v.push_back(arr[i][col]); } ret = ret < v.size() ? v.size() : ret; } return ret; } int check(char **arr, int N) { int ans = 1; for (int i = 0; i < N; i++) { int cnt = 1; for (int j = 1; j < N; j++) { if (arr[i][j] == arr[i][j - 1]) { cnt++; } else { ans = max(ans, cnt); cnt = 1; } } ans = max(ans, cnt); } for (int i = 0; i < N; i++) { int cnt = 1; for (int j = 1; j < N; j++) { if (arr[j][i] == arr[j - 1][i]) { cnt++; } else { ans = max(ans, cnt); cnt = 1; } } ans = max(ans, cnt); } return ans; } int print_arr(char **arr, int N) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { cout << arr[i][j] << " "; } cout << endl; } cout << endl; return 0; } int main() { int N; cin >> N; char **arr = new char*[N]; for (int i = 0; i < N; i++) { arr[i] = new char[N]; for (int j = 0; j < N; j++) { cin >> arr[i][j]; } } int a, b, c, d, answer = 0; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { //cout << "ij " << i << " " << j << endl; if (i != N - 1) { change_with_down(arr, i, j); //print_arr(arr, N); a = check(arr, N); change_with_down(arr, i, j); } if (j != N - 1) { change_with_right(arr, i, j); //print_arr(arr, N); b = check(arr, N); change_with_right(arr, i, j); } answer = std::max({ answer, a, b }); //cout << a << " " << b << " " << c << " " << d << endl; } } cout << answer << endl; return 0; }
[ "dhgi0630@gmail.com" ]
dhgi0630@gmail.com
3dbd1e82be52f0a5df698d0b4613b46579d40da8
5bf2806085854089e7027dce1519a183685afe6e
/leetcode/BalancedBinaryTree.cpp
a056ff1930b601f751fa861492ec3e756dcd8bae
[]
no_license
sarreddym/ms_interview_100
bd5d7360d412c6bb2e6def25a6b424d6db5ac051
7a8622de2984c108b5cc5f2e46dead6f3cb8d5b4
refs/heads/master
2021-01-22T11:42:27.540336
2015-10-23T04:33:30
2015-10-23T04:33:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,087
cpp
#include <iostream> #include "Tree.h" using namespace std; /** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: bool isBalanced(TreeNode *root) { return maxDepth(root) != -1; } int maxDepth(TreeNode *root) { if (root == NULL) { return 0; } int L = maxDepth(root->left); if (L == -1) { return -1; } int R = maxDepth(root->right); if (R == -1) { return -1; } return abs(L - R) <= 1 ? max(L, R) + 1 : -1; } bool isBalanced2(TreeNode *root) { if (root == NULL) { return true; } return abs(maxDepth2(root->left) - maxDepth2(root->right)) <= 1 && isBalanced(root->left) && isBalanced(root->right); } int maxDepth2(TreeNode *root) { if (root == NULL) { return true; } return max(maxDepth2(root->left), maxDepth2(root->right)) + 1; } // Need to improve performance bool isBalanced1(TreeNode *root) { if (root == NULL) { return true; } if (isBalanced(root->left) && isBalanced(root->right)) { // Be very careful!! // When one of the children is NULL, it is checking the high of // the other child. SO if its high is >= 1, the current node // has one branch >= 2, the other branch == 0. if (root->left == NULL && root->right != NULL) { if (highOfTree(root->right) >= 1) { return false; } else { return true; } } else if (root->left != NULL && root->right == NULL) { if (highOfTree(root->left) >= 1) { return false; } else { return true; } } else { int left = highOfTree(root->left); int right = highOfTree(root->right); if (abs(left - right) > 1) { return false; } else { return true; } } } else { return false; } } int highOfTree(TreeNode *root) { if (root == NULL) { return 0; } else if (root->left == NULL && root->right == NULL) { return 0; } else if (root->left == NULL && root->right != NULL) { int h = highOfTree(root->right); //std::cout << "node " << root->val << "; high " << 1 + h << endl; return 1 + h; } else if (root->left != NULL && root->right == NULL) { int h = highOfTree(root->left); //std::cout << "node " << root->val << "; high " << 1 + h << endl; return 1 + h; } else { int h = max(highOfTree(root->right), highOfTree(root->left)); //std::cout << "node " << root->val << "; high " << 1 + h << endl; return 1 + h; } } }; int main() { Solution sln; TreeNode *root = NULL; //const int TREELEN = 7; //int szInOrder[TREELEN] = {3, 2, 4, 1, 6, 5, 7}; //int szPostOrder[TREELEN] = {3, 4, 2, 6, 7, 5, 1}; //ReBuildTreeFromInPost2(szInOrder, szPostOrder, TREELEN, root); string leaf[11] = {"1", "2", "2", "3", "#", "#", "3", "4", "#", "#", "4"}; vector<string> s(leaf, leaf + 11); ReBuildTreeFromOrderLevel<TreeNode>(s, root); std::cout << sln.isBalanced(root) << endl; CleanUp(root); return 0; }
[ "qingyun.oracle@gmail.com" ]
qingyun.oracle@gmail.com
07da0f29fc78505d7bbd9f10b0f3e18c040d3f37
272bb0fd833f42ed383cc41454b9e9aad9b31527
/dx11-space-shooter/AppStates/MainMenuState.h
85e5e583982deed327c60b081a79257a0f2054ec
[]
no_license
jamesmcgill/dx11-space-shooter
fed071387cccd74cbbe3f6adc1f18242ea6cc5d7
d1b7aa3a736ab850563e4412b71f2928924ea729
refs/heads/master
2022-02-19T12:47:03.315517
2019-09-23T13:22:31
2019-09-23T13:26:46
113,332,376
1
0
null
null
null
null
UTF-8
C++
false
false
759
h
#pragma once #include "IAppState.h" //------------------------------------------------------------------------------ class MainMenuState : public IAppState { public: MainMenuState( AppStates& states, AppContext& context, AppResources& resources, GameLogic& logic) : IAppState(states, context, resources, logic) { } void handleInput(const DX::StepTimer& timer) override; void update(const DX::StepTimer& timer) override; void render() override; void load() override; void unload() override; bool isLoaded() const override; void enter() override; void exit() override; private: void resetTimer(); float m_timeoutS = 0.0f; }; //------------------------------------------------------------------------------
[ "jamesmcgill@users.noreply.github.com" ]
jamesmcgill@users.noreply.github.com
12e1a86e9e8f9d1313a5acd8aaa12b59460b1ada
44ab57520bb1a9b48045cb1ee9baee8816b44a5b
/Assist/Code/Toolset/Framework/WinMainEntryPoint1/WinMainEntryPoint1.h
76b5c9b0164cfe590e011a9233b766e96b699479
[ "BSD-3-Clause" ]
permissive
WuyangPeng/Engine
d5d81fd4ec18795679ce99552ab9809f3b205409
738fde5660449e87ccd4f4878f7bf2a443ae9f1f
refs/heads/master
2023-08-17T17:01:41.765963
2023-08-16T07:27:05
2023-08-16T07:27:05
246,266,843
10
0
null
null
null
null
GB18030
C++
false
false
1,176
h
/// Copyright (c) 2010-2023 /// Threading Core Render Engine /// /// 作者:彭武阳,彭晔恩,彭晔泽 /// 联系作者:94458936@qq.com /// /// 标准:std:c++20 /// 版本:0.9.1.2 (2023/07/28 10:54) #ifndef WIN_MAIN_ENTRY_POINT1_H #define WIN_MAIN_ENTRY_POINT1_H #include "Framework/MainFunctionHelper/WindowMainFunctionHelper.h" #include "Framework/WindowsAPIFrame/WindowsAPIFrameBuild.h" namespace Framework { using BaseType = WindowMainFunctionHelper<WindowsAPIFrameBuild, WindowProcessInterface>; class WinMainEntryPoint1 final : public BaseType { public: using ClassType = WinMainEntryPoint1; using ParentType = BaseType; public: WinMainEntryPoint1(WindowsHInstance instance, const char* commandLine, const WindowApplicationInformation& information, const EnvironmentDirectory& environmentDirectory); CLASS_INVARIANT_FINAL_DECLARE; NODISCARD static std::shared_ptr<WinMainEntryPoint1> Create(WindowsHInstance instance, const char* commandLine, const WindowApplicationInformation& information, const EnvironmentDirectory& environmentDirectory); }; } #endif // WIN_MAIN_ENTRY_POINT1_H
[ "94458936@qq.com" ]
94458936@qq.com
7f71fec00026d0ababce1bdbde7e0d3b80ca44df
f22f1c9b9f0265295be7cb83433fcba66b620776
/core/rmi/src/main/c++/jcpp/rmi/server/connection/JServer.cpp
4e4239e72d20a0d8f70f9ed373ea082810e1ff4b
[]
no_license
egelor/jcpp-1
63c72c3257b52b37a952344a62fa43882247ba6e
9b5a180b00890d375d2e8a13b74ab5039ac4388c
refs/heads/master
2021-05-09T03:46:22.585245
2015-08-07T16:04:20
2015-08-07T16:04:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
14,622
cpp
#include "jcpp/rmi/server/connection/JServer.h" #include "jcpp/util/concurrent/JThreadPoolExecutor.h" #include "jcpp/util/concurrent/JSynchronousQueue.h" #include "jcpp/util/concurrent/JExecutors.h" #include "jcpp/util/concurrent/JScheduledThreadPoolExecutor.h" #include "jcpp/lang/reflect/JProxy.h" #include "jcpp/rmi/server/connection/JObjectPointer.h" #include "jcpp/rmi/server/connection/JInvoker.h" using namespace jcpp::util::concurrent; namespace jcpp{ namespace rmi{ namespace server{ namespace connection{ JServer::JServer(JEndPoint* endPoint, JITransportRouter* transportRouter, JConnectionConfiguration* connectionConfiguration): JObject(getClazz()){ this->notExportedObjectListener=null; this->notSerializableObjectHandler=null; this->invocationExceptionHandler=null; this->endPoint = endPoint; this->connectionConfiguration = connectionConfiguration; this->lifecycles = new JArrayList(); this->gcClientListeners = new JArrayList(); this->invocationListeners=new JArrayList(); this->executorService = new JThreadPoolExecutor(0, JInteger::MAX_VALUE, 30L,new JSynchronousQueue()); this->scheduledExecutorService = JExecutors::newScheduledThreadPool(connectionConfiguration->getExecutorCorePoolSize()->get()); this->gc = new JGC(executorService, scheduledExecutorService, connectionConfiguration); this->gcClient = new JGCClient(this, this); this->objectInformations = new JObjectInformations(this, this, gc, gcClient,this); this->connectionTransportDispatcher = new JConnectionTransportDispatcher(objectInformations); this->transport = new JTransport(endPoint, transportRouter, connectionTransportDispatcher, executorService, scheduledExecutorService, connectionConfiguration->getTransportConfiguration()); this->objectInformations->setTransport(transport); this->registry = new JRegistry(objectInformations); this->iregistry = registry; JList* inter=new JArrayList(); inter->add(JIRegistry::getClazz()); this->registry->bind(JIRegistry::getClazz()->getName(), registry, inter); inter=new JArrayList(); inter->add(JIServer::getClazz()); this->registry->bind(JIServer::getClazz()->getName(), this, inter); inter=new JArrayList(); inter->add(JIGC::getClazz()); this->registry->bind(JIGC::getClazz()->getName(), gc, inter); inter=new JArrayList(); inter->add(JIGCClient::getClazz()); this->registry->bind(JIGCClient::getClazz()->getName(), gcClient, inter); } JIServer* JServer::getRemoteServer(JObject* object){ if (object->getClass()->isProxy()){ JObjectHandler* objectHandler = getObjectHandlerFromProxy(object); JObjectPointer* objectPointer = objectHandler->getInvoker()->getObjectPointer(); return dynamic_cast<JIServer*>(objectHandler->getInvoker()->getObjectInformations()->getServer()->lookup(objectPointer->getEndPoint(), JIServer::getClazz())); } return null; } JIServer* JServer::getLocalServer(JObject* object){ JObjectHandler* objectHandler = getObjectHandlerFromProxy(object); return objectHandler->getInvoker()->getObjectInformations()->getServer(); } JString* JServer::getHost(JObject* object){ return getEndPoint(object)->getAddress()->getHostName(); } jint JServer::getPort(JObject* object){ return getEndPoint(object)->getAddress()->getPort(); } JString* JServer::getSite(JObject* object){ return getEndPoint(object)->getSite(); } JEndPoint* JServer::getEndPoint(JObject* object){ if (object->getClass()->isProxy()) { JObjectPointer* objectPointer = getObjectHandlerFromProxy(object)->getInvoker()->getObjectPointer(); return objectPointer->getEndPoint(); } return null; } JString* JServer::getId(JObject* object){ if (object->getClass()->isProxy()) { JObjectPointer* objectPointer = getObjectHandlerFromProxy(object)->getInvoker()->getObjectPointer(); return objectPointer->getId(); } return null; } JObject* JServer::lookup(JEndPoint* endPoint, JClass* clazz){ JList* inter=new JArrayList(); inter->add(clazz); JObjectHandler* objectHandler = new JObjectHandler(objectInformations, clazz->getClassLoader(), inter, new JObjectPointer(endPoint, clazz->getName())); return objectHandler->getProxy(); } JObject* JServer::lookup(JString* id, JEndPoint* endPoint, JClassLoader* classLoader, JList* interfaces){ JObjectHandler* objectHandler = new JObjectHandler(objectInformations, classLoader, interfaces, new JObjectPointer(endPoint, id)); return objectHandler->getProxy(); } JIRegistry* JServer::getIRegistry(){ return iregistry; } JEndPoint* JServer::getEndPoint(){ return endPoint; } JIGC* JServer::getGC(){ return gc; } JIGCClient* JServer::getGCClient(){ return gcClient; } JExecutorService* JServer::getExecutorService(){ return executorService; } JScheduledExecutorService* JServer::getScheduledExecutorService(){ return scheduledExecutorService; } JObjectInformations* JServer::getObjectInformations(){ return objectInformations; } JConnectionTransportDispatcher* JServer::getConnectionTransportDispatcher(){ return connectionTransportDispatcher; } JConnectionConfiguration* JServer::getConnectionConfiguration(){ return connectionConfiguration; } JINotExportedObjectListener* JServer::getNotExportedObjectListener(){ return notExportedObjectListener; } void JServer::setNotExportedObjectListener(JINotExportedObjectListener* notExportedObjectListener){ this->notExportedObjectListener=notExportedObjectListener; } JINotSerializableObjectHandler* JServer::getNotSerializableObjectHandler(){ return notSerializableObjectHandler; } void JServer::setNotSerializableObjectHandler(JINotSerializableObjectHandler* notSerializableObjectHandler){ this->notSerializableObjectHandler=notSerializableObjectHandler; } JIInvocationExceptionHandler* JServer::getInvocationExceptionHandler(){ return invocationExceptionHandler; } void JServer::setInvocationExceptionHandler(JIInvocationExceptionHandler* i){ this->invocationExceptionHandler=i; } void JServer::unexport(){ gcClient->unexport(); gc->unexport(); objectInformations->unexport(); scheduledExecutorService->shutdown(); executorService->shutdown(); } void JServer::addLifecycle(JILifecycle* lifecycle){ lifecycles->add(dynamic_cast<JObject*>(lifecycle)); } void JServer::removeLifecycle(JILifecycle* lifecycle){ lifecycles->remove(dynamic_cast<JObject*>(lifecycle)); } void JServer::addGCClientListener(JIGCClientListener* gcClientListener){ gcClientListeners->add(dynamic_cast<JObject*>(gcClientListener)); } void JServer::removeGCClientListener(JIGCClientListener* gcClientListener){ gcClientListeners->remove(dynamic_cast<JObject*>(gcClientListener)); } void JServer::addInvocationListener(JIInvocationListener* i){ invocationListeners->add(dynamic_cast<JObject*>(i)); } void JServer::removeInvocationListener(JIInvocationListener* i){ invocationListeners->remove(dynamic_cast<JObject*>(i)); } JObjectHandler* JServer::getObjectHandlerFromProxy(JObject* object){ if (object->getClass()->isProxy()) { JInvocationHandler* invocationHandler = (dynamic_cast<JProxy*>(object))->getInvocationHandler(); if ((dynamic_cast<JObject*>(invocationHandler))->getClass()==JObjectHandler::getClazz()) { JObjectHandler* objectHandler = dynamic_cast<JObjectHandler*>( invocationHandler); return objectHandler; } JStringBuilder* builder=new JStringBuilder(); builder->append("The Proxy object: ") ->append(object) ->append(" is not an instance of ObjectHandler."); throw new JException(builder->toString()); } JStringBuilder* builder=new JStringBuilder(); builder->append("The object: ") ->append(object) ->append(" is not of type Proxy."); throw new JException(builder->toString()); } void JServer::doExport(JObjectInformation* objectInformation, JEndPoint* endPoint){ for (jint i=0;i<lifecycles->size();i++){ JILifecycle* l=dynamic_cast<JILifecycle*>(lifecycles->get(i)); l->doExport(objectInformation,endPoint); } } void JServer::unexport(JObjectInformation* objectInformation){ for (jint i=0;i<lifecycles->size();i++){ JILifecycle* l=dynamic_cast<JILifecycle*>(lifecycles->get(i)); l->unexport(objectInformation); } } void JServer::doExport(JObjectInformation* objectInformation){ for (jint i=0;i<lifecycles->size();i++){ JILifecycle* l=dynamic_cast<JILifecycle*>(lifecycles->get(i)); l->doExport(objectInformation); } } void JServer::unexport(JObjectInformation* objectInformation, JEndPoint* endPoint){ for (jint i=0;i<lifecycles->size();i++){ JILifecycle* l=dynamic_cast<JILifecycle*>(lifecycles->get(i)); l->unexport(objectInformation,endPoint); } } void JServer::objectAlive(JEndPoint* endPoint, JPrimitiveObjectArray* objects){ for (jint i=0;i<gcClientListeners->size();i++){ JIGCClientListener* l=dynamic_cast<JIGCClientListener*>(gcClientListeners->get(i)); l->objectAlive(endPoint,objects); } } void JServer::objectDead(JEndPoint* endPoint, JPrimitiveObjectArray* objects){ for (jint i=0;i<gcClientListeners->size();i++){ JIGCClientListener* l=dynamic_cast<JIGCClientListener*>(gcClientListeners->get(i)); l->objectDead(endPoint,objects); } } void JServer::objectDead(JEndPoint* endPoint, JPrimitiveObjectArray* objects, JThrowable* throwable){ for (jint i=0;i<gcClientListeners->size();i++){ JIGCClientListener* l=dynamic_cast<JIGCClientListener*>(gcClientListeners->get(i)); l->objectDead(endPoint,objects,throwable); } } void JServer::objectMaybeDead(JEndPoint* endPoint, JPrimitiveObjectArray* objects, JThrowable* throwable){ for (jint i=0;i<gcClientListeners->size();i++){ JIGCClientListener* l=dynamic_cast<JIGCClientListener*>(gcClientListeners->get(i)); l->objectMaybeDead(endPoint,objects,throwable); } } void JServer::invocationSucceeded(JObject* proxy, JMethod* method, JList* args){ for (jint i=0;i<invocationListeners->size();i++){ JIInvocationListener* l=dynamic_cast<JIInvocationListener*>(invocationListeners->get(i)); l->invocationSucceeded(proxy,method,args); } } void JServer::invocationFailed(JObject* proxy, JMethod* method, JList* args, JThrowable* e){ for (jint i=0;i<invocationListeners->size();i++){ JIInvocationListener* l=dynamic_cast<JIInvocationListener*>(invocationListeners->get(i)); l->invocationFailed(proxy,method,args,e); } } JString* JServer::toString(){ return this->endPoint->toString(); } JServer::~JServer(){ } } } } }
[ "mimi4930" ]
mimi4930
be856d543cdf89adaa6a9ba803352b1eae2eda37
b0a1e2b1c8337bc6ced4830449f68445adb711e6
/src/DlibDotNet.Native/dlib/data_io/image_dataset_metadata.h
499d4f4fa481b8db33a8f13a766e8fed253f7a66
[ "MIT", "Zlib", "Libpng", "BSL-1.0" ]
permissive
ejoebstl/DlibDotNet
63092a8319c641066c3649a19928612df5c1219a
47436a573c931fc9c9107442b10cf32524805378
refs/heads/master
2020-09-17T06:19:29.651608
2019-12-01T14:21:43
2019-12-01T14:21:43
224,016,962
0
0
MIT
2019-11-25T18:40:19
2019-11-25T18:40:18
null
UTF-8
C++
false
false
10,432
h
#ifndef _CPP_IMAGE_DATASET_METADATA_H_ #define _CPP_IMAGE_DATASET_METADATA_H_ #include "../export.h" #include <dlib/pixel.h> #include <dlib/matrix.h> #include <dlib/data_io/image_dataset_metadata.h> #include "../shared.h" using namespace dlib; using namespace std; #pragma region box DLLEXPORT image_dataset_metadata::box* image_dataset_metadata_box_new() { return new image_dataset_metadata::box(); } DLLEXPORT double image_dataset_metadata_box_get_age(image_dataset_metadata::box* box) { return box->age; } DLLEXPORT void image_dataset_metadata_box_set_age(image_dataset_metadata::box* box, double value) { box->age = value; } DLLEXPORT double image_dataset_metadata_box_get_angle(image_dataset_metadata::box* box) { return box->angle; } DLLEXPORT void image_dataset_metadata_box_set_angle(image_dataset_metadata::box* box, double value) { box->angle = value; } DLLEXPORT image_dataset_metadata::gender_t image_dataset_metadata_box_get_gender(image_dataset_metadata::box* box) { return box->gender; } DLLEXPORT void image_dataset_metadata_box_set_gender(image_dataset_metadata::box* box, image_dataset_metadata::gender_t value) { box->gender = value; } DLLEXPORT bool image_dataset_metadata_box_has_label(image_dataset_metadata::box* box) { return box->has_label(); } DLLEXPORT double image_dataset_metadata_box_get_detection_score(image_dataset_metadata::box* box) { return box->detection_score; } #pragma region parts DLLEXPORT bool image_dataset_metadata_box_get_parts_get_value(image_dataset_metadata::box* box, const char* key, dlib::point** result) { std::map<std::string,point>& m = box->parts; if (m.find(key) == m.end()) { return false; } else { *result = new dlib::point(m[key]); return true; } } DLLEXPORT void image_dataset_metadata_box_get_parts_set_value(image_dataset_metadata::box* box, const char* key, dlib::point* value) { std::map<std::string,dlib::point>& m = box->parts; dlib::point p(*value); m[key] = p; } DLLEXPORT void image_dataset_metadata_box_parts_clear(image_dataset_metadata::box* box) { std::map<std::string,dlib::point>& m = box->parts; m.clear(); } DLLEXPORT int image_dataset_metadata_box_get_parts_get_size(image_dataset_metadata::box* box) { return box->parts.size(); } DLLEXPORT void image_dataset_metadata_box_get_parts_get_all(image_dataset_metadata::box* box, std::vector<std::string*>* strings, std::vector<dlib::point*>* points) { std::map<std::string,dlib::point>& m = box->parts; auto end = m.end(); for (auto it = m.begin(); it != end; it++) { auto f = it->first; auto s = it->second; strings->push_back(new std::string(f)); points->push_back(new dlib::point(s)); } } #pragma endregion parts DLLEXPORT void image_dataset_metadata_box_set_detection_score(image_dataset_metadata::box* box, double value) { box->detection_score = value; } DLLEXPORT bool image_dataset_metadata_box_get_difficult(image_dataset_metadata::box* box) { return box->difficult; } DLLEXPORT void image_dataset_metadata_box_set_difficult(image_dataset_metadata::box* box, bool value) { box->difficult = value; } DLLEXPORT bool image_dataset_metadata_box_get_ignore(image_dataset_metadata::box* box) { return box->ignore; } DLLEXPORT void image_dataset_metadata_box_set_ignore(image_dataset_metadata::box* box, bool value) { box->ignore = value; } DLLEXPORT std::string* image_dataset_metadata_box_get_label(image_dataset_metadata::box* box) { return new std::string(box->label); } DLLEXPORT void image_dataset_metadata_box_set_label(image_dataset_metadata::box* box, const char* value) { box->label = std::string(value); } DLLEXPORT bool image_dataset_metadata_box_get_occluded(image_dataset_metadata::box* box) { return box->occluded; } DLLEXPORT void image_dataset_metadata_box_set_occluded(image_dataset_metadata::box* box, bool value) { box->occluded = value; } DLLEXPORT double image_dataset_metadata_box_get_pose(image_dataset_metadata::box* box) { return box->pose; } DLLEXPORT void image_dataset_metadata_box_set_pose(image_dataset_metadata::box* box, double value) { box->pose = value; } DLLEXPORT dlib::rectangle* image_dataset_metadata_box_get_rect(image_dataset_metadata::box* box) { return new dlib::rectangle(box->rect); } DLLEXPORT void image_dataset_metadata_box_set_rect(image_dataset_metadata::box* box, dlib::rectangle* value) { box->rect = *value; } DLLEXPORT bool image_dataset_metadata_box_get_truncated(image_dataset_metadata::box* box) { return box->truncated; } DLLEXPORT void image_dataset_metadata_box_set_truncated(image_dataset_metadata::box* box, bool value) { box->truncated = value; } DLLEXPORT void image_dataset_metadata_box_delete(image_dataset_metadata::box* box) { delete box; } #pragma endregion box #pragma region dataset DLLEXPORT image_dataset_metadata::dataset* image_dataset_metadata_dataset_new() { return new image_dataset_metadata::dataset(); } DLLEXPORT std::string* image_dataset_metadata_dataset_get_comment(image_dataset_metadata::dataset* dataset) { return new std::string(dataset->comment); } DLLEXPORT void image_dataset_metadata_dataset_set_comment(image_dataset_metadata::dataset* dataset, const char* value) { dataset->comment = std::string(value); } #pragma region images DLLEXPORT std::vector<image_dataset_metadata::image*>* image_dataset_metadata_dataset_get_images(image_dataset_metadata::dataset* dataset) { std::vector<image_dataset_metadata::image>& src = dataset->images; auto dst = new std::vector<image_dataset_metadata::image*>(); vector_to_new_instance(dlib::image_dataset_metadata::image, src, dst); return dst; } DLLEXPORT image_dataset_metadata::image* image_dataset_metadata_dataset_get_images_at(image_dataset_metadata::dataset* dataset, int index) { image_dataset_metadata::image& image = dataset->images.at(index); return &image; } DLLEXPORT int image_dataset_metadata_dataset_get_images_get_size(image_dataset_metadata::dataset* dataset) { return dataset->images.size(); } DLLEXPORT void image_dataset_metadata_dataset_get_images_clear(image_dataset_metadata::dataset* dataset) { dataset->images.clear(); } DLLEXPORT void image_dataset_metadata_dataset_get_images_push_back(image_dataset_metadata::dataset* dataset, image_dataset_metadata::image* image) { image_dataset_metadata::image& i = *image; dataset->images.push_back(i); } DLLEXPORT void image_dataset_metadata_dataset_get_images_remove_at(image_dataset_metadata::dataset* dataset, int index) { dataset->images.erase(dataset->images.begin() + index); } #pragma endregion images DLLEXPORT std::string* image_dataset_metadata_dataset_get_name(image_dataset_metadata::dataset* dataset) { return new std::string(dataset->name); } DLLEXPORT void image_dataset_metadata_dataset_set_name(image_dataset_metadata::dataset* dataset, const char* value) { dataset->name = std::string(value); } DLLEXPORT void image_dataset_metadata_dataset_delete(image_dataset_metadata::dataset* dataset) { delete dataset; } #pragma endregion dataset #pragma region image DLLEXPORT image_dataset_metadata::image* image_dataset_metadata_image_new(const char* filename) { return new image_dataset_metadata::image(filename); } DLLEXPORT image_dataset_metadata::image* image_dataset_metadata_image_new2() { return new image_dataset_metadata::image(); } #pragma region boxes DLLEXPORT std::vector<image_dataset_metadata::box*>* image_dataset_metadata_dataset_get_boxes(image_dataset_metadata::image* image) { std::vector<image_dataset_metadata::box>& src = image->boxes; auto dst = new std::vector<image_dataset_metadata::box*>(); vector_to_new_instance(dlib::image_dataset_metadata::box, src, dst); return dst; } DLLEXPORT image_dataset_metadata::box* image_dataset_metadata_dataset_get_boxes_at(image_dataset_metadata::image* image, int index) { image_dataset_metadata::box& box = image->boxes.at(index); return &box; } DLLEXPORT int image_dataset_metadata_dataset_get_boxes_get_size(image_dataset_metadata::image* image) { return image->boxes.size(); } DLLEXPORT void image_dataset_metadata_dataset_get_boxes_clear(image_dataset_metadata::image* image) { image->boxes.clear(); } DLLEXPORT void image_dataset_metadata_dataset_get_boxes_push_back(image_dataset_metadata::image* image, image_dataset_metadata::box* box) { image_dataset_metadata::box& b = *box; image->boxes.push_back(b); } #pragma endregion boxes DLLEXPORT std::string* image_dataset_metadata_image_get_filename(image_dataset_metadata::image* image) { return new std::string(image->filename); } DLLEXPORT void image_dataset_metadata_image_set_filename(image_dataset_metadata::image* image, const char* value) { image->filename = std::string(value); } DLLEXPORT void image_dataset_metadata_image_delete(image_dataset_metadata::image* image) { delete image; } #pragma endregion image DLLEXPORT int load_image_dataset_metadata(image_dataset_metadata::dataset* meta, const char* filename) { int err = ERR_OK; image_dataset_metadata::dataset& in_meta = *meta; std::string in_filename(filename); try { dlib::image_dataset_metadata::load_image_dataset_metadata(in_meta, filename); } catch(dlib::error e) { err = ERR_GENERAL_FILE_IO; } return err; } DLLEXPORT int save_image_dataset_metadata(image_dataset_metadata::dataset* meta, const char* filename) { int err = ERR_OK; const image_dataset_metadata::dataset& in_meta = *meta; std::string in_filename(filename); try { dlib::image_dataset_metadata::save_image_dataset_metadata(in_meta, filename); } catch(dlib::error e) { err = ERR_GENERAL_FILE_IO; } return err; } #endif
[ "takuya.takeuchi.dev@gmail.com" ]
takuya.takeuchi.dev@gmail.com
44cfa25b5039bbfa82c850e97796b3ddac4ec03d
d92fbcd901a23de9fd42e6892f86d16b9ba063e5
/doublematrix.h
b6322d75d34e84a5d85219a62660767f4adefe34
[]
no_license
lichengchen/calculator
4fadc12fbdc5d6789c2ac58b9b4fd944d246b474
d01e0a9659a2897a8176130336e602bf58d970d5
refs/heads/main
2023-06-30T10:02:49.375994
2021-08-08T07:50:59
2021-08-08T07:50:59
393,889,609
1
0
null
null
null
null
UTF-8
C++
false
false
873
h
#ifndef DOUBLEMATRIX_H #define DOUBLEMATRIX_H #include <QWidget> namespace Ui { class DoubleMatrix; } class DoubleMatrix : public QWidget { Q_OBJECT public: explicit DoubleMatrix(QWidget *parent = 0); ~DoubleMatrix(); private slots: void on_toolButton_1rowadd_clicked(); void on_toolButton_1rowsubb_clicked(); void on_toolButton_1coladd_clicked(); void on_toolButton_1colsub_clicked(); void on_toolButton_2rowadd_clicked(); void on_toolButton_2rowsubb_clicked(); void on_toolButton_2coladd_clicked(); void on_toolButton_2colsub_clicked(); void on_pushButton_Go_clicked(); void on_pushButton_Reset1_clicked(); void on_pushButton_Reset2_clicked(); void on_pushButton_ResetAll_clicked(); private: Ui::DoubleMatrix *ui; }; #endif // DOUBLEMATRIX_H
[ "noreply@github.com" ]
noreply@github.com
8070bde8dc36c158db93f41e93ddd1e341276643
d2afc362494662592cc7a2a79dea826ed582973f
/components/engine/state.h
58a0ff622750c279a542c9649df4204188c01536
[]
no_license
LordTocs/TocsEngine2
9603bcc1f5cc773d604b3765d04c6a9927c230b1
81b945c8e4308b1c481f2b53d3b2bf950eb9aa47
refs/heads/master
2020-04-12T22:13:59.105823
2019-05-23T23:10:19
2019-05-23T23:10:19
162,785,248
0
0
null
null
null
null
UTF-8
C++
false
false
4,973
h
#pragma once #include <vector> #include <memory> #include <bitset> #include "Serializer.h" #include "Interpolation.h" namespace tocs { namespace engine { template<class ValType> class state_value { bool changed; ValType value; public: state_value() : value(), changed(false) {} explicit state_value(const ValType &value) : value(value), changed(false) {} typedef ValType underlying_type; operator ValType () const { //read return value; } const ValType &get_value() const { return value; } state_value<ValType> &operator=(const ValType &new_value) { changed = true; value = new_value; } bool has_changed() const { return changed; } //SFINAE enabled operators. }; class state_object_diff { public: std::bitset<64> changed_values; std::vector<unsigned char> value_memory; }; template <class outer_type> class base_state_value_metadata { public: int value_index; std::string value_name; base_state_value_metadata(int value_index, const std::string &value_name) : value_index(value_index) , value_name(value_name) {} virtual ~base_state_value_metadata() {} virtual size_t data_size() const = 0; virtual void serialize(outer_type *obj, void *data) = 0; //We might be able to avoid a virtual call here if we know the dirty flag is always the first thing in the state_value<> virtual bool is_dirty(outer_type *obj) const = 0; }; template <class outer_type, class type, class interpolation_type = no_interp<type>, class serialization_type = serializer<type>> class state_value_meta_data_constructor { public: const char *name; state_value<type> outer_type::*value_ptr; template<int n> constexpr state_value_meta_data_constructor(state_value<type> outer_type::* value_ptr, const char(&name)[n]) : name(&name[0]) , value_ptr(value_ptr) {} constexpr state_value_meta_data_constructor(const state_value_meta_data_constructor &copyme) = default; template <class new_interp> constexpr auto interpolation() const { return state_value_meta_data_constructor<outer_type, type, new_interp, serialization_type>(*this); } template <class new_serialization> constexpr auto serialization() const { return state_value_meta_data_constructor<outer_type, type, interpolation_type, new_serialization>(*this); } }; #define STATE_REGISTRATION(NAME) \ state_value_meta_data_constructor< \ decltype(state)::meta_data_type::obj_type, \ decltype(NAME)::underlying_type> \ (&decltype(state)::meta_data_type::obj_type::NAME, #NAME) template <class type, class outer_type, class interpolation = no_interp, class type_serializer = serializer<type>> class state_value_metadata : public base_state_value_metadata<outer_type> { public: state_value<type> outer_type::*value_ptr; state_value_metadata(state_value<type> outer_type::* value_ptr, int index, const std::string &value_name) : base_state_value_metadata<outer_type>(index, value_name) , value_ptr(value_ptr) {} size_t data_size() const final override { return type_serializer::size_in_bytes(); } void serialize(outer_type *obj, void *data) final override { type_serializer::write((obj->*value_ptr).get_value(), data); } bool is_dirty(outer_type *obj) const final override { return (obj->*value_ptr).has_changed(); } }; template <class outer_type> class state_object_metadata { public: std::vector<std::unique_ptr<base_state_value_metadata<outer_type>>> values; typedef outer_type obj_type; state_object_metadata() { outer_type::init_state_metadata(); } template <class type, class interpolation, class serializer> void register_value(state_value_meta_data_constructor<outer_type, type, interpolation, serializer> & value_data) { values.emplace_back(new state_value_metadata<type, outer_type, interpolation, serializer>(value_data.value_ptr, values.size(), value_data.name)); } state_object_diff create_diff(outer_type &obj) { state_object_diff result; size_t result_binary_size = 0; for (auto &value : values) { if (value->is_dirty(&obj)) { result.changed_values[value->value_index] = true; result_binary_size += value->data_size(); } } //TODO: Some sort of allocation pool? result.value_memory.resize(result_binary_size, 0); unsigned char *data_ptr = &result.value_memory[0]; for (auto &value : values) { if (value->is_dirty(&obj)) { value->serialize(&obj, data_ptr); data_ptr += value->data_size(); } } } }; template<class outer_type> class state_object { public: typedef state_object_metadata<outer_type> meta_data_type; static meta_data_type meta_data; int priority; }; //register(var_name) //.interp<interp_type>() //.serializer<serial_type>() //.replication //Heirarchical state // //state diffs vs state history //state diffs computed for updates //diffs for history? //cache last update for each value? //difference between volatile_state and state? //volatile stored per frame //normal state stored per update and cached update indexes. } }
[ "Tocs1001@gmail.com" ]
Tocs1001@gmail.com
babafad4a8aee793f0da29fbf208964b90cf4d85
3e5c8a669a7cf38e5f0bcca102f01eb8d0d581ba
/testcpp.cpp
3d708693b0f2a333b2d2640bbcddc250de77da37
[]
no_license
hahahouomg/test_for_cmakeVScode
89f45e67916beaa950741cf7752b3ac5fd5f7304
2cbfc81f02e3b2afca961cd660bf94d78c3a79dd
refs/heads/main
2023-01-23T14:28:15.632896
2020-11-26T09:35:01
2020-11-26T09:35:01
316,143,311
0
0
null
null
null
null
UTF-8
C++
false
false
22
cpp
#include"testheader.h"
[ "noreply@github.com" ]
noreply@github.com
686d1deb28f9c78ef28c7a6ccb913de0bbf9896a
71a87e9b5fa105b7a8965e97e293c986f61b9402
/ProblemInCPP/GenerateParentheses.cpp
2f764e1d8b90d66349ec03645e2da6b4198006b9
[]
no_license
ltp19930730/__Algorithm__
e03d1afce2f4b42978fabfe17edec3c353846a36
e62acc3c9fb83d387f454e2f9198514fe6cd3969
refs/heads/master
2021-06-12T12:51:35.201381
2017-03-01T23:43:13
2017-03-01T23:43:13
54,263,284
0
0
null
null
null
null
UTF-8
C++
false
false
883
cpp
#include <iostream> #include <vector> #include <string> using namespace std; class Parentheses{ public: vector<string> generateParentheses(int n){ vector<string> result; if(n<1){ return result; } string temp; generate(result,temp,n,0,0,0); return result; } void generate(vector<string>&result,string& temp,int n,int deep,int leftP,int rightP){ if(deep==2*n){ result.push_back(temp); return; } if(leftP<n){ temp.push_back('('); generate(result,temp,n,deep+1,leftP+1,rightP); temp.pop_back(); } if(rightP<leftP){ temp.push_back(')'); generate(result,temp,n,deep+1,leftP,rightP+1); temp.pop_back(); } } }; int main(){ Parentheses a; vector<string> b; b=a.generateParentheses(3); for(int i = 0;i<b.size();i++){ cout<<b[i]<<endl; } return 0; }
[ "tluo4@stevens.edu" ]
tluo4@stevens.edu
f2fa3d91d01524611b9a480e657a85c0f40e0a5a
31ac07ecd9225639bee0d08d00f037bd511e9552
/externals/OCCTLib/inc/GeomFill_PipeError.hxx
0f522019163f66f6e8915cca7953d0e71549f2bc
[]
no_license
litao1009/SimpleRoom
4520e0034e4f90b81b922657b27f201842e68e8e
287de738c10b86ff8f61b15e3b8afdfedbcb2211
refs/heads/master
2021-01-20T19:56:39.507899
2016-07-29T08:01:57
2016-07-29T08:01:57
64,462,604
1
0
null
null
null
null
UTF-8
C++
false
false
574
hxx
// This file is generated by WOK (CPPExt). // Please do not edit this file; modify original file instead. // The copyright and license terms as defined for the original file apply to // this header file considered to be the "object code" form of the original source. #ifndef _GeomFill_PipeError_HeaderFile #define _GeomFill_PipeError_HeaderFile enum GeomFill_PipeError { GeomFill_PipeOk, GeomFill_PipeNotOk, GeomFill_PlaneNotIntersectGuide, GeomFill_ImpossibleContact }; #ifndef _Standard_PrimitiveTypes_HeaderFile #include <Standard_PrimitiveTypes.hxx> #endif #endif
[ "litao1009@gmail.com" ]
litao1009@gmail.com
bdfb6924d6be942ccac046f08f7a9cb054814925
050a5e9bd3970f802f3a10adffd7eb4d965511a2
/src/api/operator/random/np_normal_op.cc
60e89e15ceb344d1d1a63bdfda6082552bf65b63
[ "MIT", "BSD-3-Clause", "LLVM-exception", "Zlib", "BSL-1.0", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0", "Unlicense", "BSD-2-Clause" ]
permissive
rongzha1/incubator-mxnet
758948b2cadc7ea469bf02aa28e1af876ed8e6e5
1687b442d9eedf4d9acc36bb84ed2f26da6bb969
refs/heads/master
2023-03-17T13:20:31.260076
2022-05-25T18:29:08
2022-05-25T18:29:08
116,620,123
2
0
Apache-2.0
2019-07-24T05:12:13
2018-01-08T02:39:37
C++
UTF-8
C++
false
false
3,829
cc
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. */ /*! * \file np_normal_op.cc * \brief Implementation of the API of functions in src/operator/numpy/random/np_normal_op.cc */ #include <mxnet/api_registry.h> #include <mxnet/runtime/packed_func.h> #include <vector> #include "../utils.h" #include "../../../operator/numpy/random/np_normal_op.h" namespace mxnet { MXNET_REGISTER_API("_npi.normal") .set_body([](runtime::MXNetArgs args, runtime::MXNetRetValue* ret) { using namespace runtime; const nnvm::Op* op = Op::Get("_npi_normal"); nnvm::NodeAttrs attrs; op::NumpyNormalParam param = {}; int num_inputs = 0; std::vector<NDArray*> inputs; if (args[0].type_code() == kDLFloat || args[0].type_code() == kDLInt) { if (args[1].type_code() == kDLFloat || args[1].type_code() == kDLInt) { // 'loc' and 'scale' are both numeric types num_inputs = 0; param.loc = args[0].operator double(); param.scale = args[1].operator double(); } else { // 'loc' is numeric types but 'scale' is not numeric types num_inputs = 1; param.loc = args[0].operator double(); param.scale = dmlc::nullopt; inputs.push_back(args[1].operator mxnet::NDArray*()); } } else { if (args[1].type_code() == kDLFloat || args[1].type_code() == kDLInt) { // 'loc' is not numeric types but 'scale' is numeric types num_inputs = 1; param.loc = dmlc::nullopt; param.scale = args[1].operator double(); inputs.push_back(args[0].operator mxnet::NDArray*()); } else { // nither 'loc' or 'scale' is numeric types num_inputs = 2; inputs.push_back(args[0].operator mxnet::NDArray*()); inputs.push_back(args[1].operator mxnet::NDArray*()); } } if (args[2].type_code() == kNull) { param.size = dmlc::optional<mxnet::Tuple<index_t>>(); } else if (args[2].type_code() == kDLInt || args[2].type_code() == kDLFloat) { param.size = Tuple<index_t>(1, args[2].operator int64_t()); } else { param.size = Tuple<index_t>(args[2].operator ObjectRef()); } if (args[4].type_code() == kNull) { param.dtype = mxnet::common::GetDefaultDtype(); } else { param.dtype = String2MXNetTypeWithBool(args[4].operator std::string()); } attrs.parsed = param; attrs.op = op; if (args[3].type_code() != kNull) { attrs.dict["ctx"] = args[3].operator std::string(); } NDArray* out = args[5].operator mxnet::NDArray*(); NDArray** outputs = out == nullptr ? nullptr : &out; int num_outputs = out != nullptr; SetAttrDict<op::NumpyNormalParam>(&attrs); auto ndoutputs = Invoke(op, &attrs, num_inputs, inputs.data(), &num_outputs, outputs); if (out) { *ret = PythonArg(5); } else { *ret = reinterpret_cast<mxnet::NDArray*>(ndoutputs[0]); } }); } // namespace mxnet
[ "noreply@github.com" ]
noreply@github.com
6833a841c87f00bf0ce036dec123253fa76405cf
56be00bf237608fbc16f026d76611cef83c8986c
/ListaProjeteis.h
6c1ff88090b1b4706b2862cb271498ed8d0491c8
[]
no_license
pedro-sodre/LemuriaGame
4c20155a73d3becbaa500dfb1e6f7a4b67dee7eb
0ef3ae0b5bdc5760806c19dd9603a515c8865a3c
refs/heads/master
2020-08-06T16:21:11.990088
2019-11-25T04:27:17
2019-11-25T04:27:17
213,070,691
2
0
null
null
null
null
UTF-8
C++
false
false
378
h
#pragma once #include "Lista.h" #include "BolaDeFogo.h" class ListaProjeteis { private: vector<BolaDeFogo*> LTProjeteis; public: ListaProjeteis(); ~ListaProjeteis(); vector<BolaDeFogo*> getLTProjeteis(); void Draw(sf::RenderWindow& window); void limpaLista(); void incluir(BolaDeFogo* pp); void retirar(const int i); };
[ "noreply@github.com" ]
noreply@github.com
8e7b73a78c959f7cd77d4d0fa666a134a9684ba6
701d19cedb341099cafd5602314a0a48ca3e7a50
/RSEngine/SoundClass.h
6176798cdee9a9ca8d5d825aa5ab71c4d7df6999
[]
no_license
denghc/danmugame
9ab9da54f96b12484689154c2588de7263d775c2
12ec3147a95585709d97eae51f82aa1074a56b91
refs/heads/master
2021-01-01T18:21:54.764551
2012-06-11T06:55:54
2012-06-11T06:55:54
4,621,859
2
0
null
null
null
null
UTF-8
C++
false
false
439
h
#pragma once // a wrapper for FMOD::Sound // attach a tag into the sound #include <string> #include "fmod.hpp" #include "fmod_errors.h" class SoundClass { public: SoundClass(void); ~SoundClass(void); public: void Initialize(FMOD::Sound* asnd, std::string tag); bool NameEqual(std::string tname); void Release(); FMOD::Sound* GetSound(); bool IsStream(); private: bool m_isStream; std::string m_tag; FMOD::Sound* m_sound; };
[ "denghc09@gmail.com" ]
denghc09@gmail.com
bd07c2cfc08178cddccda74c8ff17a470954fe01
105cea794f718d34d0c903f1b4b111fe44018d0e
/components/safe_browsing/core/browser/db/hash_prefix_map.cc
e7a050a0fd78c8774c12b01a5181df3d27ca0593
[ "BSD-3-Clause" ]
permissive
blueboxd/chromium-legacy
27230c802e6568827236366afe5e55c48bb3f248
e6d16139aaafff3cd82808a4660415e762eedf12
refs/heads/master.lion
2023-08-12T17:55:48.463306
2023-07-21T22:25:12
2023-07-21T22:25:12
242,839,312
164
12
BSD-3-Clause
2022-03-31T17:44:06
2020-02-24T20:44:13
null
UTF-8
C++
false
false
21,674
cc
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/safe_browsing/core/browser/db/hash_prefix_map.h" #include "base/debug/crash_logging.h" #include "base/files/file_util.h" #include "base/memory/ptr_util.h" #include "base/memory/raw_ref.h" #include "base/run_loop.h" #include "base/strings/strcat.h" #include "components/safe_browsing/core/browser/db/prefix_iterator.h" #include "components/safe_browsing/core/common/features.h" namespace safe_browsing { namespace { constexpr uint32_t kInvalidOffset = std::numeric_limits<uint32_t>::max(); // This is the max size of the offset map since only the first two bytes of the // hash are used to compute the index. constexpr size_t kMaxOffsetMapSize = std::numeric_limits<uint16_t>::max(); std::string GenerateExtension(PrefixSize size) { return base::StrCat( {base::NumberToString(size), "_", base::NumberToString( base::Time::Now().ToDeltaSinceWindowsEpoch().InMicroseconds())}); } // Returns true if |hash_prefix| with PrefixSize |size| exists in |prefixes|. bool HashPrefixMatches(base::StringPiece prefix, HashPrefixesView prefixes, PrefixSize size, size_t start, size_t end) { return std::binary_search(PrefixIterator(prefixes, start, size), PrefixIterator(prefixes, end, size), prefix); } // Gets the index |prefix| should map to in an offset map of size |size|. // The index is calculated as follows: // - Take the first 16 bits of the prefix. // - Divide that number evenly into |size| buckets. size_t GetOffsetIndex(HashPrefixesView prefix, size_t size) { CHECK_GT(prefix.size(), 1u); uint16_t high = static_cast<uint8_t>(prefix[0]); uint16_t low = static_cast<uint8_t>(prefix[1]); uint16_t n = (high << 8) | low; return (n * size) / (std::numeric_limits<uint16_t>::max() + 1); } // Gets the size of the offset map based on the experiment configuration. size_t GetOffsetMapSize(size_t file_size) { static const base::FeatureParam<int> kBytesPerOffsetParam{ &kMmapSafeBrowsingDatabase, "store-bytes-per-offset", 0}; size_t bytes_per_offset = kBytesPerOffsetParam.Get(); if (!bytes_per_offset) return 0; return std::min(kMaxOffsetMapSize, file_size / bytes_per_offset); } // Builds the offset map for a prefix DB file. class OffsetMapBuilder { public: explicit OffsetMapBuilder(PrefixSize prefix_size) : prefix_size_(prefix_size) {} void Reserve(size_t size) { offsets_.Resize(GetOffsetMapSize(size), kInvalidOffset); } // Add() may be called in two situations: // - During a full update, where it will be called with the full hash prefix // list. In this case we will use the size of hash prefix list passed in to // determine the offset map size. // - During a partial update, where it will be called for each hash prefix // individually. In this case, Reserve() must have been called first to // reserve space in the offset map. void Add(HashPrefixesView data) { // If space in the offset map hasn't been reserved and more than one prefix // is being added, reserve space now. if (offsets_.empty() && data.size() > prefix_size_) Reserve(data.size()); if (offsets_.empty()) { cur_offset_ += data.size() / prefix_size_; return; } for (size_t i = 0; i < data.size(); i += prefix_size_) { size_t index = GetOffsetIndex(data.substr(i), offsets_.size()); if (offsets_[index] == kInvalidOffset) offsets_[index] = cur_offset_; cur_offset_++; } } google::protobuf::RepeatedField<uint32_t> TakeOffsets() { // Backfill any empty spots with the value right after it. uint32_t last = cur_offset_; for (int i = offsets_.size() - 1; i >= 0; i--) { if (offsets_[i] == kInvalidOffset) { offsets_[i] = last; } else { last = offsets_[i]; } } return std::move(offsets_); } size_t GetFileSize() const { return cur_offset_ * prefix_size_; } private: const PrefixSize prefix_size_; google::protobuf::RepeatedField<uint32_t> offsets_; size_t cur_offset_ = 0; }; } // namespace InMemoryHashPrefixMap::InMemoryHashPrefixMap() = default; InMemoryHashPrefixMap::~InMemoryHashPrefixMap() = default; void InMemoryHashPrefixMap::Clear() { map_.clear(); } HashPrefixMapView InMemoryHashPrefixMap::view() const { HashPrefixMapView view; view.reserve(map_.size()); for (const auto& kv : map_) view.emplace(kv.first, kv.second); return view; } HashPrefixesView InMemoryHashPrefixMap::at(PrefixSize size) const { return map_.at(size); } void InMemoryHashPrefixMap::Append(PrefixSize size, HashPrefixesView prefix) { map_[size].append(prefix); } void InMemoryHashPrefixMap::Reserve(PrefixSize size, size_t capacity) { map_[size].reserve(capacity); } ApplyUpdateResult InMemoryHashPrefixMap::ReadFromDisk( const V4StoreFileFormat& file_format) { // This is currently handled in V4Store::UpdateHashPrefixMapFromAdditions(). // TODO(cduvall): Move that logic here? DCHECK(file_format.hash_files().empty()); return APPLY_UPDATE_SUCCESS; } namespace { class InMemoryHashPrefixMapWriteSession : public HashPrefixMap::WriteSession { public: InMemoryHashPrefixMapWriteSession( std::unordered_map<PrefixSize, HashPrefixes>& map, ListUpdateResponse* lur) : map_(map), lur_(*lur) {} InMemoryHashPrefixMapWriteSession(const InMemoryHashPrefixMapWriteSession&) = delete; InMemoryHashPrefixMapWriteSession& operator=( const InMemoryHashPrefixMapWriteSession&) = delete; ~InMemoryHashPrefixMapWriteSession() override { auto addition_scanner = lur_->mutable_additions()->begin(); // Move each raw hash from the `ListUpdateResponse` back into the map. for (auto& entry : *map_) { auto raw_hashes = base::WrapUnique( addition_scanner->mutable_raw_hashes()->release_raw_hashes()); entry.second = std::move(*raw_hashes); ++addition_scanner; } } private: const base::raw_ref<std::unordered_map<PrefixSize, HashPrefixes>> map_; const base::raw_ref<ListUpdateResponse> lur_; }; } // namespace std::unique_ptr<HashPrefixMap::WriteSession> InMemoryHashPrefixMap::WriteToDisk( V4StoreFileFormat* file_format) { ListUpdateResponse* const lur = file_format->mutable_list_update_response(); // `file_format` is expected to not contain any additions at this point. It // will during migration from an MmapHashPrefixMap, but the map itself is // empty in that case so there is no data to move into/out of the session. CHECK(lur->additions_size() == 0 || map_.empty()); for (auto& entry : map_) { ThreatEntrySet* additions = lur->add_additions(); // TODO(vakh): Write RICE encoded hash prefixes on disk. Not doing so // currently since it takes a long time to decode them on startup, which // blocks resource load. See: http://crbug.com/654819 additions->set_compression_type(RAW); additions->mutable_raw_hashes()->set_prefix_size(entry.first); // Avoid copying the raw hashes by temporarily moving them into // `file_format`. They will be returned to the map when the caller destroys // the returned write session. auto raw_hashes = std::make_unique<std::string>(std::move(entry.second)); additions->mutable_raw_hashes()->set_allocated_raw_hashes( raw_hashes.release()); } return std::make_unique<InMemoryHashPrefixMapWriteSession>(map_, lur); } ApplyUpdateResult InMemoryHashPrefixMap::IsValid() const { return APPLY_UPDATE_SUCCESS; } HashPrefixStr InMemoryHashPrefixMap::GetMatchingHashPrefix( base::StringPiece full_hash) { for (const auto& [size, prefixes] : map_) { base::StringPiece hash_prefix = full_hash.substr(0, size); if (HashPrefixMatches(hash_prefix, prefixes, size, 0, prefixes.size() / size)) { return std::string(hash_prefix); } } return HashPrefixStr(); } HashPrefixMap::MigrateResult InMemoryHashPrefixMap::MigrateFileFormat( const base::FilePath& store_path, V4StoreFileFormat* file_format) { if (file_format->hash_files().empty()) return MigrateResult::kNotNeeded; ListUpdateResponse* lur = file_format->mutable_list_update_response(); for (const auto& hash_file : file_format->hash_files()) { std::string contents; base::FilePath hashes_path = MmapHashPrefixMap::GetPath(store_path, hash_file.extension()); if (!base::ReadFileToStringWithMaxSize(hashes_path, &contents, kMaxStoreSizeBytes)) { return MigrateResult::kFailure; } auto* additions = lur->add_additions(); additions->set_compression_type(RAW); additions->mutable_raw_hashes()->set_prefix_size(hash_file.prefix_size()); additions->mutable_raw_hashes()->set_raw_hashes(std::move(contents)); } file_format->clear_hash_files(); return MigrateResult::kSuccess; } void InMemoryHashPrefixMap::GetPrefixInfo( google::protobuf::RepeatedPtrField< DatabaseManagerInfo::DatabaseInfo::StoreInfo::PrefixSet>* prefix_sets) { for (const auto& size_and_prefixes : map_) { const PrefixSize& size = size_and_prefixes.first; const HashPrefixes& hash_prefixes = size_and_prefixes.second; DatabaseManagerInfo::DatabaseInfo::StoreInfo::PrefixSet* prefix_set = prefix_sets->Add(); prefix_set->set_size(size); prefix_set->set_count(hash_prefixes.size() / size); } } // Writes a hash prefix file, and buffers writes to avoid a write call for each // hash prefix. The file will be deleted if Finish() is never called. class MmapHashPrefixMap::BufferedFileWriter { public: BufferedFileWriter(const base::FilePath& store_path, PrefixSize prefix_size, size_t buffer_size) : extension_(GenerateExtension(prefix_size)), path_(GetPath(store_path, extension_)), buffer_size_(buffer_size), offset_builder_(prefix_size), file_(path_, base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE), has_error_(!file_.IsValid()) { buffer_.reserve(buffer_size); } ~BufferedFileWriter() { // File was never finished, delete now. if (file_.IsValid() || has_error_) { file_.Close(); base::DeleteFile(path_); } } void Write(HashPrefixesView data) { if (has_error_) return; offset_builder_.Add(data); if (buffer_.size() + data.size() >= buffer_size_) Flush(); if (data.size() > buffer_size_) WriteToFile(data); else buffer_.append(data); } bool Finish() { Flush(); file_.Close(); return !has_error_; } void Reserve(size_t size) { offset_builder_.Reserve(size); } google::protobuf::RepeatedField<uint32_t> TakeOffsets() { return offset_builder_.TakeOffsets(); } size_t GetFileSize() const { return offset_builder_.GetFileSize(); } const std::string& extension() const { return extension_; } private: void Flush() { WriteToFile(buffer_); buffer_.clear(); } void WriteToFile(HashPrefixesView data) { if (has_error_ || data.empty()) return; if (!file_.WriteAtCurrentPosAndCheck(base::as_bytes(base::make_span(data)))) has_error_ = true; } const std::string extension_; const base::FilePath path_; const size_t buffer_size_; OffsetMapBuilder offset_builder_; base::File file_; std::string buffer_; bool has_error_; }; MmapHashPrefixMap::MmapHashPrefixMap( const base::FilePath& store_path, scoped_refptr<base::SequencedTaskRunner> task_runner, size_t buffer_size) : store_path_(store_path), task_runner_(task_runner ? std::move(task_runner) : base::SequencedTaskRunner::GetCurrentDefault()), buffer_size_(buffer_size) {} MmapHashPrefixMap::~MmapHashPrefixMap() { DCHECK(task_runner_->RunsTasksInCurrentSequence()); } void MmapHashPrefixMap::Clear() { if (kMmapSafeBrowsingDatabaseAsync.Get() && !task_runner_->RunsTasksInCurrentSequence()) { // Clear the map on the db task runner, since the memory mapped files should // be destroyed on the same thread they were created. base::Unretained is // safe since the map is destroyed on the db task runner. task_runner_->PostTask(FROM_HERE, base::BindOnce(&MmapHashPrefixMap::ClearOnTaskRunner, base::Unretained(this))); } else { map_.clear(); } } void MmapHashPrefixMap::ClearOnTaskRunner() { DCHECK(task_runner_->RunsTasksInCurrentSequence()); map_.clear(); } HashPrefixMapView MmapHashPrefixMap::view() const { HashPrefixMapView view; view.reserve(map_.size()); for (const auto& kv : map_) { if (!kv.second.IsReadable()) continue; view.emplace(kv.first, kv.second.GetView()); } return view; } HashPrefixesView MmapHashPrefixMap::at(PrefixSize size) const { const FileInfo& info = map_.at(size); CHECK(info.IsReadable()); return info.GetView(); } void MmapHashPrefixMap::Append(PrefixSize size, HashPrefixesView prefix) { if (prefix.empty()) return; GetFileInfo(size).GetOrCreateWriter(buffer_size_)->Write(prefix); } void MmapHashPrefixMap::Reserve(PrefixSize size, size_t capacity) { GetFileInfo(size).GetOrCreateWriter(buffer_size_)->Reserve(capacity); } ApplyUpdateResult MmapHashPrefixMap::ReadFromDisk( const V4StoreFileFormat& file_format) { DCHECK(file_format.list_update_response().additions().empty()); for (const auto& hash_file : file_format.hash_files()) { PrefixSize prefix_size = hash_file.prefix_size(); auto& file_info = GetFileInfo(prefix_size); if (!file_info.Initialize(hash_file)) { return MMAP_FAILURE; } static const base::FeatureParam<bool> kCheckMapSorted{ &kMmapSafeBrowsingDatabase, "check-sb-map-sorted", true}; if (kCheckMapSorted.Get()) { HashPrefixesView prefixes = file_info.GetView(); uint32_t end = prefixes.size() / prefix_size; if (!std::is_sorted(PrefixIterator(prefixes, 0, prefix_size), PrefixIterator(prefixes, end, prefix_size))) { return MMAP_FAILURE; } } } return APPLY_UPDATE_SUCCESS; } namespace { class MmapHashPrefixMapWriteSession : public HashPrefixMap::WriteSession { public: MmapHashPrefixMapWriteSession() = default; MmapHashPrefixMapWriteSession(const MmapHashPrefixMapWriteSession&) = delete; MmapHashPrefixMapWriteSession& operator=( const MmapHashPrefixMapWriteSession&) = delete; ~MmapHashPrefixMapWriteSession() override = default; }; } // namespace std::unique_ptr<HashPrefixMap::WriteSession> MmapHashPrefixMap::WriteToDisk( V4StoreFileFormat* file_format) { for (auto& [size, file_info] : map_) { auto* hash_file = file_format->add_hash_files(); if (!file_info.Finalize(hash_file)) return nullptr; if (!file_info.Initialize(*hash_file)) return nullptr; } return std::make_unique<MmapHashPrefixMapWriteSession>(); } ApplyUpdateResult MmapHashPrefixMap::IsValid() const { for (const auto& kv : map_) { if (!kv.second.IsReadable()) return MMAP_FAILURE; } return APPLY_UPDATE_SUCCESS; } HashPrefixStr MmapHashPrefixMap::GetMatchingHashPrefix( base::StringPiece full_hash) { for (const auto& kv : map_) { HashPrefixStr matching_prefix = kv.second.Matches(full_hash); if (!matching_prefix.empty()) return matching_prefix; } return HashPrefixStr(); } HashPrefixMap::MigrateResult MmapHashPrefixMap::MigrateFileFormat( const base::FilePath& store_path, V4StoreFileFormat* file_format) { // Check if the offset map needs to be updated. This should only happen if a // user switches to an experiment group with a different offset map size // parameter. bool offsets_updated = false; for (auto& hash_file : *file_format->mutable_hash_files()) { if (GetOffsetMapSize(hash_file.file_size()) == static_cast<size_t>(hash_file.offsets().size())) { continue; } OffsetMapBuilder builder(hash_file.prefix_size()); FileInfo info(store_path, hash_file.prefix_size()); if (!info.Initialize(hash_file)) return MigrateResult::kFailure; builder.Add(info.GetView()); *hash_file.mutable_offsets() = builder.TakeOffsets(); offsets_updated = true; } if (offsets_updated) return MigrateResult::kSuccess; ListUpdateResponse* lur = file_format->mutable_list_update_response(); if (lur->additions().empty()) return MigrateResult::kNotNeeded; for (auto& addition : *lur->mutable_additions()) { Append(addition.raw_hashes().prefix_size(), addition.raw_hashes().raw_hashes()); } lur->clear_additions(); return MigrateResult::kSuccess; } void MmapHashPrefixMap::GetPrefixInfo( google::protobuf::RepeatedPtrField< DatabaseManagerInfo::DatabaseInfo::StoreInfo::PrefixSet>* prefix_sets) { for (const auto& size_and_info : map_) { const PrefixSize& size = size_and_info.first; const FileInfo& info = size_and_info.second; DatabaseManagerInfo::DatabaseInfo::StoreInfo::PrefixSet* prefix_set = prefix_sets->Add(); prefix_set->set_size(size); prefix_set->set_count(info.GetView().size() / size); } } // static base::FilePath MmapHashPrefixMap::GetPath(const base::FilePath& store_path, const std::string& extension) { return store_path.AddExtensionASCII(extension); } const std::string& MmapHashPrefixMap::GetExtensionForTesting(PrefixSize size) { return GetFileInfo(size).GetExtensionForTesting(); // IN-TEST } void MmapHashPrefixMap::ClearAndWaitForTesting() { Clear(); base::RunLoop run_loop; task_runner_->PostTask(FROM_HERE, run_loop.QuitClosure()); run_loop.Run(); } MmapHashPrefixMap::FileInfo& MmapHashPrefixMap::GetFileInfo(PrefixSize size) { auto [it, inserted] = map_.try_emplace(size, store_path_, size); return it->second; } MmapHashPrefixMap::FileInfo::FileInfo(const base::FilePath& store_path, PrefixSize size) : store_path_(store_path), prefix_size_(size) {} MmapHashPrefixMap::FileInfo::~FileInfo() = default; HashPrefixesView MmapHashPrefixMap::FileInfo::GetView() const { DCHECK(IsReadable()); return HashPrefixesView(reinterpret_cast<const char*>(file_.data()), file_.length()); } bool MmapHashPrefixMap::FileInfo::Initialize(const HashFile& hash_file) { // Make sure file size is correct before attempting to mmap. int64_t file_size; base::FilePath path = GetPath(store_path_, hash_file.extension()); if (!GetFileSize(path, &file_size)) { return false; } if (static_cast<uint64_t>(file_size) != hash_file.file_size()) { return false; } if (IsReadable()) { DCHECK_EQ(offsets_.size(), static_cast<size_t>(hash_file.offsets().size())); DCHECK_EQ(file_.length(), hash_file.file_size()); return true; } if (!file_.Initialize(path)) { return false; } if (file_.length() != static_cast<size_t>(file_size)) { return false; } offsets_.assign(hash_file.offsets().begin(), hash_file.offsets().end()); return true; } bool MmapHashPrefixMap::FileInfo::Finalize(HashFile* hash_file) { if (!writer_->Finish()) return false; hash_file->set_prefix_size(prefix_size_); *hash_file->mutable_offsets() = writer_->TakeOffsets(); hash_file->set_file_size(writer_->GetFileSize()); hash_file->set_extension(writer_->extension()); writer_.reset(); return true; } HashPrefixStr MmapHashPrefixMap::FileInfo::Matches( base::StringPiece full_hash) const { HashPrefixStr hash_prefix(full_hash.substr(0, prefix_size_)); HashPrefixesView prefixes = GetView(); uint32_t start = 0; uint32_t end = prefixes.size() / prefix_size_; // Check the offset map to see if we can optimize the search. if (!offsets_.empty()) { size_t index = GetOffsetIndex(hash_prefix, offsets_.size()); start = offsets_[index]; if (++index < offsets_.size()) end = offsets_[index]; // If the start is the same as end, the hash doesn't exist. if (start == end) return HashPrefixStr(); } // TODO(crbug.com/1409674): Remove crash logging. base::StringPiece start_prefix = prefixes.substr(0, prefix_size_); base::StringPiece end_prefix = prefixes.substr(prefix_size_ * (end - 1), prefix_size_); SCOPED_CRASH_KEY_STRING64( "SafeBrowsing", "prefix_match", base::StrCat({base::NumberToString(start), ":", base::NumberToString(end), ":", base::NumberToString(prefix_size_), ":", base::NumberToString(prefixes.size()), ":", base::NumberToString(start_prefix.compare(hash_prefix)), ":", base::NumberToString(end_prefix.compare(hash_prefix))})); if (HashPrefixMatches(hash_prefix, prefixes, prefix_size_, start, end)) return hash_prefix; return HashPrefixStr(); } MmapHashPrefixMap::BufferedFileWriter* MmapHashPrefixMap::FileInfo::GetOrCreateWriter(size_t buffer_size) { DCHECK(!file_.IsValid()); if (!writer_) { writer_ = std::make_unique<BufferedFileWriter>(store_path_, prefix_size_, buffer_size); } return writer_.get(); } const std::string& MmapHashPrefixMap::FileInfo::GetExtensionForTesting() const { return writer_->extension(); } } // namespace safe_browsing
[ "chromium-scoped@luci-project-accounts.iam.gserviceaccount.com" ]
chromium-scoped@luci-project-accounts.iam.gserviceaccount.com
27dd713d6e8fef9ae2ba9335a3a4f9add37d03ee
0b2794e85d7aa2158d59bbd3dd581a50cd2781d1
/CrevoLib/src/AutonVectors.h
78a7a10e8434db5e405dc4cee52d8d8e9f78ac28
[]
no_license
CrevolutionRoboticsProgramming/CrevoLib
ec6657debae268770f2b3ec6b999bf2391c9bed4
31bc19e6d4fbf5a767da2d4db694f2e22e463246
refs/heads/v7
2021-01-13T03:28:06.981062
2017-03-02T13:23:44
2017-03-02T13:23:44
77,540,598
1
1
null
2017-03-14T02:44:17
2016-12-28T14:58:53
C++
UTF-8
C++
false
false
943
h
/* * AutonVectors.h * * Created on: Feb 15, 2017 * Author: Martin */ #ifndef SRC_AUTONVECTORS_H_ #define SRC_AUTONVECTORS_H_ #include <crevoglb.h> #include <CrevoRobot.h> #include <DriveTrain.h> #include <Math.h> class AutonVectors { public: enum AutonStratagey { IDLE, SHOOT_FROM_HOPPER, SCORE_GEAR_RIGHT_SHOOT_FROM_LIFT, SCORE_GEAR_CENTER_SHOOT_FROM_BASELINE, SCORE_GEAR_LEFT_SHOOT_FROM_BASELINE, SCORE_GEAR_LEFT_KNOCK_DOWN_HOPPER }; enum AutonAction { SHOOT, SCORE_GEAR, DUMP_HOPPER, NOTHING, FIND_BOILER}; enum GamePiece { FUEL, GEAR }; void AutonChooser(AutonStratagey strat); bool AutonStateProcess(void); AutonVectors(); virtual ~AutonVectors(); private: CrevoRobot crvbot; DriveTrain drvt; Vision vs; void IntakeState(MotorState state); void DoMove(void); void DoGear(void); void DoShoot(void); void DoAline(void); }; #endif /* SRC_AUTONVECTORS_H_ */
[ "mvsmoger@gmail.com" ]
mvsmoger@gmail.com
5870cc84f8731184eceae4a0f24dd0011c321154
34aadfb024f98b6de7441f17b4796c39af168b93
/argus_utils/include/argus_utils/utils/GeometryParsers.h
33d75c0e6c1771b21f26436a9776c9fb5aea2c99
[ "LicenseRef-scancode-unknown-license-reference", "AFL-3.0", "AFL-2.1" ]
permissive
cbuchxrn/argus_utils
5a393014ed9a6dd977995d176fe8ca5f3eea81fc
d19be5bdd54e324d1bb23e10625462bf2c6bd5e0
refs/heads/master
2022-01-12T14:17:12.322705
2018-04-10T17:57:32
2018-04-10T17:57:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,673
h
#pragma once #include "argus_utils/utils/CoreParsers.h" #include "argus_utils/geometry/GeometryTypes.h" #include "argus_utils/geometry/GeometryUtils.h" namespace argus { template <typename S> bool GetParam( const S& nh, const std::string& name, QuaternionType& quat ) { YAML::Node node; if( !GetParam( nh, name, node ) ) { return false; } double w, x, y, z; if( !GetParam( node, "qx", x ) || !GetParam( node, "qy", y ) || !GetParam( node, "qz", z ) || !GetParam( node, "qw", w ) ) { return false; } quat = QuaternionType( w, x, y, z ); return true; } template <typename S> bool GetParam( const S& nh, const std::string& name, EulerAngles& eul ) { YAML::Node node; if( !GetParam( nh, name, node ) ) { return false; } if( !GetParam( node, "yaw", eul.yaw ) || !GetParam( node, "pitch", eul.pitch ) || !GetParam( node, "roll", eul.roll ) ) { return false; } return true; } template <typename S> bool GetParam( const S& nh, const std::string& name, Translation3Type& trans ) { YAML::Node node; if( !GetParam( nh, name, node ) ) { return false; } double x, y, z; if( !GetParam( node, "x", x ) || !GetParam( node, "y", y ) || !GetParam( node, "z", z ) ) { return false; } trans = Translation3Type( x, y, z ); return true; } template <typename S> bool GetParam( const S& nh, const std::string& name, PoseSE3& pose ) { QuaternionType quat; Translation3Type trans; if( !GetParam( nh, name, trans ) ) { return false; } if( !GetParam( nh, name, quat ) ) { EulerAngles eul; if( !GetParam( nh, name, eul ) ) { return false; } quat = EulerToQuaternion( eul ); } pose = PoseSE3( trans, quat ); return true; } }
[ "humhu@cmu.edu" ]
humhu@cmu.edu
a2472ca589347fd11e6199698ae5d4c18585ea78
e467aaa1526f50638eb8feb4e9de8e4fefbd95a5
/classwork7/task01/List.cpp
a66473adbec834c56381d18b3b0faae7560adc44
[]
no_license
KazzModan/My-projects
09114c8d89e7116d7c6f4e6eeaa3e797afbefd53
27d3c933cbd66c80fb3ada65980eaa0366490e21
refs/heads/master
2023-01-13T07:43:17.203421
2020-11-22T14:58:30
2020-11-22T14:58:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,898
cpp
#include "List.h" #include <iostream> using namespace std; template<typename T> List<T>::List() { size = 0; var = nullptr; isEmpty = true; } template<typename T> List<T>::~List() { delete[] var; var = nullptr; size = 0; } template<typename T> List<T>::List(T* var, size_t size) { SetVar(var); setSize(size); } template<typename T> List<T>::List(const List& list, size_t size) { SetVar(list.SetVar()); setSize(list.getSize()); } template<typename T> void List<T>::SetVar(T* var) { this->var = var; } template<typename T> T List<T>::getVar() const { return this->var; } template<typename T> void List<T>::setEmpty(bool isEmpty) { this->isEmpty = isEmpty; } template<typename T> bool List<T>::getEmpty() const { return this->isEmpty; } template<typename T> size_t List<T>::getSize(size_t size) { return this->size; } template<typename T> void List<T>::setSize(size_t size) { this->size = size; } template<typename T> void List<T>::addBack(T nVar) { if (size = 0) { this->var = new T[1] this->var[0] = nVar; this->size++; } newVar = new T[size + 1]; for (size_t i = 0; i < size; i++) { newVar[i] = var[i]; } newVar[size] = nVar; this->size++; delete[] var; this->var = newVar; } template<typename T> void List<T>::Delete(size_t index) { if (index >= size) { cout << "Incorrect number"; return; } this->size--; T* newList = new T[size]; size_t count = 0; for (size_t i = 1; i < this->size; i++) { if (i != index) newList[count++] = this->var[i]; } delete[] this->var; this->var = newList; } template<typename T> void List<T>::addFront(T nVar) { if (size = 0) { this->var = new T[1] this->var[0] = nVar; this->size++; } newVar = new T[size + 1]; newVar[0] = nVar; for (size_t i = 0; i < size; i++) { newVar[i + 1] = var[i]; } newVar[size] = nVar; this->size++; delete[] var; this->var = newVar; } template<typename T> void List<T>::print() { for (size_t i = 0; i < size; i++) { cout<<<<"[" << i << "] :" << var[i] << endl; } } template<typename T> void List<T>::operator = (const List& data) { delete[] this->list; this->list = data.get(); this->size = data.getSize(); } template<typename T> const T& List<T>::operator [] (size_t index) const { if (index >= 0 && index < getSize()) return this->list[index]; return none; } template<typename T> void List<T> :: operator += (const List& data) { T* newList = new T[getSize() + data.getSize()]; for (size_t i = 0; i < this->size; i++) newList[i] = this->list[i]; size_t count = 0; for (size_t i = getSize(); i < getSize() + data.getSize(); i++) newList[i] = data[count++]; this->size = getSize() + data.getSize(); delete[] this->list; this->list = newList; } template<typename T> void List<T> ::operator += (const T& data) { T* newList = new T[getSize() + 1]; for (size_t i = 0; i < this->size; i++) newList[i] = this->list[i]; newList[this->size] = data; this->size++; delete[] this->list; this->list = newList; } template<typename T> void List<T>::find(size_t index) { if (index >= size) { cout << "Incorrect number\n"; return; } for (size_t i = 0; i < size; i++) { if(index==i) cout<<<<"[" << i << "] :" << var[i] << endl; } } template<typename T> ostream& operator<<(ostream& out,const List<T>& var) { out << "size: " << var.getSize() << endl; for (size_t i = 0; i < var.getSize(); i++) out << "[" << i << "] :\t" << var[i] << endl; return out; } template<typename T> void List<T>::sort(size_t leftIndex, size_t rightIndex) { int i = leftIndex, j = rightIndex; int middle = (rightIndex + leftIndex) / 2; do { while (this->var[i] < this->var[middle]) i++; while (this->var[middle] < this->var[j]) j--; if (i <= j) { swap(this->var[i], this->var[j]); i++; j--; } } while (i < j); if (leftIndex < j) sort(leftIndex, j); if (i < rightIndex) sort(i, rightIndex); }
[ "kklopov64@gmail.com" ]
kklopov64@gmail.com
62b1e708ab45435fcada861acb87e7362b998026
e28e5e34a399c49ec61409dfb66a33d3c033498f
/2753/2753.cpp
f5e99e30a1ee760c7b323427c897bedf1f9aae95
[]
no_license
rupc/boj
e72f2e8ec1a69da7d735ac1723273b977cf2155e
281ce9561c152a7330acc31ded83198a1d0c34c7
refs/heads/master
2020-07-02T08:07:00.618675
2017-01-24T05:56:32
2017-01-24T05:56:32
66,392,534
0
0
null
null
null
null
UTF-8
C++
false
false
1,454
cpp
// input, output #include <iostream> #include <iomanip> // container #include <vector> #include <array> #include <list> #include <map> #include <set> #include <string> #include <unordered_map> #include <unordered_set> // container adaper #include <stack> #include <queue> #include <deque> // STL algorithm related #include <algorithm> #include <iterator> #include <functional> #include <numeric> #include <memory> #include <utility> // C standard library #include <cmath> #include <cstdlib> // // #define DEBUG using namespace std; // Declaration of variables // Declaration of auxiliary function class genProbSolver { public: genProbSolver(string s) : name(s) {} void process_input(istream &); void process_solution(); void process_output(ostream &); void echo_input(); private: string name; }; void genProbSolver::process_input(istream &pin) { int year; pin >> year; if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) { std::cout << 1; } else { std::cout << 0; } } void genProbSolver::echo_input() { } void genProbSolver::process_solution() { } void genProbSolver::process_output(ostream &pout) { } int main(int argc, const char *argv[]) { genProbSolver probsolver(""); probsolver.process_input(std::cin); probsolver.echo_input(); probsolver.process_solution(); probsolver.process_output(std::cout); return 0; }
[ "neurosilver@gmail.com" ]
neurosilver@gmail.com
6b4d9ded3928567843c2acff539f9c73e4f45757
756b5994f75dae5c0fe40f5d5a4b338ea895df67
/bspzipgui.h
42477d5666d24b49c84d8ea9bc0015143c13261f
[ "MIT" ]
permissive
geotavros/BspZipGui
c1885431987185fa7654694db61a2e2a5e018d15
462caeecb98c4df408e35655eb9216582d16e39b
refs/heads/master
2021-01-19T09:35:37.306472
2020-06-19T09:09:24
2020-06-19T09:09:24
26,120,350
20
3
null
null
null
null
UTF-8
C++
false
false
977
h
#ifndef BSPZIPGUI_H #define BSPZIPGUI_H #include <QDialog> #include <QDir> #include <QProcess> #include <QProgressDialog> #include <QString> #include "ui_bspzipgui.h" class BspZipGui : public QDialog { Q_OBJECT public: BspZipGui(QWidget *parent = 0, Qt::WindowFlags flags = 0); ~BspZipGui(); public slots: void on_browse_bspzip_clicked(); void on_browse_bsp_file_clicked(); void on_browse_data_folder_clicked(); void on_embed_clicked(); void on_extract_clicked(); void onBspZipProcessFinished(int exitCode, QProcess::ExitStatus exitStatus ); private: void log(const QString &logstr); void getDataFolderFiles(const QDir &dir, QStringList *file_list); bool filesExist(const QStringList &files); void disableAllButtons(); void enableAllButtons(); QStringList data_folder_files_; QProcess *bspzip_process_; //QProgressDialog *progress_dialog_; Ui::BspZipGuiClass ui; }; #endif // BSPZIPGUI_H
[ "geotavros@gmail.com" ]
geotavros@gmail.com
3876d729cc245dff6e06732b0695c0f41ddde2e5
b3331cc7fb9143323d37bb6bff661e7be72b29d3
/18/test04_apply.cpp
7a8e0d3f49e159e79628f36bf0cd64b6ca5cbb4f
[]
no_license
lzb991435344/gittime-CPLUSPLUS
5676fe1a2dd77581973658589bd8725b1fcaab8d
bb5df77618c84b492fe39c7fd00e3972dde96646
refs/heads/master
2023-03-31T18:02:22.520724
2021-03-30T14:49:52
2021-03-30T14:49:52
247,653,183
3
3
null
null
null
null
UTF-8
C++
false
false
1,379
cpp
#include <iostream> // std::cout/endl #include <tuple> // std::tuple/make_tuple/get #include <type_traits> // std::remove_reference_t #include <utility> // std::forward #include <stddef.h> // size_t #include <stdio.h> // printf template <class T, T... Ints> struct integer_sequence {}; template <size_t... Ints> using index_sequence = integer_sequence<size_t, Ints...>; //重载函数 template <size_t N, size_t... Ints> struct index_sequence_helper { typedef typename index_sequence_helper<N - 1, N - 1, Ints...>::type type; }; template <size_t... Ints> struct index_sequence_helper<0, Ints...> { typedef index_sequence<Ints...> type; }; template <size_t N> using make_index_sequence = typename index_sequence_helper<N>::type; template <class F, class Tuple, size_t... I> constexpr decltype(auto) apply_impl(F&& f, Tuple&& t, index_sequence<I...>) { return f(std::get<I>(std::forward<Tuple>(t))...); } template <class F, class Tuple> constexpr decltype(auto) apply(F&& f, Tuple&& t) { return apply_impl( std::forward<F>(f), std::forward<Tuple>(t), make_index_sequence< std::tuple_size_v<std::remove_reference_t<Tuple>>>{}); } int main() { auto tup = std::make_tuple("Hell%d %s!\n", 0, "world"); // Force to use our version of apply, but not std::apply ::apply(printf, tup); }
[ "991435344@qq.com" ]
991435344@qq.com
485c2024140dcc0e4796be7bd866d09c3c9e41d5
e91828f8e87a17b942cc26da4bf061f65e3a04c8
/storage/src/vespa/storage/storageserver/encoded_cluster_state_bundle.h
6f25a6b67a681e43fc6a16dfbbac63240aa17b37
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
NolanJos/vespa
69dbe95b1a9e8cba2879d7b39d882501dc92bebc
fdc4350398029fbffbed3c0498380589a73571d7
refs/heads/master
2022-08-02T10:29:40.065863
2020-06-02T12:47:31
2020-06-02T12:47:31
268,804,702
1
0
Apache-2.0
2020-06-02T13:12:47
2020-06-02T13:12:46
null
UTF-8
C++
false
false
541
h
// Copyright 2018 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #pragma once #include <vespa/vespalib/data/databuffer.h> #include <vespa/vespalib/util/compressor.h> namespace storage { /** * Contains an opaque encoded (possibly compressed) representation of a ClusterStateBundle. */ struct EncodedClusterStateBundle { vespalib::compression::CompressionConfig::Type _compression_type; uint32_t _uncompressed_length; std::unique_ptr<vespalib::DataBuffer> _buffer; }; }
[ "vekterli@oath.com" ]
vekterli@oath.com
2784806cf44dd2528c31f1d75672558519e3bb7d
41e27e40d9c5c820f194b65e466a496d441d9704
/1300_ladder/266A.cpp
f8ca7be2b0f3b7fe4d39f6685bb1ea572538f00f
[ "MIT" ]
permissive
saivarshith2000/A20J
35d51d6fc96f0b23e7d78dff075d8b6ea4ce5147
2faa77eb10ce93cb1822fffba278ef6a24b86cee
refs/heads/master
2020-12-03T03:14:25.785214
2020-01-04T10:34:20
2020-01-04T10:34:20
231,193,839
0
0
null
null
null
null
UTF-8
C++
false
false
428
cpp
// http://codeforces.com/problemset/problem/266/A #include <bits/stdc++.h> using namespace std; int main(){ int n; string input; cin >> n; cin >> input; vector<char> stones; for(int i = 0; i < n; i++)stones.push_back(input[i]); int removals = 0; for(auto itr = stones.begin(); itr < stones.end()-1; itr++){ if (*itr == *(itr+1)){ stones.erase(itr+1); removals ++; } } cout << removals << endl; return 0; }
[ "hosvarshith@gmail.com" ]
hosvarshith@gmail.com
48dcd063c6c16d92e1cc46e361016e090142a66e
464aa9d7d6c4906b083e6c3da12341504b626404
/src/lib/ashes/frame_gui_component.hpp
e646c07dd357d71e9a96d0d350d27d58573427cb
[]
no_license
v2v3v4/BigWorld-Engine-2.0.1
3a6fdbb7e08a3e09bcf1fd82f06c1d3f29b84f7d
481e69a837a9f6d63f298a4f24d423b6329226c6
refs/heads/master
2023-01-13T03:49:54.244109
2022-12-25T14:21:30
2022-12-25T14:21:30
163,719,991
182
167
null
null
null
null
UTF-8
C++
false
false
3,897
hpp
/****************************************************************************** BigWorld Technology Copyright BigWorld Pty, Ltd. All Rights Reserved. Commercial in confidence. WARNING: This computer program is protected by copyright law and international treaties. Unauthorized use, reproduction or distribution of this program, or any portion of this program, may result in the imposition of civil and criminal penalties as provided by law. ******************************************************************************/ #ifndef FRAME_GUI_COMPONENT_HPP #define FRAME_GUI_COMPONENT_HPP #include "simple_gui_component.hpp" /*~ class GUI.FrameGUIComponent * @components{ client, tools } * * This class inherits from SimpleGUIComponent. In addition to the basic * (tiled) image displayed by the SimpleGUIComponent, it adds extra images on * top to form a frame around the image. * * It uses two extra textures. The first is the corner texture, which is * split into four quarters, which are rendered in the corresponding corners * of the overall component. The width and height of the corners is based on * the tiledWidth and tiledHeight attributes of the component. * * The second extra texture is the edge texture. This is assumed to be * oriented correctly to display along the bottom edge of the * FrameGUIComponent. It is then mirrored to display along the top, and * rotated to display along either side edge. * * The height of the top and bottom edges is specified by the tiledHeight * attribute, and the texture is tiled along the top and bottom using the * tiledWidth attribute. * * The width of the side edges is specified by the tiledWidth attribute, and * the texture is tiled long the side edges using the tiledHeight attribute. * * The background image is always displayed tiled, using the tiledWidth and * tiledHeight attributes. It is rendered across the entire surface of the * FrameGUIComponent, with the corners and edges rendered on top of it. * * A new FrameGUIComponent is created using GUI.Frame function. */ /** * FrameGUIComponent is a SimpleGUIComponent. * The only addition in the frame GUI component, is that it * updates the texture coordinates of the base mesh to tile * the background frame texture. */ class FrameGUIComponent : public SimpleGUIComponent { Py_Header( FrameGUIComponent, SimpleGUIComponent ) public: FrameGUIComponent( const std::string& backgroundTextureName, const std::string& frameTextureName, const std::string& edgeTextureName, int tileWidth, int tileHeight, PyTypePlus * pType = &s_type_ ); ~FrameGUIComponent(); PyObject * pyGetAttribute( const char * attr ); int pySetAttribute( const char * attr, PyObject * value ); PY_RW_ACCESSOR_ATTRIBUTE_DECLARE( std::string, edgeTextureName, edgeTextureName ) PY_RW_ACCESSOR_ATTRIBUTE_DECLARE( std::string, cornerTextureName, cornerTextureName ) PY_FACTORY_DECLARE() void update( float dTime, float relParentWidth, float relParentHeight ); void applyShaders( float dTime ); void applyShader( GUIShader& shader, float dTime ); void draw( bool reallyDraw, bool overlay = true ); const std::string & edgeTextureName() const; void edgeTextureName( const std::string & name ); const std::string & cornerTextureName() const; void cornerTextureName( const std::string & name ); private: FrameGUIComponent(const FrameGUIComponent&); FrameGUIComponent& operator=(const FrameGUIComponent&); SimpleGUIComponent* corners_[4]; SimpleGUIComponent* edges_[4]; virtual bool load( DataSectionPtr pSect, const std::string& ownerName, LoadBindings & bindings ); virtual void save( DataSectionPtr pSect, SaveBindings & bindings ); COMPONENT_FACTORY_DECLARE( FrameGUIComponent("","","",16,16) ) }; #ifdef CODE_INLINE #include "frame_gui_component.ipp" #endif #endif // FRAME_GUI_COMPONENT_HPP
[ "terran.erre@mail.ru" ]
terran.erre@mail.ru
bce7d5b89dd6e1d46bd022b54d8c97bed9e6af0b
81159441bf7249cd04e2ea8925ed2ce4ea3eb969
/native/message_router_handler.cpp
86f1e78bd1fffa7d253b65077f7dee1a6b55dd0c
[ "BSD-3-Clause" ]
permissive
DalavanCloud/java-cef
f3108ee835a13b6e3680af1f7319c2dd4ccd40b1
71141140e1ef3ca71704e83915ddd2b7ec8272d8
refs/heads/master
2020-04-22T00:02:05.315618
2019-02-08T21:42:33
2019-02-08T21:42:33
169,965,448
1
0
NOASSERTION
2019-02-10T10:17:46
2019-02-10T10:17:46
null
UTF-8
C++
false
false
2,538
cpp
// Copyright (c) 2014 The Chromium Embedded Framework Authors. All rights // reserved. Use of this source code is governed by a BSD-style license that // can be found in the LICENSE file. #include "message_router_handler.h" #include "client_handler.h" #include "jni_util.h" #include "util.h" MessageRouterHandler::MessageRouterHandler(JNIEnv* env, jobject handler) { jhandler_ = env->NewGlobalRef(handler); } MessageRouterHandler::~MessageRouterHandler() { JNIEnv* env = GetJNIEnv(); env->DeleteGlobalRef(jhandler_); } bool MessageRouterHandler::OnQuery( CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, int64 query_id, const CefString& request, bool persistent, CefRefPtr<CefMessageRouterBrowserSide::Callback> callback) { JNIEnv* env = GetJNIEnv(); if (!env) return false; jobject query_callback = NewJNIObject(env, "org/cef/callback/CefQueryCallback_N"); if (!query_callback) return false; SetCefForJNIObject(env, query_callback, callback.get(), "CefQueryCallback"); jboolean jresult = JNI_FALSE; jstring jrequest = NewJNIString(env, request); jobject jframe = GetJNIFrame(env, frame); JNI_CALL_METHOD(env, jhandler_, "onQuery", "(Lorg/cef/browser/CefBrowser;Lorg/cef/browser/" "CefFrame;JLjava/lang/String;ZLorg/cef/" "callback/CefQueryCallback;)Z", Boolean, jresult, GetJNIBrowser(browser), jframe, (jlong)query_id, jrequest, (jboolean)persistent, query_callback); env->DeleteLocalRef(jrequest); bool result = (jresult != JNI_FALSE); if (!result) { // If the java method returns "false", the callback won't be used and // therefore the reference can be removed. SetCefForJNIObject<CefMessageRouterBrowserSide::Callback>( env, query_callback, NULL, "CefQueryCallback"); } if (jframe) env->DeleteLocalRef(jframe); env->DeleteLocalRef(query_callback); return result; } void MessageRouterHandler::OnQueryCanceled(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, int64 query_id) { JNIEnv* env = GetJNIEnv(); if (!env) return; jobject jframe = GetJNIFrame(env, frame); JNI_CALL_VOID_METHOD( env, jhandler_, "onQueryCanceled", "(Lorg/cef/browser/CefBrowser;Lorg/cef/browser/CefFrame;J)V", GetJNIBrowser(browser), jframe, (jlong)query_id); if (jframe) env->DeleteLocalRef(jframe); }
[ "magreenblatt@gmail.com" ]
magreenblatt@gmail.com
e101cf6c7284dfb87d954d72c5d4e9be5e708864
66f0ebe87722b7a8db1fe621982614096d6ba647
/AutoColor/AutoColor.cpp
b72c94850ef6c3217cc463a15e0407199384bdc5
[]
no_license
15831944/C_Sharp_Class_Exsample
490f7a1cf8caab86711cba6a32a2ebf4e7c4a16c
d8fbf10246e7450ae69c2793e73c7c88b53a16b0
refs/heads/master
2021-09-25T16:59:51.857493
2018-10-24T09:42:07
2018-10-24T09:42:07
null
0
0
null
null
null
null
GB18030
C++
false
false
1,766
cpp
#include "stdafx.h" #include "AutoColor.h" #include "stdafx.h" void Edit(int * buf, int arrLen) { //获取直方图 vector<int*> Histogram(3, new int[256]); for (int i = 0; i < arrLen; i += 3) { Histogram[0][buf[i]]++; Histogram[1][buf[i + 1]]++; Histogram[2][buf[i + 2]]++; } //获取截断区 int minmax[6], filter = arrLen / (6000 * 3); for (int i = 0; i < 3; i++) { int* hist = Histogram[i]; int minV = 0, maxV = 255; for (; minV < 256; minV++) if (hist[minV] > filter && hist[minV] < hist[minV + 1] && hist[minV + 1] < hist[minV + 2]) break; for (; maxV > -1; maxV--) if (hist[maxV] > filter && hist[maxV] < hist[maxV - 1] && hist[maxV - 1] < hist[maxV - 2]) break; minmax[i * 2] = minV; minmax[i * 2 + 1] = maxV; //保护机制,触发后不对源数据做任何处理,保护域10/245 //截断区与启始区过近,表示原图质量OK,不需要做处理 //截断区过大,保留区不足以用于拉伸,表示原图质量过差,没有处理的意义 //屏蔽已经做过拉伸的图像 if ((minV < 10 && maxV > 245) || minV > 245 || maxV < 10) return; } //分波段拉伸 for (int i = 0; i < 3; i++) { float zo = 255.0 / (minmax[i * 2 + 1] - minmax[i * 2]); for (int u = i; u < arrLen; u += 3) { int res = (buf[u] - minmax[i * 2]) * zo;//这里需要类型转换 buf[u] = res < 0 ? 0 : res > 255 ? 255 : res; } } //gamma float gammas[3]; { for (int i = 0; i < arrLen; i += 3) { gammas[0] += buf[i]; gammas[1] += buf[i + 1]; gammas[2] += buf[i + 2]; } for (int i = 0; i < 3; i++) gammas[i] = (gammas[i] / (arrLen / 3)) / 100; for (int i = 0; i < arrLen; i++) buf[i] = pow(buf[i] / 255.0, gammas[i % 3]) * 255;//这里需要类型转换 } }
[ "304701204@qq.com" ]
304701204@qq.com
7faaaeeffd92efcbd1bec03b14e8af0d8145aa86
622ed4861b043a280c98c9c6146d02d393adfadc
/05.class/main.cpp
beeeae8371f439ca9eeeb5179179be09b3907d7d
[]
no_license
jinsenglin/cplusplus
0efc19c59740813c48a04fa33a6a0d86104574d1
f6f1f2955b647ee133e19afd6690a36297fe2f06
refs/heads/master
2021-05-15T04:02:06.611983
2018-01-07T14:31:11
2018-01-07T14:31:11
106,149,264
0
1
null
null
null
null
UTF-8
C++
false
false
899
cpp
#include <iostream> using namespace std; class Person { // private membe int age; // public member public: string gender; // constructor Person (int a, string g) { age = a; gender = g; } // getter int getAge() { return age; } }; class SubPerson : public Person { public: string vendor; // constructor SubPerson (int a, string g, string v) : Person(a, g) { vendor = v; } }; int main() { Person yuyu (25, "female"); cout << "Gender: " << yuyu.gender << endl; cout << "Age: " << yuyu.getAge() << endl; SubPerson david (35, "male", "Weyland Corporation"); cout << "Gender: " << david.gender << endl; cout << "Age: " << david.getAge() << endl; cout << "Vendor: " << david.vendor << endl; return 0; }
[ "jimlintw922@gmail.com" ]
jimlintw922@gmail.com
3b9ad5e676b3d166d32bd5b9b234524fec04ac78
fef58dcd0c1434724a0a0a82e4c84ae906200289
/usages/0x4EF47FE21698A8B6.cpp
421a0bbc9689286622aa6ccd0d718d3acd667a3f
[]
no_license
DottieDot/gta5-additional-nativedb-data
a8945d29a60c04dc202f180e947cbdb3e0842ace
aea92b8b66833f063f391cb86cbcf4d58e1d7da3
refs/heads/main
2023-06-14T08:09:24.230253
2021-07-11T20:43:48
2021-07-11T20:43:48
380,364,689
1
0
null
null
null
null
UTF-8
C++
false
false
1,011
cpp
// finalec1.ysc @ L113820 void func_625(int iParam0, int iParam1) { int iVar0; if (!func_787(Local_150[iParam0 /*14*/])) { return; } if (!func_787(iParam1)) { return; } func_626(iParam0); PED::REMOVE_PED_DEFENSIVE_AREA(Local_150[iParam0 /*14*/], 0); PED::REMOVE_PED_DEFENSIVE_AREA(Local_150[iParam0 /*14*/], 1); PED::SET_PED_DEFENSIVE_AREA_ATTACHED_TO_PED(Local_150[iParam0 /*14*/], iParam1, 10f, 0f, 10f, -10f, 0f, -10f, 10f, 0, 0); TASK::OPEN_SEQUENCE_TASK(&iVar0); TASK::TASK_SET_BLOCKING_OF_NON_TEMPORARY_EVENTS(0, 1); TASK::TASK_GO_TO_ENTITY_WHILE_AIMING_AT_ENTITY(0, iParam1, iParam1, 2f, 1, 5f, 8f, 1, 0, -687903391); TASK::TASK_SET_BLOCKING_OF_NON_TEMPORARY_EVENTS(0, 0); TASK::TASK_COMBAT_HATED_TARGETS_AROUND_PED(0, 100f, 0); TASK::CLOSE_SEQUENCE_TASK(iVar0); TASK::TASK_PERFORM_SEQUENCE(Local_150[iParam0 /*14*/], iVar0); TASK::CLEAR_SEQUENCE_TASK(&iVar0); PED::SET_PED_ACCURACY(Local_150[iParam0 /*14*/], 5); Local_150[iParam0 /*14*/].f_11 = 5; }
[ "tvangroenigen@outlook.com" ]
tvangroenigen@outlook.com
55a17614e7d0227c7c479fc7fa12300e994dc1f9
d1cf34b4d5280e33ebcf1cd788b470372fdd5a26
/zoj/28/2863.cpp
188fa782860a7be1550db9ec45376aa506eb5bd9
[]
no_license
watashi/AlgoSolution
985916ac511892b7e87f38c9b364069f6b51a0ea
bbbebda189c7e74edb104615f9c493d279e4d186
refs/heads/master
2023-08-17T17:25:10.748003
2023-08-06T04:34:19
2023-08-06T04:34:19
2,525,282
97
32
null
2020-10-09T18:52:29
2011-10-06T10:40:07
C++
WINDOWS-1252
C++
false
false
3,546
cpp
// ¶þ·Öͼ #include <list> #include <cstdio> #include <utility> #include <algorithm> using namespace std; pair<int, int> xp[250]; list<int> xe[250]; int x, y, x2y[250], y2x[250]; int mp[20][20]; int doit, next, mark[250], temp[250]; void dfs(int id) { if(doit != -1) return; for (list<int>::iterator itr = xe[id].begin(); itr != xe[id].end(); ++itr) { int yy = *itr; if(mark[yy] == -1) { mark[yy] = 1; temp[yy] = id; if(y2x[yy] == -1) { doit = yy; break; } else dfs(y2x[yy]); } } } int main() { int re; scanf("%d", &re); for (int ri = 1; ri <= re; ri++) { for (int i = 0; i < 15; i++) for (int j = 0; j < 15; j++) scanf("%d", &mp[i][j]); x = y = 0; for (int i = 0; i < 15; i++) for (int j = 0; j < 15; j++) { if(mp[i][j] == 1) { xp[x].first = i; xp[x].second = j; xe[x].clear(); if(j > 0 && mp[i][j - 1] != 0 && mp[i][j - 1] != 1) xe[x].push_front((mp[i][j - 1] >> 1) - 1); if(j < 14 && mp[i][j + 1] != 0 && mp[i][j + 1] != 1) xe[x].push_front((mp[i][j + 1] >> 1) - 1); if(i > 0) { if(mp[i - 1][j] != 0 && mp[i - 1][j] != 1) xe[x].push_front((mp[i - 1][j] >> 1) - 1); if(j > 0 && mp[i - 1][j - 1] != 0 && mp[i - 1][j - 1] != 1) xe[x].push_front((mp[i - 1][j - 1] >> 1) - 1); if(j < 14 && mp[i - 1][j + 1] != 0 && mp[i - 1][j + 1] != 1) xe[x].push_front((mp[i - 1][j + 1] >> 1) - 1); } if(i < 14) { if(mp[i + 1][j] != 0 && mp[i + 1][j] != 1) xe[x].push_front((mp[i + 1][j] >> 1) - 1); if(j > 0 && mp[i + 1][j - 1] != 0 && mp[i + 1][j - 1] != 1) xe[x].push_front((mp[i + 1][j - 1] >> 1) - 1); if(j < 14 && mp[i + 1][j + 1] != 0 && mp[i + 1][j + 1] != 1) xe[x].push_front((mp[i + 1][j + 1] >> 1) - 1); } x++; } else if(mp[i][j] != 0) y = max(y, mp[i][j] >> 1); } printf("Round #%d:\n", ri); if(x != y && x != y + 1) { puts("No solution.\n"); continue; } fill(x2y, x2y + x, -1); fill(y2x, y2x + y, -1); for (int i = 0; i < x; i++) { doit = -1; fill(mark, mark + y, -1); fill(temp, temp + y, -1); dfs(i); while(doit != -1) { y2x[doit] = temp[doit]; next = x2y[temp[doit]]; x2y[temp[doit]] = doit; doit = next; } } if(*min_element(y2x, y2x + y) == -1) { puts("No solution.\n"); continue; } for (int i = 0; i < x; i++) { if(x2y[i] == -1) mp[xp[i].first][xp[i].second] = (y << 1) + 1; else mp[xp[i].first][xp[i].second] = (x2y[i] << 1) + 1; } for (int i = 0; i < 15; i++) { printf("%d", mp[i][0]); for (int j = 1; j < 15; j++) printf(" %d", mp[i][j]); putchar('\n'); } putchar('\n'); } } //2747426 2008-02-10 00:49:10 Accepted 2863 C++ 00:00.01 852K ¤ï¤¿¤· // 2012-09-07 01:43:42 | Accepted | 2863 | C++ | 0 | 188 | watashi | Source
[ "zejun.wu@gmail.com" ]
zejun.wu@gmail.com
b6626ee0e753a49f8bd251b720319edd43958a97
7e2105de2da22f6bbd82cc20e85f9ac684a691f1
/include/evaluator.hpp
78bc0a23f238480d905b4ae1e715eb443a0ee50d
[]
no_license
JohnVithor/BARES
bdb626f2e389bec3cf72eac6250ab94027792425
bcbfb0f6ff487ec837240c50799a4dd2106da58d
refs/heads/master
2021-08-14T18:14:24.854626
2017-11-15T12:12:11
2017-11-15T12:12:11
110,348,392
0
0
null
null
null
null
UTF-8
C++
false
false
5,464
hpp
/** * @file evaluator.hpp * @brief Declaração dos métodos e atributos da classe Evaluator. * @details Converte uma expressão aritmética em notação infixa para posfixa e * depois que a conversão for feita, o programa avalia a expressão * utilizando stacks. Apenas os operadores '+', '-', '*', '%', '/', * e '^' ( para exponenciação ) são aceitos. * * @author João Vítor Venceslau Coelho / Selan Rodrigues dos Santos * @since 28/10/2017 * @date 15/11/2017 */ #ifndef _EVALUATOR_H_ #define _EVALUATOR_H_ #include <string> // std::string #include <cassert> // std::assert #include <cmath> // std::pow #include <stdexcept> // std::runtime_error #include <limits> // std::numeric_limits #include <vector> // std::vector #include "token.hpp" // Token #include "stack.hpp" // jv::stack /** * @brief Classe para converter uma expressão infixa para posfixa e então * avaliando-a */ class Evaluator { using value_type = long int; public: /** * @brief Struct que guarda o valor da avalização e um código que * representa o resultado ( ocorreu um erro ou não ) */ struct EvaluatorResult { /** * @brief Enum com os possiveis resultados que podem ocorrer ( erros ) */ enum code_t { RESULT_OK = 0, DIVISION_BY_ZERO, NUMERIC_OVERFLOW }; value_type value; code_t type; /** * @brief Construtor para EvaluatorResult * * @param[in] val O valor a ser armazenado * @param[in] cod O código para o resultado */ explicit EvaluatorResult( value_type val = 0, code_t cod = code_t::RESULT_OK ) : value( val ) , type( cod ) { /* Vazio */ } }; private: std::vector< Token > expression; /** * @brief Converte o valor de um token em um valor numérico * * @param[in] tok O token a ser convertido * * @return O valor convertido */ value_type Token2Value ( Token tok ); /** * @brief Determina se o token avalizado é um operando * * @param[in] tok Token a ser avaliado * * @return True se for operando, False caso contrário. */ bool is_operand ( Token tok ); /** * @brief Determina se o token avalizado é um operador * * @param[in] tok Token a ser avaliado * * @return True se for operador, False caso contrário. */ bool is_operator ( Token tok ); /** * @brief Determina se o token avalizado é um "(" * * @param[in] tok Token a ser avaliado * * @return True se for "(", False caso contrário. */ bool is_opening_scope ( Token tok ); /** * @brief Determina se o token avalizado é um ")" * * @param[in] tok Token a ser avaliado * * @return True se for ")", False caso contrário. */ bool is_closing_scope ( Token tok ); /** * @brief Determina se o token avalizado é um "^" * * @param[in] tok Token a ser avaliado * * @return True se for "^", False caso contrário. */ bool is_right_association ( Token tok ); /** * @brief Determina qual a prioridade desse token ( operador ) * * @param[in] c Char a ser avaliado * * @return A prioridade do token avaliado. */ short get_precedence ( char c ); /** * @brief Determina qual dos dois tokens possui maior prioridade * * @param[in] op1 A operação representada pelo primeiro token * @param[in] op1 A operação representada pelo segundo token * * @return True se a primeira operação tiver maior prioridade, False caso contrário. */ bool has_higher_precedence ( Token op1, Token op2 ); /** * @brief Executa a operação entre os dois valores informados com a * operação indicada pelo token * * @param[in] term1 Primeiro termo * @param[in] term2 Segundo termo * @param[in] op Token que representa a operação * * @return Retorna um EvaluatorResult, com o valor da operação e * caso tenha ocorrido um erro qual foi. */ Evaluator::EvaluatorResult execute_operator ( value_type term1, value_type term2, char op ); public: /** * @brief Construtor padrão do Evaluator */ Evaluator() = default; /** * @brief Destrutor padrão do Evaluator */ ~Evaluator() = default; /** * @brief Construtor cópia do Evaluator deletado * * @param[in] other O outro Evaluator */ Evaluator( const Evaluator & other ) = delete; /** * @brief Sobrecarga do operador = deletado * * @param[in] other O outro Evaluator * * @return O novo Evaluator */ Evaluator & operator=( const Evaluator & other ) = delete; /** * @brief Converte a expressão tokenizada de infixa para posfixa * * @param[in] infix_ Expressão em notação infixa * * @return Mesma expressão em notação posfixa */ std::vector< Token > infix_to_postfix ( std::vector< Token > infix_ ); /** * @brief Avalia o valor representado pela expressão posfixa * * @param[in] postfix expressão a ser avaliada * * @return EvaluatorResult contendo o valor encontrado e um código * indicando se houve ou não um erro */ Evaluator::EvaluatorResult evaluate_postfix ( std::vector< Token > postfix ); }; #endif
[ "jv.venceslau.c@gmail.com" ]
jv.venceslau.c@gmail.com
1cd6852315fcc77c656712c188d34abbeaac5a14
f653f068b84a26dabf60cd275b98096bf977f9fc
/aeron-driver/src/main/cpp/DriverConductorProxy.h
4c89e4af2be4c1140f67e12fb2ee4b03484c674b
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
onyx-platform/Aeron
817925e0e5013b26744e6fffba43989408601721
262ec06015e0c1a476f5a49338d4a022e0bd28d0
refs/heads/master
2021-05-03T09:43:39.569985
2016-03-28T08:47:04
2016-03-28T08:47:20
54,891,052
3
0
null
2016-03-28T12:34:51
2016-03-28T12:34:51
null
UTF-8
C++
false
false
1,378
h
/* * Copyright 2016 Real Logic Ltd. * * 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 AERON_DRIVERCONDUCTORPROXY_H #define AERON_DRIVERCONDUCTORPROXY_H #include <cstdint> #include <media/InetAddress.h> #include <media/ReceiveChannelEndpoint.h> namespace aeron { namespace driver { using namespace aeron::driver::media; class DriverConductorProxy { public: DriverConductorProxy() {} inline COND_MOCK_VIRTUAL void createPublicationImage( std::int32_t sessionId, std::int32_t streamId, std::int32_t initialTermId, std::int32_t activeTermId, std::int32_t termOffset, std::int32_t termLength, std::int32_t mtuLength, InetAddress& controlAddress, InetAddress& srcAddress, ReceiveChannelEndpoint& channelEndpoint) { } }; }}; #endif //AERON_DRIVERCONDUCTORPROXY_H
[ "mikeb01@gmail.com" ]
mikeb01@gmail.com
a8b391d37a608d707aa179a670caa0663147ca1a
b0b01e896eec4ada3908363c2d6ca3131790e163
/transporter.tests/TestMessage.h
7174feddb342c732789e133f81d9c23f0fb0f4d5
[ "MIT" ]
permissive
aliakbarRashidi/transporter
09374170af4edec5796b08e9f90750db83c52ca1
c6071714995d25f93e7315506c4aba6226423e06
refs/heads/master
2020-04-23T10:22:16.481028
2018-05-27T21:16:49
2018-05-27T21:16:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
585
h
#pragma once #include "transporter/INetworkMessage.h" #include <cstdint> #include <string> class TestMessage : public transporter::network::messages::INetworkMessage { public: static const transporter::network::messages::NetworkMessageId MESSAGE_ID = 1; virtual transporter::network::messages::NetworkMessageId getMessageId() const noexcept override; virtual void serialize(transporter::data::io::IDataOutput &output) const noexcept override; virtual void deserialize(transporter::data::io::IDataInput &input) noexcept override; std::string m_str1; std::int32_t m_i1; };
[ "guillaume.truchot@outlook.com" ]
guillaume.truchot@outlook.com
3b970c0cdeeca90b54fa561e801352c710dc0146
92ada3eabb986350da3f4919a1d75c71a170854d
/autoupdate/common/3rd/boost/mpl/erase.hpp
14641f3fa74c94b6c61114074b1906df33d50a1b
[]
no_license
jjzhang166/autoupdate
126e52be7d610fe121b615c0998af69dcbe70104
7a54996619f03b0febd762c007d5de0c85045a31
refs/heads/master
2021-05-05T20:09:44.330623
2015-08-27T08:57:52
2015-08-27T08:57:52
103,895,533
0
1
null
null
null
null
UTF-8
C++
false
false
1,141
hpp
#ifndef BOOST_MPL_ERASE_HPP_INCLUDED #define BOOST_MPL_ERASE_HPP_INCLUDED // 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) // // See http://www.boost.org/libs/mpl for documentation. // $Source: /repo/3rd/boost/mpl/erase.hpp,v $ // $Date: 2010/04/29 03:06:03 $ // $Revision: 1.1.1.1 $ #include <boost/mpl/erase_fwd.hpp> #include <boost/mpl/sequence_tag.hpp> #include <boost/mpl/aux_/erase_impl.hpp> #include <boost/mpl/aux_/na_spec.hpp> #include <boost/mpl/aux_/lambda_support.hpp> #include <boost/mpl/aux_/config/msvc_typename.hpp> namespace boost { namespace mpl { template< typename BOOST_MPL_AUX_NA_PARAM(Sequence) , typename BOOST_MPL_AUX_NA_PARAM(First) , typename BOOST_MPL_AUX_NA_PARAM(Last) > struct erase : erase_impl< typename sequence_tag<Sequence>::type > ::template apply< Sequence,First,Last > { BOOST_MPL_AUX_LAMBDA_SUPPORT(3,erase,(Sequence,First,Last)) }; BOOST_MPL_AUX_NA_SPEC(3,erase) }} #endif // BOOST_MPL_ERASE_HPP_INCLUDED
[ "269221745@qq.com" ]
269221745@qq.com
8a6e410706176abcc21b15830878851adc08ff2d
79434e1b1ef8e379b28a28a204887a473fe5e875
/loss.h
cf08b68277eb78eff9f7c83037cced10b0b2db44
[]
no_license
thucgn/FrameworkML
18faa6b20393078af51b16776ea324ce25996d2b
e9031f94bff02cfa719b9d03b21722dfedc30690
refs/heads/master
2022-03-03T08:14:52.275460
2018-12-02T11:30:33
2018-12-02T11:30:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,657
h
/************************************************************************* > File Name: loss.h > Author: > Mail: > Created Time: Fri Nov 30 15:31:13 2018 ************************************************************************/ #ifndef _LOSS_H #define _LOSS_H #include "tensor.h" #include "util.h" template <typename T> class Loss { public: virtual void forward(Tensor<T>* y, Tensor<T>* t, Tensor<T>* loss) = 0; virtual void backward(Tensor<T>* y, Tensor<T>* t, Tensor<T>* grad_y) = 0; }; template <typename T> class SquareLoss : public Loss<T> { public: void forward(Tensor<T>* y, Tensor<T>* t, Tensor<T>* loss) { CHECK(y->size == t->size && y->size == loss->size); for(int i = 0;i < loss->size; i ++) loss->data[i] = 0.5 * (y->data[i]-t->data[i]) * (y->data[i]-t->data[i]); } void backward(Tensor<T>* y, Tensor<T>* t, Tensor<T>* grad_y) { CHECK(y->size == t->size && y->size == grad_y->size); for(int i = 0;i < grad_y->size; i ++) grad_y->data[i] = y->data[i] - t->data[i]; } }; template <typename T> class SoftmaxLoss : public Loss<T> { public: /*void forward(Tensor<T>* y, Tensor<T>* label, Tensor<T>* loss) { CHECK(y->size == label->size && y->axes(0) == loss->size); for(int i = 0;i < loss->size; i ++) for(int j = 0;j < label->axes(1); j ++) if((*label)(i, j) == 1) loss->data[i] = 0 - log((*y)(i, j)); }*/ /* * \bref note !!! input is z */ void forward(Tensor<T>* z, Tensor<T>* label, Tensor<T>* loss) { loss->set_zeros(); CHECK(z->size == label->size && z->axes(0) == loss->size); double max_num = 0.0; double sum = 0.0; for(int i = 0; i < z->axes(0); i ++) { sum = max_num = 0.0; for(int j = 0;j < z->axes(1); j ++) if((*z)(i,j) > max_num) max_num = (*z)(i,j); for(int j = 0;j < z->axes(1); j ++) sum += exp((*z)(i,j) - max_num); for(int j = 0;j < z->axes(1); j ++) if((*label)(i,j) == 1) (*loss)(i,0) = max_num - (*z)(i,j) + log(sum); } } /** * \bref output is gradient of z */ void backward(Tensor<T>* y, Tensor<T>* label, Tensor<T>* grad_z) { CHECK(y->size == label->size && label->size == grad_z->size); for(int i = 0;i < grad_z->axes(0); i ++) for(int j = 0;j < grad_z->axes(1); j ++) (*grad_z)(i, j) = (*y)(i, j) - (*label)(i,j); } }; #endif
[ "sdjzgw@163.com" ]
sdjzgw@163.com
3490096d80dc90b57d55c482473a2edf9ace1790
6ced41da926682548df646099662e79d7a6022c5
/aws-cpp-sdk-cloudcontrol/source/model/UpdateResourceResult.cpp
7d32497878729231f3104279a765ad1de89cf904
[ "Apache-2.0", "MIT", "JSON" ]
permissive
irods/aws-sdk-cpp
139104843de529f615defa4f6b8e20bc95a6be05
2c7fb1a048c96713a28b730e1f48096bd231e932
refs/heads/main
2023-07-25T12:12:04.363757
2022-08-26T15:33:31
2022-08-26T15:33:31
141,315,346
0
1
Apache-2.0
2022-08-26T17:45:09
2018-07-17T16:24:06
C++
UTF-8
C++
false
false
975
cpp
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/cloudcontrol/model/UpdateResourceResult.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/AmazonWebServiceResult.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/UnreferencedParam.h> #include <utility> using namespace Aws::CloudControlApi::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; using namespace Aws; UpdateResourceResult::UpdateResourceResult() { } UpdateResourceResult::UpdateResourceResult(const Aws::AmazonWebServiceResult<JsonValue>& result) { *this = result; } UpdateResourceResult& UpdateResourceResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result) { JsonView jsonValue = result.GetPayload().View(); if(jsonValue.ValueExists("ProgressEvent")) { m_progressEvent = jsonValue.GetObject("ProgressEvent"); } return *this; }
[ "aws-sdk-cpp-automation@github.com" ]
aws-sdk-cpp-automation@github.com
f45b507701b6a825102595a8277c5fe3caf8d790
d4fdf31a38382d1f9a3122482a6bc5f7c5859144
/D3DFramework/StaticMesh.h
5d463f37f00d50b0a3500c93ec85d94956d8f784
[]
no_license
Dr1ve/D3DFramework
cbfbace43543f7bcf2fda972c7e28d260d4d8eb2
9bbbac9c8802dab5cdb179d3023d83d53f7bc0d0
refs/heads/master
2021-01-19T00:10:35.992226
2016-11-10T22:26:46
2016-11-10T22:26:46
72,943,000
0
0
null
null
null
null
UTF-8
C++
false
false
889
h
#pragma once #include "Render.h" namespace D3D11Framework { const int buffermax = 16546; class StaticMesh { public: StaticMesh(Render *render); bool Init(wchar_t *name, wchar_t *fnametex); void Draw(CXMMATRIX viewmatrix); void Close(); void Translate(float x, float y, float z); void Rotate(float angle, float x, float y, float z); void Scale(float x, float y, float z); void Identity(); void *operator new(size_t i) { return _aligned_malloc(i, 16); } void operator delete(void *p) { _aligned_free(p); } private: void LoadMeshFromObj(wchar_t *fname); void m_RenderBuffers(); void m_SetShaderParameters(CXMMATRIX viewmatrix); void m_RenderShader(); Render *m_render; ID3D11Buffer *m_vertexBuffer; ID3D11Buffer *m_indexBuffer; ID3D11Buffer *m_constantBuffer; Shader *m_shader; XMMATRIX m_objMatrix; unsigned short m_indexCount; }; }
[ "nazin_konstantin@mail.ru" ]
nazin_konstantin@mail.ru
04770519cc23e517c2dbe9aee0b249ea006c8833
a2b5344ec8ee1d2b801137596b269619eacc4530
/v3/qa_testing/production_tests/LightSensorsTest/coresense/airsense.ino
c16d3b06a361b13633ea2b3696743bf820d36917
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
waggle-sensor/sensors
3029916268c1286d15b89c22e71dcea5a3fe2987
2ce1142b6fd7efd17ae5ae99ad49c6e008fdebb2
refs/heads/master
2021-01-22T20:49:53.053294
2019-04-10T14:50:32
2019-04-10T14:50:32
85,365,782
12
14
null
2018-07-30T22:06:19
2017-03-18T00:39:17
HTML
UTF-8
C++
false
false
5,042
ino
void airsense_acquire (void) { // #ifdef SERIAL_DEBUG // SerialUSB.print("\n"); // SerialUSB.println("Acquiring AirSense Data."); // #endif #ifdef SPV1840LR5HB_include SPV1840LR5HB[0] = ID_SPV1840LR5HB; SPV1840LR5HB[1] = (1 << 7) | LENGTH_FORMAT1; Temp_uint16 = analogRead(PIN_RAW_MIC); format1(Temp_uint16); SPV1840LR5HB[2] = formatted_data_buffer[0]; SPV1840LR5HB[3] = formatted_data_buffer[1]; #ifdef SERIAL_DEBUG SerialUSB.print("SPV1840LR5HB:"); SerialUSB.println(Temp_uint16); #endif #endif #ifdef TMP112_include TMP112_read(); TMP112[0] = ID_TMP112; TMP112[1] = (1 << 7) | LENGTH_FORMAT6; format6(Temp_float[0]); // Put it into format 1 TMP112[2] = formatted_data_buffer[0]; TMP112[3] = formatted_data_buffer[1]; #ifdef SERIAL_DEBUG SerialUSB.print("TMP112:"); SerialUSB.println(Temp_float[0]); #endif #endif #ifdef HTU21D_include Temp_float[1] = myHumidity.readHumidity(); Temp_float[0] = myHumidity.readTemperature(); HTU21D[0] = ID_HTU21D; HTU21D[1] = (1 << 7) | (LENGTH_FORMAT6 * 2); format6(Temp_float[0]); // Put it into format 1 HTU21D[2] = formatted_data_buffer[0]; HTU21D[3] = formatted_data_buffer[1]; format6(Temp_float[1]); // Put it into format 1 HTU21D[4] = formatted_data_buffer[0]; HTU21D[5] = formatted_data_buffer[1]; #ifdef SERIAL_DEBUG SerialUSB.print("HTU21D:"); SerialUSB.print(Temp_float[0]); SerialUSB.print(","); SerialUSB.print(Temp_float[1]); SerialUSB.println(); #endif #endif #ifdef BMP180_include BMP180[0] = ID_BMP180; bmp.getEvent(&event); /* Display the results (barometric pressure is measure in Pascals) */ if (event.pressure) { BMP180[1] = (1 << 7) | (LENGTH_FORMAT6 + LENGTH_FORMAT5); Temp_long = long(event.pressure); bmp.getTemperature(&Temp_float[0]); format6(Temp_float[0]); BMP180[2] = formatted_data_buffer[0]; BMP180[3] = formatted_data_buffer[1]; format5(Temp_long); BMP180[4] = formatted_data_buffer[0]; BMP180[5] = formatted_data_buffer[1]; BMP180[6] = formatted_data_buffer[2]; } else { BMP180[1] = (0 << 7) | (LENGTH_FORMAT6 + LENGTH_FORMAT5); } #ifdef SERIAL_DEBUG SerialUSB.print("BMP180:"); SerialUSB.print(Temp_float[0]); SerialUSB.print(","); SerialUSB.print(Temp_long); SerialUSB.println(); #endif #endif #ifdef PR103J2_include PR103J2[0] = ID_PR103J2; PR103J2[1] = (1 << 7) | LENGTH_FORMAT1; Temp_uint16 = analogRead(A2D_PRJ103J2); format1(Temp_uint16); PR103J2[2] = formatted_data_buffer[0]; PR103J2[3] = formatted_data_buffer[1]; #ifdef SERIAL_DEBUG SerialUSB.print("PR103J2:"); SerialUSB.println(Temp_uint16); #endif #endif #ifdef TSL250RD_1_include TSL250RD_1[0] = ID_TSL250RD_1; TSL250RD_1[1] = (1 << 7) | LENGTH_FORMAT1; Temp_uint16 = analogRead(A2D_TSL250RD_1); format1(Temp_uint16); TSL250RD_1[2] = formatted_data_buffer[0]; TSL250RD_1[3] = formatted_data_buffer[1]; #ifdef SERIAL_DEBUG SerialUSB.print("TSL250RD:"); SerialUSB.println(Temp_uint16); #endif #endif #ifdef MMA8452Q_include MMA8452_read(); MMA8452Q[0] = ID_MMA8452Q; MMA8452Q[1] = (1 << 7) | (LENGTH_FORMAT6 * 4); format6(Temp_float[0]); // Put it into format 1 MMA8452Q[2] = formatted_data_buffer[0]; MMA8452Q[3] = formatted_data_buffer[1]; format6(Temp_float[1]); // Put it into format 1 MMA8452Q[4] = formatted_data_buffer[0]; MMA8452Q[5] = formatted_data_buffer[1]; format6(Temp_float[2]); // Put it into format 1 MMA8452Q[6] = formatted_data_buffer[0]; MMA8452Q[7] = formatted_data_buffer[1]; format6(0); // Put it into format 1 MMA8452Q[8] = formatted_data_buffer[0]; MMA8452Q[9] = formatted_data_buffer[1]; #ifdef SERIAL_DEBUG SerialUSB.print("MMA8452Q:"); SerialUSB.print(Temp_float[0]); SerialUSB.print(","); SerialUSB.print(Temp_float[1]); SerialUSB.print(","); SerialUSB.print(Temp_float[2]); SerialUSB.print(","); SerialUSB.println(0); #endif #endif #ifdef TSYS01_include TSYS01_read(); TSYS01[0] = ID_TSYS01; TSYS01[1] = (1 << 7) | LENGTH_FORMAT6; format6(Temp_float[0]); // Put it into format 2 TSYS01[2] = formatted_data_buffer[0]; TSYS01[3] = formatted_data_buffer[1]; #ifdef SERIAL_DEBUG SerialUSB.print("TSYS01:"); SerialUSB.println(Temp_float[0]); #endif #endif #ifdef HIH4030_include HIH4030[0] = ID_HIH4030; HIH4030[1] = (1 << 7) | LENGTH_FORMAT1; Temp_uint16 = analogRead(PIN_HIH4030); format1(Temp_uint16); HIH4030[2] = formatted_data_buffer[0]; HIH4030[3] = formatted_data_buffer[1]; #ifdef SERIAL_DEBUG SerialUSB.print("HIH4030:"); SerialUSB.println(Temp_uint16); #endif #endif }
[ "r@anl.gov" ]
r@anl.gov
d5e76410f6d5fbab7563976c63d5a4687737257d
8e0d00d27481866c21b8bedb30fe30bcc7471e0f
/FizzBuzzHandler.h
f729736d92a19b544edb2b4e80022985717ddca6
[]
no_license
kaelzhang81/KataFizzBuzzCpp
630e218b4488be67f8ba055ca5ff3628d5342a2d
84999216bf9d8e157e9fe4767b23de25a11241d6
refs/heads/master
2016-09-11T07:11:16.448712
2014-10-01T14:17:48
2014-10-01T14:17:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
210
h
#pragma once #include "wordhandler.h" class FizzBuzzHandler : public WordHandler { public: FizzBuzzHandler(WordHandler* successor); ~FizzBuzzHandler(void); string Handle(const int number); };
[ "zhangy1981@qq.com" ]
zhangy1981@qq.com
cf3892f42bca4e086f358794ecc995f451b4f72a
228b3991847efd8ba9ce8783e2e98b7748c6c666
/string/multiply_complex_numbers.cpp
2f4e3d492bcbdf82e782ee78db04e35830b05d8c
[]
no_license
lion38925/kit
04f23dd95a6acda1e01a09c1046bac63c398ff62
ad77a5ed19e0f390c2e405dd0c1ac24599582458
refs/heads/main
2023-07-07T03:14:03.029206
2021-08-12T17:08:45
2021-08-12T17:08:45
395,386,440
0
0
null
null
null
null
UTF-8
C++
false
false
536
cpp
class Solution { public: string complexNumberMultiply(string a, string b) { int r1, c1, r2, c2, r3, c3; int pos1 = a.find('+'); int pos2 = b.find('+'); r1 = stoi(a.substr(0, pos1)); r2 = stoi(b.substr(0, pos2)); c1 = stoi(a.substr(pos1+1, a.size()-1-pos1)); c2 = stoi(b.substr(pos2+1, b.size()-1-pos2)); r3 = (r1 * r2) - (c1 * c2); c3 = (r1 * c2) + (r2 * c1); return to_string(r3) + '+' + to_string(c3) + 'i'; } };
[ "noreply@github.com" ]
noreply@github.com
7ee1528951dad5e6e9c5be37825a83ef7da74c25
48e9625fcc35e6bf790aa5d881151906280a3554
/Sources/Elastos/LibCore/src/elastos/io/ByteArrayBuffer.cpp
ade3de2db0a3d6cd6a6ed91f95158565bf06e1c5
[ "Apache-2.0" ]
permissive
suchto/ElastosRT
f3d7e163d61fe25517846add777690891aa5da2f
8a542a1d70aebee3dbc31341b7e36d8526258849
refs/heads/master
2021-01-22T20:07:56.627811
2017-03-17T02:37:51
2017-03-17T02:37:51
85,281,630
4
2
null
2017-03-17T07:08:49
2017-03-17T07:08:49
null
UTF-8
C++
false
false
23,430
cpp
//========================================================================= // Copyright (C) 2012 The Elastos 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. //========================================================================= #include "Elastos.CoreLibrary.Libcore.h" #include "ByteArrayBuffer.h" #include "Memory.h" #include "ByteBufferAsCharBuffer.h" #include "ByteBufferAsDoubleBuffer.h" #include "ByteBufferAsFloatBuffer.h" #include "ByteBufferAsInt16Buffer.h" #include "ByteBufferAsInt32Buffer.h" #include "ByteBufferAsInt64Buffer.h" #include "CByteOrderHelper.h" #include "Math.h" #include "logging/Logger.h" using Libcore::IO::ISizeOf; using Libcore::IO::Memory; using Elastos::Utility::Logging::Logger; namespace Elastos { namespace IO { CAR_INTERFACE_IMPL(ByteArrayBuffer, ByteBuffer, IByteArrayBuffer) ByteArrayBuffer::ByteArrayBuffer() : mArrayOffset(0) , mIsReadOnly(FALSE) {} ECode ByteArrayBuffer::constructor( /* [in] */ ArrayOf<Byte>* backingArray) { return ByteArrayBuffer::constructor(backingArray->GetLength(), backingArray, 0, FALSE); } ECode ByteArrayBuffer::constructor( /* [in] */ Int32 capacity, /* [in] */ ArrayOf<Byte>* backingArray, /* [in] */ Int32 arrayOffset, /* [in] */ Boolean isReadOnly) { FAIL_RETURN(ByteBuffer::constructor(capacity, 0)) if (arrayOffset + capacity > backingArray->GetLength()) { // throw new IndexOutOfBoundsException("backingArray.length=" + backingArray.length + // ", capacity=" + capacity + ", arrayOffset=" + arrayOffset); return E_INDEX_OUT_OF_BOUNDS_EXCEPTION; } mBackingArray = backingArray; mArrayOffset = arrayOffset; mIsReadOnly = isReadOnly; return NOERROR; } ECode ByteArrayBuffer::GetPrimitiveArray( /* [out] */ Handle64* arrayHandle) { AutoPtr<ArrayOf<Byte> > arrayTemp; GetArray((ArrayOf<Byte>**)&arrayTemp); if (arrayTemp == NULL) { *arrayHandle = 0; return NOERROR; } Byte* primitiveArray = arrayTemp->GetPayload(); *arrayHandle = reinterpret_cast<Handle64>(primitiveArray); return NOERROR; } ECode ByteArrayBuffer::Copy( /* [in] */ ByteArrayBuffer* other, /* [in] */ Int32 markOfOther, /* [in] */ Boolean mIsReadOnly, /* [out] */ IByteBuffer** bab) { Int32 capvalue = 0; other->GetCapacity(&capvalue); AutoPtr<ByteArrayBuffer> buf = new ByteArrayBuffer(); FAIL_RETURN(buf->constructor(capvalue, other->mBackingArray, other->mArrayOffset, mIsReadOnly)) buf->mLimit = other->mLimit; buf->mPosition = other->mPosition; buf->mMark = markOfOther; *bab = IByteBuffer::Probe(buf); REFCOUNT_ADD(*bab) return NOERROR; } ECode ByteArrayBuffer::AsReadOnlyBuffer( /* [out] */ IByteBuffer** buffer) { return Copy(this, mMark, TRUE, buffer); } ECode ByteArrayBuffer::Compact() { if (mIsReadOnly) { // throw new ReadOnlyBufferException(); return E_READ_ONLY_BUFFER_EXCEPTION; } Int32 remainvalue = 0; GetRemaining(&remainvalue); // System.arraycopy(mBackingArray, mPosition + mArrayOffset, mBackingArray, mArrayOffset, remaining()); mBackingArray->Copy(mArrayOffset, mBackingArray, mPosition + mArrayOffset, remainvalue); mPosition = mLimit - mPosition; mLimit = mCapacity; mMark = UNSET_MARK; return NOERROR; } ECode ByteArrayBuffer::Duplicate( /* [out] */ IByteBuffer** buffer) { return Copy(this, mMark, mIsReadOnly, buffer); } ECode ByteArrayBuffer::Slice( /* [out] */ IByteBuffer** buffer) { VALIDATE_NOT_NULL(buffer) *buffer = NULL; Int32 remainvalue = 0; GetRemaining(&remainvalue); AutoPtr<ByteArrayBuffer> res = new ByteArrayBuffer(); FAIL_RETURN(res->constructor(remainvalue, mBackingArray, mArrayOffset + mPosition, mIsReadOnly)) *buffer = IByteBuffer::Probe(res); REFCOUNT_ADD(*buffer) return NOERROR; } ECode ByteArrayBuffer::IsReadOnly( /* [out] */ Boolean* isReadOnly) { VALIDATE_NOT_NULL(isReadOnly) *isReadOnly = mIsReadOnly; return NOERROR; } ECode ByteArrayBuffer::ProtectedArray( /* [out, callee] */ ArrayOf<Byte>** array) { VALIDATE_NOT_NULL(array) *array = NULL; if (mIsReadOnly) { Logger::E("ByteArrayBuffer", "ProtectedArray: ReadOnlyBufferException"); return E_READ_ONLY_BUFFER_EXCEPTION; } *array = mBackingArray; REFCOUNT_ADD(*array) return NOERROR; } ECode ByteArrayBuffer::ProtectedArrayOffset( /* [out] */ Int32* offset) { VALIDATE_NOT_NULL(offset) *offset = 0; if (mIsReadOnly) { Logger::E("ByteArrayBuffer", "ProtectedArrayOffset: ReadOnlyBufferException"); return E_READ_ONLY_BUFFER_EXCEPTION; } *offset = mArrayOffset; return NOERROR; } ECode ByteArrayBuffer::ProtectedHasArray( /* [out] */ Boolean* hasArray) { VALIDATE_NOT_NULL(hasArray) *hasArray = TRUE; if (mIsReadOnly) { *hasArray = FALSE; } return NOERROR; } ECode ByteArrayBuffer::Get( /* [out] */ Byte* value) { VALIDATE_NOT_NULL(value) *value = '\0'; if (mPosition == mLimit) { Logger::E("ByteArrayBuffer", "Get: BufferUnderflowException"); return E_BUFFER_UNDERFLOW_EXCEPTION; } *value = (*mBackingArray)[mArrayOffset + mPosition++]; return NOERROR; } ECode ByteArrayBuffer::Get( /* [in] */ Int32 index, /* [out] */ Byte* value) { VALIDATE_NOT_NULL(value) *value = '\0'; FAIL_RETURN(CheckIndex(index)); *value = (*mBackingArray)[mArrayOffset + index]; return NOERROR; } ECode ByteArrayBuffer::Get( /* [in] */ ArrayOf<Byte>* dst, /* [in] */ Int32 dstOffset, /* [in] */ Int32 byteCount) { Int32 outvalue = 0; FAIL_RETURN(CheckGetBounds(1, dst->GetLength(), dstOffset, byteCount, &outvalue)) // System.arraycopy(mBackingArray, mArrayOffset + mPosition, dst, dstOffset, byteCount); dst->Copy(dstOffset, mBackingArray, mArrayOffset + mPosition, byteCount); mPosition += byteCount; return NOERROR; } ECode ByteArrayBuffer::GetChar( /* [out] */ Char32* value) { VALIDATE_NOT_NULL(value) *value = '\0'; Int32 newPosition = mPosition + ISizeOf::CHAR; if (newPosition > mLimit) { // throw new BufferUnderflowException(); return E_BUFFER_UNDERFLOW_EXCEPTION; } Char32 result = (Char32) Memory::PeekInt32(mBackingArray, mArrayOffset + mPosition, mOrder); mPosition = newPosition; *value = result; return NOERROR; } ECode ByteArrayBuffer::GetChar( /* [in] */ Int32 index, /* [out] */ Char32* value) { VALIDATE_NOT_NULL(value) *value = '\0'; FAIL_RETURN(CheckIndex(index, ISizeOf::CHAR)); *value = (Char32) Memory::PeekInt32(mBackingArray, mArrayOffset + index, mOrder); return NOERROR; } ECode ByteArrayBuffer::GetDouble( /* [out] */ Double* value) { VALIDATE_NOT_NULL(value) Int64 l; FAIL_RETURN(GetInt64(&l)); *value = Elastos::Core::Math::Int64BitsToDouble(l); return NOERROR; } ECode ByteArrayBuffer::GetDouble( /* [in] */ Int32 index, /* [out] */ Double* value) { VALIDATE_NOT_NULL(value) Int64 l; FAIL_RETURN(GetInt64(index, &l)); *value = Elastos::Core::Math::Int64BitsToDouble(l); return NOERROR; } ECode ByteArrayBuffer::GetFloat( /* [out] */ Float* value) { VALIDATE_NOT_NULL(value) Int32 i; FAIL_RETURN(GetInt32(&i)); *value = Elastos::Core::Math::Int32BitsToFloat(i); return NOERROR; } ECode ByteArrayBuffer::GetFloat( /* [in] */ Int32 index, /* [out] */ Float* value) { VALIDATE_NOT_NULL(value) Int32 i; FAIL_RETURN(GetInt32(index, &i)); *value = Elastos::Core::Math::Int32BitsToFloat(i); return NOERROR; } ECode ByteArrayBuffer::GetInt32( /* [out] */ Int32* value) { VALIDATE_NOT_NULL(value) Int32 newPosition = mPosition + ISizeOf::INT32; if (newPosition > mLimit) { // throw new BufferUnderflowException(); return E_BUFFER_UNDERFLOW_EXCEPTION; } Int32 result = Memory::PeekInt32(mBackingArray, mArrayOffset + mPosition, mOrder); mPosition = newPosition; *value = result; return NOERROR; } ECode ByteArrayBuffer::GetInt32( /* [in] */ Int32 index, /* [out] */ Int32* value) { VALIDATE_NOT_NULL(value) FAIL_RETURN(CheckIndex(index, ISizeOf::INT32)); *value = Memory::PeekInt32(mBackingArray, mArrayOffset + index, mOrder); return NOERROR; } ECode ByteArrayBuffer::GetInt64( /* [out] */ Int64* value) { VALIDATE_NOT_NULL(value) Int32 newPosition = mPosition + ISizeOf::INT64; if (newPosition > mLimit) { // throw new BufferUnderflowException(); return E_BUFFER_UNDERFLOW_EXCEPTION; } Int64 result = Memory::PeekInt64(mBackingArray, mArrayOffset + mPosition, mOrder); mPosition = newPosition; *value = result; return NOERROR; } ECode ByteArrayBuffer::GetInt64( /* [in] */ Int32 index, /* [out] */ Int64* value) { VALIDATE_NOT_NULL(value) FAIL_RETURN(CheckIndex(index, ISizeOf::INT64)); *value = Memory::PeekInt64(mBackingArray, mArrayOffset + index, mOrder); return NOERROR; } ECode ByteArrayBuffer::GetInt16( /* [out] */ Int16* value) { VALIDATE_NOT_NULL(value) Int32 newPosition = mPosition + ISizeOf::INT16; if (newPosition > mLimit) { // throw new BufferUnderflowException(); return E_BUFFER_UNDERFLOW_EXCEPTION; } Int16 result = Memory::PeekInt16(mBackingArray, mArrayOffset + mPosition, mOrder); mPosition = newPosition; *value = result; return NOERROR; } ECode ByteArrayBuffer::GetInt16( /* [in] */ Int32 index, /* [out] */ Int16* value) { VALIDATE_NOT_NULL(value) FAIL_RETURN(CheckIndex(index, ISizeOf::INT16)); *value = Memory::PeekInt16(mBackingArray, mArrayOffset + index, mOrder); return NOERROR; } ECode ByteArrayBuffer::IsDirect( /* [out] */ Boolean* isDirect) { VALIDATE_NOT_NULL(isDirect) *isDirect = FALSE; return NOERROR; } ECode ByteArrayBuffer::Put( /* [in] */ Byte b) { if (mIsReadOnly) { // throw new ReadOnlyBufferException(); return E_READ_ONLY_BUFFER_EXCEPTION; } if (mPosition == mLimit) { // throw new BufferOverflowException(); return E_BUFFER_OVERFLOW_EXCEPTION; } (*mBackingArray)[mArrayOffset + mPosition++] = b; return NOERROR; } ECode ByteArrayBuffer::Put( /* [in] */ Int32 index, /* [in] */ Byte b) { if (mIsReadOnly) { // throw new ReadOnlyBufferException(); return E_READ_ONLY_BUFFER_EXCEPTION; } FAIL_RETURN(CheckIndex(index)); (*mBackingArray)[mArrayOffset + index] = b; return NOERROR; } ECode ByteArrayBuffer::Put( /* [in] */ ArrayOf<Byte>* src, /* [in] */ Int32 srcOffset, /* [in] */ Int32 byteCount) { if (mIsReadOnly) { // throw new ReadOnlyBufferException(); return E_READ_ONLY_BUFFER_EXCEPTION; } Int32 outcount = 0; FAIL_RETURN(CheckPutBounds(1, src->GetLength(), srcOffset, byteCount, &outcount)); // System.arraycopy(src, srcOffset, mBackingArray, mArrayOffset + mPosition, byteCount); mBackingArray->Copy(mArrayOffset + mPosition, src, srcOffset, byteCount); mPosition += byteCount; return NOERROR; } ECode ByteArrayBuffer::PutChar( /* [in] */ Char32 value) { if (mIsReadOnly) { // throw new ReadOnlyBufferException(); return E_READ_ONLY_BUFFER_EXCEPTION; } Int32 newPosition = mPosition + ISizeOf::CHAR; if (newPosition > mLimit) { // throw new BufferOverflowException(); return E_BUFFER_OVERFLOW_EXCEPTION; } Memory::PokeInt32(mBackingArray, mArrayOffset + mPosition, (Int32) value, mOrder); mPosition = newPosition; return NOERROR; } ECode ByteArrayBuffer::PutChar( /* [in] */ Int32 index, /* [in] */ Char32 value) { if (mIsReadOnly) { // throw new ReadOnlyBufferException(); return E_READ_ONLY_BUFFER_EXCEPTION; } FAIL_RETURN(CheckIndex(index, ISizeOf::CHAR)); Memory::PokeInt32(mBackingArray, mArrayOffset + index, (Int32) value, mOrder); return NOERROR; } ECode ByteArrayBuffer::PutDouble( /* [in] */ Double value) { Int64 l = Elastos::Core::Math::DoubleToRawInt64Bits(value); return PutInt64(l); } ECode ByteArrayBuffer::PutDouble( /* [in] */ Int32 index, /* [in] */ Double value) { Int64 l = Elastos::Core::Math::DoubleToRawInt64Bits(value); return PutInt64(index, l); } ECode ByteArrayBuffer::PutFloat( /* [in] */ Float value) { Int32 l = Elastos::Core::Math::FloatToRawInt32Bits(value); return PutInt32(l); } ECode ByteArrayBuffer::PutFloat( /* [in] */ Int32 index, /* [in] */ Float value) { Int32 l = Elastos::Core::Math::FloatToRawInt32Bits(value); return PutInt32(index, l); } ECode ByteArrayBuffer::PutInt16( /* [in] */ Int16 value) { if (mIsReadOnly) { // throw new ReadOnlyBufferException(); return E_READ_ONLY_BUFFER_EXCEPTION; } Int32 newPosition = mPosition + ISizeOf::INT16; if (newPosition > mLimit) { // throw new BufferOverflowException(); return E_BUFFER_OVERFLOW_EXCEPTION; } Memory::PokeInt16(mBackingArray, mArrayOffset + mPosition, value, mOrder); mPosition = newPosition; return NOERROR; } ECode ByteArrayBuffer::PutInt16( /* [in] */ Int32 index, /* [in] */ Int16 value) { if (mIsReadOnly) { // throw new ReadOnlyBufferException(); return E_READ_ONLY_BUFFER_EXCEPTION; } FAIL_RETURN(CheckIndex(index, ISizeOf::INT16)); Memory::PokeInt16(mBackingArray, mArrayOffset + index, value, mOrder); return NOERROR; } ECode ByteArrayBuffer::PutInt32( /* [in] */ Int32 value) { if (mIsReadOnly) { // throw new ReadOnlyBufferException(); return E_READ_ONLY_BUFFER_EXCEPTION; } Int32 newPosition = mPosition + ISizeOf::INT32; if (newPosition > mLimit) { // throw new BufferOverflowException(); return E_BUFFER_OVERFLOW_EXCEPTION; } Memory::PokeInt32(mBackingArray, mArrayOffset + mPosition, value, mOrder); mPosition = newPosition; return NOERROR; } ECode ByteArrayBuffer::PutInt32( /* [in] */ Int32 index, /* [in] */ Int32 value) { if (mIsReadOnly) { // throw new ReadOnlyBufferException(); return E_READ_ONLY_BUFFER_EXCEPTION; } FAIL_RETURN(CheckIndex(index, ISizeOf::INT32)); Memory::PokeInt32(mBackingArray, mArrayOffset + index, value, mOrder); return NOERROR; } ECode ByteArrayBuffer::PutInt64( /* [in] */ Int64 value) { if (mIsReadOnly) { // throw new ReadOnlyBufferException(); return E_READ_ONLY_BUFFER_EXCEPTION; } Int32 newPosition = mPosition + ISizeOf::INT64; if (newPosition > mLimit) { // throw new BufferOverflowException(); return E_BUFFER_OVERFLOW_EXCEPTION; } Memory::PokeInt64(mBackingArray, mArrayOffset + mPosition, value, mOrder); mPosition = newPosition; return NOERROR; } ECode ByteArrayBuffer::PutInt64( /* [in] */ Int32 index, /* [in] */ Int64 value) { if (mIsReadOnly) { // throw new ReadOnlyBufferException(); return E_READ_ONLY_BUFFER_EXCEPTION; } FAIL_RETURN(CheckIndex(index, ISizeOf::INT64)); Memory::PokeInt64(mBackingArray, mArrayOffset + index, value, mOrder); return NOERROR; } ECode ByteArrayBuffer::AsCharBuffer( /* [out] */ ICharBuffer** buffer) { VALIDATE_NOT_NULL(buffer) AutoPtr<ICharBuffer> res = ByteBufferAsCharBuffer::AsCharBuffer(this); *buffer = res; REFCOUNT_ADD(*buffer) return NOERROR; } ECode ByteArrayBuffer::AsDoubleBuffer( /* [out] */ IDoubleBuffer** buffer) { VALIDATE_NOT_NULL(buffer) AutoPtr<IDoubleBuffer> res = ByteBufferAsDoubleBuffer::AsDoubleBuffer(this); *buffer = res; REFCOUNT_ADD(*buffer) return NOERROR; } ECode ByteArrayBuffer::AsFloatBuffer( /* [out] */ IFloatBuffer** buffer) { VALIDATE_NOT_NULL(buffer) AutoPtr<IFloatBuffer> res = ByteBufferAsFloatBuffer::AsFloatBuffer(this); *buffer = res; REFCOUNT_ADD(*buffer) return NOERROR; } ECode ByteArrayBuffer::AsInt16Buffer( /* [out] */ IInt16Buffer** buffer) { VALIDATE_NOT_NULL(buffer) AutoPtr<IInt16Buffer> res = ByteBufferAsInt16Buffer::AsInt16Buffer(this); *buffer = res; REFCOUNT_ADD(*buffer) return NOERROR; } ECode ByteArrayBuffer::AsInt32Buffer( /* [out] */ IInt32Buffer** buffer) { VALIDATE_NOT_NULL(buffer) AutoPtr<IInt32Buffer> res = ByteBufferAsInt32Buffer::AsInt32Buffer(this); *buffer = res; REFCOUNT_ADD(*buffer) return NOERROR; } ECode ByteArrayBuffer::AsInt64Buffer( /* [out] */ IInt64Buffer** buffer) { VALIDATE_NOT_NULL(buffer) AutoPtr<IInt64Buffer> res = ByteBufferAsInt64Buffer::AsInt64Buffer(this); *buffer = res; REFCOUNT_ADD(*buffer) return NOERROR; } ECode ByteArrayBuffer::GetChars( /* [in] */ ArrayOf<Char32>* dst, /* [in] */ Int32 dstOffset, /* [in] */ Int32 charCount) { Int32 byteCount = 0; FAIL_RETURN(CheckGetBounds(ISizeOf::CHAR, dst->GetLength(), dstOffset, charCount, &byteCount)); Memory::UnsafeBulkGet((Byte*)dst->GetPayload(), 0, byteCount, mBackingArray, mArrayOffset + mPosition, ISizeOf::CHAR, CByteOrderHelper::_IsNeedsSwap(mOrder)); mPosition += byteCount; return NOERROR; } ECode ByteArrayBuffer::GetDoubles( /* [in] */ ArrayOf<Double>* dst, /* [in] */ Int32 dstOffset, /* [in] */ Int32 doubleCount) { Int32 byteCount = 0; FAIL_RETURN(CheckGetBounds(ISizeOf::DOUBLE, dst->GetLength(), dstOffset, doubleCount, &byteCount)); Memory::UnsafeBulkGet((Byte*)dst->GetPayload(), dstOffset, byteCount, mBackingArray, mArrayOffset + mPosition, ISizeOf::DOUBLE, CByteOrderHelper::_IsNeedsSwap(mOrder)); mPosition += byteCount; return NOERROR; } ECode ByteArrayBuffer::GetFloats( /* [in] */ ArrayOf<Float>* dst, /* [in] */ Int32 dstOffset, /* [in] */ Int32 floatCount) { Int32 byteCount = 0; FAIL_RETURN(CheckGetBounds(ISizeOf::FLOAT, dst->GetLength(), dstOffset, floatCount, &byteCount)); Memory::UnsafeBulkGet((Byte*)dst->GetPayload(), dstOffset, byteCount, mBackingArray, mArrayOffset + mPosition, ISizeOf::FLOAT, CByteOrderHelper::_IsNeedsSwap(mOrder)); mPosition += byteCount; return NOERROR; } ECode ByteArrayBuffer::GetInt32s( /* [in] */ ArrayOf<Int32>* dst, /* [in] */ Int32 dstOffset, /* [in] */ Int32 intCount) { Int32 byteCount = 0; FAIL_RETURN(CheckGetBounds(ISizeOf::INT32, dst->GetLength(), dstOffset, intCount, &byteCount)); Memory::UnsafeBulkGet((Byte*)dst->GetPayload(), dstOffset, byteCount, mBackingArray, mArrayOffset + mPosition, ISizeOf::INT32, CByteOrderHelper::_IsNeedsSwap(mOrder)); mPosition += byteCount; return NOERROR; } ECode ByteArrayBuffer::GetInt64s( /* [in] */ ArrayOf<Int64>* dst, /* [in] */ Int32 dstOffset, /* [in] */ Int32 longCount) { Int32 byteCount = 0; FAIL_RETURN(CheckGetBounds(ISizeOf::INT64, dst->GetLength(), dstOffset, longCount, &byteCount)); Memory::UnsafeBulkGet((Byte*)dst->GetPayload(), dstOffset, byteCount, mBackingArray, mArrayOffset + mPosition, ISizeOf::INT64, CByteOrderHelper::_IsNeedsSwap(mOrder)); mPosition += byteCount; return NOERROR; } ECode ByteArrayBuffer::GetInt16s( /* [in] */ ArrayOf<Int16>* dst, /* [in] */ Int32 dstOffset, /* [in] */ Int32 shortCount) { Int32 byteCount = 0; FAIL_RETURN(CheckGetBounds(ISizeOf::INT16, dst->GetLength(), dstOffset, shortCount, &byteCount)); Memory::UnsafeBulkGet((Byte*)dst->GetPayload(), dstOffset, byteCount, mBackingArray, mArrayOffset + mPosition, ISizeOf::INT16, CByteOrderHelper::_IsNeedsSwap(mOrder)); mPosition += byteCount; return NOERROR; } ECode ByteArrayBuffer::PutChars( /* [in] */ ArrayOf<Char32>* src, /* [in] */ Int32 srcOffset, /* [in] */ Int32 charCount) { Int32 byteCount = 0; FAIL_RETURN(CheckPutBounds(ISizeOf::CHAR, src->GetLength(), srcOffset, charCount, &byteCount)); Memory::UnsafeBulkPut(mBackingArray, mArrayOffset + mPosition, byteCount, (Byte*)src->GetPayload(), srcOffset, ISizeOf::CHAR, CByteOrderHelper::_IsNeedsSwap(mOrder)); mPosition += byteCount; return NOERROR; } ECode ByteArrayBuffer::PutDoubles( /* [in] */ ArrayOf<Double>* src, /* [in] */ Int32 srcOffset, /* [in] */ Int32 doubleCount) { Int32 byteCount = 0; FAIL_RETURN(CheckPutBounds(ISizeOf::DOUBLE, src->GetLength(), srcOffset, doubleCount, &byteCount)); Memory::UnsafeBulkPut(mBackingArray, mArrayOffset + mPosition, byteCount, (Byte*)src->GetPayload(), srcOffset, ISizeOf::DOUBLE, CByteOrderHelper::_IsNeedsSwap(mOrder)); mPosition += byteCount; return NOERROR; } ECode ByteArrayBuffer::PutFloats( /* [in] */ ArrayOf<Float>* src, /* [in] */ Int32 srcOffset, /* [in] */ Int32 floatCount) { Int32 byteCount = 0; FAIL_RETURN(CheckPutBounds(ISizeOf::FLOAT, src->GetLength(), srcOffset, floatCount, &byteCount)); Memory::UnsafeBulkPut(mBackingArray, mArrayOffset + mPosition, byteCount, (Byte*)src->GetPayload(), srcOffset, ISizeOf::FLOAT, CByteOrderHelper::_IsNeedsSwap(mOrder)); mPosition += byteCount; return NOERROR; } ECode ByteArrayBuffer::PutInt32s( /* [in] */ ArrayOf<Int32>* src, /* [in] */ Int32 srcOffset, /* [in] */ Int32 intCount) { Int32 byteCount = 0; FAIL_RETURN(CheckPutBounds(ISizeOf::INT32, src->GetLength(), srcOffset, intCount, &byteCount)); Memory::UnsafeBulkPut(mBackingArray, mArrayOffset + mPosition, byteCount, (Byte*)src->GetPayload(), srcOffset, ISizeOf::INT32, CByteOrderHelper::_IsNeedsSwap(mOrder)); mPosition += byteCount; return NOERROR; } ECode ByteArrayBuffer::PutInt64s( /* [in] */ ArrayOf<Int64>* src, /* [in] */ Int32 srcOffset, /* [in] */ Int32 longCount) { Int32 byteCount = 0; FAIL_RETURN(CheckPutBounds(ISizeOf::INT64, src->GetLength(), srcOffset, longCount, &byteCount)); Memory::UnsafeBulkPut(mBackingArray, mArrayOffset + mPosition, byteCount, (Byte*)src->GetPayload(), srcOffset, ISizeOf::INT64, CByteOrderHelper::_IsNeedsSwap(mOrder)); mPosition += byteCount; return NOERROR; } ECode ByteArrayBuffer::PutInt16s( /* [in] */ ArrayOf<Int16>* src, /* [in] */ Int32 srcOffset, /* [in] */ Int32 shortCount) { Int32 byteCount = 0; FAIL_RETURN(CheckPutBounds(ISizeOf::INT16, src->GetLength(), srcOffset, shortCount, &byteCount)); Memory::UnsafeBulkPut(mBackingArray, mArrayOffset + mPosition, byteCount, (Byte*)src->GetPayload(), srcOffset, ISizeOf::INT16, CByteOrderHelper::_IsNeedsSwap(mOrder)); mPosition += byteCount; return NOERROR; } } // namespace IO } // namespace Elastos
[ "cao.jing@kortide.com" ]
cao.jing@kortide.com
2ce4ec75873bc88cf7884a8ec44fb5a2abb96f83
082b729b2a5ca8f0075759ab6de559a7f5bb52db
/오목사본/오목/omok.h
2abda539ebb30180d5ab9a729b4a86f1f7e77327
[]
no_license
kimhanyo/kimhanyo
1ef81fede427930333bc13368554f91fcd3d4985
01e6b25bf41d418183d4549e30d6f1bd128a790e
refs/heads/master
2021-05-18T15:43:50.450607
2020-03-31T16:15:31
2020-03-31T16:15:31
251,302,144
0
1
null
2020-03-31T09:53:27
2020-03-30T12:46:52
C++
UHC
C++
false
false
1,117
h
#pragma once #define FIELD_INTERVAL 26 //오목판 눈과 눈사이의 간격 #define STONE_INTERVAL (FIELD_INTERVAL/2) //돌의 반지름 #define ROW 19 //행 #define COL 19 //열 #define LEFT_SIDE 300 //오른쪽 여백공간 크기 #define UP_SIDE 50 //윗쪽 여백공간 크기 #define FLOWER_SPOT 4 //화점의 반지름 class omok { int field_Row[ROW] = { 0 }; int field_Col[COL] = { 0 }; //오목판의 줄 위치를 저장하는 배열 int stone[ROW][COL]; //바둑돌의 상태 정보 ( 0 : 안 둔 상태, 1 : 흑돌 존재, 2: 백돌 존재 ) bool next_Stone = true; //흑백의 순서 true : 흑 flase : 백 public: omok(); int get_Row(int row) { return field_Row[row]; } int get_Col(int col) { return field_Col[col]; } int get_State(int row, int col) { return stone[row][col]; } //오목판의 상태(돌들의 상태) 리턴 void swap(); //흑백 교환 void get_down_Black(int row, int col); //흑돌 착수 void get_down_White(int row, int col); //백돌 착수 bool next(); bool win_Check(int row, int col); }; //int omok::stone[ROW][COL] = { 0 };
[ "noreply@github.com" ]
noreply@github.com
e097cd17124ad109b01ce05e0fb91e77b47d32f5
824bd369015bb137a5f105a3549e56651faf969b
/source/Messages/Create_FireBoss_FireBall_Message.cpp
26c74b5dfee9170fb36f602a6393c4d15c090cea
[]
no_license
kendellm/Trials-of-Mastery
2839f8a74bbe724a1541df1c023471e7fefba3cf
944d528291414914d8533135a0ac646fd2dcd3ee
refs/heads/master
2021-01-20T13:48:36.852609
2015-09-03T20:53:31
2015-09-03T20:53:31
41,883,293
0
0
null
null
null
null
UTF-8
C++
false
false
306
cpp
#include "Create_FireBoss_Fireball_Message.h" CCreate_FireBoss_Fireball_Message::CCreate_FireBoss_Fireball_Message(int owner, bool flipped) : CMessage( MSG_FIREBOSS_FIREBALL ) { m_nOwner = owner; m_bFlipped = flipped; } CCreate_FireBoss_Fireball_Message::~CCreate_FireBoss_Fireball_Message(void) { }
[ "kendell.monrose@gmail.com" ]
kendell.monrose@gmail.com
8180d0d925e8a7f67e01e04f6a47d3ea6b3c6692
ee9b14bc1a457cacddf76dc18a62f29200ad5c51
/friends.cpp
78e3fc31d3663ce311cbce9831a65f33a7cd87ab
[]
no_license
tuncerm/cpp_refresher
046830947a79834b2a8f6b75a5d66d7d42106f8e
0b9c5e6c734df6b23f6a6d02e3bbc02a5176f154
refs/heads/master
2021-05-20T03:32:11.419796
2020-04-15T23:02:30
2020-04-15T23:02:30
252,167,387
0
0
null
null
null
null
UTF-8
C++
false
false
1,049
cpp
// Example solution for Rectangle and Square friend classes #include <assert.h> // Declare class Rectangle class Rectangle; // Define class Square as friend of Rectangle class Square { // Add public constructor to Square, initialize side public: Square(int s) : side(s) {} private: // Add friend class Rectangle friend class Rectangle; // Add private attribute side to Square int side; }; // Define class Rectangle class Rectangle { // Add public functions to Rectangle: area() and convert() public: Rectangle(const Square& a); int Area() const; private: // Add private attributes width, height int width {0}; int height {0}; }; // Define a Rectangle constructor that takes a Square Rectangle::Rectangle(const Square& a) : width(a.side), height(a.side) { } // Define Area() to compute area of Rectangle int Rectangle::Area() const { return width * height; } // Update main() to pass the tests int main() { Square square(4); Rectangle rectangle(square); assert(rectangle.Area() == 16); }
[ "tuncerm@gmail.com" ]
tuncerm@gmail.com
44fba61ca3a8ae0a3ab6a4e4db9f15be7aca55c9
2c765e5a27e19e2ac24466b25b29716b45398151
/src/StateBoxes.hpp
df2e7a6f446b95a36d567f3fb4e33a369ad80909
[ "BSD-2-Clause" ]
permissive
JoshuaBrookover/Physics2D
cc089eb97166d8a058c6b3996219c7a184b2187d
d570bbc0a6e412d3968cb77c3a65a1b1c1d4677e
refs/heads/master
2021-01-23T07:17:00.326144
2014-01-03T00:20:07
2014-01-03T00:20:07
15,016,771
7
2
null
null
null
null
UTF-8
C++
false
false
417
hpp
#pragma once #include <CGUL.hpp> #include "State.hpp" #include "Circle.hpp" #include "AxisAlignedBox.hpp" #include "OrientedBox.hpp" #include "Line.hpp" class StateBoxes : public State { OrientedBox box1; OrientedBox box2; AxisAlignedBox box3; Line line; Circle circle; public: StateBoxes(); ~StateBoxes(); void Enter(); void Update(CGUL::Float32 deltaTime); void Exit(); };
[ "josh@jalb.me" ]
josh@jalb.me
d04c7234e292ba886e7fbcd9dc04cc9c84709265
80c360c920bd67833475a7b377f40840686265ff
/src/barnes-hut/Node.hpp
2d943314d5c43d55bdd6cd1ae1dc123e70c23b94
[]
no_license
T7025/charon_opencl
ba79e6af13269929e4e45284e8ec94b77e458ec0
aa01fe1ca87211bfbdf1eb970d4dfe4252b3338b
refs/heads/master
2020-04-03T08:00:20.250596
2019-01-29T04:00:42
2019-01-29T04:00:42
155,120,480
0
0
null
null
null
null
UTF-8
C++
false
false
3,753
hpp
// // Created by thomas on 12/01/19. // #pragma once #include "SFCIndex.hpp" #include <base/Vec3.hpp> //constexpr unsigned k = 64; // Max tree depth. //using uintv = uint64_t; template <typename FP> class Node { public: Node() : sfcIndex{}, depth{}, mass{-1}, position{}, data{} {}; Node(const Vec3<FP> &pos, const Vec3<FP> &vel, const Vec3<FP> &acc, const FP mass) : sfcIndex{}, depth{k}, mass{mass}, position{pos}, data{vel, acc} {} // const Vec3<FP> &getPosition() const; // Vec3<FP> &getPosition(); // const SFCIndex &getSFCIndex() const; // SFCIndex &getSFCIndex(); // const unsigned &getDepth() const; // unsigned &getDepth(); // const intv *getChildren() const; // intv *getChildren(); // const FP &getMass() const; // FP &getMass(); // const Vec3<FP> &getVelocity() const; // Vec3<FP> &getVelocity(); // const Vec3<FP> &getAcceleration() const; // Vec3<FP> &getAcceleration(); // // bool isLeaf() const; // bool isParentOf(const Node &other) const; // // bool operator<(const Node &other) const; // bool operator==(const Node &other) const; const Vec3<FP> &getPosition() const { return position; } Vec3<FP> &getPosition() { return position; } const SFCIndex &getSFCIndex() const { return sfcIndex; } SFCIndex &getSFCIndex() { return sfcIndex; } bool operator==(const Node &other) const { return sfcIndex == other.sfcIndex && depth == other.depth; } const unsigned &getDepth() const { return depth; } unsigned &getDepth() { return depth; } const intv *getChildren() const { return data.children; } intv *getChildren() { return data.children; } const FP &getMass() const { return mass; } FP &getMass() { return mass; } const Vec3<FP> &getVelocity() const { return data.leafData.vel; } Vec3<FP> &getVelocity() { return data.leafData.vel; } const Vec3<FP> &getAcceleration() const { return data.leafData.acc; } Vec3<FP> &getAcceleration() { return data.leafData.acc; } bool isLeaf() const { return depth == k; } bool isParentOf(const Node &other) const { if (depth < other.depth) { auto shift = k - depth; // If xor of (depth) most significant bits is zero (=they are equal), // then this Node is a parent of other Node. return depth == 0 || (((sfcIndex.x ^ other.sfcIndex.x) >> shift) == 0 && ((sfcIndex.y ^ other.sfcIndex.y) >> shift) == 0 && ((sfcIndex.z ^ other.sfcIndex.z) >> shift) == 0); } return false; } bool operator<(const Node &other) const { return sfcIndex < other.sfcIndex || (other.sfcIndex == sfcIndex && depth > other.depth); } private: SFCIndex sfcIndex; unsigned depth; FP mass; Vec3<FP> position; union Data { Data() : children{-1, -1, -1, -1, -1, -1, -1, -1} {} Data(const Vec3<FP> &vel, const Vec3<FP> &acc) : leafData{vel, acc} {} intv children[8]; struct { Vec3<FP> vel; Vec3<FP> acc; } leafData; } data; }; template <typename FP> std::ostream &operator<<(std::ostream &out, const Node<FP> &node) { out << node.getSFCIndex() << "; " << node.getDepth() << "; " << node.getMass() << "; " << node.getPosition(); if (node.getDepth() < k) { out << "; " << node.getChildren()[0]; for (int i = 1; i < 8; ++i) { out << "," << node.getChildren()[i]; } } return out; }
[ "thomas.vanbogaert@student.uantwerpen.be" ]
thomas.vanbogaert@student.uantwerpen.be
c659bf6de24787371be059fd0c2d0b53346c554a
a9cbc183306f3b4dae5fcfa92d95e346b93e0344
/katana/src/PowerRails.cpp
bb6a8b536cf3fbb9d289eb57d1de881d58a73535
[]
no_license
0x01be/coriolis
f4ca0c1eba2a1fd358b5b669178a962bfeaa8ba9
3db5f27aecff1cb858302e3833a46195efd91238
refs/heads/master
2022-12-16T18:34:59.364602
2019-05-28T13:37:10
2019-05-28T13:37:10
282,252,121
0
0
null
null
null
null
UTF-8
C++
false
false
41,798
cpp
// -*- C++ -*- // // This file is part of the Coriolis Software. // Copyright (c) UPMC 2008-2018, All Rights Reserved // // +-----------------------------------------------------------------+ // | C O R I O L I S | // | K i t e - D e t a i l e d R o u t e r | // | | // | Author : Jean-Paul CHAPUT | // | E-mail : Jean-Paul.Chaput@asim.lip6.fr | // | =============================================================== | // | C++ Module : "./PowerRails.cpp" | // +-----------------------------------------------------------------+ #include <map> #include <list> #include "hurricane/DebugSession.h" #include "hurricane/Error.h" #include "hurricane/Warning.h" #include "hurricane/DataBase.h" #include "hurricane/Technology.h" #include "hurricane/BasicLayer.h" #include "hurricane/RegularLayer.h" #include "hurricane/Horizontal.h" #include "hurricane/Vertical.h" #include "hurricane/RoutingPad.h" #include "hurricane/NetExternalComponents.h" #include "hurricane/NetRoutingProperty.h" #include "hurricane/Instance.h" #include "hurricane/Plug.h" #include "hurricane/Path.h" #include "hurricane/Query.h" #include "crlcore/AllianceFramework.h" #include "anabatic/GCell.h" #include "katana/RoutingPlane.h" #include "katana/TrackFixedSegment.h" #include "katana/Track.h" #include "katana/KatanaEngine.h" namespace { using namespace std; using Hurricane::DebugSession; using Hurricane::Warning; using Hurricane::Error; using Hurricane::DbU; using Hurricane::Box; using Hurricane::Interval; using Hurricane::Net; using Hurricane::DeepNet; using Hurricane::Horizontal; using Hurricane::Vertical; using Hurricane::RoutingPad; using Hurricane::NetExternalComponents; using Hurricane::NetRoutingExtension; using Hurricane::NetRoutingState; using Hurricane::Instance; using Hurricane::Plug; using Hurricane::Path; using Hurricane::Query; using Hurricane::Go; using Hurricane::Rubber; using Hurricane::Layer; using Hurricane::BasicLayer; using Hurricane::RegularLayer; using Hurricane::Transformation; using Hurricane::Technology; using Hurricane::DataBase; using CRL::AllianceFramework; using Anabatic::GCell; using Anabatic::ChipTools; using namespace Katana; // ------------------------------------------------------------------- // Local Functions. void destroyRing ( Net* net ) { for( RoutingPad* rp : net->getRoutingPads() ) { bool allMasters = true; vector<Hook*> ring; for( Hook* hook : rp->getBodyHook()->getHooks() ) { if (not hook->isMaster()) { allMasters = false; break; } ring.push_back( hook ); } if (allMasters) { for ( auto hook : ring ) { hook->_setNextHook( hook ); } } } } // ------------------------------------------------------------------- // Class : "::GlobalNetTable". class GlobalNetTable { public: enum Flag { ClockIsRouted=0x0001 }; public: GlobalNetTable ( KatanaEngine* ); bool isCoreClockNetRouted ( const Net* ) const; inline Cell* getTopCell () const; Net* getRootNet ( const Net*, Path ) const; inline Net* getVdd () const; inline Net* getVss () const; inline Net* getCk () const; inline Net* getBlockage () const; inline void setBlockage ( Net* ); private: bool guessGlobalNet ( const Name&, Net* ); private: uint32_t _flags; Name _vddCoreName; Name _vssCoreName; Name _ckCoreName; Net* _vdd; Net* _vss; Net* _ck; Net* _blockage; Cell* _topCell; }; inline Cell* GlobalNetTable::getTopCell () const { return _topCell; } inline Net* GlobalNetTable::getVdd () const { return _vdd; } inline Net* GlobalNetTable::getVss () const { return _vss; } inline Net* GlobalNetTable::getCk () const { return _ck; } inline Net* GlobalNetTable::getBlockage () const { return _blockage; } inline void GlobalNetTable::setBlockage ( Net* net ) { _blockage=net; } GlobalNetTable::GlobalNetTable ( KatanaEngine* katana ) : _flags (0) , _vddCoreName() , _vssCoreName() , _ckCoreName () , _vdd (NULL) , _vss (NULL) , _ck (NULL) , _blockage (NULL) , _topCell (katana->getCell()) { if (_topCell == NULL) return; cmess1 << " o Looking for powers/grounds & clocks." << endl; for( Net* net : _topCell->getNets() ) { Net::Type netType = net->getType(); if (netType == Net::Type::CLOCK) { if (not net->isExternal()) continue; if (_ckCoreName.isEmpty()) { cmess1 << " - Using <" << net->getName() << "> as internal (core) clock net." << endl; _ckCoreName = net->getName(); _ck = net; if (NetRoutingExtension::isMixedPreRoute(net)) { cmess1 << " (core clock net is already routed)" << endl; _flags |= ClockIsRouted; } else { cmess1 << " (core clock net will be routed as an ordinary signal)" << endl; } } else { cerr << Error("Second clock net <%s> net at top block level will be ignored.\n" " (will consider only <%s>)" , getString(net->getName()).c_str() , getString(_ck->getName()).c_str() ) << endl; } } if (NetRoutingExtension::isManualGlobalRoute(net)) continue; if (netType == Net::Type::POWER) { if (_vddCoreName.isEmpty()) { _vddCoreName = net->getName(); _vdd = net; } else { cerr << Error("Second power supply net <%s> net at top block level will be ignored.\n" " (will consider only <%s>)" , getString(net ->getName()).c_str() , getString(_vdd->getName()).c_str() ) << endl; } } if (netType == Net::Type::GROUND) { if (_vssCoreName.isEmpty()) { _vssCoreName = net->getName(); _vss = net; } else { cerr << Error("Second power ground net <%s> net at top block level will be ignored.\n" " (will consider only <%s>)" , getString(net ->getName()).c_str() , getString(_vss->getName()).c_str() ) << endl; } } } if (_vdd == NULL) cerr << Error("Missing POWER net at top block level." ) << endl; else destroyRing( _vdd ); if (_vss == NULL) cerr << Error("Missing GROUND net at top block level." ) << endl; else destroyRing( _vss ); if (_ck == NULL) cparanoid << Warning("No CLOCK net at top level." ) << endl; } bool GlobalNetTable::guessGlobalNet ( const Name& name, Net* net ) { if (name == _vddCoreName) { cmess1 << " - Using <" << net->getName() << "> as core (internal:vdd) power net." << endl; _vdd = net; return true; } if (name == _vssCoreName) { cmess1 << " - Using <" << net->getName() << "> as core (internal:vss) ground net." << endl; _vss = net; return true; } if (name == _ckCoreName) { cmess1 << " - Using <" << net->getName() << "> as core (internal:ck) clock net." << endl; _ck = net; if (NetRoutingExtension::isMixedPreRoute(_ck)) { cmess1 << " (core clock net is already routed)" << endl; _flags |= ClockIsRouted; } else { cmess1 << " (core clock net will be routed as an ordinary signal)" << endl; } return true; } return false; } Net* GlobalNetTable::getRootNet ( const Net* net, Path path ) const { cdebug_log(159,0) << " getRootNet:" << path << ":" << net << endl; if (net == _blockage) return _blockage; if (net->getType() == Net::Type::POWER ) return _vdd; if (net->getType() == Net::Type::GROUND) return _vss; if (net->getType() != Net::Type::CLOCK ) { return NULL; } // Track up, *only* for clocks. const Net* upNet = net; if (not path.isEmpty()) { DeepNet* deepClockNet = getTopCell()->getDeepNet( path, net ); if (deepClockNet) { cdebug_log(159,0) << " Deep Clock Net:" << deepClockNet << " state:" << NetRoutingExtension::getFlags(deepClockNet) << endl; return NetRoutingExtension::isFixed(deepClockNet) ? _blockage : NULL; } else { cdebug_log(159,0) << " Top Clock Net:" << net << " state:" << NetRoutingExtension::getFlags(net) << endl; } Path upPath = path; Instance* instance = NULL; Plug* plug = NULL; while ( true ) { cdebug_log(159,0) << " " << path << "+" << upNet << endl; if (path.isEmpty()) break; if ((upNet == NULL) or not upNet->isExternal()) return _blockage; instance = path.getTailInstance(); plug = instance->getPlug(upNet); if (plug == NULL) return NULL; upNet = plug->getNet(); path = path.getHeadPath(); } } cdebug_log(159,0) << " Check againts top clocks ck:" << ((_ck) ? _ck->getName() : "NULL") << endl; if (_ck) { if (upNet->getName() == _ck->getName()) { if (isCoreClockNetRouted(upNet)) return _ck; } } return NetRoutingExtension::isFixed(upNet) ? _blockage : NULL; } bool GlobalNetTable::isCoreClockNetRouted ( const Net* net ) const { return (net == _ck) and (_flags & ClockIsRouted); } // ------------------------------------------------------------------- // Class : "::PowerRailsPlanes". class PowerRailsPlanes { public: class Rails; class Plane; class Rail { public: Rail ( Rails*, DbU::Unit axis, DbU::Unit width ); inline DbU::Unit getAxis () const; inline DbU::Unit getWidth () const; inline Rails* getRails () const; inline RoutingPlane* getRoutingPlane () const; inline Flags getDirection () const; inline Net* getNet () const; void merge ( DbU::Unit source, DbU::Unit target ); void doLayout ( const Layer* ); string _getString () const; private: Rails* _rails; DbU::Unit _axis; DbU::Unit _width; list<Interval> _chunks; }; private: class RailCompare { public: bool operator() ( const Rail* lhs, const Rail* rhs ); }; class RailMatch : public unary_function<Rail*,bool> { public: inline RailMatch ( DbU::Unit axis, DbU::Unit width ); inline bool operator() ( const Rail* ); private: DbU::Unit _axis; DbU::Unit _width; }; public: class Rails { public: Rails ( Plane*, Flags direction, Net* ); ~Rails (); inline Plane* getPlane (); inline RoutingPlane* getRoutingPlane (); inline Flags getDirection () const; inline Net* getNet () const; void merge ( const Box& ); void doLayout ( const Layer* ); private: Plane* _plane; Flags _direction; Net* _net; vector<Rail*> _rails; }; public: class Plane { public: typedef map<Net*,Rails*,Net::CompareById> RailsMap; public: Plane ( const Layer*, RoutingPlane* ); ~Plane (); inline const Layer* getLayer () const; inline RoutingPlane* getRoutingPlane (); inline Flags getDirection () const; inline Flags getPowerDirection () const; void merge ( const Box&, Net* ); void doLayout (); private: const Layer* _layer; RoutingPlane* _routingPlane; RailsMap _horizontalRails; RailsMap _verticalRails; Flags _powerDirection; }; public: typedef map<const BasicLayer*,Plane*,BasicLayer::CompareByMask> PlanesMap; public: PowerRailsPlanes ( KatanaEngine* ); ~PowerRailsPlanes (); inline Net* getRootNet ( Net*, Path ); inline bool isCoreClockNetRouted ( const Net* ) const; bool hasPlane ( const BasicLayer* ); bool setActivePlane ( const BasicLayer* ); inline Plane* getActivePlane () const; inline Plane* getActiveBlockagePlane () const; void merge ( const Box&, Net* ); void doLayout (); private: KatanaEngine* _katana; GlobalNetTable _globalNets; PlanesMap _planes; Plane* _activePlane; Plane* _activeBlockagePlane; }; PowerRailsPlanes::Rail::Rail ( Rails* rails, DbU::Unit axis, DbU::Unit width ) : _rails (rails) , _axis (axis) , _width (width) , _chunks() { cdebug_log(159,0) << " new Rail " << " @" << DbU::getValueString(axis) << " " << getRoutingPlane()->getLayer()->getName() << " " << getRails()->getNet() << " " << ((getDirection()==Flags::Horizontal) ? "Horizontal" : "Vertical")<< endl; } inline DbU::Unit PowerRailsPlanes::Rail::getAxis () const { return _axis; } inline DbU::Unit PowerRailsPlanes::Rail::getWidth () const { return _width; } inline PowerRailsPlanes::Rails* PowerRailsPlanes::Rail::getRails () const { return _rails; } inline RoutingPlane* PowerRailsPlanes::Rail::getRoutingPlane () const { return _rails->getRoutingPlane(); } inline Flags PowerRailsPlanes::Rail::getDirection () const { return _rails->getDirection(); } inline Net* PowerRailsPlanes::Rail::getNet () const { return _rails->getNet(); } void PowerRailsPlanes::Rail::merge ( DbU::Unit source, DbU::Unit target ) { Interval chunkToMerge ( source, target ); cdebug_log(159,0) << " Rail::merge() " << ((getDirection()==Flags::Horizontal) ? "Horizontal" : "Vertical") << " " << chunkToMerge << endl; cdebug_log(159,0) << " | " << _getString() << endl; list<Interval>::iterator imerge = _chunks.end(); list<Interval>::iterator ichunk = _chunks.begin(); while ( ichunk != _chunks.end() ) { if (imerge == _chunks.end()) { if (chunkToMerge.getVMax() < (*ichunk).getVMin()) { cdebug_log(159,0) << " | Insert before " << *ichunk << endl; imerge = _chunks.insert( ichunk, chunkToMerge ); break; } if (chunkToMerge.intersect(*ichunk)) { cdebug_log(159,0) << " | Merge with " << *ichunk << endl; imerge = ichunk; (*imerge).merge( chunkToMerge ); } } else { if (chunkToMerge.getVMax() >= (*ichunk).getVMin()) { (*imerge).merge( *ichunk ); cdebug_log(159,0) << " | Absorb (erase) " << *ichunk << endl; ichunk = _chunks.erase( ichunk ); continue; } else break; } // if (chunkToMerge.intersect(*ichunk)) { // if (imerge == _chunks.end()) { // cdebug_log(159,0) << " | Merge with " << *ichunk << endl; // imerge = ichunk; // (*imerge).merge( chunkToMerge ); // } else { // (*imerge).merge( *ichunk ); // cdebug_log(159,0) << " | Absorb (erase) " << *ichunk << endl; // ichunk = _chunks.erase( ichunk ); // continue; // } // } ++ichunk; } if (imerge == _chunks.end()) { _chunks.insert( ichunk, chunkToMerge ); cdebug_log(159,0) << " | Insert at end " << DbU::getValueString(_axis) << " " << chunkToMerge << endl; cdebug_log(159,0) << " | " << _getString() << endl; } } void PowerRailsPlanes::Rail::doLayout ( const Layer* layer ) { cdebug_log(159,0) << "Doing layout of rail: " << " " << layer->getName() << " " << ((getDirection()==Flags::Horizontal) ? "Horizontal" : "Vertical") << " @" << DbU::getValueString(_axis) << endl; cdebug_log(159,0) << _getString() << endl; Net* net = getNet(); RoutingPlane* plane = getRoutingPlane(); Segment* segment = NULL; //DbU::Unit delta = plane->getLayerGauge()->getPitch() // - plane->getLayerGauge()->getHalfWireWidth() // - DbU::fromLambda(0.1); DbU::Unit delta = plane->getLayerGauge()->getObstacleDw() - DbU::fromLambda(0.1); DbU::Unit extension = layer->getExtentionCap() - plane->getLayerGauge()->getLayer()->getMinimalSpacing()/2; //DbU::Unit extension = layer->getExtentionCap() - plane->getLayerGauge()->getHalfPitch() + getHalfWireWidth(); //DbU::Unit extension = layer->getExtentionCap(); //DbU::Unit extension = Session::getExtentionCap(); //unsigned int type = plane->getLayerGauge()->getType(); const Box& coronaBb = plane->getKatanaEngine()->getChipTools().getCoronaBb(); DbU::Unit axisMin = 0; DbU::Unit axisMax = 0; cdebug_log(159,0) << " delta:" << DbU::getValueString(delta) << " (pitch:" << DbU::getValueString(plane->getLayerGauge()->getPitch()) << " , ww/2:" << DbU::getValueString(plane->getLayerGauge()->getHalfWireWidth()) << ")" << endl; // if ( type == Constant::PinOnly ) { // cdebug_log(159,0) << " Layer is PinOnly." << endl; // return; // } if ( getDirection() == Flags::Horizontal ) { list<Interval>::iterator ichunk = _chunks.begin(); list<Interval>::iterator ichunknext = ichunk; ++ichunknext; for ( ; ichunk != _chunks.end() ; ++ichunk, ++ichunknext ) { if (ichunknext != _chunks.end()) { if ((*ichunk).intersect(*ichunknext)) cerr << Error( "Overlaping consecutive chunks in %s %s Rail @%s:\n" " %s" , getString(layer->getName()).c_str() , ((getDirection()==Flags::Horizontal) ? "Horizontal" : "Vertical") , DbU::getValueString(_axis).c_str() , _getString().c_str() ) << endl; } cdebug_log(159,0) << " chunk: [" << DbU::getValueString((*ichunk).getVMin()) << ":" << DbU::getValueString((*ichunk).getVMax()) << "]" << endl; segment = Horizontal::create ( net , layer , _axis , _width , (*ichunk).getVMin()+extension , (*ichunk).getVMax()-extension ); if ( segment and net->isExternal() ) NetExternalComponents::setExternal ( segment ); axisMin = _axis - _width/2; axisMax = _axis + _width/2; if (coronaBb.contains(segment->getBoundingBox())) { axisMin -= delta; axisMax += delta; } Track* track = plane->getTrackByPosition ( axisMin, Constant::Superior ); for ( ; track and (track->getAxis() <= axisMax) ; track = track->getNextTrack() ) { TrackElement* element = TrackFixedSegment::create ( track, segment ); cdebug_log(159,0) << " Insert in " << track << "+" << element << endl; } } } else { list<Interval>::iterator ichunk = _chunks.begin(); for ( ; ichunk != _chunks.end() ; ichunk++ ) { cdebug_log(159,0) << " chunk: [" << DbU::getValueString((*ichunk).getVMin()) << ":" << DbU::getValueString((*ichunk).getVMax()) << "]" << endl; segment = Vertical::create ( net , layer , _axis , _width , (*ichunk).getVMin()+extension , (*ichunk).getVMax()-extension ); if ( segment and net->isExternal() ) NetExternalComponents::setExternal ( segment ); axisMin = _axis - _width/2; axisMax = _axis + _width/2; //if (coronaBb.contains(segment->getBoundingBox())) { axisMin -= delta; axisMax += delta; //} cdebug_log(159,0) << " axisMin:" << DbU::getValueString(axisMin) << " axisMax:" << DbU::getValueString(axisMax) << endl; Track* track = plane->getTrackByPosition ( axisMin, Constant::Superior ); for ( ; track and (track->getAxis() <= axisMax) ; track = track->getNextTrack() ) { TrackElement* element = TrackFixedSegment::create ( track, segment ); cdebug_log(159,0) << " Insert in " << track << "+" << element << " " << (net->isExternal() ? "external" : "internal") << endl; } } } } string PowerRailsPlanes::Rail::_getString () const { ostringstream os; os << "<Rail " << ((getDirection()==Flags::Horizontal) ? "Horizontal" : "Vertical") << " @" << DbU::getValueString(_axis) << " " << " w:" << DbU::getValueString(_width) << " "; list<Interval>::const_iterator ichunk = _chunks.begin(); for ( ; ichunk != _chunks.end() ; ++ichunk ) { if (ichunk != _chunks.begin()) os << " "; os << "[" << DbU::getValueString((*ichunk).getVMin()) << " " << DbU::getValueString((*ichunk).getVMax()) << "]"; } os << ">"; return os.str(); } inline bool PowerRailsPlanes::RailCompare::operator() ( const Rail* lhs, const Rail* rhs ) { if ( lhs->getAxis () < rhs->getAxis () ) return true; if ( lhs->getWidth() < rhs->getWidth() ) return true; return false; } inline PowerRailsPlanes::RailMatch::RailMatch ( DbU::Unit axis, DbU::Unit width ) : _axis(axis) , _width(width) { } inline bool PowerRailsPlanes::RailMatch::operator() ( const Rail* rail ) { return (rail->getAxis() == _axis) and (rail->getWidth() == _width); } PowerRailsPlanes::Rails::Rails ( PowerRailsPlanes::Plane* plane , Flags direction , Net* net ) : _plane (plane) , _direction (direction) , _net (net) , _rails () { cdebug_log(159,0) << " new Rails @" << " " << getRoutingPlane()->getLayer()->getName() << " " << net << " " << ((getDirection()==Flags::Horizontal) ? "Horizontal": "Vertical") << endl; } PowerRailsPlanes::Rails::~Rails () { while ( not _rails.empty() ) { delete (*_rails.begin()); _rails.erase ( _rails.begin() ); } } inline PowerRailsPlanes::Plane* PowerRailsPlanes::Rails::getPlane () { return _plane; } inline RoutingPlane* PowerRailsPlanes::Rails::getRoutingPlane () { return getPlane()->getRoutingPlane(); } inline Flags PowerRailsPlanes::Rails::getDirection () const { return _direction; } inline Net* PowerRailsPlanes::Rails::getNet () const { return _net; } void PowerRailsPlanes::Rails::merge ( const Box& bb ) { DbU::Unit axis; DbU::Unit width; DbU::Unit sourceU; DbU::Unit targetU; if (getDirection() == Flags::Horizontal) { axis = bb.getYCenter(); width = bb.getHeight(); sourceU = bb.getXMin(); targetU = bb.getXMax(); } else { axis = bb.getXCenter(); width = bb.getWidth(); sourceU = bb.getYMin(); targetU = bb.getYMax(); } vector<Rail*>::iterator irail = find_if ( _rails.begin(), _rails.end(), RailMatch(axis,width) ); Rail* rail = NULL; if ( irail == _rails.end() ) { rail = new Rail(this,axis,width); _rails.push_back ( rail ); stable_sort ( _rails.begin(), _rails.end(), RailCompare() ); } else { rail = *irail; } rail->merge ( sourceU, targetU ); } void PowerRailsPlanes::Rails::doLayout ( const Layer* layer ) { cdebug_log(159,0) << "Doing layout of rails: " << layer->getName() << " " << ((_direction==Flags::Horizontal) ? "Horizontal" : "Vertical") << " " << _net->getName() << endl; for ( size_t irail=0 ; irail<_rails.size() ; irail++ ) _rails[irail]->doLayout ( layer ); } PowerRailsPlanes::Plane::Plane ( const Layer* layer, RoutingPlane* routingPlane ) : _layer (layer) , _routingPlane (routingPlane) , _horizontalRails () , _verticalRails () , _powerDirection (routingPlane->getDirection()) { cdebug_log(159,0) << "New Plane " << _layer->getName() << " " << _routingPlane << endl; // Hard-coded SxLib gauge. if (_routingPlane->getDepth() == 0) _powerDirection = Flags::Horizontal; } PowerRailsPlanes::Plane::~Plane () { RailsMap::iterator irail = _horizontalRails.begin(); for ( ; irail != _horizontalRails.end() ; ++irail ) { delete (*irail).second; } irail = _verticalRails.begin(); for ( ; irail != _verticalRails.end() ; ++irail ) { delete (*irail).second; } } inline const Layer* PowerRailsPlanes::Plane::getLayer () const { return _layer; } inline RoutingPlane* PowerRailsPlanes::Plane::getRoutingPlane () { return _routingPlane; } inline Flags PowerRailsPlanes::Plane::getDirection () const { return _routingPlane->getDirection(); } inline Flags PowerRailsPlanes::Plane::getPowerDirection () const { return _powerDirection; } void PowerRailsPlanes::Plane::merge ( const Box& bb, Net* net ) { Rails* rails = NULL; cdebug_log(159,0) << " Plane::merge() " << net->getName() << " " << bb << endl; Flags direction = getDirection(); if ( (net->getType() == Net::Type::POWER) or (net->getType() == Net::Type::GROUND) ) direction = getPowerDirection(); if (direction == Flags::Horizontal) { RailsMap::iterator irails = _horizontalRails.find(net); if ( irails == _horizontalRails.end() ) { rails = new Rails(this,Flags::Horizontal,net); _horizontalRails.insert ( make_pair(net,rails) ); } else rails = (*irails).second; rails->merge ( bb ); } else { RailsMap::iterator irails = _verticalRails.find(net); if ( irails == _verticalRails.end() ) { rails = new Rails(this,Flags::Vertical,net); _verticalRails.insert ( make_pair(net,rails) ); } else rails = (*irails).second; cdebug_log(159,0) << " Vertical Merging" << endl; rails->merge ( bb ); } } void PowerRailsPlanes::Plane::doLayout () { cdebug_log(159,0) << "Doing layout of plane: " << _layer->getName() << endl; RailsMap::iterator irails = _horizontalRails.begin(); for ( ; irails != _horizontalRails.end() ; ++irails ) { (*irails).second->doLayout(_layer); } irails = _verticalRails.begin(); for ( ; irails != _verticalRails.end() ; ++irails ) { (*irails).second->doLayout(_layer); } } PowerRailsPlanes::PowerRailsPlanes ( KatanaEngine* katana ) : _katana (katana) , _globalNets (katana) , _planes () , _activePlane (NULL) , _activeBlockagePlane(NULL) { _globalNets.setBlockage( katana->getBlockageNet() ); Technology* technology = DataBase::getDB()->getTechnology(); RoutingGauge* rg = _katana->getConfiguration()->getRoutingGauge(); for( Layer* layer : technology->getLayers() ) { RegularLayer* regular = dynamic_cast<RegularLayer*>(layer); if ( not regular or (regular->getBasicLayer()->getMaterial() != BasicLayer::Material::metal) ) continue; RoutingLayerGauge* lg = rg->getLayerGauge(regular); if ( not lg ) continue; cdebug_log(159,0) << "Gauge: [" << lg->getDepth() << "] " << lg << endl; RoutingPlane* rp = _katana->getRoutingPlaneByIndex(lg->getDepth()); cdebug_log(159,0) << "Plane:" << rp << endl; _planes.insert( make_pair(regular->getBasicLayer(),new Plane(regular,rp)) ); if (lg->getType() == Constant::PinOnly) continue; const BasicLayer* blockageLayer = regular->getBasicLayer()->getBlockageLayer(); if (not blockageLayer) continue; _planes.insert( make_pair(blockageLayer,new Plane(blockageLayer,rp)) ); } } PowerRailsPlanes::~PowerRailsPlanes () { while ( not _planes.empty() ) { delete _planes.begin()->second; _planes.erase ( _planes.begin() ); } } inline Net* PowerRailsPlanes::getRootNet ( Net* net, Path path ) { return _globalNets.getRootNet(net,path); } inline bool PowerRailsPlanes::isCoreClockNetRouted ( const Net* net ) const { return _globalNets.isCoreClockNetRouted(net); } bool PowerRailsPlanes::hasPlane ( const BasicLayer* layer ) { return (_planes.find(layer) != _planes.end()); } bool PowerRailsPlanes::setActivePlane ( const BasicLayer* layer ) { PlanesMap::iterator iplane = _planes.find(layer); if (iplane == _planes.end()) return false; _activePlane = iplane->second; _activeBlockagePlane = NULL; if (layer->getMaterial() != BasicLayer::Material::blockage) { BasicLayer* blockageLayer = layer->getBlockageLayer(); PlanesMap::iterator ibplane = _planes.find(blockageLayer); if (ibplane != _planes.end()) _activeBlockagePlane = ibplane->second; } return true; } inline PowerRailsPlanes::Plane* PowerRailsPlanes::getActivePlane () const { return _activePlane; } inline PowerRailsPlanes::Plane* PowerRailsPlanes::getActiveBlockagePlane () const { return _activeBlockagePlane; } void PowerRailsPlanes::merge ( const Box& bb, Net* net ) { if (not _activePlane) return; Net* topGlobalNet = _globalNets.getRootNet( net, Path() ); if (topGlobalNet == NULL) { cdebug_log(159,0) << "Not a global net: " << net << endl; return; } if ( (topGlobalNet == _globalNets.getBlockage()) and (_activeBlockagePlane != NULL) ) _activeBlockagePlane->merge( bb, topGlobalNet ); else _activePlane->merge( bb, topGlobalNet ); } void PowerRailsPlanes::doLayout () { PlanesMap::iterator iplane = _planes.begin(); for ( ; iplane != _planes.end() ; iplane++ ) iplane->second->doLayout (); } // ------------------------------------------------------------------- // Class : "::QueryPowerRails". class QueryPowerRails : public Query { public: QueryPowerRails ( KatanaEngine* ); virtual bool hasGoCallback () const; virtual void setBasicLayer ( const BasicLayer* ); virtual bool hasBasicLayer ( const BasicLayer* ); virtual void goCallback ( Go* ); virtual void rubberCallback ( Rubber* ); virtual void extensionGoCallback ( Go* ); virtual void masterCellCallback (); void addToPowerRail ( const Go* go , const BasicLayer* basicLayer , const Box& area , const Transformation& transformation ); void ringAddToPowerRails (); virtual void doQuery (); inline void doLayout (); inline uint32_t getGoMatchCount () const; private: AllianceFramework* _framework; KatanaEngine* _katana; RoutingGauge* _routingGauge; const ChipTools& _chipTools; PowerRailsPlanes _powerRailsPlanes; bool _isBlockagePlane; vector<const Segment*> _hRingSegments; vector<const Segment*> _vRingSegments; uint32_t _goMatchCount; }; QueryPowerRails::QueryPowerRails ( KatanaEngine* katana ) : Query () , _framework (AllianceFramework::get()) , _katana (katana) , _routingGauge (katana->getConfiguration()->getRoutingGauge()) , _chipTools (katana->getChipTools()) , _powerRailsPlanes(katana) , _isBlockagePlane (false) , _hRingSegments () , _vRingSegments () , _goMatchCount (0) { setCell ( katana->getCell() ); setArea ( katana->getCell()->getAbutmentBox() ); setBasicLayer ( NULL ); setFilter ( Query::DoTerminalCells|Query::DoComponents ); cmess1 << " o Building power rails." << endl; } inline uint32_t QueryPowerRails::getGoMatchCount () const { return _goMatchCount; } inline void QueryPowerRails::doLayout () { return _powerRailsPlanes.doLayout(); } bool QueryPowerRails::hasBasicLayer ( const BasicLayer* basicLayer ) { return _powerRailsPlanes.hasPlane ( basicLayer ); } void QueryPowerRails::setBasicLayer ( const BasicLayer* basicLayer ) { _isBlockagePlane = (basicLayer) and (basicLayer->getMaterial() == BasicLayer::Material::blockage); _powerRailsPlanes.setActivePlane ( basicLayer ); Query::setBasicLayer ( basicLayer ); } void QueryPowerRails::doQuery () { PowerRailsPlanes::Plane* activePlane = _powerRailsPlanes.getActivePlane(); if (not activePlane) return; cmess1 << " - PowerRails in " << activePlane->getLayer()->getName() << " ..." << endl; Query::doQuery(); } void QueryPowerRails::masterCellCallback () { } bool QueryPowerRails::hasGoCallback () const { return true; } void QueryPowerRails::goCallback ( Go* go ) { //ltrace(80) << "QueryPowerRails::goCallback() " << go->getId() << ":" << go // << " " << getPath().getName() << endl; addToPowerRail ( go, getBasicLayer(), getArea(), getTransformation() ); } void QueryPowerRails::addToPowerRail ( const Go* go , const BasicLayer* basicLayer , const Box& area , const Transformation& transformation ) { const Component* component = dynamic_cast<const Component*>(go); if ( component ) { if ( _framework->isPad(getMasterCell()) and ( (_routingGauge->getLayerDepth(component->getLayer()) < 2) or (component->getLayer()->getBasicLayers().getFirst()->getMaterial() != BasicLayer::Material::blockage) ) ) return; Net* rootNet = _katana->getBlockageNet(); if (not _isBlockagePlane) { rootNet = _powerRailsPlanes.getRootNet(component->getNet(),getPath()); } #if 0 Net* rootNet = NULL; if ( not _isBlockagePlane ) rootNet = _powerRailsPlanes.getRootNet(component->getNet(),getPath()); else { rootNet = _katana->getBlockageNet(); } #endif if ( rootNet == NULL ) { cdebug_log(159,0) << " rootNet is NULL, not taken into account." << endl; return; } cdebug_log(159,0) << " rootNet " << rootNet << " (" << rootNet->isClock() << ") " << go->getCell() << " (" << go->getCell()->isTerminal() << ")" << endl; const Segment* segment = dynamic_cast<const Segment*>(component); if ( segment != NULL ) { _goMatchCount++; cdebug_log(159,0) << " Merging PowerRail element: " << segment << endl; Box bb = segment->getBoundingBox ( basicLayer ); uint32_t depth = _routingGauge->getLayerDepth ( segment->getLayer() ); if ( _chipTools.isChip() and ((depth == 2) or (depth == 3)) and (segment->getWidth () == _chipTools.getPadPowerWidth()) and (segment->getLength() > _chipTools.getPadWidth()) and (_katana->getChipTools().getCorona().contains(bb)) ) { switch ( depth ) { case 2: _vRingSegments.push_back ( segment ); break; // M3 V. case 3: _hRingSegments.push_back ( segment ); break; // M4 H. } return; } transformation.applyOn ( bb ); _powerRailsPlanes.merge ( bb, rootNet ); } else { const Contact* contact = dynamic_cast<const Contact*>(component); if ( contact != NULL ) { _goMatchCount++; Box bb = contact->getBoundingBox ( basicLayer ); transformation.applyOn ( bb ); cdebug_log(159,0) << " Merging PowerRail element: " << contact << " bb:" << bb << " " << basicLayer << endl; _powerRailsPlanes.merge ( bb, rootNet ); } } } } void QueryPowerRails::ringAddToPowerRails () { if ( not _hRingSegments.empty() ) { const RegularLayer* layer = dynamic_cast<const RegularLayer*>(_routingGauge->getRoutingLayer(3)); setBasicLayer ( layer->getBasicLayer() ); DbU::Unit xmin = DbU::Max; DbU::Unit xmax = DbU::Min; vector<Box> boxes; for ( size_t i=0 ; i<_hRingSegments.size() ; ++i ) { boxes.push_back ( _hRingSegments[i]->getBoundingBox() ); xmin = std::min ( xmin, boxes.back().getXMin() ); xmax = std::max ( xmax, boxes.back().getXMax() ); } for ( size_t i=0 ; i<_hRingSegments.size() ; ++i ) { _powerRailsPlanes.merge ( Box(xmin,boxes[i].getYMin(),xmax,boxes[i].getYMax()) , _powerRailsPlanes.getRootNet(_hRingSegments[i]->getNet(),Path()) ); } } if ( not _vRingSegments.empty() ) { const RegularLayer* layer = dynamic_cast<const RegularLayer*>(_routingGauge->getRoutingLayer(2)); setBasicLayer ( layer->getBasicLayer() ); DbU::Unit ymin = DbU::Max; DbU::Unit ymax = DbU::Min; vector<Box> boxes; for ( size_t i=0 ; i<_vRingSegments.size() ; ++i ) { boxes.push_back ( _vRingSegments[i]->getBoundingBox() ); ymin = std::min ( ymin, boxes.back().getYMin() ); ymax = std::max ( ymax, boxes.back().getYMax() ); } for ( size_t i=0 ; i<_vRingSegments.size() ; ++i ) { _powerRailsPlanes.merge ( Box(boxes[i].getXMin(),ymin,boxes[i].getXMax(),ymax) , _powerRailsPlanes.getRootNet(_vRingSegments[i]->getNet(),Path()) ); } } } void QueryPowerRails::rubberCallback ( Rubber* ) { } void QueryPowerRails::extensionGoCallback ( Go* ) { } } // End of anonymous namespace. namespace Katana { using Hurricane::DataBase; using Hurricane::Technology; using Hurricane::BasicLayer; using Anabatic::NetRoutingState; using Anabatic::NetData; void KatanaEngine::setupPowerRails () { //DebugSession::open( 150, 160 ); openSession(); if (not getBlockageNet()) { setBlockageNet( getCell()->getNet("blockagenet") ); if (not getBlockageNet()) { setBlockageNet( Net::create( getCell(), "blockagenet" ) ); getBlockageNet()->setType( Net::Type::BLOCKAGE ); } NetData* state = getNetData( getBlockageNet(), Flags::Create ); state->getNetRoutingState()->setFlags( NetRoutingState::Fixed ); } QueryPowerRails query ( this ); Technology* technology = DataBase::getDB()->getTechnology(); for( BasicLayer* layer : technology->getBasicLayers() ) { if ( (layer->getMaterial() != BasicLayer::Material::metal) and (layer->getMaterial() != BasicLayer::Material::blockage) ) continue; if (_configuration->isGMetal(layer)) continue; if (not query.hasBasicLayer(layer)) continue; query.setBasicLayer( layer ); query.doQuery (); } query.ringAddToPowerRails(); query.doLayout(); cmess1 << " - " << query.getGoMatchCount() << " power rails elements found." << endl; const vector<GCell*>& gcells = getGCells(); for ( auto gcell : gcells ) { gcell->truncDensities(); } Session::close(); //DebugSession::close(); } } // Katana namespace.
[ "Jean-Paul.Chaput@lip6.fr" ]
Jean-Paul.Chaput@lip6.fr
bb1ea07d79cbd3d6e571d7c5fae9bbf921779e48
123255b45f1d8f142d0b36f4143b7682b07c4a50
/DynamicProgramming/PerfectSquares_279.cpp
9499a46f7606877ee4c9b58c1920f975c3406f5c
[]
no_license
Aradhana-Singh/DSA_CPP
4d54d7c5f192fe344f97c740722c96baca63b197
8dd568bd0cc3651df11465a68eda3c3794e3e355
refs/heads/master
2022-11-07T13:42:28.503040
2020-06-18T11:43:08
2020-06-18T11:43:08
260,713,533
1
0
null
null
null
null
UTF-8
C++
false
false
325
cpp
class Solution { public: int numSquares(int n) { int dp[n+1]; dp[1] = 1; dp[0] = 0; for(int i =2 ; i<=n; i++){ dp[i] = INT_MAX; for(int j = 1; j*j<=i; j++){ dp[i] = min(dp[i] , dp[i-(j*j)] + 1); } } return dp[n]; } };
[ "aradhana971127@gmail.com" ]
aradhana971127@gmail.com
a0564190545244dd639b5f51fd1ee5d90369524e
15a1bb876832ce5eb0e9584a5cad2b1977d74b6f
/operator/include/operator/pool_param.hpp
7254b882e3f2241b8aea6d588d5b096c63aff20b
[ "Apache-2.0" ]
permissive
houzh/Tengine
b5359844004d0d7876d58c792c0312cb588fcbfb
423aaaf7e9008679f64a78ee93c8ebf7dbd58dc9
refs/heads/master
2020-05-05T10:55:47.329897
2019-04-18T12:30:27
2019-04-18T12:30:27
179,966,947
3
0
null
null
null
null
UTF-8
C++
false
false
2,019
hpp
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * License); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * AS IS BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright (c) 2017, Open AI Lab * Author: haitao@openailab.com */ #ifndef __POOLING_PARAM_HPP__ #define __POOLING_PARAM_HPP__ #include "parameter.hpp" enum PoolArg { kPoolMax, kPoolAvg, kPoolRand }; enum PoolingSize { POOL_GENERIC, POOL_K2S2, POOL_K3S2, POOL_K3S1 }; namespace TEngine { struct PoolParam : public NamedParam { int alg; int kernel_h; int kernel_w; int pad_h; int pad_w; int stride_h; int stride_w; int global; int caffe_flavor; std::vector<int> kernel_shape; ///> The size of the kernel along each axis (H, W). std::vector<int> strides; ///> stride along each axis (H, W). std::vector<int> pads; ///> [x1_begin, x2_begin...x1_end, x2_end,...] for each axis. DECLARE_PARSER_STRUCTURE(PoolParam) { DECLARE_PARSER_ENTRY(alg); DECLARE_PARSER_ENTRY(kernel_h); DECLARE_PARSER_ENTRY(kernel_w); DECLARE_PARSER_ENTRY(stride_h); DECLARE_PARSER_ENTRY(stride_w); DECLARE_PARSER_ENTRY(pad_h); DECLARE_PARSER_ENTRY(pad_w); DECLARE_PARSER_ENTRY(global); DECLARE_PARSER_ENTRY(caffe_flavor); }; }; } // namespace TEngine #endif
[ "houzh@21cn.com" ]
houzh@21cn.com
941b60a8448e835c6650aa287c614184d0548640
c948afe7abef4cede06415f14b209b3b1699bf3b
/Window.h
da509f15217888130be273a55dbfa81be42bc6df
[]
no_license
RyanSwann1/BLergh
caa73f437dc45bf13ae38645166b8cca0ad10e31
55baa38a786cfd596785809acca201e9697ea17e
refs/heads/master
2020-12-24T08:41:40.731127
2016-11-09T22:51:42
2016-11-09T22:51:42
73,327,708
0
0
null
null
null
null
UTF-8
C++
false
false
1,140
h
#pragma once #include "EventManager.h" #include <SFML\Graphics.hpp> #include <SFML\Window.hpp> #include <string> //https://www.reddit.com/r/programming/comments/4nrsw1/is_dark_theme_in_ides_actually_worse_for_you/ struct SharedContext; class Window { public: Window(SharedContext* sharedContext, const sf::Vector2u& size = sf::Vector2u(900, 600), const std::string& name = "SFML_WINDOW"); ~Window(); void beginDraw() { m_window.clear(sf::Color::Black); } void draw(sf::Drawable& drawable) { m_window.draw(drawable); } void endDraw() { m_window.display(); } bool isRunning() const { return m_isRunning; } void stopRunning() { m_isRunning = false; } void close() { m_window.close(); } void setup(const sf::Vector2u& size, const std::string& name); void update(); sf::RenderWindow& getWindow() { return m_window; } EventManager& getEventManager() { return m_eventManager; } sf::FloatRect getViewSpace() const; private: sf::RenderWindow m_window; sf::Vector2u m_size; std::string m_name; EventManager m_eventManager; bool m_fullScreen; bool m_isRunning; void create(); };
[ "noreply@github.com" ]
noreply@github.com
4bf766c29e4a91ac57363a1f811bfce07fbc3bf0
a94169ceb4b232ff67e675a89932c4438d87e798
/O4_ASU/O4.video/Storytelling_v1.0/Max Patches Libs/externals/externals/jit/tml/outlines/max.jit.tml.outlines.cpp
2b981d1a757ecb18880d19bac414cee394c5c786
[]
no_license
Synthesis-ASU-TML/Synthesis-TML
78872e0dee07a05b2d900137f9e8b5294a728d2b
f1536ae3c58624d34ecf5fad61393f92a06a24a4
refs/heads/master
2021-01-18T01:30:44.559970
2016-11-26T03:55:11
2016-11-26T03:55:11
17,074,532
4
1
null
null
null
null
UTF-8
C++
false
false
1,754
cpp
#include "jit.common.h" #include "max.jit.mop.h" #define EXTERNAL_NAME "jit_tml_outlines" typedef struct _max_jit_tml_outlines { t_object ob; void *obex; } t_max_jit_tml_outlines; t_jit_err jit_tml_outlines_init(void); void *max_jit_tml_outlines_class; t_symbol *ps_getmap; /* * Constructor */ void *max_jit_tml_outlines_new(t_symbol *s, long argc, t_atom *argv) { t_max_jit_tml_outlines *x; //long attrstart; void *o; //Allocate memory x = (t_max_jit_tml_outlines *)max_jit_obex_new(max_jit_tml_outlines_class,NULL); //only max object, no jit object o = jit_object_new(gensym(EXTERNAL_NAME)); if (o) { max_jit_mop_setup_simple(x, o, argc, argv); max_jit_attr_args(x, argc, argv); } else { error("jit.tml.outlines: unable to allocate object"); freeobject((struct object *)x); } return (x); } /* * Destructor */ void max_jit_tml_outlines_delete(t_max_jit_tml_outlines *x) { //only max object, no jit object max_jit_mop_free(x); jit_object_free(max_jit_obex_jitob_get(x)); max_jit_obex_free(x); } /* * Main method */ int main(void) { //long attrflags; void *p, *q;//, *attr; //Initialize the ODE stuff jit_tml_outlines_init(); setup((t_messlist**)&max_jit_tml_outlines_class, //Define class type (method)max_jit_tml_outlines_new, //Constructor (method)max_jit_tml_outlines_delete, //Destructor (short)sizeof(t_max_jit_tml_outlines), //Size of data to allocate 0L, A_GIMME, 0); //Default get-all p = max_jit_classex_setup(calcoffset(t_max_jit_tml_outlines,obex)); q = jit_class_findbyname(gensym(EXTERNAL_NAME)); max_jit_classex_mop_wrap(p,q,0); max_jit_classex_standard_wrap(p,q,0); post("Initialized: jit.tml.outlines - XCode Build"); return 0; }
[ "assegid@asu.edu" ]
assegid@asu.edu
78a904ee98e94d9fa330c1a0f0e5085f2b647081
5aac3bb8f8b6630b2132004444b4e4e090d97206
/Codechef/SOLBLTY.cpp
8a351dbbc5ba863df930c78753f8a857fb08956b
[]
no_license
himanshumishra508/APS-Code-Library
07d57ebf4db68139086a9355fb3ca531391cef75
a635ca24e6b2a2c9ca3837dbcbfe4850f8c5f4a2
refs/heads/main
2023-08-10T17:21:09.795823
2021-10-04T18:40:22
2021-10-04T18:40:22
380,039,178
0
3
null
2021-10-04T18:40:23
2021-06-24T20:09:02
C++
UTF-8
C++
false
false
361
cpp
#include<bits/stdc++.h> using namespace std; #define int long long int #define pb push_back #define io ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL) int32_t main() { io; int t; cin>>t; while(t--) { int x,a,b,answer; cin>>x>>a>>b; answer = (a*10); answer=answer+((100-x)*b*10); cout<<answer<<"\n"; } return 0; }
[ "mishrahimanshu.hmi@gmail.com" ]
mishrahimanshu.hmi@gmail.com
bac91378248184f982636328a4c35349ede79763
e2083f5399af23a1484529421b56889de74817c2
/src/solvers/dgfm/parallel_dgfm/mpi_dgfm.cpp
3f74ee4f50dc3f1aac01e1d85dca25076138e179
[]
no_license
cemagg/SUN-EM-CMOM
d297dcbcbde5ba31162227b85203b97ae9b5c5cf
d9b06f92f9cc1eaf0fe9093aacaf068a454741e1
refs/heads/master
2020-04-25T10:07:20.024323
2019-08-06T15:40:54
2019-08-06T15:40:54
172,698,309
16
13
null
2019-08-06T15:40:55
2019-02-26T11:26:45
C++
UTF-8
C++
false
false
3,634
cpp
#include "mpi_dgfm.h" #define TIMING #ifdef TIMING #define INIT_TIMER auto start = std::chrono::high_resolution_clock::now(); #define START_TIMER start = std::chrono::high_resolution_clock::now(); #define STOP_TIMER(name) std::cout << "RUNTIME of " << name << ": " << \ std::chrono::duration_cast<std::chrono::milliseconds>( \ std::chrono::high_resolution_clock::now()-start \ ).count() << " ms " << std::endl; #else #define INIT_TIMER #define START_TIMER #define STOP_TIMER(name) #endif void mpiPerformDGFM(std::map<std::string, std::string> &const_map, std::map<int, Label> &label_map, std::vector<Triangle> &triangles, std::vector<Edge> &edges, std::vector<Node<double>> &nodes, std::vector<Excitation> &excitations, std::complex<double> *ilhs) { int size; int rank; MPI_Comm_size(MPI_COMM_WORLD, &size); MPI_Comm_rank(MPI_COMM_WORLD, &rank); // Get num domains and domain size int num_domains = label_map.size(); int domain_size = label_map[0].edge_indices.size(); // Allocate Work int *displs = new int[size]; displs[0] = 0; for (int i = 1; i < size; i++) { displs[i] = displs[i - 1] + ((num_domains + i) / size); } int local_num_rows; if (rank == (size - 1)) { local_num_rows = num_domains - displs[rank]; } else { local_num_rows = displs[rank + 1] - displs[rank]; } // Allocate Memory std::vector<DGFMRow> dgfm_rows; DGFMExcitations dgfm_excitations; dgfm_rows.resize(local_num_rows); // for (int i = 0; i < local_num_rows; i++) // { // allocateDGFMRowMemory(dgfm_rows[i], num_domains, domain_size); // } allocateDGFMExcitations(dgfm_excitations, num_domains, domain_size); std::complex<double> *local_ilhs = new std::complex<double>[local_num_rows * domain_size]; // Do the work fillDGFMExcitations( dgfm_excitations, num_domains, domain_size, const_map, label_map, triangles, edges, nodes, excitations); int start_index = displs[rank]; int end_index = displs[rank] + local_num_rows; bool use_threading = (num_domains/size) < size; // #pragma omp parallel for //if(!use_threading) for (int i = start_index; i < end_index; i++) { double start = omp_get_wtime(); allocateDGFMRowMemory(dgfm_rows[i - start_index], num_domains, domain_size); calculateDGFMRow(dgfm_rows[i - start_index], dgfm_excitations, i, num_domains, domain_size, use_threading, const_map, label_map, triangles, edges, nodes, excitations); std::copy(dgfm_excitations.excitations[i], dgfm_excitations.excitations[i] + domain_size, local_ilhs + ((i - start_index) * domain_size)); deAllocateDGFMRowMemory(dgfm_rows[i - start_index], num_domains); double end = omp_get_wtime(); std::cout << "tid: " << "none" << " time: " << end - start << std::endl; } // for (int i = 0; i < local_num_rows; i++) // { // deAllocateDGFMRowMemory(dgfm_rows[i], num_domains); // } // Gather to proc 0 int *recv_counts; if (rank == 0) { recv_counts = new int[size]; for (int i = 0; i < size; i++) { if (i == (size - 1)) { recv_counts[i] = (num_domains - displs[i]) * domain_size; } else { recv_counts[i] = (displs[i + 1] - displs[i]) * domain_size; } displs[i] = displs[i] * domain_size; } } MPI_Gatherv( local_ilhs, local_num_rows * domain_size, MPI_CXX_DOUBLE_COMPLEX, ilhs, recv_counts, displs, MPI_CXX_DOUBLE_COMPLEX, 0, MPI_COMM_WORLD); }
[ "etameez@gmail.com" ]
etameez@gmail.com
138dbbef15746025afc03d9ef943c0fa0bb4130e
2499fe2d1703374905a0074f87cf517760f65ad8
/Cpp/assignment3/template.cpp
95c77ccf37cdb3bfee4278eee82045faa3f82dd3
[]
no_license
shubham19ss/NCRwork
c10ba25118d9eee8ef8df84b557deaf8ab9ec8de
5288e74959ea1a882e9e7e0caa9981b4f9758664
refs/heads/master
2020-04-20T05:08:49.873446
2019-02-21T05:10:51
2019-02-21T05:10:51
168,647,937
0
0
null
2019-02-01T11:44:15
2019-02-01T05:36:18
C
UTF-8
C++
false
false
2,624
cpp
#include<iostream> #include<cstring> using namespace std; template < class T > // template declaration int linear_search(T arr[], int size, T ele) // template function to implement search {int i; for (i = 0; i < size; i++) { if (arr[i] == ele) return i; } return -1; } class Complex { int real, imag; public: Complex() //default constructor { real = imag = 0; } Complex(int x, int y) // parameterized constructor { real = x; imag = y; } Complex(const Complex & b) //copy constructor { real = b.real; imag = b.imag; }~Complex() {} bool operator == (const Complex & a) { if (real == a.real && imag == a.imag) return true; else return false; } friend istream & operator >> (istream & cin, Complex & b); //overloading cin }; istream & operator >> (istream & cin, Complex & x) { cin >> x.real >> x.imag; return cin; } int linear_search(const char * arr[], int size, char eles[20]) //search function for char * type data { int i; for (i = 0; i < size; i++) { if (strcmp(arr[i], eles) == 0) return i; } return -1; } int main() { int arrInt[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int pos = linear_search(arrInt, 10, 6); if (pos == -1) { cout << "element not found\n"; } else { cout << "Element found at " << pos << endl; } double arrFloat[] = { 1.0 , 2.0 , 3.0 , 4.0 , 5.0 , 6.0 , 7.0 , 8.0 , 9.0 , 10.0 }; int posF = linear_search(arrFloat, 10, 10.0); if (posF == -1) { cout << "element not found\n"; } else { cout << "Element found at " << posF << endl; } // passing doubles double arrDouble[] = { 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0 }; int posd = linear_search(arrDouble, 10, 5.0); if (posd == -1) { cout << "element not found\n"; } else { cout << "Element found at " << posd << endl; } //passing char* arrray const char * arr[4] = { "ncr", "cdac", "hello", "vce" }; char eles[20] = "cdac"; int posc = linear_search(arr, 4, eles); if (posc == -1) { cout << "element not found\n"; } else { cout << "Element found at " << posc << endl; } // passing complex objects Complex c(10, 5), ar[5]; cout << "enter the complex objects \n"; int i; for ( i = 0; i < 5; i++) { cin >> ar[i]; } int posco = linear_search(ar, 5, c); if (posco == -1) { cout << "element not found\n"; } else { cout << "Element found at " << posco << endl; } return 0; }
[ "35145373+shubham19ss@users.noreply.github.com" ]
35145373+shubham19ss@users.noreply.github.com
62d399c1c984d0fdc87ebb9c72c6657e323ba34c
d09945668f19bb4bc17087c0cb8ccbab2b2dd688
/codeforce/751-800/774/e2.cpp
851706208a496d387d5fa1ff56e2d10bea28eff9
[]
no_license
kmjp/procon
27270f605f3ae5d80fbdb28708318a6557273a57
8083028ece4be1460150aa3f0e69bdb57e510b53
refs/heads/master
2023-09-04T11:01:09.452170
2023-09-03T15:25:21
2023-09-03T15:25:21
30,825,508
23
2
null
2023-08-18T14:02:07
2015-02-15T11:25:23
C++
UTF-8
C++
false
false
1,608
cpp
#include <bits/stdc++.h> using namespace std; typedef signed long long ll; #define _P(...) (void)printf(__VA_ARGS__) #define FOR(x,to) for(x=0;x<(to);x++) #define FORR(x,arr) for(auto& x:arr) #define FORR2(x,y,arr) for(auto& [x,y]:arr) #define ALL(a) (a.begin()),(a.end()) #define ZERO(a) memset(a,0,sizeof(a)) #define MINUS(a) memset(a,0xff,sizeof(a)) template<class T> bool chmax(T &a, const T &b) { if(a<b){a=b;return 1;}return 0;} template<class T> bool chmin(T &a, const T &b) { if(a>b){a=b;return 1;}return 0;} //------------------------------------------------------- ll N,M; ll did[1010101]; vector<int> V[22]; int C[22]; vector<int> W; void solve() { int i,j,k,l,r,x,y; string s; cin>>N>>M; W.resize(M); vector<int> V; for(i=1;i<=19;i++) { vector<int> X; for(j=1;j<=M;j++) W[j-1]=i*j; x=y=0; while(x<V.size()||y<W.size()) { if(y==W.size()) { X.push_back(V[x++]); } else if(x==V.size()) { X.push_back(W[y++]); } else if(V[x]==W[y]) { X.push_back(W[y++]); x++; } else if(V[x]<W[y]) { X.push_back(V[x++]); } else { X.push_back(W[y++]); } } C[i]=X.size(); swap(V,X); } ll ret=1; for(i=2;i<=N;i++) if(did[i]==0) { x=1; ll a=i; while(a*i<=N) a*=i,x++, did[a]=1; ret+=C[x]; } cout<<ret<<endl; } int main(int argc,char** argv){ string s;int i; if(argc==1) ios::sync_with_stdio(false), cin.tie(0); FOR(i,argc-1) s+=argv[i+1],s+='\n'; FOR(i,s.size()) ungetc(s[s.size()-1-i],stdin); cout.tie(0); solve(); return 0; }
[ "kmjp@users.noreply.github.com" ]
kmjp@users.noreply.github.com
71a8865e034030708e88fe17530a4a6ae70c9402
1c57e996dbbb390a2e4654de855e7f3fd04b69c5
/src/BoostLib/boost/serialization/array.h
2cabe267ae0195ed374e684f869cfebdfaaa7735
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
BrainTwister/GeneHunter
20a906e6607a6058acd4f72fbfccb7d6d8f13578
c8990fac4ef48c4a3322053b34095e70ae591dd8
refs/heads/master
2020-05-30T06:38:35.699017
2017-01-31T14:35:34
2017-01-31T14:35:34
19,794,742
4
1
null
2016-09-23T15:47:57
2014-05-14T20:18:32
C++
UTF-8
C++
false
false
552
h
#ifndef BOOSTSERIALIZEARRAY_H_ #define BOOSTSERIALIZEARRAY_H_ #include <boost/config.hpp> #include <boost/serialization/array.hpp> #include <boost/version.hpp> #include <array> #if ((BOOST_VERSION / 100 % 1000) < 58) namespace boost { namespace serialization { template < class Archive, class T, size_t N > inline void serialize( Archive & ar, std::array<T,N>& a, const unsigned int version ) { ar & boost::serialization::make_array(a.data(), N); } } // serialization } // boost #endif /* BOOST_VERSION */ #endif /* BOOSTSERIALIZEARRAY_H_ */
[ "bernd.doser@braintwister.eu" ]
bernd.doser@braintwister.eu
362c440b0e8079e17d5d997de1fefe8a6a7a49e1
33cec150dcc1a4ab9973a2a6607ae74a668010b9
/Plugins/LogicDriver/Intermediate/Build/Win32/UE4/Inc/SMSystem/SMInstance.generated.h
c8e33eefb21230be88503705c49c7b3f279b8f05
[]
no_license
westomopresto/PL_Game_test
93dcf6200182c647bd9a151427f5e49a8002a972
3863f8925725e4e9bf59434bcde11ace88b5820d
refs/heads/master
2023-06-21T10:33:23.957383
2021-08-05T03:25:17
2021-08-05T03:25:17
392,566,951
0
0
null
null
null
null
UTF-8
C++
false
false
18,969
h
// Copyright Epic Games, Inc. All Rights Reserved. /*=========================================================================== Generated code exported from UnrealHeaderTool. DO NOT modify this manually! Edit the corresponding .h files instead! ===========================================================================*/ #include "UObject/ObjectMacros.h" #include "UObject/ScriptMacros.h" #include "Net/Core/PushModel/PushModelMacros.h" PRAGMA_DISABLE_DEPRECATION_WARNINGS class USMInstance; struct FSMStateInfo; struct FSMTransitionInfo; struct FGuid; class USMStateMachineInstance; class USMTransitionInstance; class USMStateInstance_Base; class UObject; class USMStateMachineComponent; #ifdef SMSYSTEM_SMInstance_generated_h #error "SMInstance.generated.h already included, missing '#pragma once' in SMInstance.h" #endif #define SMSYSTEM_SMInstance_generated_h #define HostProject_Plugins_SMSystem_Source_SMSystem_Public_SMInstance_h_25_GENERATED_BODY \ friend struct Z_Construct_UScriptStruct_FSMDebugStateMachine_Statics; \ SMSYSTEM_API static class UScriptStruct* StaticStruct(); template<> SMSYSTEM_API UScriptStruct* StaticStruct<struct FSMDebugStateMachine>(); #define HostProject_Plugins_SMSystem_Source_SMSystem_Public_SMInstance_h_19_DELEGATE \ struct _Script_SMSystem_eventOnStateMachineStateChangedSignature_Parms \ { \ USMInstance* Instance; \ FSMStateInfo NewState; \ FSMStateInfo PreviousState; \ }; \ static inline void FOnStateMachineStateChangedSignature_DelegateWrapper(const FMulticastScriptDelegate& OnStateMachineStateChangedSignature, USMInstance* Instance, FSMStateInfo NewState, FSMStateInfo PreviousState) \ { \ _Script_SMSystem_eventOnStateMachineStateChangedSignature_Parms Parms; \ Parms.Instance=Instance; \ Parms.NewState=NewState; \ Parms.PreviousState=PreviousState; \ OnStateMachineStateChangedSignature.ProcessMulticastDelegate<UObject>(&Parms); \ } #define HostProject_Plugins_SMSystem_Source_SMSystem_Public_SMInstance_h_18_DELEGATE \ struct _Script_SMSystem_eventOnStateMachineTransitionTakenSignature_Parms \ { \ USMInstance* Instance; \ FSMTransitionInfo Transition; \ }; \ static inline void FOnStateMachineTransitionTakenSignature_DelegateWrapper(const FMulticastScriptDelegate& OnStateMachineTransitionTakenSignature, USMInstance* Instance, FSMTransitionInfo Transition) \ { \ _Script_SMSystem_eventOnStateMachineTransitionTakenSignature_Parms Parms; \ Parms.Instance=Instance; \ Parms.Transition=Transition; \ OnStateMachineTransitionTakenSignature.ProcessMulticastDelegate<UObject>(&Parms); \ } #define HostProject_Plugins_SMSystem_Source_SMSystem_Public_SMInstance_h_17_DELEGATE \ struct _Script_SMSystem_eventOnStateMachineStoppedSignature_Parms \ { \ USMInstance* Instance; \ }; \ static inline void FOnStateMachineStoppedSignature_DelegateWrapper(const FMulticastScriptDelegate& OnStateMachineStoppedSignature, USMInstance* Instance) \ { \ _Script_SMSystem_eventOnStateMachineStoppedSignature_Parms Parms; \ Parms.Instance=Instance; \ OnStateMachineStoppedSignature.ProcessMulticastDelegate<UObject>(&Parms); \ } #define HostProject_Plugins_SMSystem_Source_SMSystem_Public_SMInstance_h_16_DELEGATE \ struct _Script_SMSystem_eventOnStateMachineUpdatedSignature_Parms \ { \ USMInstance* Instance; \ float DeltaSeconds; \ }; \ static inline void FOnStateMachineUpdatedSignature_DelegateWrapper(const FMulticastScriptDelegate& OnStateMachineUpdatedSignature, USMInstance* Instance, float DeltaSeconds) \ { \ _Script_SMSystem_eventOnStateMachineUpdatedSignature_Parms Parms; \ Parms.Instance=Instance; \ Parms.DeltaSeconds=DeltaSeconds; \ OnStateMachineUpdatedSignature.ProcessMulticastDelegate<UObject>(&Parms); \ } #define HostProject_Plugins_SMSystem_Source_SMSystem_Public_SMInstance_h_15_DELEGATE \ struct _Script_SMSystem_eventOnStateMachineStartedSignature_Parms \ { \ USMInstance* Instance; \ }; \ static inline void FOnStateMachineStartedSignature_DelegateWrapper(const FMulticastScriptDelegate& OnStateMachineStartedSignature, USMInstance* Instance) \ { \ _Script_SMSystem_eventOnStateMachineStartedSignature_Parms Parms; \ Parms.Instance=Instance; \ OnStateMachineStartedSignature.ProcessMulticastDelegate<UObject>(&Parms); \ } #define HostProject_Plugins_SMSystem_Source_SMSystem_Public_SMInstance_h_14_DELEGATE \ struct _Script_SMSystem_eventOnStateMachineInitializedSignature_Parms \ { \ USMInstance* Instance; \ }; \ static inline void FOnStateMachineInitializedSignature_DelegateWrapper(const FMulticastScriptDelegate& OnStateMachineInitializedSignature, USMInstance* Instance) \ { \ _Script_SMSystem_eventOnStateMachineInitializedSignature_Parms Parms; \ Parms.Instance=Instance; \ OnStateMachineInitializedSignature.ProcessMulticastDelegate<UObject>(&Parms); \ } #define HostProject_Plugins_SMSystem_Source_SMSystem_Public_SMInstance_h_81_SPARSE_DATA #define HostProject_Plugins_SMSystem_Source_SMSystem_Public_SMInstance_h_81_RPC_WRAPPERS \ virtual void OnStateMachineStateChanged_Implementation(FSMStateInfo const& ToState, FSMStateInfo const& FromState); \ virtual void OnStateMachineTransitionTaken_Implementation(FSMTransitionInfo const& Transition); \ virtual void OnStateMachineStop_Implementation(); \ virtual void OnStateMachineUpdate_Implementation(float DeltaSeconds); \ virtual void OnStateMachineStart_Implementation(); \ virtual void OnStateMachineInitialized_Implementation(); \ virtual void Tick_Implementation(float DeltaTime); \ \ DECLARE_FUNCTION(execREP_StartChanged); \ DECLARE_FUNCTION(execInternal_EventCleanup); \ DECLARE_FUNCTION(execInternal_Update); \ DECLARE_FUNCTION(execOnStateMachineStateChanged); \ DECLARE_FUNCTION(execOnStateMachineTransitionTaken); \ DECLARE_FUNCTION(execOnStateMachineStop); \ DECLARE_FUNCTION(execOnStateMachineUpdate); \ DECLARE_FUNCTION(execOnStateMachineStart); \ DECLARE_FUNCTION(execOnStateMachineInitialized); \ DECLARE_FUNCTION(execSetStateMachineClass); \ DECLARE_FUNCTION(execGetStateMachineClass); \ DECLARE_FUNCTION(execGetMasterReferenceOwner); \ DECLARE_FUNCTION(execGetReferenceOwner); \ DECLARE_FUNCTION(execIsInitialized); \ DECLARE_FUNCTION(execHasStarted); \ DECLARE_FUNCTION(execGetAllTransitionInstances); \ DECLARE_FUNCTION(execGetAllStateInstances); \ DECLARE_FUNCTION(execSetContext); \ DECLARE_FUNCTION(execIsInEndState); \ DECLARE_FUNCTION(execSetStopOnEndState); \ DECLARE_FUNCTION(execGetTickInterval); \ DECLARE_FUNCTION(execCanAutoManageTime); \ DECLARE_FUNCTION(execSetAutoManageTime); \ DECLARE_FUNCTION(execSetTickInterval); \ DECLARE_FUNCTION(execSetCanTickWhenPaused); \ DECLARE_FUNCTION(execCanTickOnManualUpdate); \ DECLARE_FUNCTION(execSetTickOnManualUpdate); \ DECLARE_FUNCTION(execSetCanEverTick); \ DECLARE_FUNCTION(execCanEverTick); \ DECLARE_FUNCTION(execIsActive); \ DECLARE_FUNCTION(execGetRootStateMachineInstance); \ DECLARE_FUNCTION(execGetTransitionInstanceByGuid); \ DECLARE_FUNCTION(execGetStateInstanceByGuid); \ DECLARE_FUNCTION(execGetReferencedInstanceByGuid); \ DECLARE_FUNCTION(execTryGetTransitionInfo); \ DECLARE_FUNCTION(execTryGetStateInfo); \ DECLARE_FUNCTION(execGetAllReferencedInstances); \ DECLARE_FUNCTION(execGetAllActiveStateInstances); \ DECLARE_FUNCTION(execGetSingleActiveStateInstance); \ DECLARE_FUNCTION(execGetActiveStateInstance); \ DECLARE_FUNCTION(execGetAllActiveStateGuids); \ DECLARE_FUNCTION(execGetSingleActiveStateGuid); \ DECLARE_FUNCTION(execGetAllCurrentStateGuids); \ DECLARE_FUNCTION(execTryGetNestedActiveState); \ DECLARE_FUNCTION(execGetNestedActiveStateGuid); \ DECLARE_FUNCTION(execGetActiveStateGuid); \ DECLARE_FUNCTION(execGetNestedActiveStateName); \ DECLARE_FUNCTION(execGetActiveStateName); \ DECLARE_FUNCTION(execLoadFromMultipleStates); \ DECLARE_FUNCTION(execLoadFromState); \ DECLARE_FUNCTION(execEvaluateTransitions); \ DECLARE_FUNCTION(execStartWithNewContext); \ DECLARE_FUNCTION(execShutdown); \ DECLARE_FUNCTION(execStop); \ DECLARE_FUNCTION(execUpdate); \ DECLARE_FUNCTION(execStart); \ DECLARE_FUNCTION(execInitialize); \ DECLARE_FUNCTION(execGetComponentOwner); \ DECLARE_FUNCTION(execGetContext); \ DECLARE_FUNCTION(execIsTickableWhenPaused); \ DECLARE_FUNCTION(execIsTickable); \ DECLARE_FUNCTION(execTick); #define HostProject_Plugins_SMSystem_Source_SMSystem_Public_SMInstance_h_81_RPC_WRAPPERS_NO_PURE_DECLS \ \ DECLARE_FUNCTION(execREP_StartChanged); \ DECLARE_FUNCTION(execInternal_EventCleanup); \ DECLARE_FUNCTION(execInternal_Update); \ DECLARE_FUNCTION(execOnStateMachineStateChanged); \ DECLARE_FUNCTION(execOnStateMachineTransitionTaken); \ DECLARE_FUNCTION(execOnStateMachineStop); \ DECLARE_FUNCTION(execOnStateMachineUpdate); \ DECLARE_FUNCTION(execOnStateMachineStart); \ DECLARE_FUNCTION(execOnStateMachineInitialized); \ DECLARE_FUNCTION(execSetStateMachineClass); \ DECLARE_FUNCTION(execGetStateMachineClass); \ DECLARE_FUNCTION(execGetMasterReferenceOwner); \ DECLARE_FUNCTION(execGetReferenceOwner); \ DECLARE_FUNCTION(execIsInitialized); \ DECLARE_FUNCTION(execHasStarted); \ DECLARE_FUNCTION(execGetAllTransitionInstances); \ DECLARE_FUNCTION(execGetAllStateInstances); \ DECLARE_FUNCTION(execSetContext); \ DECLARE_FUNCTION(execIsInEndState); \ DECLARE_FUNCTION(execSetStopOnEndState); \ DECLARE_FUNCTION(execGetTickInterval); \ DECLARE_FUNCTION(execCanAutoManageTime); \ DECLARE_FUNCTION(execSetAutoManageTime); \ DECLARE_FUNCTION(execSetTickInterval); \ DECLARE_FUNCTION(execSetCanTickWhenPaused); \ DECLARE_FUNCTION(execCanTickOnManualUpdate); \ DECLARE_FUNCTION(execSetTickOnManualUpdate); \ DECLARE_FUNCTION(execSetCanEverTick); \ DECLARE_FUNCTION(execCanEverTick); \ DECLARE_FUNCTION(execIsActive); \ DECLARE_FUNCTION(execGetRootStateMachineInstance); \ DECLARE_FUNCTION(execGetTransitionInstanceByGuid); \ DECLARE_FUNCTION(execGetStateInstanceByGuid); \ DECLARE_FUNCTION(execGetReferencedInstanceByGuid); \ DECLARE_FUNCTION(execTryGetTransitionInfo); \ DECLARE_FUNCTION(execTryGetStateInfo); \ DECLARE_FUNCTION(execGetAllReferencedInstances); \ DECLARE_FUNCTION(execGetAllActiveStateInstances); \ DECLARE_FUNCTION(execGetSingleActiveStateInstance); \ DECLARE_FUNCTION(execGetActiveStateInstance); \ DECLARE_FUNCTION(execGetAllActiveStateGuids); \ DECLARE_FUNCTION(execGetSingleActiveStateGuid); \ DECLARE_FUNCTION(execGetAllCurrentStateGuids); \ DECLARE_FUNCTION(execTryGetNestedActiveState); \ DECLARE_FUNCTION(execGetNestedActiveStateGuid); \ DECLARE_FUNCTION(execGetActiveStateGuid); \ DECLARE_FUNCTION(execGetNestedActiveStateName); \ DECLARE_FUNCTION(execGetActiveStateName); \ DECLARE_FUNCTION(execLoadFromMultipleStates); \ DECLARE_FUNCTION(execLoadFromState); \ DECLARE_FUNCTION(execEvaluateTransitions); \ DECLARE_FUNCTION(execStartWithNewContext); \ DECLARE_FUNCTION(execShutdown); \ DECLARE_FUNCTION(execStop); \ DECLARE_FUNCTION(execUpdate); \ DECLARE_FUNCTION(execStart); \ DECLARE_FUNCTION(execInitialize); \ DECLARE_FUNCTION(execGetComponentOwner); \ DECLARE_FUNCTION(execGetContext); \ DECLARE_FUNCTION(execIsTickableWhenPaused); \ DECLARE_FUNCTION(execIsTickable); \ DECLARE_FUNCTION(execTick); #define HostProject_Plugins_SMSystem_Source_SMSystem_Public_SMInstance_h_81_EVENT_PARMS \ struct SMInstance_eventOnStateMachineStateChanged_Parms \ { \ FSMStateInfo ToState; \ FSMStateInfo FromState; \ }; \ struct SMInstance_eventOnStateMachineTransitionTaken_Parms \ { \ FSMTransitionInfo Transition; \ }; \ struct SMInstance_eventOnStateMachineUpdate_Parms \ { \ float DeltaSeconds; \ }; \ struct SMInstance_eventTick_Parms \ { \ float DeltaTime; \ }; #define HostProject_Plugins_SMSystem_Source_SMSystem_Public_SMInstance_h_81_CALLBACK_WRAPPERS #define HostProject_Plugins_SMSystem_Source_SMSystem_Public_SMInstance_h_81_INCLASS_NO_PURE_DECLS \ private: \ static void StaticRegisterNativesUSMInstance(); \ friend struct Z_Construct_UClass_USMInstance_Statics; \ public: \ DECLARE_CLASS(USMInstance, UObject, COMPILED_IN_FLAGS(0), CASTCLASS_None, TEXT("/Script/SMSystem"), NO_API) \ DECLARE_SERIALIZER(USMInstance) \ virtual UObject* _getUObject() const override { return const_cast<USMInstance*>(this); } \ enum class ENetFields_Private : uint16 \ { \ NETFIELD_REP_START=(uint16)((int32)Super::ENetFields_Private::NETFIELD_REP_END + (int32)1), \ R_StateMachineContext=NETFIELD_REP_START, \ R_ActiveStates, \ R_bHasStarted, \ NETFIELD_REP_END=R_bHasStarted }; \ NO_API virtual void ValidateGeneratedRepEnums(const TArray<struct FRepRecord>& ClassReps) const override; \ private: \ REPLICATED_BASE_CLASS(USMInstance) \ public: #define HostProject_Plugins_SMSystem_Source_SMSystem_Public_SMInstance_h_81_INCLASS \ private: \ static void StaticRegisterNativesUSMInstance(); \ friend struct Z_Construct_UClass_USMInstance_Statics; \ public: \ DECLARE_CLASS(USMInstance, UObject, COMPILED_IN_FLAGS(0), CASTCLASS_None, TEXT("/Script/SMSystem"), NO_API) \ DECLARE_SERIALIZER(USMInstance) \ virtual UObject* _getUObject() const override { return const_cast<USMInstance*>(this); } \ enum class ENetFields_Private : uint16 \ { \ NETFIELD_REP_START=(uint16)((int32)Super::ENetFields_Private::NETFIELD_REP_END + (int32)1), \ R_StateMachineContext=NETFIELD_REP_START, \ R_ActiveStates, \ R_bHasStarted, \ NETFIELD_REP_END=R_bHasStarted }; \ NO_API virtual void ValidateGeneratedRepEnums(const TArray<struct FRepRecord>& ClassReps) const override; \ private: \ REPLICATED_BASE_CLASS(USMInstance) \ public: #define HostProject_Plugins_SMSystem_Source_SMSystem_Public_SMInstance_h_81_STANDARD_CONSTRUCTORS \ /** Standard constructor, called after all reflected properties have been initialized */ \ NO_API USMInstance(const FObjectInitializer& ObjectInitializer); \ DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(USMInstance) \ DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, USMInstance); \ DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(USMInstance); \ private: \ /** Private move- and copy-constructors, should never be used */ \ NO_API USMInstance(USMInstance&&); \ NO_API USMInstance(const USMInstance&); \ public: #define HostProject_Plugins_SMSystem_Source_SMSystem_Public_SMInstance_h_81_ENHANCED_CONSTRUCTORS \ private: \ /** Private move- and copy-constructors, should never be used */ \ NO_API USMInstance(USMInstance&&); \ NO_API USMInstance(const USMInstance&); \ public: \ DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, USMInstance); \ DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(USMInstance); \ DEFINE_DEFAULT_CONSTRUCTOR_CALL(USMInstance) #define HostProject_Plugins_SMSystem_Source_SMSystem_Public_SMInstance_h_81_PRIVATE_PROPERTY_OFFSET \ FORCEINLINE static uint32 __PPO__ComponentOwner() { return STRUCT_OFFSET(USMInstance, ComponentOwner); } \ FORCEINLINE static uint32 __PPO__ServerStateMachine() { return STRUCT_OFFSET(USMInstance, ServerStateMachine); } \ FORCEINLINE static uint32 __PPO__ActiveTransactions() { return STRUCT_OFFSET(USMInstance, ActiveTransactions); } \ FORCEINLINE static uint32 __PPO__RootStateMachine() { return STRUCT_OFFSET(USMInstance, RootStateMachine); } \ FORCEINLINE static uint32 __PPO__R_StateMachineContext() { return STRUCT_OFFSET(USMInstance, R_StateMachineContext); } \ FORCEINLINE static uint32 __PPO__R_ActiveStates() { return STRUCT_OFFSET(USMInstance, R_ActiveStates); } \ FORCEINLINE static uint32 __PPO__ReferenceOwner() { return STRUCT_OFFSET(USMInstance, ReferenceOwner); } \ FORCEINLINE static uint32 __PPO__StateMachineClass() { return STRUCT_OFFSET(USMInstance, StateMachineClass); } \ FORCEINLINE static uint32 __PPO__bAutoManageTime() { return STRUCT_OFFSET(USMInstance, bAutoManageTime); } \ FORCEINLINE static uint32 __PPO__bStopOnEndState() { return STRUCT_OFFSET(USMInstance, bStopOnEndState); } \ FORCEINLINE static uint32 __PPO__bCanEverTick() { return STRUCT_OFFSET(USMInstance, bCanEverTick); } \ FORCEINLINE static uint32 __PPO__bCanTickWhenPaused() { return STRUCT_OFFSET(USMInstance, bCanTickWhenPaused); } \ FORCEINLINE static uint32 __PPO__TickInterval() { return STRUCT_OFFSET(USMInstance, TickInterval); } \ FORCEINLINE static uint32 __PPO__bTickRegistered() { return STRUCT_OFFSET(USMInstance, bTickRegistered); } \ FORCEINLINE static uint32 __PPO__bTickBeforeInitialize() { return STRUCT_OFFSET(USMInstance, bTickBeforeInitialize); } \ FORCEINLINE static uint32 __PPO__MaxTimeToWaitForUpdate() { return STRUCT_OFFSET(USMInstance, MaxTimeToWaitForUpdate); } \ FORCEINLINE static uint32 __PPO__TimeSinceAllowedTick() { return STRUCT_OFFSET(USMInstance, TimeSinceAllowedTick); } \ FORCEINLINE static uint32 __PPO__WorldSeconds() { return STRUCT_OFFSET(USMInstance, WorldSeconds); } \ FORCEINLINE static uint32 __PPO__WorldTimeDelta() { return STRUCT_OFFSET(USMInstance, WorldTimeDelta); } \ FORCEINLINE static uint32 __PPO__bCallTickOnManualUpdate() { return STRUCT_OFFSET(USMInstance, bCallTickOnManualUpdate); } \ FORCEINLINE static uint32 __PPO__bIsTicking() { return STRUCT_OFFSET(USMInstance, bIsTicking); } \ FORCEINLINE static uint32 __PPO__bIsUpdating() { return STRUCT_OFFSET(USMInstance, bIsUpdating); } #define HostProject_Plugins_SMSystem_Source_SMSystem_Public_SMInstance_h_78_PROLOG \ HostProject_Plugins_SMSystem_Source_SMSystem_Public_SMInstance_h_81_EVENT_PARMS #define HostProject_Plugins_SMSystem_Source_SMSystem_Public_SMInstance_h_81_GENERATED_BODY_LEGACY \ PRAGMA_DISABLE_DEPRECATION_WARNINGS \ public: \ HostProject_Plugins_SMSystem_Source_SMSystem_Public_SMInstance_h_81_PRIVATE_PROPERTY_OFFSET \ HostProject_Plugins_SMSystem_Source_SMSystem_Public_SMInstance_h_81_SPARSE_DATA \ HostProject_Plugins_SMSystem_Source_SMSystem_Public_SMInstance_h_81_RPC_WRAPPERS \ HostProject_Plugins_SMSystem_Source_SMSystem_Public_SMInstance_h_81_CALLBACK_WRAPPERS \ HostProject_Plugins_SMSystem_Source_SMSystem_Public_SMInstance_h_81_INCLASS \ HostProject_Plugins_SMSystem_Source_SMSystem_Public_SMInstance_h_81_STANDARD_CONSTRUCTORS \ public: \ PRAGMA_ENABLE_DEPRECATION_WARNINGS #define HostProject_Plugins_SMSystem_Source_SMSystem_Public_SMInstance_h_81_GENERATED_BODY \ PRAGMA_DISABLE_DEPRECATION_WARNINGS \ public: \ HostProject_Plugins_SMSystem_Source_SMSystem_Public_SMInstance_h_81_PRIVATE_PROPERTY_OFFSET \ HostProject_Plugins_SMSystem_Source_SMSystem_Public_SMInstance_h_81_SPARSE_DATA \ HostProject_Plugins_SMSystem_Source_SMSystem_Public_SMInstance_h_81_RPC_WRAPPERS_NO_PURE_DECLS \ HostProject_Plugins_SMSystem_Source_SMSystem_Public_SMInstance_h_81_CALLBACK_WRAPPERS \ HostProject_Plugins_SMSystem_Source_SMSystem_Public_SMInstance_h_81_INCLASS_NO_PURE_DECLS \ HostProject_Plugins_SMSystem_Source_SMSystem_Public_SMInstance_h_81_ENHANCED_CONSTRUCTORS \ private: \ PRAGMA_ENABLE_DEPRECATION_WARNINGS template<> SMSYSTEM_API UClass* StaticClass<class USMInstance>(); #undef CURRENT_FILE_ID #define CURRENT_FILE_ID HostProject_Plugins_SMSystem_Source_SMSystem_Public_SMInstance_h PRAGMA_ENABLE_DEPRECATION_WARNINGS
[ "westonmitchell@live.com" ]
westonmitchell@live.com
fedb4d0d96eff5e07090823c7a619c2aed049fa4
49cd5b923560b3258bdc4bddf183a89d847bd3ff
/test/extensions/filters/listener/original_dst/original_dst_fuzz_test.cc
e5dabf1520f2cd68f5b11de95561bbf4d7698452
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
envoyproxy/envoy-wasm
4b12c109387594122915dcc8de36bf5958eba95b
ab5d9381fdf92a1efa0b87cff80036b5b3e81198
refs/heads/master
2023-08-01T12:38:34.269641
2020-10-09T18:27:33
2020-10-09T18:27:33
185,880,979
223
96
Apache-2.0
2020-12-15T18:56:39
2019-05-09T22:37:07
C++
UTF-8
C++
false
false
865
cc
#include "extensions/filters/listener/original_dst/original_dst.h" #include "test/extensions/filters/listener/common/fuzz/listener_filter_fuzzer.h" #include "test/extensions/filters/listener/common/fuzz/listener_filter_fuzzer.pb.validate.h" #include "test/fuzz/fuzz_runner.h" namespace Envoy { namespace Extensions { namespace ListenerFilters { namespace OriginalDst { DEFINE_PROTO_FUZZER(const test::extensions::filters::listener::FilterFuzzTestCase& input) { try { TestUtility::validate(input); } catch (const ProtoValidationException& e) { ENVOY_LOG_MISC(debug, "ProtoValidationException: {}", e.what()); return; } auto filter = std::make_unique<OriginalDstFilter>(); ListenerFilterFuzzer fuzzer; fuzzer.fuzz(*filter, input); } } // namespace OriginalDst } // namespace ListenerFilters } // namespace Extensions } // namespace Envoy
[ "noreply@github.com" ]
noreply@github.com
60b16b97903ee992f1b2be7b8f48edc920c50363
4571960295d7f420c2137f2a5b0925488fab280c
/fordip/ping/Cpp/Internet/Bcb1/poptst.cpp
646df0f1caef372f9ee591efa380eb5c8613d081
[ "Zlib", "LicenseRef-scancode-unknown-license-reference" ]
permissive
klel/Netadministrator
a6f37b5c49abeb79c42acf0c4231afb613fc673e
d13996b0463e094231cc853a506c6505dc9861c9
refs/heads/master
2021-01-19T06:40:45.838709
2015-04-26T18:50:11
2015-04-26T18:50:11
34,625,147
4
0
null
null
null
null
UTF-8
C++
false
false
1,147
cpp
//--------------------------------------------------------------------------- // This is an outdated sample program which use an outdated POP3 component. // For new programs, use new POP3 component in Pop3Prot.pas source file. // New sample program is called MailRcv. The new component is not 100% // compatible with the old one because the new is fully asynchronous. // Name has been slightly changed to allow installation of both component // if you need to support old code. #include <vcl\vcl.h> #pragma hdrstop //--------------------------------------------------------------------------- USERES("PopTst.res"); USEFORM("..\Poptst1.cpp", POP3ExcercizerForm); //--------------------------------------------------------------------------- WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int) { try { Application->Initialize(); Application->CreateForm(__classid(TPOP3ExcercizerForm), &POP3ExcercizerForm); Application->Run(); } catch (Exception &exception) { Application->ShowException(&exception); } return 0; } //---------------------------------------------------------------------------
[ "klimelm@gmail.com" ]
klimelm@gmail.com
3f213f71c3390fa114d4f885e38880676835d5e5
d4d4e9c9b22bdbc7af03e79af3559e6effe4f63e
/HackerRank/ProjetEuler/MultiplesOf3And5.cpp
c915869c4d7e24e43f015819de320f4049c4f142
[]
no_license
deeepeshthakur/CodeFiles
ea8d9c4a2b7a21c853ba8fc953c532e74576a791
3c9f08770a2628fa6eaef28fff212bfa1db96d16
refs/heads/master
2021-07-09T20:08:30.258607
2020-07-06T03:50:57
2020-07-06T03:50:57
160,020,105
2
1
null
2020-07-06T03:44:02
2018-12-02T06:26:50
C++
UTF-8
C++
false
false
500
cpp
#include <bits/stdc++.h> using namespace std; long long apSum( long long a, long long n, long long d){ long long l = a + (n - 1)*d; return (n*(a + l))/2; } int main(){ std::ios::sync_with_stdio(false); int test = 0; std::cin >> test; while( test--){ long long n = 0; std::cin >> n; long long n3 = (n - 1)/3, n5 = (n - 1)/5, n15 = (n - 1)/15; n3 = apSum( 3ll, n3, 3ll); n5 = apSum( 5ll, n5, 5ll); n15 = apSum( 15ll, n15, 15ll); std::cout << n3 + n5 - n15 << "\n"; } return 0; }
[ "deeepeshthakur@gmail.com" ]
deeepeshthakur@gmail.com
9a058d5a9f930254b72b88ae0e601f5815ae25d6
7adcde2c020a273554cc8dafa05ae9dc80bea246
/text.cpp
1cce56d14d6fd8cbf20ecd5c9ceacddec34883a4
[]
no_license
noox/Motox
3a635251693d0bdf3359c3b4b3aa660891f31fd7
f080acd3043d3dc80f17c0c5422712b04769ea7b
refs/heads/master
2020-12-26T01:37:18.317706
2016-02-14T15:51:24
2016-02-14T15:51:24
25,726,894
0
0
null
null
null
null
UTF-8
C++
false
false
10,516
cpp
#include "text.h" #include <GL/gl.h> #include <stdio.h> #include <iostream> using namespace std; //funkce pro kresleni jednotlivych znaku (charu) void draw_char(char c) { glPushMatrix(); //prevod na mala pismenka if ((c>='a')&&(c<='z')) { c-='a'-'A'; glScalef(1,0.7,1); } glBegin(GL_LINES); switch (c) { case '0': glVertex2f(2,1); glVertex2f(1,2); glVertex2f(1,2); glVertex2f(1,5); glVertex2f(1,5); glVertex2f(2,6); glVertex2f(2,6); glVertex2f(3,6); glVertex2f(3,6); glVertex2f(4,5); glVertex2f(4,5); glVertex2f(4,2); glVertex2f(4,2); glVertex2f(3,1); glVertex2f(3,1); glVertex2f(2,1); glVertex2f(2,3); glVertex2f(3,4); break; case '1': glVertex2f(3,1); glVertex2f(3,6); glVertex2f(3,6); glVertex2f(1,4); break; case '2': glVertex2f(1,5); glVertex2f(2,6); glVertex2f(2,6); glVertex2f(3,6); glVertex2f(3,6); glVertex2f(4,5); glVertex2f(4,5); glVertex2f(4,4); glVertex2f(4,4); glVertex2f(1,1); glVertex2f(1,1); glVertex2f(4,1); break; case '3': glVertex2f(1,5); glVertex2f(2,6); glVertex2f(2,6); glVertex2f(3,6); glVertex2f(3,6); glVertex2f(4,5); glVertex2f(4,5); glVertex2f(4,4); glVertex2f(4,4); glVertex2f(3,3.5); glVertex2f(3,3.5); glVertex2f(4,3); glVertex2f(4,3); glVertex2f(4,2); glVertex2f(4,2); glVertex2f(3,1); glVertex2f(3,1); glVertex2f(2,1); glVertex2f(2,1); glVertex2f(1,2); glVertex2f(1,2); break; case '4': glVertex2f(3,1); glVertex2f(3,5); glVertex2f(4,3); glVertex2f(1,3); glVertex2f(1,3); glVertex2f(1,6); break; case '5': glVertex2f(1,2); glVertex2f(2,1); glVertex2f(2,1); glVertex2f(3,1); glVertex2f(3,1); glVertex2f(4,2); glVertex2f(4,2); glVertex2f(4,3); glVertex2f(4,3); glVertex2f(3,4); glVertex2f(3,4); glVertex2f(1,4); glVertex2f(1,4); glVertex2f(1,6); glVertex2f(1,6); glVertex2f(4,6); break; case '6': glVertex2f(4,5); glVertex2f(3,6); glVertex2f(3,6); glVertex2f(2,6); glVertex2f(2,6); glVertex2f(1,5); glVertex2f(1,5); glVertex2f(1,2); glVertex2f(1,2); glVertex2f(2,1); glVertex2f(2,1); glVertex2f(3,1); glVertex2f(3,1); glVertex2f(4,2); glVertex2f(4,2); glVertex2f(4,3); glVertex2f(4,3); glVertex2f(3,4); glVertex2f(3,4); glVertex2f(2,4); glVertex2f(2,4); glVertex2f(1,3); break; case '7': glVertex2f(2,1); glVertex2f(4,5); glVertex2f(4,5); glVertex2f(4,6); glVertex2f(4,6); glVertex2f(1,6); break; case '8': glVertex2f(2,3.5); glVertex2f(1,3); glVertex2f(1,3); glVertex2f(1,2); glVertex2f(1,2); glVertex2f(2,1); glVertex2f(2,1); glVertex2f(3,1); glVertex2f(3,1); glVertex2f(4,2); glVertex2f(4,2); glVertex2f(4,3); glVertex2f(4,3); glVertex2f(3,3.5); glVertex2f(3,3.5); glVertex2f(2,3.5); glVertex2f(2,3.5); glVertex2f(1,4); glVertex2f(1,4); glVertex2f(1,5); glVertex2f(1,5); glVertex2f(2,6); glVertex2f(2,6); glVertex2f(3,6); glVertex2f(3,6); glVertex2f(4,5); glVertex2f(4,5); glVertex2f(4,4); glVertex2f(4,4); glVertex2f(3,3.5); break; case '9': glVertex2f(1,2); glVertex2f(2,1); glVertex2f(2,1); glVertex2f(3,1); glVertex2f(3,1); glVertex2f(4,2); glVertex2f(4,2); glVertex2f(4,5); glVertex2f(4,5); glVertex2f(3,6); glVertex2f(3,6); glVertex2f(2,6); glVertex2f(2,6); glVertex2f(1,5); glVertex2f(1,5); glVertex2f(1,4); glVertex2f(1,4); glVertex2f(2,3); glVertex2f(2,3); glVertex2f(3,3); glVertex2f(3,3); glVertex2f(4,4); break; case 'A': glVertex2f(1,1); glVertex2f(1,5); glVertex2f(1,5); glVertex2f(2,6); glVertex2f(2,6); glVertex2f(3,6); glVertex2f(3,6); glVertex2f(4,5); glVertex2f(4,5); glVertex2f(4,1); glVertex2f(1,3.5); glVertex2f(4,3.5); break; case 'B': glVertex2f(1,1); glVertex2f(1,6); glVertex2f(1,6); glVertex2f(3,6); glVertex2f(3,6); glVertex2f(4,5); glVertex2f(4,5); glVertex2f(4,4); glVertex2f(4,4); glVertex2f(3,3.5); glVertex2f(3,3.5); glVertex2f(1,3.5); glVertex2f(1,3.5); glVertex2f(3,3.5); glVertex2f(3,3.5); glVertex2f(4,3); glVertex2f(4,3); glVertex2f(4,2); glVertex2f(4,2); glVertex2f(3,1); glVertex2f(3,1); glVertex2f(1,1); break; case 'C': glVertex2f(4,2); glVertex2f(3,1); glVertex2f(3,1); glVertex2f(2,1); glVertex2f(2,1); glVertex2f(1,2); glVertex2f(1,2); glVertex2f(1,5); glVertex2f(1,5); glVertex2f(2,6); glVertex2f(2,6); glVertex2f(3,6); glVertex2f(3,6); glVertex2f(4,5); break; case 'D': glVertex2f(1,1); glVertex2f(1,6); glVertex2f(1,6); glVertex2f(2,6); glVertex2f(2,6); glVertex2f(4,4); glVertex2f(4,4); glVertex2f(4,3); glVertex2f(4,3); glVertex2f(2,1); glVertex2f(2,1); glVertex2f(1,1); break; case 'E': glVertex2f(4,1); glVertex2f(1,1); glVertex2f(1,1); glVertex2f(1,6); glVertex2f(1,6); glVertex2f(4,6); glVertex2f(1,3.5); glVertex2f(3,3.5); break; case 'F': glVertex2f(1,1); glVertex2f(1,6); glVertex2f(1,6); glVertex2f(4,6); glVertex2f(1,3.5); glVertex2f(3,3.5); break; case 'G': glVertex2f(2,3); glVertex2f(4,3); glVertex2f(4,3); glVertex2f(4,2); glVertex2f(4,2); glVertex2f(3,1); glVertex2f(3,1); glVertex2f(2,1); glVertex2f(2,1); glVertex2f(1,2); glVertex2f(1,2); glVertex2f(1,5); glVertex2f(1,5); glVertex2f(2,6); glVertex2f(2,6); glVertex2f(3,6); glVertex2f(3,6); glVertex2f(4,5); break; case 'H': glVertex2f(1,1); glVertex2f(1,6); glVertex2f(4,1); glVertex2f(4,6); glVertex2f(1,3.5); glVertex2f(4,3.5); break; case 'I': glVertex2f(2,1); glVertex2f(3,1); glVertex2f(2.5,1); glVertex2f(2.5,6); glVertex2f(2,6); glVertex2f(3,6); break; case 'J': glVertex2f(4,6); glVertex2f(4,2); glVertex2f(4,2); glVertex2f(3,1); glVertex2f(3,1); glVertex2f(2,1); glVertex2f(2,1); glVertex2f(1,3); break; case 'K': glVertex2f(1,1); glVertex2f(1,6); glVertex2f(1,3.5); glVertex2f(2,3.5); glVertex2f(2,3.5); glVertex2f(4,6); glVertex2f(2,3.5); glVertex2f(4,1); break; case 'L': glVertex2f(1,6); glVertex2f(1,1); glVertex2f(1,1); glVertex2f(4,1); break; case 'M': glVertex2f(1,1); glVertex2f(1,6); glVertex2f(1,6); glVertex2f(2.5,4); glVertex2f(2.5,4); glVertex2f(4,6); glVertex2f(4,6); glVertex2f(4,1); break; case 'N': glVertex2f(1,1); glVertex2f(1,6); glVertex2f(1,6); glVertex2f(4,1); glVertex2f(4,1); glVertex2f(4,6); break; case 'O': glVertex2f(2,1); glVertex2f(1,2); glVertex2f(1,2); glVertex2f(1,5); glVertex2f(1,5); glVertex2f(2,6); glVertex2f(2,6); glVertex2f(3,6); glVertex2f(3,6); glVertex2f(4,5); glVertex2f(4,5); glVertex2f(4,2); glVertex2f(4,2); glVertex2f(3,1); glVertex2f(3,1); glVertex2f(2,1); break; case 'P': glVertex2f(1,1); glVertex2f(1,6); glVertex2f(1,6); glVertex2f(3,6); glVertex2f(3,6); glVertex2f(4,5); glVertex2f(4,5); glVertex2f(4,4); glVertex2f(4,4); glVertex2f(3,3); glVertex2f(3,3); glVertex2f(1,3); break; case 'Q': glVertex2f(2,1); glVertex2f(1,2); glVertex2f(1,2); glVertex2f(1,5); glVertex2f(1,5); glVertex2f(2,6); glVertex2f(2,6); glVertex2f(3,6); glVertex2f(3,6); glVertex2f(4,5); glVertex2f(4,5); glVertex2f(4,2); glVertex2f(4,2); glVertex2f(3,1); glVertex2f(3,1); glVertex2f(2,1); glVertex2f(2,3); glVertex2f(4,1); break; case 'R': glVertex2f(1,1); glVertex2f(1,6); glVertex2f(1,6); glVertex2f(3,6); glVertex2f(3,6); glVertex2f(4,5); glVertex2f(4,5); glVertex2f(4,4); glVertex2f(4,4); glVertex2f(3,3); glVertex2f(3,3); glVertex2f(1,3); glVertex2f(2.5,3); glVertex2f(4,1); break; case 'S': glVertex2f(1,2); glVertex2f(2,1); glVertex2f(2,1); glVertex2f(3,1); glVertex2f(3,1); glVertex2f(4,2); glVertex2f(4,2); glVertex2f(4,3); glVertex2f(4,3); glVertex2f(3,3.5); glVertex2f(3,3.5); glVertex2f(2,3.5); glVertex2f(2,3.5); glVertex2f(1,4); glVertex2f(1,4); glVertex2f(1,5); glVertex2f(1,5); glVertex2f(2,6); glVertex2f(2,6); glVertex2f(3,6); glVertex2f(3,6); glVertex2f(4,5); break; case 'T': glVertex2f(1,6); glVertex2f(4,6); glVertex2f(2.5,1); glVertex2f(2.5,6); break; case 'U': glVertex2f(1,6); glVertex2f(1,2); glVertex2f(1,2); glVertex2f(2,1); glVertex2f(2,1); glVertex2f(3,1); glVertex2f(3,1); glVertex2f(4,2); glVertex2f(4,2); glVertex2f(4,6); break; case 'V': glVertex2f(1,6); glVertex2f(1,4); glVertex2f(1,4); glVertex2f(2.5,1); glVertex2f(2.5,1); glVertex2f(4,4); glVertex2f(4,4); glVertex2f(4,6); glVertex2f(4,6); break; case 'W': glVertex2f(1,6); glVertex2f(1.5,1); glVertex2f(1.5,1); glVertex2f(2.5,4); glVertex2f(2.5,4); glVertex2f(3.5,1); glVertex2f(3.5,1); glVertex2f(4,6); break; case 'X': glVertex2f(1,1); glVertex2f(4,6); glVertex2f(1,6); glVertex2f(4,1); break; case 'Y': glVertex2f(2.5,1); glVertex2f(2.5,4); glVertex2f(2.5,4); glVertex2f(4,6); glVertex2f(2.5,4); glVertex2f(1,6); break; case 'Z': glVertex2f(1,6); glVertex2f(4,6); glVertex2f(4,6); glVertex2f(1,1); glVertex2f(1,1); glVertex2f(4,1); glVertex2f(4,1); break; case '.': glVertex2f(2.5,1); glVertex2f(3,1.5); glVertex2f(3,1.5); glVertex2f(2.5,2); glVertex2f(2.5,2); glVertex2f(2,1.5); glVertex2f(2,1.5); glVertex2f(2.5,1); case ' ': break; default: glVertex2f(0,0); glVertex2f(5,7); glVertex2f(5,0); glVertex2f(0,7); break; } glEnd(); glPopMatrix(); } //kresli text do hry void draw_string(const char* s) { glPushMatrix(); //scale pro dobrou praci s chary glScalef(0.125,0.125,1); for(;*s;s++) { //s++: adresa++ draw_char(*s); glTranslatef(5,0,0); } glPopMatrix(); } //zjisti delku stringu float text_length(const char *s) { int len; for(len=0;*s;len++,s++); return len*0.625; } //predelava cisla na chary void draw_int(int n) { char buffer[64]; sprintf(buffer,"%d",n); draw_string(buffer); }
[ "katka.nevolova@gmail.com" ]
katka.nevolova@gmail.com
9171ddc2c211474d29dc66d8b2021286c09f3cc7
bdc291a3a064c9eba540c61028f090848515a358
/src/prefix.hpp
20dbeca60a4283b5589a254f41004c7ca80e0154
[]
no_license
bjornjohansson/ircbot
36661644a064f9549b3e7a21a05ae60ed2c02f1d
da6b726d50c0d6adff0c2cfc3aab96f695ba66b4
refs/heads/master
2021-01-18T23:16:15.139763
2016-05-02T03:42:18
2016-05-02T03:42:18
4,683,081
0
0
null
null
null
null
UTF-8
C++
false
false
528
hpp
#pragma once #include <string> #include <boost/regex.hpp> class Prefix { public: /** * @throw Exception if parsing of the prefix fails catastrophically. */ Prefix() {}; explicit Prefix(const std::string& text); const std::string& GetNick() const { return nick_; } const std::string& GetUser() const { return user_; } const std::string& GetHost() const { return host_; } private: std::string nick_; std::string user_; std::string host_; static boost::regex textRegex_; };
[ "bjorn@fiskbil.org" ]
bjorn@fiskbil.org
0e25bf136f96635753812ad539ab568020c2839d
f8c7140cfea3359be623518319617f8d48c3da3d
/AbgabeShaderPrograming/System.h
b65892517299ace46d37aad37cb6525519176b66
[]
no_license
Kadameck/MyFirstRepo-Shader-
f1a8febc7d438d3c2160247c3b074b783d07eaa4
f6ad4c506a4e784a0da3e9fcc8bc53d99ed6086e
refs/heads/master
2020-08-14T12:59:23.259216
2019-10-15T00:30:57
2019-10-15T00:30:57
215,172,851
0
0
null
null
null
null
ISO-8859-1
C++
false
false
932
h
#ifndef _SYSTEM_H_ #define _SYSTEM_H_ // Beschleunigt den Build indem es die Headergröße reduziert #define WIN32_LEAN_AND_MEAN #include "Input.h" #include "Graphics.h" #include <Windows.h> class System { public: System(); ~System(); bool Init(); void Shutdown(); void Run(); LRESULT CALLBACK MessageHandler(HWND, UINT, WPARAM, LPARAM); private: bool Frame(); bool InitWindows(int& width, int& height); void ShutdownWindows(); LPCWSTR applicationName; HWND hwnd; HINSTANCE hInstance; Input* input; Graphics* graphics; // Hight Frequency Timer float secsPerTick = .0f; float deltaTime = .0f; float framesPerSeconds = .0f; int framesPerSecondCount = 0; int framesCounter = 0; float frametimer = .0f; LARGE_INTEGER oldTicks; bool InitHighFrequencyTimer(); bool UpdateHightFrequencyTimer(); }; static LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); static System* ApplicationHandle = 0; #endif
[ "k.zandorax@gmail.com" ]
k.zandorax@gmail.com
392991c6f8087b008d299ff080e3f830ca6ffa5a
d4b733f2e00b5d0ab103ea0df6341648d95c993b
/src/c-cpp/include/sst/catalog/checked_cast.hpp
7b0937f5a67360c9dcc4a44e5687df1ca768e1c9
[ "MIT" ]
permissive
stealthsoftwareinc/sst
ad6117a3d5daf97d947862674336e6938c0bc699
f828f77db0ab27048b3204e10153ee8cfc1b2081
refs/heads/master
2023-04-06T15:21:14.371804
2023-03-24T08:30:48
2023-03-24T08:30:48
302,539,309
1
0
null
null
null
null
UTF-8
C++
false
false
1,737
hpp
// // Copyright (C) 2012-2023 Stealth Software Technologies, Inc. // // 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 (including // the next paragraph) 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. // // SPDX-License-Identifier: MIT // #ifndef SST_CATALOG_CHECKED_CAST_HPP #define SST_CATALOG_CHECKED_CAST_HPP #include <utility> #include <sst/catalog/checked_t.hpp> #include <sst/catalog/remove_cvref_t.hpp> namespace sst { #define SST_dst (sst::checked_t<Dst>(std::forward<Src>(src)).value()) template<class Dst, class Src> constexpr auto checked_cast(Src && src) noexcept(noexcept(SST_dst)) -> sst::remove_cvref_t<decltype(SST_dst)> { return SST_dst; } #undef SST_dst } // namespace sst #endif // #ifndef SST_CATALOG_CHECKED_CAST_HPP
[ "sst@stealthsoftwareinc.com" ]
sst@stealthsoftwareinc.com
843f691a2a16fd2f8710aa86d7e352d08f829638
5dd0c2a5bd2a06429958341334d8d61bb17f1752
/thread/network-display/src/coap_service.hpp
620b493f88c4a180284844d4037fc4ad9a2005be
[ "Apache-2.0" ]
permissive
chacal/arduino
ce3581cabf6f61dbd6c951f7fc73c3a53a3e3e7a
6b77e59138a36d0627ab6f529e6f2ea7e65bcdfd
refs/heads/master
2021-07-03T06:03:38.413444
2021-05-20T15:42:32
2021-05-20T15:42:32
40,070,062
4
1
Apache-2.0
2019-12-30T12:42:15
2015-08-02T05:33:46
C
UTF-8
C++
false
false
259
hpp
#pragma once #include <functional> #include <coap_api.h> #include "coap_helpers.hpp" #include "common_coap_service.hpp" namespace coap_service { void initialize(const common_request_handler &, const coap_helpers::post_handler &display_post_handler); }
[ "jouni.hartikainen@reaktor.com" ]
jouni.hartikainen@reaktor.com
956e9c09d3be629b2f895987a4f16a9837f93a1c
a91f7ef0afaae7bd5cdcf5b60217066f3f7030ce
/source/slider.h
91d4b35ecc1f28f31969d0fb479fb11ac75fc329
[]
no_license
robertsdionne/texttennis
dcb27b6b7bb25cf1876bf63330ca64b77557abc9
9b6ebc6a76aba0b45637587f775f99c08c0d071c
refs/heads/master
2021-01-17T00:08:51.691962
2013-05-29T03:59:10
2013-05-29T03:59:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
779
h
#ifndef TEXTTENNIS_SLIDER_H_ #define TEXTTENNIS_SLIDER_H_ #include <string> #include "ofxBaseGui.h" #include "parameter.h" template<typename T> class Slider : public ofxBaseGui { friend class ofPanel; public: Slider() {} Slider(Parameter<T> *parameter, float width = defaultWidth, float height = defaultHeight); virtual void mouseMoved(ofMouseEventArgs &args); virtual void mousePressed(ofMouseEventArgs &args); virtual void mouseDragged(ofMouseEventArgs &args); virtual void mouseReleased(ofMouseEventArgs &args); virtual void saveToXml(ofxXmlSettings &xml) {}; virtual void loadFromXml(ofxXmlSettings &xml) {}; void draw(); Parameter<T> *parameter; protected: void setValue(float mx, float my, bool bCheck); }; #endif // TEXTTENNIS_SLIDER_H_
[ "robertsdionne@gmail.com" ]
robertsdionne@gmail.com
ef7c8b5315bce6994882192ce1fd19b0e8a75b26
4a351adfdeed3173768eb765d34f6637848fb73e
/src/main/engine/oanimseq.cpp
fec9790d9eaf0f507767d8f22311b9ee56edd230
[]
no_license
rsn8887/cannonball
cfa2c874ee7e9ba368a1331943ec54065fbc6316
af9d8e204996db52d45d239f5ff412a21bcf5dda
refs/heads/master
2021-06-07T15:15:42.308307
2021-05-22T20:00:45
2021-05-22T20:15:07
123,649,343
25
2
null
2021-05-22T01:28:53
2018-03-03T01:42:52
C++
UTF-8
C++
false
false
25,388
cpp
/*************************************************************************** Animation Sequences. Used in three areas of the game: - The sequence at the start with the Ferrari driving in from the side - Flag Waving Man - 5 x End Sequences See "oanimsprite.hpp" for the specific format used by animated sprites. It is essentially a deviation from the normal sprites in the game. Copyright Chris White. See license.txt for more details. ***************************************************************************/ #include "engine/obonus.hpp" #include "engine/oferrari.hpp" #include "engine/oinputs.hpp" #include "engine/oanimseq.hpp" // ---------------------------------------------------------------------------- // Animation Data Format. // Animation blocks are stored in groups of 8 bytes, and formatted as follows: // // +00 [Byte] Sprite Colour Palette // +01 [Byte] Bit 7: Make X Position Negative // Bits 4-6: Sprite To Sprite Priority // Bits 0-3: Top Bits Of Sprite Data Address // +02 [Word] Sprite Data Address // +04 [Byte] Sprite X Position // +05 [Byte] Sprite Y Position // +06 [Byte] Sprite To Road Priority // +07 [Byte] Bit 7: Set To Load Next Block Of Sprite Animation Data To 0x1E // Bit 6: Set For H-Flip // Bit 4: // Bits 0-3: Animation Frame Delay // (Before Incrementing To Next Block Of 8 Bytes) // ---------------------------------------------------------------------------- OAnimSeq oanimseq; OAnimSeq::OAnimSeq(void) { } OAnimSeq::~OAnimSeq(void) { } void OAnimSeq::init(oentry* jump_table) { // -------------------------------------------------------------------------------------------- // Flag Animation Setup // -------------------------------------------------------------------------------------------- oentry* sprite_flag = &jump_table[OSprites::SPRITE_FLAG]; anim_flag.sprite = sprite_flag; anim_flag.anim_state = 0; // Jump table initalisations sprite_flag->shadow = 7; sprite_flag->draw_props = oentry::BOTTOM; // Routine initalisations sprite_flag->control |= OSprites::ENABLE; sprite_flag->z = 400 << 16; // -------------------------------------------------------------------------------------------- // Ferrari & Passenger Animation Setup For Intro // -------------------------------------------------------------------------------------------- oentry* sprite_ferrari = &jump_table[OSprites::SPRITE_FERRARI]; anim_ferrari.init(sprite_ferrari); anim_ferrari.anim_addr_curr = outrun.adr.anim_ferrari_curr; anim_ferrari.anim_addr_next = outrun.adr.anim_ferrari_next; sprite_ferrari->control |= OSprites::ENABLE; sprite_ferrari->draw_props = oentry::BOTTOM; oentry* sprite_pass1 = &jump_table[OSprites::SPRITE_PASS1]; anim_pass1.init(sprite_pass1); anim_pass1.anim_addr_curr = outrun.adr.anim_pass1_curr; anim_pass1.anim_addr_next = outrun.adr.anim_pass1_next; sprite_pass1->draw_props = oentry::BOTTOM; oentry* sprite_pass2 = &jump_table[OSprites::SPRITE_PASS2]; anim_pass2.init(sprite_pass2); anim_pass2.anim_addr_curr = outrun.adr.anim_pass2_curr; anim_pass2.anim_addr_next = outrun.adr.anim_pass2_next; sprite_pass2->draw_props = oentry::BOTTOM; // -------------------------------------------------------------------------------------------- // End Sequence Animation // -------------------------------------------------------------------------------------------- end_seq_state = 0; // init seq_pos = 0; ferrari_stopped = false; anim_obj1.init(&jump_table[OSprites::SPRITE_CRASH]); anim_obj2.init(&jump_table[OSprites::SPRITE_CRASH_SHADOW]); anim_obj3.init(&jump_table[OSprites::SPRITE_SHADOW]); anim_obj4.init(&jump_table[OSprites::SPRITE_CRASH_PASS1]); anim_obj5.init(&jump_table[OSprites::SPRITE_CRASH_PASS1_S]); anim_obj6.init(&jump_table[OSprites::SPRITE_CRASH_PASS2]); anim_obj7.init(&jump_table[OSprites::SPRITE_CRASH_PASS2_S]); anim_obj8.init(&jump_table[OSprites::SPRITE_FLAG]); } // ------------------------------------------------------------------------------------------------ // START ANIMATION SEQUENCES (FLAG, FERRARI DRIVING IN) // ------------------------------------------------------------------------------------------------ void OAnimSeq::flag_seq() { if (!(anim_flag.sprite->control & OSprites::ENABLE)) return; if (outrun.tick_frame) { if (outrun.game_state < GS_START1 || outrun.game_state > GS_GAMEOVER) { anim_flag.sprite->control &= ~OSprites::ENABLE; return; } // Init Flag Sequence if (outrun.game_state < GS_INGAME && anim_flag.anim_state != outrun.game_state) { anim_flag.anim_state = outrun.game_state; // Index of animation sequences uint32_t index = outrun.adr.anim_seq_flag + ((outrun.game_state - 9) << 3); anim_flag.anim_addr_curr = roms.rom0p->read32(&index); anim_flag.anim_addr_next = roms.rom0p->read32(&index); anim_flag.frame_delay = roms.rom0p->read8(7 + anim_flag.anim_addr_curr) & 0x3F; anim_flag.anim_frame = 0; } // Wave Flag if (outrun.game_state <= GS_INGAME) { uint32_t index = anim_flag.anim_addr_curr + (anim_flag.anim_frame << 3); anim_flag.sprite->addr = roms.rom0p->read32(index) & 0xFFFFF; anim_flag.sprite->pal_src = roms.rom0p->read8(index); uint32_t addr = SPRITE_ZOOM_LOOKUP + (((anim_flag.sprite->z >> 16) << 2) | osprites.sprite_scroll_speed); uint32_t value = roms.rom0p->read32(addr); anim_flag.sprite->z += value; uint16_t z16 = anim_flag.sprite->z >> 16; if (z16 >= 0x200) { anim_flag.sprite->control &= ~OSprites::ENABLE; return; } anim_flag.sprite->priority = z16; anim_flag.sprite->zoom = z16 >> 2; // Set X Position int16_t sprite_x = (int8_t) roms.rom0p->read8(4 + index); sprite_x -= oroad.road0_h[z16]; int32_t final_x = (sprite_x * z16) >> 9; if (roms.rom0p->read8(1 + index) & BIT_7) final_x = -final_x; anim_flag.sprite->x = final_x; // Set Y Position int16_t sprite_y = (int8_t) roms.rom0p->read8(5 + index); int16_t final_y = (sprite_y * z16) >> 9; anim_flag.sprite->y = oroad.get_road_y(z16) - final_y; // Set H-Flip if (roms.rom0p->read8(7 + index) & BIT_6) anim_flag.sprite->control |= OSprites::HFLIP; else anim_flag.sprite->control &= ~OSprites::HFLIP; // Ready for next frame if (--anim_flag.frame_delay == 0) { // Load Next Block Of Animation Data if (roms.rom0p->read8(7 + index) & BIT_7) { anim_flag.anim_addr_curr = anim_flag.anim_addr_next; anim_flag.frame_delay = roms.rom0p->read8(7 + anim_flag.anim_addr_curr) & 0x3F; anim_flag.anim_frame = 0; } // Last Block else { anim_flag.frame_delay = roms.rom0p->read8(0x0F + index) & 0x3F; anim_flag.anim_frame++; } } } } // Order sprites osprites.map_palette(anim_flag.sprite); osprites.do_spr_order_shadows(anim_flag.sprite); } // Setup Ferrari Animation Sequence // // Source: 0x6036 void OAnimSeq::ferrari_seq() { if (!(anim_ferrari.sprite->control & OSprites::ENABLE)) return; if (outrun.game_state == GS_MUSIC) return; anim_pass1.sprite->control |= OSprites::ENABLE; anim_pass2.sprite->control |= OSprites::ENABLE; if (outrun.game_state <= GS_LOGO) { oferrari.init_ingame(); return; } anim_ferrari.frame_delay = roms.rom0p->read8(7 + anim_ferrari.anim_addr_curr) & 0x3F; anim_pass1.frame_delay = roms.rom0p->read8(7 + anim_pass1.anim_addr_curr) & 0x3F; anim_pass2.frame_delay = roms.rom0p->read8(7 + anim_pass2.anim_addr_curr) & 0x3F; oferrari.car_state = OFerrari::CAR_NORMAL; oferrari.state = OFerrari::FERRARI_SEQ2; anim_seq_intro(&anim_ferrari); } // Process Animations for Ferrari and Passengers on intro // // Source: 60AE void OAnimSeq::anim_seq_intro(oanimsprite* anim) { if (outrun.game_state <= GS_LOGO) { oferrari.init_ingame(); return; } if (outrun.tick_frame) { if (anim->anim_frame >= 1) oferrari.car_state = OFerrari::CAR_ANIM_SEQ; uint32_t index = anim->anim_addr_curr + (anim->anim_frame << 3); anim->sprite->addr = roms.rom0p->read32(index) & 0xFFFFF; anim->sprite->pal_src = roms.rom0p->read8(index); anim->sprite->zoom = 0x7F; anim->sprite->road_priority = 0x1FE; anim->sprite->priority = 0x1FE - ((roms.rom0p->read16(index) & 0x70) >> 4); // Set X int16_t sprite_x = (int8_t) roms.rom0p->read8(4 + index); int32_t final_x = (sprite_x * anim->sprite->priority) >> 9; if (roms.rom0p->read8(1 + index) & BIT_7) final_x = -final_x; anim->sprite->x = final_x; // Set Y anim->sprite->y = 221 - ((int8_t) roms.rom0p->read8(5 + index)); // Set H-Flip if (roms.rom0p->read8(7 + index) & BIT_6) anim->sprite->control |= OSprites::HFLIP; else anim->sprite->control &= ~OSprites::HFLIP; // Ready for next frame if (--anim->frame_delay == 0) { // Load Next Block Of Animation Data if (roms.rom0p->read8(7 + index) & BIT_7) { // Yeah the usual OutRun code hacks to do really odd stuff! // In this case, to exit the routine and setup the Ferrari on the last entry for passenger 2 if (anim == &anim_pass2) { if (oroad.get_view_mode() != ORoad::VIEW_INCAR) { osprites.map_palette(anim->sprite); osprites.do_spr_order_shadows(anim->sprite); } oferrari.init_ingame(); return; } anim->anim_addr_curr = anim->anim_addr_next; anim->frame_delay = roms.rom0p->read8(7 + anim->anim_addr_curr) & 0x3F; anim->anim_frame = 0; } // Last Block else { anim->frame_delay = roms.rom0p->read8(0x0F + index) & 0x3F; anim->anim_frame++; } } } // Order sprites if (oroad.get_view_mode() != ORoad::VIEW_INCAR) { osprites.map_palette(anim->sprite); osprites.do_spr_order_shadows(anim->sprite); } } // ------------------------------------------------------------------------------------------------ // END ANIMATION SEQUENCES // ------------------------------------------------------------------------------------------------ // Initialize end sequence animations on game complete // Source: 0x9978 void OAnimSeq::init_end_seq() { // Process animation sprites instead of normal routine oferrari.state = OFerrari::FERRARI_END_SEQ; // Setup Ferrari Sprite anim_ferrari.sprite->control |= OSprites::ENABLE; anim_ferrari.sprite->id = 0; anim_ferrari.sprite->draw_props = oentry::BOTTOM; anim_ferrari.anim_frame = 0; anim_ferrari.frame_delay = 0; seq_pos = 0; // Disable Passenger Sprites. These are replaced with new versions by the animation sequence. oferrari.spr_pass1->control &= ~OSprites::ENABLE; oferrari.spr_pass2->control &= ~OSprites::ENABLE; obonus.bonus_control += 4; } void OAnimSeq::tick_end_seq() { switch (end_seq_state) { case 0: // init if (outrun.tick_frame) init_end_sprites(); else return; case 1: // tick & blit anim_seq_outro_ferrari(); // Ferrari Sprite anim_seq_outro(&anim_obj1); // Car Door Opening Animation anim_seq_outro(&anim_obj2); // Interior of Ferrari anim_seq_shadow(&anim_ferrari, &anim_obj3); // Car Shadow anim_seq_outro(&anim_pass1); // Man Sprite anim_seq_shadow(&anim_pass1, &anim_obj4); // Man Shadow anim_seq_outro(&anim_pass2); // Female Sprite anim_seq_shadow(&anim_pass2, &anim_obj5); // Female Shadow anim_seq_outro(&anim_obj6); // Man Presenting Trophy if (end_seq == 4) anim_seq_outro(&anim_obj7); // Varies else anim_seq_shadow(&anim_obj6, &anim_obj7); anim_seq_outro(&anim_obj8); // Effects break; } } // Initalize Sprites For End Sequence. // Source: 0x588A void OAnimSeq::init_end_sprites() { // Ferrari Object [0x5B12 entry point] uint32_t addr = outrun.adr.anim_endseq_obj1 + (end_seq << 3); anim_ferrari.anim_addr_curr = roms.rom0p->read32(&addr); anim_ferrari.anim_addr_next = roms.rom0p->read32(&addr); ferrari_stopped = false; // 0x58A4: Car Door Opening Animation [seq_sprite_entry] anim_obj1.sprite->control |= OSprites::ENABLE; anim_obj1.sprite->id = 1; anim_obj1.sprite->shadow = 3; anim_obj1.sprite->draw_props = oentry::BOTTOM; anim_obj1.anim_frame = 0; anim_obj1.frame_delay = 0; anim_obj1.anim_props = 0; addr = outrun.adr.anim_endseq_obj2 + (end_seq << 3); anim_obj1.anim_addr_curr = roms.rom0p->read32(&addr); anim_obj1.anim_addr_next = roms.rom0p->read32(&addr); // 0x58EC: Interior of Ferrari (Note this wobbles a little when passengers exit) [seq_sprite_entry] anim_obj2.sprite->control |= OSprites::ENABLE; anim_obj2.sprite->id = 2; anim_obj2.sprite->draw_props = oentry::BOTTOM; anim_obj2.anim_frame = 0; anim_obj2.frame_delay = 0; anim_obj2.anim_props = 0; addr = outrun.adr.anim_endseq_obj3 + (end_seq << 3); anim_obj2.anim_addr_curr = roms.rom0p->read32(&addr); anim_obj2.anim_addr_next = roms.rom0p->read32(&addr); // 0x592A: Car Shadow [SeqSpriteShadow] anim_obj3.sprite->control |= OSprites::ENABLE; anim_obj3.sprite->id = 3; anim_obj3.sprite->draw_props = oentry::BOTTOM; anim_obj3.anim_frame = 0; anim_obj3.frame_delay = 0; anim_obj3.anim_props = 0; anim_obj3.sprite->addr = outrun.adr.shadow_data; // 0x5960: Man Sprite [seq_sprite_entry] anim_pass1.sprite->control |= OSprites::ENABLE; anim_pass1.sprite->id = 4; anim_pass1.sprite->draw_props = oentry::BOTTOM; anim_pass1.anim_frame = 0; anim_pass1.frame_delay = 0; anim_pass1.anim_props = 0; addr = outrun.adr.anim_endseq_obj4 + (end_seq << 3); anim_pass1.anim_addr_curr = roms.rom0p->read32(&addr); anim_pass1.anim_addr_next = roms.rom0p->read32(&addr); // 0x5998: Man Shadow [SeqSpriteShadow] anim_obj4.sprite->control = OSprites::ENABLE; anim_obj4.sprite->id = 5; anim_obj4.sprite->shadow = 7; anim_obj4.sprite->draw_props = oentry::BOTTOM; anim_obj4.anim_frame = 0; anim_obj4.frame_delay = 0; anim_obj4.anim_props = 0; anim_obj4.sprite->addr = outrun.adr.shadow_data; // 0x59BE: Female Sprite [seq_sprite_entry] anim_pass2.sprite->control |= OSprites::ENABLE; anim_pass2.sprite->id = 6; anim_pass2.sprite->draw_props = oentry::BOTTOM; anim_pass2.anim_frame = 0; anim_pass2.frame_delay = 0; anim_pass2.anim_props = 0; addr = outrun.adr.anim_endseq_obj5 + (end_seq << 3); anim_pass2.anim_addr_curr = roms.rom0p->read32(&addr); anim_pass2.anim_addr_next = roms.rom0p->read32(&addr); // 0x59F6: Female Shadow [SeqSpriteShadow] anim_obj5.sprite->control = OSprites::ENABLE; anim_obj5.sprite->id = 7; anim_obj5.sprite->shadow = 7; anim_obj5.sprite->draw_props = oentry::BOTTOM; anim_obj5.anim_frame = 0; anim_obj5.frame_delay = 0; anim_obj5.anim_props = 0; anim_obj5.sprite->addr = outrun.adr.shadow_data; // 0x5A2C: Person Presenting Trophy [seq_sprite_entry] anim_obj6.sprite->control |= OSprites::ENABLE; anim_obj6.sprite->id = 8; anim_obj6.sprite->draw_props = oentry::BOTTOM; anim_obj6.anim_frame = 0; anim_obj6.frame_delay = 0; anim_obj6.anim_props = 0; addr = outrun.adr.anim_endseq_obj6 + (end_seq << 3); anim_obj6.anim_addr_curr = roms.rom0p->read32(&addr); anim_obj6.anim_addr_next = roms.rom0p->read32(&addr); // Alternate Use Based On End Sequence anim_obj7.sprite->control |= OSprites::ENABLE; anim_obj7.sprite->id = 9; anim_obj7.sprite->draw_props = oentry::BOTTOM; anim_obj7.anim_frame = 0; anim_obj7.frame_delay = 0; anim_obj7.anim_props = 0; // [seq_sprite_entry] if (end_seq == 4) { addr = outrun.adr.anim_endseq_objB + (end_seq << 3); anim_obj7.anim_addr_curr = roms.rom0p->read32(&addr); anim_obj7.anim_addr_next = roms.rom0p->read32(&addr); } // Trophy Shadow else { anim_obj7.sprite->shadow = 7; anim_obj7.sprite->addr = outrun.adr.shadow_data; } // 0x5AD0: Enable After Effects (e.g. cloud of smoke for genie) [seq_sprite_entry] anim_obj8.sprite->control |= OSprites::ENABLE; anim_obj8.sprite->id = 10; anim_obj8.sprite->draw_props = oentry::BOTTOM; anim_obj8.anim_frame = 0; anim_obj8.frame_delay = 0; anim_obj8.anim_props = 0xFF00; addr = outrun.adr.anim_endseq_obj7 + (end_seq << 3); anim_obj8.anim_addr_curr = roms.rom0p->read32(&addr); anim_obj8.anim_addr_next = roms.rom0p->read32(&addr); end_seq_state = 1; } // Ferrari Outro Animation Sequence // Source: 0x5B12 void OAnimSeq::anim_seq_outro_ferrari() { if (/*outrun.tick_frame && */!ferrari_stopped) { // Car is moving. Turn Brake On. if (oinitengine.car_increment >> 16) { oferrari.auto_brake = true; oinputs.brake_adjust = 0xFF; } else { osoundint.queue_sound(sound::VOICE_CONGRATS); ferrari_stopped = true; } } anim_seq_outro(&anim_ferrari); } // End Sequence: Setup Animated Sprites // Source: 0x5B42 void OAnimSeq::anim_seq_outro(oanimsprite* anim) { oinputs.steering_adjust = 0; // Return if no animation data to process if (!read_anim_data(anim)) return; if (outrun.tick_frame) { // Process Animation Data uint32_t index = anim->anim_addr_curr + (anim->anim_frame << 3); anim->sprite->addr = roms.rom0p->read32(index) & 0xFFFFF; anim->sprite->pal_src = roms.rom0p->read8(index); anim->sprite->zoom = roms.rom0p->read8(6 + index) >> 1; anim->sprite->road_priority = roms.rom0p->read8(6 + index) << 1; anim->sprite->priority = anim->sprite->road_priority - ((roms.rom0p->read16(index) & 0x70) >> 4); // (bits 4-6) anim->sprite->x = (roms.rom0p->read8(4 + index) * anim->sprite->priority) >> 9; if (roms.rom0p->read8(1 + index) & BIT_7) anim->sprite->x = -anim->sprite->x; // set_sprite_xy: (similar to flag code again) // Set Y Position int16_t sprite_y = (int8_t) roms.rom0p->read8(5 + index); int16_t final_y = (sprite_y * anim->sprite->priority) >> 9; anim->sprite->y = oroad.get_road_y(anim->sprite->priority) - final_y; // Set H-Flip if (roms.rom0p->read8(7 + index) & BIT_6) anim->sprite->control |= OSprites::HFLIP; else anim->sprite->control &= ~OSprites::HFLIP; // Ready for next frame if (--anim->frame_delay == 0) { // Load Next Block Of Animation Data if (roms.rom0p->read8(7 + index) & BIT_7) { anim->anim_props |= 0xFF; anim->anim_addr_curr = anim->anim_addr_next; anim->frame_delay = roms.rom0p->read8(7 + anim->anim_addr_curr) & 0x3F; anim->anim_frame = 0; } // Last Block else { anim->frame_delay = roms.rom0p->read8(0x0F + index) & 0x3F; anim->anim_frame++; } } osprites.map_palette(anim->sprite); } // Order sprites osprites.do_spr_order_shadows(anim->sprite); } // Render Sprite Shadow For End Sequence // Use parent sprite as basis to set this up // Source: 0x5C48 void OAnimSeq::anim_seq_shadow(oanimsprite* parent, oanimsprite* anim) { // Return if no animation data to process if (!read_anim_data(anim)) return; if (outrun.tick_frame) { uint8_t zoom_shift = 3; // Car Shadow if (anim->sprite->id == 3) { zoom_shift = 1; if ((parent->anim_props & 0xFF) == 0 && oferrari.sprite_ai_x <= 5) zoom_shift++; } // 5C88 set_sprite_xy: anim->sprite->x = parent->sprite->x; uint16_t priority = parent->sprite->road_priority >> zoom_shift; anim->sprite->zoom = priority - (priority >> 2); anim->sprite->y = oroad.get_road_y(parent->sprite->road_priority); // Chris - The following extra line seems necessary due to the way I set the sprites up. // Actually, I think it's a bug in the original game, relying on this being setup by // the crash code previously. But anyway! anim->sprite->road_priority = parent->sprite->road_priority; } osprites.do_spr_order_shadows(anim->sprite); } // Read Animation Data for End Sequence // Source: 0x5CC4 bool OAnimSeq::read_anim_data(oanimsprite* anim) { uint32_t addr = outrun.adr.anim_end_table + (end_seq << 2) + (anim->sprite->id << 2) + (anim->sprite->id << 4); // a0 + d1 // Read start & end position in animation timeline for this object int16_t start_pos = roms.rom0p->read16(addr); // d0 int16_t end_pos = roms.rom0p->read16(2 + addr); // d3 int16_t pos = seq_pos; // d1 // Global Sequence Position: Advance to next position // Not particularly clean embedding this here obviously! if (outrun.tick_frame && anim->anim_props & 0xFF00) seq_pos++; // Test Whether Animation Sequence Is Over & Initalize Course Map if (obonus.bonus_control != OBonus::BONUS_DISABLE) { const uint16_t END_SEQ_LENGTHS[] = {0x244, 0x244, 0x244, 0x190, 0x258}; if (seq_pos == END_SEQ_LENGTHS[end_seq]) { obonus.bonus_control = OBonus::BONUS_DISABLE; // we're missing all the code here to disable the animsprites, but probably not necessary? if (outrun.cannonball_mode == Outrun::MODE_ORIGINAL) outrun.game_state = GS_INIT_MAP; else outrun.init_best_outrunners(); } } // -------------------------------------------------------------------------------------------- // Process Animation Sequence // -------------------------------------------------------------------------------------------- const bool DO_NOTHING = false; const bool PROCESS = true; // check_seq_pos: // Sequence: Start Position // ret_set_frame_delay: if (pos == start_pos) { // If current animation block is set, extract frame delay if (anim->anim_addr_curr) anim->frame_delay = roms.rom0p->read8(7 + anim->anim_addr_curr) & 0x3F; return PROCESS; } // Sequence: Invalid Position else if (pos < start_pos || pos > end_pos) // d1 < d0 || d1 > d3 return DO_NOTHING; // Sequence: In Progress else if (pos < end_pos) return PROCESS; // Sequence: End Position else { // End Of Animation Data if (anim->sprite->id == 8) // Trophy person { anim->sprite->id = 11; if (end_seq >= 2) anim->sprite->shadow = 7; anim->anim_addr_curr = roms.rom0p->read32(outrun.adr.anim_endseq_obj8 + (end_seq << 3)); anim->anim_addr_next = roms.rom0p->read32(outrun.adr.anim_endseq_obj8 + (end_seq << 3) + 4); anim->anim_frame = 0; return DO_NOTHING; } // 5e14 else if (anim->sprite->id == 10) { anim->sprite->id = 12; if (end_seq >= 2) anim->sprite->shadow = 7; anim->anim_addr_curr = roms.rom0p->read32(outrun.adr.anim_endseq_objA + (end_seq << 3)); anim->anim_addr_next = roms.rom0p->read32(outrun.adr.anim_endseq_objA + (end_seq << 3) + 4); anim->anim_frame = 0; return DO_NOTHING; } } return PROCESS; }
[ "pointblnk@hotmail.com" ]
pointblnk@hotmail.com
ca7c0a7ecee4fd8be28cebd555d4eba2b165d0e9
e0319092e49a75341a7945722c62b9be42cc0b44
/class_registry/dog.cc
8bdcb4cf2344becc93a98262925f8a75ecbfab1d
[]
no_license
yeshunping/codelab
e4a4fdd087111a01ec1fccb5c23f398948044fcf
146d69a42d2e66218074da78bd5864b18b76684f
refs/heads/master
2016-09-11T04:41:25.545655
2013-05-18T14:36:25
2013-05-18T14:36:25
9,851,667
0
1
null
null
null
null
UTF-8
C++
false
false
316
cc
// Copyright (c) 2013, The Toft Authors. // All rights reserved. // // Author: Ye Shunping <yeshunping@gmail.com> #include "codelab/class_registry/dog.h" #include "thirdparty/glog/logging.h" namespace animal { Dog::Dog() { } Dog::~Dog() { } void Dog::Run() { LOG(INFO) << "dog run"; } REGISTER_ANIMAL(Dog); }
[ "yeshunping@gmail.com" ]
yeshunping@gmail.com
c4dcea2c1e30282a5852596c9b1548cd5b7a9169
103751ccab80ebab7df0ea670d50c95a784f8223
/2017-03-28 Kent Nikaido Contest 1./H/H.cpp
4a3430f21390981c861dbb258259bfe7a4760adf
[]
no_license
AnimismFudan/Animism
b451ee9d0b3710f6b568ecf2dc022cffdc065d82
db1fc16841f7eeb158cca8d0a8de087a795b97ec
refs/heads/master
2020-12-25T14:14:08.979003
2017-06-03T07:02:38
2017-06-03T07:02:38
67,414,706
1
0
null
null
null
null
UTF-8
C++
false
false
743
cpp
#include <bits/stdc++.h> using namespace std; #define ll long long ll L; int N; inline ll Calc(ll m) { ll s = 0, t = 2; while (t <= m) { s += (m/t); t *= 2; } return s; } bool C(ll m, ll n) { //cout << m << ' ' << n << ' ' << Calc(m) << ' ' << Calc(n) << ' ' << Calc(m-n) << endl; return Calc(m) == Calc(n) + Calc(m-n); } int main() { cin >> L; scanf("%d", &N); bool res = false; for (int i=1; i<=N; i++) { int x, y, z; scanf("%d%d", &y, &z); y --; z --; x = L - 1 - y; y = y - z; //cout << x << ' ' << y << ' ' << z << ' ' << (C(x+y+z, x) & C(y+z, z)) << endl; res ^= C(x+y+z, x) & C(y+z, z); } if (!(L&1)) res ^= true; if (res) printf("Iori\n"); else printf("Yayoi\n"); return 0; }
[ "totoro97@outlook.com" ]
totoro97@outlook.com
3887b4690479ab6c695e9abdc873bc2e17f3955a
543908b4481ae172bc9494ad109c67d26fdcd088
/题目.cpp
f1dd8fdf83cb3a70cd510f662443f0721065ec9a
[]
no_license
hunterhe001/MyLeetCode
821d5fbf73d2219d64cb933f0353428a46b836cb
736da5beab1c6ff97228ae233385ed67273d81ea
refs/heads/master
2022-12-08T03:18:24.190192
2020-09-02T16:24:56
2020-09-02T16:24:56
288,162,922
0
0
null
null
null
null
GB18030
C++
false
false
2,194
cpp
//《数据结构》这本书里的例题 //第三章 线性结构 //线性表的链式存储实现 //1.链表定义Node //2.链表求长度Length //3.查找第K个值FindKth //4.按值查找Find //5.插入Insert //6.删除Delete //7.遍历链表Print //堆栈的顺序存储表示 //8.顺序存储结构定义Stack1 //9.入栈Push1 //10.出栈Pop1 //堆栈的链式存储表示 //11.存储结构表示Stack2 //12.创建一个堆栈CreatStack //13.堆栈是否为空IsEmpty //13.入栈Push2 //14.出栈Pop2 //队列的顺序存储实现 //15.结构定义Queue //16.插入 //17.删除 //队列的链式存储实现 //18.结构定义LinkQueue //19.插入 //20.删除 //第四章 //二叉树 //21.二叉树的链表表示TreeNode //22.二叉树递归中序遍历 //23.二叉树递归先序遍历 //24.二叉树递归后序遍历 //25.二叉树的非递归中序遍历 //26.二叉树的层序遍历 //27.输出二叉树的叶节点 //28.求二叉树高度 //二叉搜索树 //29.二叉搜索树查找Find递归 //30.二叉搜索树查找非递归IterFind //31.查找最大值FindBinTreeMax //32.查找最小值FindBinTreeMin //33.插入数据InsertBinTree //34.删除数据DeleteBinTree //平衡二叉树 //35.平衡二叉树结点定义AVLTreeNode //36.LL旋转SingleLeftRotation //37.RR旋转SingleRightRotation //38.LR旋转DoubleLeftRightRotation //39.RL旋转DoubleRightLeftRotation //40.平衡二叉树的插入AVLInsertion //41.平衡二叉树的高度 //堆 //42.最大堆的结构定义MaxHeap //43.最大堆建立MaxHeapCreat //44.最大堆的插入MaxHeapInsert //45.最大堆的删除MaxHeapDelete //第五章 图 //46.图的邻接矩阵表示法的结构定义MGraph //47.邻接矩阵表示法创建图CreateMGraph() //48.图的邻接表表示法结构定义EdgeNode、VertexNode、ALGraph //49.邻接表创建图CreateALGraph //50.深度优先搜索DFS //51.广度优先搜索BFS //52.Dijkstra算法 //排序 //53.冒泡排序Bubble_Sort //54.插入排序Insertion_Sort //55.选择排序Selection_Sort0 //56.堆排序的调整函数Adjust //57.堆排序HeapSort //58.归并排序法MergeSort,递推实现 //59.归并排序法,迭代实现 //60.快速排序 Quick_Sort
[ "you@example.com1076673002@qq.com" ]
you@example.com1076673002@qq.com
cd54d2e7ecf29cdd05e982c99126aa570871ecb2
52dc9080af88c00222cc9b37aa08c35ff3cafe86
/0800/40/841a.cpp
73b5ac6bcd0b51ad58c289cebd175a6aed72b27e
[ "Unlicense" ]
permissive
shivral/cf
1c1acde25fc6af775acaeeb6b5fe5aa9bbcfd4d2
d7be128c3a9adb014a231a399f1c5f19e1ab2a38
refs/heads/master
2023-03-20T01:29:25.559828
2021-03-05T08:30:30
2021-03-05T08:30:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
514
cpp
#include <iostream> #include <string> void answer(bool v) { constexpr const char* s[2] = { "NO", "YES" }; std::cout << s[v] << '\n'; } void solve(const std::string& s, size_t k) { size_t f[26] = {}; for (const char c : s) ++f[c - 'a']; for (size_t i = 0; i < 26; ++i) { if (f[i] > k) return answer(false); } answer(true); } int main() { size_t n, k; std::cin >> n >> k; std::string s; std::cin >> s; solve(s, k); return 0; }
[ "5691735+actium@users.noreply.github.com" ]
5691735+actium@users.noreply.github.com
02b69d20577db698e9c44cc56c69ae3dce7f037f
13c1474bfc7f9ba115180e4639b1ed1d88062d5e
/CNQT/NQTQUESTIONS/stringWithATwist.c++
fb8fa216ec8ca06a038cb5370ac918d80f6b5eb2
[]
no_license
Sudipta07151/c-plus-plus-programs
133552cfc9d05bcab215bc711a643bdd33710e61
e1f675601b8e884f50543076a32b71ade15bea01
refs/heads/master
2023-05-08T03:42:57.467650
2021-06-03T17:00:07
2021-06-03T17:00:07
354,283,731
0
0
null
null
null
null
UTF-8
C++
false
false
1,080
/****************************************************************************** Welcome to GDB Online. GDB online is an online compiler and debugger tool for C, C++, Python, Java, PHP, Ruby, Perl, C#, VB, Swift, Pascal, Fortran, Haskell, Objective-C, Assembly, HTML, CSS, JS, SQLite, Prolog. Code, Compile, Run and Debug online from anywhere in world. *******************************************************************************/ #include <iostream> #include<string> using namespace std; int main() { string str1,str2,str3; getline(cin,str1); getline(cin,str2); getline(cin,str3); for(char &v:str1) { if(v=='a'|| v=='e' || v=='i'|| v=='o' || v=='u') { v='%'; } } for(char &v:str2) { if(v!='a'|| v!='e' || v!='i'|| v!='o' || v!='u') { v='#'; } } for(char &v:str3) { if(v>=97 && v<=122) { v=(int)v-32; } } str1+=str2; str1+=str3; cout<<str1; return 0; }
[ "noreply@github.com" ]
noreply@github.com
4e02d6a69af15abb9d155665c410b3a1c3df3c20
215750938b1dd4354eab9b8581eec76881502afb
/src/test/TestBigMuffPi.cpp
798a95e423730af9ba9583e4d83e86455352275c
[ "WTFPL" ]
permissive
EleonoreMizo/pedalevite
c28fd19578506bce127b4f451c709914ff374189
3e324801e3a1c5f19a4f764176cc89e724055a2b
refs/heads/master
2023-05-30T12:13:26.159826
2023-05-01T06:53:31
2023-05-01T06:53:31
77,694,808
103
8
null
null
null
null
UTF-8
C++
false
false
4,977
cpp
/***************************************************************************** TestBigMuffPi.cpp Author: Laurent de Soras, 2020 --- Legal stuff --- This program is free software. It comes without any warranty, to the extent permitted by applicable law. You can redistribute it and/or modify it under the terms of the Do What The Fuck You Want To Public License, Version 2, as published by Sam Hocevar. See http://www.wtfpl.net/ for more details. *Tab=3***********************************************************************/ #if defined (_MSC_VER) #pragma warning (1 : 4130 4223 4705 4706) #pragma warning (4 : 4355 4786 4800) #endif /*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ #include "fstb/Approx.h" #include "fstb/fnc.h" #include "test/TestBigMuffPi.h" #include "test/TimerAccurate.h" #include "mfx/dsp/osc/SweepingSin.h" #include "mfx/dsp/va/BigMuffPi.h" #include "mfx/FileOpWav.h" #include <memory> #include <cassert> #include <cstdio> /*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ int TestBigMuffPi::perform_test () { int ret_val = 0; printf ("Testing mfx::dsp::va::BigMuffPi...\n"); const int ovrspl = 1; const double sample_freq = 44100 * ovrspl; const int ssin_len = fstb::round_int (sample_freq * 10); std::vector <float> src (ssin_len); // Sweeping sine mfx::dsp::osc::SweepingSin ssin (sample_freq, 20.0, 20000.0); ssin.generate (src.data (), ssin_len); // Sawtooth const int saw_len = fstb::round_int (sample_freq * 1); for (int o = -3; o < 7; ++o) { const double freq = 220 * pow (2.0, o + 3 / 12.0); gen_saw (src, sample_freq, freq, saw_len); } float gain = 1.0f; const int len = int (src.size ()); std::vector <float> dst (len); mfx::dsp::va::BigMuffPi muff; muff.set_sample_freq (sample_freq); #if defined (mfx_dsp_va_dkm_Simulator_STATS) muff.reset_stats (); #endif // mfx_dsp_va_dkm_Simulator_STATS printf ("Simulating...\n"); fflush (stdout); TimerAccurate tim; tim.reset (); tim.start (); for (int pos = 0; pos < len; ++pos) { float x = src [pos] * gain; #if 0 // Audio-rate modulation const int per = 337; muff.set_pot ( mfx::dsp::va::BigMuffPi::Pot_TONE, 0.5f + 0.5f * fstb::Approx::sin_nick_2pi ( float (pos % per) * (1.f / float (per)) - 0.5f ) ); #endif x = muff.process_sample (x); dst [pos] = x; } tim.stop (); const double spl_per_s = tim.get_best_rate (len); mfx::FileOpWav::save ("results/bigmuffpi1.wav", dst, sample_freq, 0.5f); const double kilo_sps = spl_per_s / 1e3; const double rt_mul = spl_per_s / sample_freq; printf ("Speed: %12.3f kspl/s (x%.3f real-time).\n", kilo_sps, rt_mul); #if defined (mfx_dsp_va_dkm_Simulator_STATS) print_stats (muff); muff.reset_stats (); #endif // mfx_dsp_va_dkm_Simulator_STATS printf ("Done.\n\n"); return ret_val; } /*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ /*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ void TestBigMuffPi::gen_saw (std::vector <float> &data, double sample_freq, double freq, int len) { const int per = fstb::round_int (sample_freq / freq); for (int pos = 0; pos < len; ++pos) { const float val = float (pos % per) * (2.f / float (per)) - 1.f; data.push_back (val); } } #if defined (mfx_dsp_va_dkm_Simulator_STATS) void TestBigMuffPi::print_stats (const mfx::dsp::va::BigMuffPi &muff) { mfx::dsp::va::dkm::Simulator::Stats st; muff.get_stats (st); print_stats (st, "global"); } void TestBigMuffPi::print_stats (mfx::dsp::va::dkm::Simulator::Stats &stats, const char *title_0) { printf ("=== Iterations: %s ===\n", title_0); print_histo ( stats._hist_it.data (), int (stats._hist_it.size ()), stats._nbr_spl_proc ); printf ("\n"); } void TestBigMuffPi::print_histo (const int hist_arr [], int nbr_bars, int nbr_spl) { int bar_max = 0; int total = 0; for (int k = 0; k < nbr_bars; ++k) { const int val = hist_arr [k]; bar_max = std::max (bar_max, val); total += val * k; } const int bar_size = 64; char bar_0 [bar_size+1]; for (int k = 0; k < bar_size; ++k) { bar_0 [k] = '#'; } bar_0 [bar_size] = '\0'; const double nbr_spl_inv = 1.0 / double (nbr_spl); const double bar_scale = double (bar_size) / double (bar_max); printf ("Average: %.2f\n", double (total) * nbr_spl_inv); for (int k = 0; k < nbr_bars; ++k) { const int val = hist_arr [k]; if (val > 0) { const double prop = double (val) * nbr_spl_inv; printf ("%3d: %10d, %5.1f %% ", k, val, prop * 100); const int bar_len = fstb::round_int (val * bar_scale); printf ("%s\n", bar_0 + bar_size - bar_len); } } } #endif // mfx_dsp_va_dkm_Simulator_STATS /*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
[ "fuck@fuck.fuck" ]
fuck@fuck.fuck
b62a00236564c68aaaae7043d0cc14a6ef1abeec
968a4cb2feb13518940f9d125c4d6b5ae2094595
/VTK/Rendering/Testing/Cxx/TestTilingCxx.cxx
d34c7f4b5d68ad61342ded67f83defe2bf7b9f4c
[ "LicenseRef-scancode-paraview-1.2", "BSD-3-Clause" ]
permissive
wildmichael/ParaView3-enhancements-old
b4f2327e09cac3f81fa8c5cdb7a56bcdf960b6c1
d889161ab8458787ec7aa3d8163904b8d54f07c5
refs/heads/master
2021-05-26T12:33:58.622473
2009-10-29T09:17:57
2009-10-29T09:17:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,735
cxx
/*========================================================================= Program: Visualization Toolkit Module: $RCSfile: TestTilingCxx.cxx,v $ Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkTestUtilities.h" #include "vtkRegressionTestImage.h" #include "vtkRenderWindowInteractor.h" #include "vtkRenderWindow.h" #include "vtkRenderer.h" #include "vtkActor.h" #include "vtkActor2D.h" #include "vtkCellData.h" #include "vtkDataObject.h" #include "vtkFloatArray.h" #include "vtkImageMapper.h" #include "vtkMath.h" #include "vtkPolyData.h" #include "vtkPolyDataMapper.h" #include "vtkProgrammableAttributeDataFilter.h" #include "vtkScalarBarActor.h" #include "vtkScalarsToColors.h" #include "vtkSphereSource.h" #include "vtkWindowToImageFilter.h" #include "vtkSmartPointer.h" #define VTK_CREATE(type, var) \ vtkSmartPointer<type> var = vtkSmartPointer<type>::New() void colorCells(void *arg) { VTK_CREATE(vtkMath, randomColorGenerator); vtkProgrammableAttributeDataFilter * randomColors = static_cast<vtkProgrammableAttributeDataFilter *>(arg); vtkPolyData * input = vtkPolyData::SafeDownCast(randomColors->GetInput()); vtkPolyData * output = randomColors->GetPolyDataOutput(); int numCells = input->GetNumberOfCells(); VTK_CREATE(vtkFloatArray, colors); colors->SetNumberOfTuples(numCells); for(int i = 0; i < numCells; i++) { colors->SetValue(i, randomColorGenerator->Random(0 ,1)); } output->GetCellData()->CopyScalarsOff(); output->GetCellData()->PassData(input->GetCellData()); output->GetCellData()->SetScalars(colors); } int TestTilingCxx(int argc, char* argv[]) { VTK_CREATE(vtkSphereSource, sphere); sphere->SetThetaResolution(20); sphere->SetPhiResolution(40); // Compute random scalars (colors) for each cell VTK_CREATE(vtkProgrammableAttributeDataFilter, randomColors); randomColors->SetInputConnection(sphere->GetOutputPort()); randomColors->SetExecuteMethod(colorCells, randomColors); // mapper and actor VTK_CREATE(vtkPolyDataMapper, mapper); mapper->SetInput(randomColors->GetPolyDataOutput()); mapper->SetScalarRange(randomColors->GetPolyDataOutput()->GetScalarRange()); VTK_CREATE(vtkActor, sphereActor); sphereActor->SetMapper(mapper); // Create a scalar bar VTK_CREATE(vtkScalarBarActor, scalarBar); scalarBar->SetLookupTable(mapper->GetLookupTable()); scalarBar->SetTitle("Temperature"); scalarBar->GetPositionCoordinate()->SetCoordinateSystemToNormalizedViewport(); scalarBar->GetPositionCoordinate()->SetValue(0.1, 0.05); scalarBar->SetOrientationToVertical(); scalarBar->SetWidth(0.8); scalarBar->SetHeight(0.9); scalarBar->SetLabelFormat("%-#6.3f"); // Test the Get/Set Position scalarBar->SetPosition(scalarBar->GetPosition()); // Create graphics stuff // Create the RenderWindow, Renderer and both Actors VTK_CREATE(vtkRenderer, ren1); VTK_CREATE(vtkRenderer, ren2); VTK_CREATE(vtkRenderWindow, renWin); renWin->SetMultiSamples(0); renWin->AddRenderer(ren1); renWin->AddRenderer(ren2); VTK_CREATE(vtkRenderWindowInteractor, iren); iren->SetRenderWindow(renWin); ren1->AddActor(sphereActor); ren2->AddActor2D(scalarBar); renWin->SetSize(160, 160); ren1->SetViewport(0, 0, 0.75, 1.0); ren2->SetViewport(0.75, 0, 1.0, 1.0); ren2->SetBackground(0.3, 0.3, 0.3); // render the image renWin->Render(); scalarBar->SetNumberOfLabels(8); renWin->Render(); VTK_CREATE(vtkWindowToImageFilter, w2i); w2i->SetInput(renWin); w2i->SetMagnification(2); w2i->Update(); // copy the output vtkImageData * outputData = w2i->GetOutput()->NewInstance(); outputData->DeepCopy(w2i->GetOutput()); VTK_CREATE(vtkImageMapper, ia); ia->SetInput(outputData); scalarBar->ReleaseGraphicsResources(renWin); sphereActor->ReleaseGraphicsResources(renWin); ia->SetColorWindow(255); ia->SetColorLevel(127.5); VTK_CREATE(vtkActor2D, ia2); ia2->SetMapper(ia); renWin->SetSize(320, 320); ren2->RemoveViewProp(scalarBar); ren1->RemoveViewProp(sphereActor); ren1->AddActor(ia2); renWin->RemoveRenderer(ren2); ren1->SetViewport(0, 0, 1, 1); renWin->Render(); int retVal = vtkRegressionTestImage( renWin ); if ( retVal == vtkRegressionTester::DO_INTERACTOR) { iren->Start(); } outputData->Delete(); return !retVal; }
[ "partyd" ]
partyd
2f93fc9f428fe730d997f01cf0b18969c21b2ed5
1d928c3f90d4a0a9a3919a804597aa0a4aab19a3
/c++/folly/2015/4/SSLContextConfig.h
9c6987af5952b389bac36d26aff80ebf8a512ae0
[]
no_license
rosoareslv/SED99
d8b2ff5811e7f0ffc59be066a5a0349a92cbb845
a062c118f12b93172e31e8ca115ce3f871b64461
refs/heads/main
2023-02-22T21:59:02.703005
2021-01-28T19:40:51
2021-01-28T19:40:51
306,497,459
1
1
null
2020-11-24T20:56:18
2020-10-23T01:18:07
null
UTF-8
C++
false
false
3,055
h
/* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #pragma once #include <string> #include <folly/io/async/SSLContext.h> #include <vector> /** * SSLContextConfig helps to describe the configs/options for * a SSL_CTX. For example: * * 1. Filename of X509, private key and its password. * 2. ciphers list * 3. NPN list * 4. Is session cache enabled? * 5. Is it the default X509 in SNI operation? * 6. .... and a few more */ namespace folly { struct SSLContextConfig { SSLContextConfig() {} ~SSLContextConfig() {} struct CertificateInfo { std::string certPath; std::string keyPath; std::string passwordPath; }; /** * Helpers to set/add a certificate */ void setCertificate(const std::string& certPath, const std::string& keyPath, const std::string& passwordPath) { certificates.clear(); addCertificate(certPath, keyPath, passwordPath); } void addCertificate(const std::string& certPath, const std::string& keyPath, const std::string& passwordPath) { certificates.emplace_back(CertificateInfo{certPath, keyPath, passwordPath}); } /** * Set the optional list of protocols to advertise via TLS * Next Protocol Negotiation. An empty list means NPN is not enabled. */ void setNextProtocols(const std::list<std::string>& inNextProtocols) { nextProtocols.clear(); nextProtocols.push_back({1, inNextProtocols}); } typedef std::function<bool(char const* server_name)> SNINoMatchFn; std::vector<CertificateInfo> certificates; folly::SSLContext::SSLVersion sslVersion{ folly::SSLContext::TLSv1}; bool sessionCacheEnabled{true}; bool sessionTicketEnabled{true}; bool clientHelloParsingEnabled{false}; std::string sslCiphers{ "ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:" "ECDHE-ECDSA-AES128-SHA:ECDHE-ECDSA-AES256-SHA:ECDHE-RSA-AES128-GCM-SHA256:" "ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-SHA:ECDHE-RSA-AES256-SHA:" "AES128-GCM-SHA256:AES256-GCM-SHA384:AES128-SHA:AES256-SHA:" "ECDHE-ECDSA-RC4-SHA:ECDHE-RSA-RC4-SHA:RC4-SHA:RC4-MD5:" "ECDHE-RSA-DES-CBC3-SHA:DES-CBC3-SHA"}; std::string eccCurveName; // Ciphers to negotiate if TLS version >= 1.1 std::string tls11Ciphers{""}; // Weighted lists of NPN strings to advertise std::list<folly::SSLContext::NextProtocolsItem> nextProtocols; bool isLocalPrivateKey{true}; // Should this SSLContextConfig be the default for SNI purposes bool isDefault{false}; // Callback function to invoke when there are no matching certificates // (will only be invoked once) SNINoMatchFn sniNoMatchFn; // File containing trusted CA's to validate client certificates std::string clientCAFile; }; }
[ "rodrigosoaresilva@gmail.com" ]
rodrigosoaresilva@gmail.com
46fe7182a837a5b2bc5c95afe06b6c2017993fb5
7072598fbcfb90f0516b71d73dc2314f08de59dd
/source/client/socks5server.h
79c009c37ac21ad2e484ff3c40ad7081307cebe9
[ "MIT" ]
permissive
ActorExpose/sims-zeus
cee9d2e870518716fe326527cbd1a80329f94499
6f0dd24222debcb48801ebb7f92b52accc607240
refs/heads/master
2021-12-13T13:47:38.758649
2017-03-21T14:18:40
2017-03-21T14:18:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
232
h
#pragma once namespace Socks5Server { void init(void); void uninit(void); bool _start5(SOCKET s, DWORD timeout); bool _start4(SOCKET s, DWORD timeout); bool _start(SOCKET s, DWORD timeout); };
[ "mikias.amdu@gmail.com" ]
mikias.amdu@gmail.com
801bca3ba15f4e99be5c487dc8cf542fb0f1a577
76cd839ad9ddee4dca934a01f2a19e3de53af166
/CocTest/proj.win32/main.cpp
40c641e7ee2b3596738aa44837cc8762813bf110
[]
no_license
pope88/CocInside
d0de227dbd653228b38426aab8e0bad6c8710e55
9a10141d0c0cce16accae40eaa65527ac5b601a8
refs/heads/master
2021-01-10T20:38:31.714405
2013-06-26T00:03:44
2013-06-26T00:03:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
920
cpp
#include "Config.h" #include "main.h" #include "AppDelegate.h" #include "CCEGLView.h" USING_NS_CC; // uncomment below line, open debug console // #define USE_WIN32_CONSOLE int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); #ifdef USE_WIN32_CONSOLE AllocConsole(); freopen("CONIN$", "r", stdin); freopen("CONOUT$", "w", stdout); freopen("CONOUT$", "w", stderr); #endif // create the application instance AppDelegate app; CCEGLView* eglView = CCEGLView::sharedOpenGLView(); eglView->setFrameSize(640, 1136); eglView->setFrameZoomFactor(0.5f); int ret = CCApplication::sharedApplication()->run(); #ifdef USE_WIN32_CONSOLE FreeConsole(); #endif return ret; }
[ "pope@pope.taomee-ex.com" ]
pope@pope.taomee-ex.com
95e0a2e65a06787ab65a28dda0642a75e67fd20d
e5422975481b1283b4a8a5207c2ff9a5e0d73ff1
/cl_dll/overview.cpp
d04d394abd6f4564c658b2a5917ca9207b1c945d
[]
no_license
mittorn/hlwe_src
ae6ebd30c3dc2965f501b7e5ee460a7c7de58892
7abbe2ab834d636af4224a0bd0c192c958242b49
refs/heads/master
2021-01-13T16:30:25.223519
2015-12-01T19:07:15
2015-12-01T19:07:15
47,205,047
2
1
null
null
null
null
WINDOWS-1252
C++
false
false
4,711
cpp
//========= Copyright © 1996-2002, Valve LLC, All rights reserved. ============ // // Purpose: // // $NoKeywords: $ //============================================================================= #include "hud.h" #include "cl_util.h" #include "cl_entity.h" #include "triangleapi.h" //#include "vgui_TeamFortressViewport.h" // these are included for the math functions #include "com_model.h" #include "studio_util.h" #include "overview.h" #pragma warning(disable: 4244) //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- int CHudOverview::Init() { gHUD.AddHudElem(this); m_iFlags |= HUD_ACTIVE; return 1; } //----------------------------------------------------------------------------- // Purpose: Loads new icons //----------------------------------------------------------------------------- int CHudOverview::VidInit() { m_hsprPlayer = gEngfuncs.pfnSPR_Load("sprites/ring.spr"); m_hsprViewcone = gEngfuncs.pfnSPR_Load("sprites/camera.spr"); return 1; } //----------------------------------------------------------------------------- // Purpose: // Input : flTime - // intermission - //----------------------------------------------------------------------------- int CHudOverview::Draw(float flTime) { // only draw in overview mode // if (!gEngfuncs.Overview_GetOverviewState()) return 1; /* // make sure we have player info gViewPort->GetAllPlayersInfo(); */ // calculate player size on the overview int x1, y1, x2, y2; float v0[3]={0,0,0}, v1[3]={64,64,0}; // gEngfuncs.Overview_WorldToScreen(v0, &x1, &y1); // gEngfuncs.Overview_WorldToScreen(v1, &x2, &y2); float scale = abs(x2 - x1); // loop through all the players and draw them on the map for (int i = 1; i < MAX_PLAYERS; i++) { cl_entity_t *pl = gEngfuncs.GetEntityByIndex(i); if (pl && pl->player && pl->curstate.health > 0 && pl->curstate.solid != SOLID_NOT) { int x, y, z = 0; float v[3]={pl->origin[0], pl->origin[1], 0}; // gEngfuncs.Overview_WorldToScreen(v, &x, &y); // hack in some team colors float r, g, bc; if (g_PlayerExtraInfo[i].teamnumber == 1) { r = 0.0f; g = 0.0f; bc = 1.0f; } else if (g_PlayerExtraInfo[i].teamnumber == 2) { r = 1.0f; g = 0.0f; bc = 0.0f; } else { // just use the default orange color if the team isn't set r = 1.0f; g = 0.7f; bc = 0.0f; } // set the current texture gEngfuncs.pTriAPI->SpriteTexture((struct model_s *)gEngfuncs.GetSpritePointer(m_hsprPlayer), 0); // additive render mode gEngfuncs.pTriAPI->RenderMode(kRenderTransAdd); // no culling gEngfuncs.pTriAPI->CullFace(TRI_NONE); // draw a square gEngfuncs.pTriAPI->Begin(TRI_QUADS); // set the color to be that of the team gEngfuncs.pTriAPI->Color4f(r, g, bc, 1.0f); // calculate rotational matrix vec3_t a, b, angles; float rmatrix[3][4]; // transformation matrix VectorCopy(pl->angles, angles); angles[0] = 0.0f; angles[1] += 90.f; angles[1] = -angles[1]; angles[2] = 0.0f; AngleMatrix(angles, rmatrix); a[2] = 0; a[0] = -scale; a[1] = -scale; VectorTransform(a, rmatrix , b ); gEngfuncs.pTriAPI->TexCoord2f( 0, 0 ); gEngfuncs.pTriAPI->Vertex3f(x + b[0], y + b[1], z); a[0]=-scale; a[1] = scale; VectorTransform(a, rmatrix , b ); gEngfuncs.pTriAPI->TexCoord2f( 0, 1 ); gEngfuncs.pTriAPI->Vertex3f (x + b[0], y + b[1], z); a[0]=scale; a[1] = scale; VectorTransform(a, rmatrix , b ); gEngfuncs.pTriAPI->TexCoord2f( 1, 1 ); gEngfuncs.pTriAPI->Vertex3f (x + b[0], y + b[1], z); a[0]=scale; a[1] = -scale; VectorTransform(a, rmatrix , b ); gEngfuncs.pTriAPI->TexCoord2f( 1, 0 ); gEngfuncs.pTriAPI->Vertex3f (x + b[0], y + b[1], z); // finish up gEngfuncs.pTriAPI->End(); gEngfuncs.pTriAPI->RenderMode( kRenderNormal ); // draw the players name and health underneath char string[256]; sprintf(string, "%s (%i%%)", g_PlayerInfoList[i].name, pl->curstate.health); DrawConsoleString(x, y + (1.1 * scale), string); } } return 1; } //----------------------------------------------------------------------------- // Purpose: called every time a server is connected to //----------------------------------------------------------------------------- void CHudOverview::InitHUDData() { // this block would force the spectator view to be on // gEngfuncs.Overview_SetDrawOverview( 1 ); // gEngfuncs.Overview_SetDrawInset( 0 ); }
[ "mittorn@sibmail.com" ]
mittorn@sibmail.com
ec7c23429527602966ac19f8ce0af949a0f9d233
dbbe7dabb7fd058b21a5cd1a6834063e6ce866a8
/genI213.cc
e05db02ea8cf7f634e9d72c3cfebf59a3cbca4c4
[]
no_license
bopopescu/pilot
789a66b4b361d753eb564151018b5c2564fcdf2a
b6a3ffafbc07863eda59544ddae12576e4b20b31
refs/heads/master
2022-11-21T12:46:43.149773
2011-09-24T08:04:54
2011-09-24T08:04:54
282,576,529
0
0
null
2020-07-26T04:36:55
2020-07-26T04:36:54
null
UTF-8
C++
false
false
41,267
cc
// -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*- // vi: set ts=2 noet: // // This file is part of the Rosetta software suite and is made available under license. // The Rosetta software is developed by the contributing members of the Rosetta Commons consortium. // (C) 199x-2009 Rosetta Commons participating institutions and developers. // For more information, see http://www.rosettacommons.org/. /// @file /src/apps/pilat/will/genmatch.cc /// @brief ??? #include <basic/options/keys/in.OptionKeys.gen.hh> #include <basic/options/keys/out.OptionKeys.gen.hh> #include <basic/options/keys/smhybrid.OptionKeys.gen.hh> //#include <basic/options/keys/willmatch.OptionKeys.gen.hh> #include <basic/options/option.hh> #include <basic/options/util.hh> #include <basic/Tracer.hh> #include <core/chemical/ChemicalManager.hh> #include <core/chemical/ResidueTypeSet.hh> #include <core/chemical/util.hh> #include <core/chemical/VariantType.hh> #include <core/conformation/Residue.hh> #include <core/conformation/ResidueFactory.hh> #include <core/conformation/symmetry/SymDof.hh> #include <core/conformation/symmetry/SymmData.hh> #include <core/conformation/symmetry/SymmetryInfo.hh> #include <core/conformation/symmetry/util.hh> #include <core/import_pose/import_pose.hh> #include <core/init.hh> #include <core/io/pdb/pose_io.hh> #include <core/io/silent/ScoreFileSilentStruct.hh> #include <core/io/silent/SilentFileData.hh> #include <core/kinematics/FoldTree.hh> #include <core/kinematics/MoveMap.hh> #include <core/kinematics/Stub.hh> #include <core/pack/optimizeH.hh> #include <core/pack/task/PackerTask.hh> #include <core/pack/task/TaskFactory.hh> #include <core/pack/dunbrack/RotamerLibrary.hh> #include <core/pack/dunbrack/RotamerLibraryScratchSpace.hh> #include <core/pack/dunbrack/SingleResidueDunbrackLibrary.hh> #include <core/pose/annotated_sequence.hh> #include <core/pose/Pose.hh> #include <core/pose/symmetry/util.hh> #include <core/pose/util.hh> #include <core/scoring/dssp/Dssp.hh> #include <core/scoring/Energies.hh> #include <core/scoring/rms_util.hh> #include <core/scoring/ScoreFunction.hh> #include <core/scoring/ScoreFunctionFactory.hh> #include <core/scoring/ScoringManager.hh> #include <core/scoring/symmetry/SymmetricScoreFunction.hh> #include <numeric/conversions.hh> #include <numeric/model_quality/rms.hh> #include <numeric/random/random.hh> #include <numeric/xyz.functions.hh> #include <numeric/xyz.io.hh> #include <ObjexxFCL/FArray2D.hh> #include <ObjexxFCL/format.hh> #include <ObjexxFCL/string.functions.hh> #include <protocols/moves/symmetry/SetupForSymmetryMover.hh> #include <protocols/moves/symmetry/SymMinMover.hh> #include <protocols/moves/symmetry/SymPackRotamersMover.hh> #include <protocols/scoring/ImplicitFastClashCheck.hh> #include <sstream> #include <utility/io/izstream.hh> #include <utility/io/ozstream.hh> // #include <devel/init.hh> // #include <core/scoring/constraints/LocalCoordinateConstraint.hh> #include "apps/pilot/will/will_util.hh" #include "mynamespaces.hh" using core::kinematics::Stub; using protocols::scoring::ImplicitFastClashCheck; using core::pose::Pose; using core::conformation::ResidueOP; static basic::Tracer TR("genI213"); static core::io::silent::SilentFileData sfd; inline Real const sqr(Real const r) { return r*r; } inline Real sigmoidish_neighbor( Real const & sqdist ) { if( sqdist > 9.*9. ) { return 0.0; } else if( sqdist < 6.*6. ) { return 1.0; } else { Real dist = sqrt( sqdist ); return sqr(1.0 - sqr( (dist - 6.) / (9. - 6.) ) ); } } vector1<Size> get_scanres(Pose const & pose) { vector1<Size> scanres; //if(basic::options::option[basic::options::OptionKeys::willmatch::residues].user()) { //TR << "input scanres!!!!!!" << std::endl; //scanres = basic::options::option[basic::options::OptionKeys::willmatch::residues](); //} else { for(Size i = 1; i <= pose.n_residue(); ++i) { if(!pose.residue(i).has("N" )) { continue; } if(!pose.residue(i).has("CA")) { continue; } if(!pose.residue(i).has("C" )) { continue; } if(!pose.residue(i).has("O" )) { continue; } if(!pose.residue(i).has("CB")) { continue; } if(pose.residue(i).name3()=="PRO") { continue; } scanres.push_back(i); } //} return scanres; } void dumpsym(Pose const & pose, Mat R2, Mat R3a, Mat R3b, Vec cen2, string fname) { vector1<Vec> seenit; Mat R3[3]; R3[0] = Mat::identity(); R3[1] = R3a; R3[2] = R3b; TR << "output" << std::endl; vector1<string> ANAME(3); ANAME[1] = " N "; ANAME[2] = " CA "; ANAME[3] = " C "; string CHAIN = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; ozstream out( fname ); Size acount=0,rcount=0,ccount=0; for(Size i3a = 0; i3a < 3; i3a++) { for(Size i2a = 0; i2a < 2; i2a++) { for(Size j3a = 0; j3a < 3; j3a++) { for(Size j2a = 0; j2a < 2; j2a++) { for(Size k3a = 0; k3a < 3; k3a++) { for(Size k2a = 0; k2a < 2; k2a++) { for(Size l3a = 0; l3a < 3; l3a++) { for(Size l2a = 0; l2a < 2; l2a++) { for(Size m3a = 0; m3a < 2; m3a++) { for(Size m2a = 0; m2a < 2; m2a++) { for(Size n3a = 0; n3a < 2; n3a++) { for(Size n2a = 0; n2a < 2; n2a++) { Vec chk( pose.xyz(AtomID(1,1)) ); chk = R3[i3a]*chk; if(i2a) chk = R2*(chk-cen2)+cen2; chk = R3[j3a]*chk; if(j2a) chk = R2*(chk-cen2)+cen2; chk = R3[k3a]*chk; if(k2a) chk = R2*(chk-cen2)+cen2; chk = R3[l3a]*chk; if(l2a) chk = R2*(chk-cen2)+cen2; chk = R3[m3a]*chk; if(m2a) chk = R2*(chk-cen2)+cen2; chk = R3[n3a]*chk; if(n2a) chk = R2*(chk-cen2)+cen2; for(vector1<Vec>::const_iterator i = seenit.begin(); i != seenit.end(); ++i) { if( i->distance_squared(chk) < 1.0 ) goto cont2; } goto done2; cont2: continue; done2: seenit.push_back(chk); char chain = CHAIN[ccount]; if( (i2a+j2a+k2a+l2a+m2a+n2a) % 2 == 1 ) chain = 'B'; for(Size ir = 1; ir <= pose.n_residue(); ++ir) { if( rcount >= 9999) { rcount = 0; ccount++; } Size rn = ++rcount; for(Size ia = 1; ia <= 3; ia++) { Vec tmp(pose.residue(ir).xyz(ia)); tmp = R3[i3a]*tmp; if(i2a) tmp = R2*(tmp-cen2)+cen2; tmp = R3[j3a]*tmp; if(j2a) tmp = R2*(tmp-cen2)+cen2; tmp = R3[k3a]*tmp; if(k2a) tmp = R2*(tmp-cen2)+cen2; tmp = R3[l3a]*tmp; if(l2a) tmp = R2*(tmp-cen2)+cen2; tmp = R3[m3a]*tmp; if(m2a) tmp = R2*(tmp-cen2)+cen2; tmp = R3[n3a]*tmp; if(n2a) tmp = R2*(tmp-cen2)+cen2; string X = F(8,3,tmp.x()); string Y = F(8,3,tmp.y()); string Z = F(8,3,tmp.z()); out<<"ATOM "<<I(5,++acount)<<' '<<ANAME[ia]<<' '<<"ALA"<<' '<<chain<<I(4,rn)<<" "<<X<<Y<<Z<<F(6,2,1.0)<<F(6,2,0.0)<<'\n'; } } out << "TER" << std::endl; } } } } } } } } } } } } out.close(); } void dumpsym6(Pose const & pose, Mat R2, Mat R3a, Mat R3b, Vec HG, string fname, Size irsd, Size ch1, Size ch2, Real ANG) { vector1<Vec> seenit; Mat R3[3]; R3[0] = Mat::identity(); R3[1] = R3a; R3[2] = R3b; TR << "output" << std::endl; for(Size i3a = 0; i3a < 3; i3a++) { for(Size i2a = 0; i2a < 2; i2a++) { for(Size j3a = 0; j3a < 3; j3a++) { for(Size j2a = 0; j2a < 2; j2a++) { for(Size k3a = 0; k3a < 3; k3a++) { for(Size k2a = 0; k2a < 2; k2a++) { for(Size l3a = 0; l3a < 3; l3a++) { for(Size l2a = 0; l2a < 2; l2a++) { for(Size m3a = 0; m3a < 2; m3a++) { for(Size m2a = 0; m2a < 2; m2a++) { for(Size n3a = 0; n3a < 2; n3a++) { for(Size n2a = 0; n2a < 2; n2a++) { Pose tmp(pose); rot_pose(tmp,R3[i3a]); if(i2a) rot_pose(tmp,R2,HG); rot_pose(tmp,R3[j3a]); if(j2a) rot_pose(tmp,R2,HG); rot_pose(tmp,R3[k3a]); if(k2a) rot_pose(tmp,R2,HG); rot_pose(tmp,R3[l3a]); if(l2a) rot_pose(tmp,R2,HG); rot_pose(tmp,R3[m3a]); if(m2a) rot_pose(tmp,R2,HG); rot_pose(tmp,R3[n3a]); if(n2a) rot_pose(tmp,R2,HG); Vec chk( tmp.xyz(AtomID(1,1)) ); for(vector1<Vec>::const_iterator i = seenit.begin(); i != seenit.end(); ++i) { if( i->distance_squared(chk) < 1.0 ) goto cont2; } goto done2; cont2: continue; done2: seenit.push_back(chk); tmp.dump_pdb( utility::file_basename(fname) +"_"+ F(4,1,ANG)+"_"+ lzs(irsd,3)+"_"+ lzs((Size)ch1,3)+"_"+ lzs((Size)ch2,3)+"_"+ lzs(i3a,1)+"_"+lzs(i2a,1)+"_"+lzs(j3a,1)+"_"+lzs(j2a,1)+"_"+lzs(k3a,1)+"_"+lzs(k2a,1)+"_"+ lzs(l3a,1)+"_"+lzs(l2a,1)+"_"+lzs(m3a,1)+"_"+lzs(m2a,1)+"_"+lzs(n3a,1)+"_"+lzs(n2a,1)+".pdb"); } } } } } } } } } } } } } void dumpsym2(Pose const & pose, Mat R2, Mat R3a, Mat R3b, Vec HG, string fname, Size irsd, Size ch1, Size ch2, Real ANG) { vector1<Vec> seenit; Mat R3[3]; R3[0] = Mat::identity(); R3[1] = R3a; R3[2] = R3b; TR << "output" << std::endl; for(Size i3a = 0; i3a < 3; i3a++) { for(Size i2a = 0; i2a < 2; i2a++) { for(Size j3a = 0; j3a < 3; j3a++) { for(Size j2a = 0; j2a < 2; j2a++) { Pose tmp(pose); rot_pose(tmp,R3[i3a]); if(i2a) rot_pose(tmp,R2,HG); rot_pose(tmp,R3[j3a]); if(j2a) rot_pose(tmp,R2,HG); Vec chk( tmp.xyz(AtomID(1,1)) ); for(vector1<Vec>::const_iterator i = seenit.begin(); i != seenit.end(); ++i) { if( i->distance_squared(chk) < 1.0 ) goto cont2; } goto done2; cont2: continue; done2: seenit.push_back(chk); tmp.dump_pdb( utility::file_basename(fname) +"_"+ F(4,1,ANG)+"_"+ lzs(irsd,3)+"_"+ lzs((Size)ch1,3)+"_"+ lzs((Size)ch2,3)+"_"+ lzs(i3a,1)+"_"+lzs(i2a,1)+"_"+lzs(j3a,1)+"_"+lzs(j2a,1)+".pdb"); } } } } } struct Hit { Size rsd,cbc;; Real chi1,chi2; Vec axs,cen; bool sym; }; std::pair<vector1<Hit>,vector1<Hit> > dock(Pose & init, string fname) { using namespace basic::options::OptionKeys; core::chemical::ResidueTypeSetCAP rs = core::chemical::ChemicalManager::get_instance()->residue_type_set( core::chemical::FA_STANDARD ); Pose cys; make_pose_from_sequence(cys,"C","fa_standard",false); remove_lower_terminus_type_from_pose_residue(cys,1); remove_upper_terminus_type_from_pose_residue(cys,1); // add_variant_type_to_pose_residue(cys,"DISULF_PARTNER",1); core::scoring::dssp::Dssp dssp(init); dssp.insert_ss_into_pose(init); Vec com(0,0,0); for(Size ir = 1; ir <= init.n_residue(); ++ir) { init.replace_residue(ir,cys.residue(1),true); replace_pose_residue_copying_existing_coordinates(init,ir,init.residue(ir).residue_type_set().name_map("ALA")); com += init.xyz(AtomID(2,ir)); } com /= init.n_residue(); protocols::scoring::ImplicitFastClashCheck ifc3(init,3.5); protocols::scoring::ImplicitFastClashCheck ifc2(init,2.8); Size nres = init.n_residue(); // ScoreFunctionOP sf = core::scoring::getScoreFunction(); ScoreFunctionOP sf = new core::scoring::symmetry::SymmetricScoreFunction(core::scoring::getScoreFunction()); Pose pose = init; Mat R3a = rotation_matrix_degrees(Vec(0,0,1), 120.0); Mat R3b = rotation_matrix_degrees(Vec(0,0,1),-120.0); vector1<Size> scanres = get_scanres(pose); core::pack::dunbrack::SingleResidueRotamerLibraryCAP dunlib = core::pack::dunbrack::RotamerLibrary::get_instance().get_rsd_library( rs->name_map("CYS") ); core::pack::dunbrack::RotamerLibraryScratchSpace scratch; vector1<Hit> hits,allhits; for(vector1<Size>::const_iterator iiter = scanres.begin(); iiter != scanres.end(); ++iiter) { Size irsd = *iiter; // ssq for( int iss = int(irsd)-2; iss <= int(irsd)+2; ++iss) { if( iss < 1 || iss > pose.n_residue() ) goto contss; if( pose.secstruct(iss) != 'L' ) goto doness; } goto doness; contss: continue; doness: // if(irsd != 42) continue; //TR << fname << " RES " << irsd << std::endl; //if( pose.residue(irsd).name3()=="GLY" || pose.residue(irsd).name3()=="PRO" ) continue; ResidueOP rprev = pose.residue(irsd).clone(); pose.replace_residue(irsd,cys.residue(1),true); Vec CA = pose.residue(irsd).xyz("CA"); Vec CB = pose.residue(irsd).xyz("CB"); vector1<Vec> seen_axs,seen_cen; vector1<Vec> asym_axs,asym_cen; bool foundhit = false; for(Size stage=0; stage<=1; ++stage) { for(Real ch1 = 0.0; ch1 < 360.0; ch1+=2.0) { pose.set_chi(1,irsd,ch1); Vec SG = pose.residue(irsd).xyz("SG"); if( ! ifc2.clash_check(SG,irsd) ) continue; for(Real ch2 = 0.0; ch2 < 360.0; ch2+=3.0) { pose.set_chi(2,irsd,ch2); Real dun = dunlib->rotamer_energy( pose.residue(irsd), scratch ); //if( dun > 4.0 ) continue; // DUNBRACK Vec HG = pose.residue(irsd).xyz("HG"); if( ! ifc2.clash_check(HG,irsd) ) continue; for(Size iaxs = 0; iaxs <= 1; iaxs++) { for(Size isg = 1; isg <= 2; isg++) { Real const ANG( isg==1 ? 54.7 : 35.3 ); Vec axs = rotation_matrix_degrees(HG-SG, iaxs?45.0:-45.0 ) * projperp(HG-SG,SG-CB).normalized(); Real a1 = fabs(angle_degrees( axs,Vec(0,0,0), Vec(0,0,1) ) - ANG); Real a2 = fabs(angle_degrees( axs,Vec(0,0,0),-Vec(0,0,1) ) - ANG); Vec axs1; if(stage==1 && foundhit) { //////////////////////////////////////////////////////////////////////////////// axs1 = axs; Mat R2 = rotation_matrix_degrees(axs1,180.0); if( ! ifc2.clash_check( R2*(SG-HG)+HG ,irsd) ) continue; Vec cen = R2*(com-HG)+HG; // filter redundency at ~0.7Á and 5deg for(Size i = 1; i <= asym_cen.size(); ++i) { if( asym_cen[i].distance_squared(cen) < 0.25 && asym_axs[i].dot(axs1) > 0.9962 ) goto cont0; } goto done0; cont0: continue; done0: for(Size ir = 1; ir <= pose.n_residue(); ++ir) { for(Size ia = 1; ia <= 5; ++ia) { if( ! ifc3.clash_check( ( R2*((pose.xyz(AtomID(ia,ir)))-HG) + HG ) ) ) goto cont1; } } goto done1; cont1: continue; done1: Size cbc = 0; for(Size ir = 1; ir <= pose.n_residue(); ++ir) { Vec CB12 = R2 * ( (pose.xyz(AtomID(5,ir)))-HG) + HG; Vec CB22 = R2 * ( R3a * (pose.xyz(AtomID(5,ir)))-HG) + HG; Vec CB32 = R2 * ( R3b * (pose.xyz(AtomID(5,ir)))-HG) + HG; for(Size jr = 1; jr <= pose.n_residue(); ++jr) { Vec CB11 = pose.xyz(AtomID(5,jr)); Vec CB21 = R3a * pose.xyz(AtomID(5,jr)); Vec CB31 = R3b * pose.xyz(AtomID(5,jr)); if( CB11.distance_squared(CB12) < 49.0 ) cbc++; if( CB21.distance_squared(CB12) < 49.0 ) cbc++; if( CB31.distance_squared(CB12) < 49.0 ) cbc++; if( CB11.distance_squared(CB22) < 49.0 ) cbc++; if( CB21.distance_squared(CB22) < 49.0 ) cbc++; if( CB31.distance_squared(CB22) < 49.0 ) cbc++; if( CB11.distance_squared(CB32) < 49.0 ) cbc++; if( CB21.distance_squared(CB32) < 49.0 ) cbc++; if( CB31.distance_squared(CB32) < 49.0 ) cbc++; } } if( cbc < 20 ) continue; // TR << "4" << std::endl; for(Size ir = 1; ir <= pose.n_residue(); ++ir) { for(Size ia = 1; ia <= 5; ++ia) { if( ! ifc3.clash_check( ( R2 * ( (pose.xyz(AtomID(ia,ir)))-HG) + HG ) ) ) goto cont2; if( ! ifc3.clash_check( ( R2 * ( R3a * (pose.xyz(AtomID(ia,ir)))-HG) + HG ) ) ) goto cont2; if( ! ifc3.clash_check( ( R2 * ( R3b * (pose.xyz(AtomID(ia,ir)))-HG) + HG ) ) ) goto cont2; if( ! ifc3.clash_check( R3a * ( R2 * ( (pose.xyz(AtomID(ia,ir)))-HG) + HG ) ) ) goto cont2; if( ! ifc3.clash_check( R3a * ( R2 * ( R3a * (pose.xyz(AtomID(ia,ir)))-HG) + HG ) ) ) goto cont2; if( ! ifc3.clash_check( R3a * ( R2 * ( R3b * (pose.xyz(AtomID(ia,ir)))-HG) + HG ) ) ) goto cont2; if( ! ifc3.clash_check( R3b * ( R2 * ( (pose.xyz(AtomID(ia,ir)))-HG) + HG ) ) ) goto cont2; if( ! ifc3.clash_check( R3b * ( R2 * ( R3a * (pose.xyz(AtomID(ia,ir)))-HG) + HG ) ) ) goto cont2; if( ! ifc3.clash_check( R3b * ( R2 * ( R3b * (pose.xyz(AtomID(ia,ir)))-HG) + HG ) ) ) goto cont2; } } goto done2; cont2: continue; done2: //TR << "5" << std::endl; asym_cen.push_back(R2*(com-HG)+HG); asym_axs.push_back(axs1); Hit h; h.rsd = irsd; h.cbc = cbc; h.axs = axs1; h.cen = HG; h.chi1 = ch1; h.chi2 = ch2; h.sym = false; allhits.push_back(h); } if(stage != 0) continue; if( dun > 2.0 ) continue; // DUNBRACK if( a1 > 15.0 && a2 > 15.0 ) continue; /////////////////////////////////////////////////////////////////////////////////////////////////////////////// if( a1 < a2 ) axs1 = rotation_matrix_degrees( Vec(0,0, 1).cross(axs), ANG ) * Vec(0,0, 1); else axs1 = rotation_matrix_degrees( Vec(0,0,-1).cross(axs), ANG ) * Vec(0,0,-1); if( angle_degrees(axs1,Vec(0,0,0),axs) > 15.0 ) { TR << "VEC " << axs << " " << axs1 << " " << a1 << " " << a2 << " " << angle_degrees(axs1,Vec(0,0,0),axs) << std::endl; utility_exit_with_message("axs alignment issue"); } if(axs1.z() < 0.0) axs1 = -axs1; Mat R2 = rotation_matrix_degrees(axs1,180.0); if( ! ifc2.clash_check( R2*(SG-HG)+HG ,irsd) ) continue; Vec cen = R2*(com-HG)+HG; // filter redundency at 0.5Á and 5deg for(Size i = 1; i <= seen_cen.size(); ++i) { if( seen_cen[i].distance_squared(cen) < 0.25 && seen_axs[i].dot(axs1) > 0.9962 ) goto cont3; } goto done3; cont3: continue; done3: for(Size ir = 1; ir <= pose.n_residue(); ++ir) { for(Size ia = 1; ia <= 5; ++ia) { if( ! ifc3.clash_check( ( R2*((pose.xyz(AtomID(ia,ir)))-HG) + HG ) ) ) goto cont4; } } goto done4; cont4: continue; done4: Size cbc = 0; for(Size ir = 1; ir <= pose.n_residue(); ++ir) { Vec CB12 = R2 * ( (pose.xyz(AtomID(5,ir)))-HG) + HG; Vec CB22 = R2 * ( R3a * (pose.xyz(AtomID(5,ir)))-HG) + HG; Vec CB32 = R2 * ( R3b * (pose.xyz(AtomID(5,ir)))-HG) + HG; for(Size jr = 1; jr <= pose.n_residue(); ++jr) { Vec CB11 = pose.xyz(AtomID(5,jr)); Vec CB21 = R3a * pose.xyz(AtomID(5,jr)); Vec CB31 = R3b * pose.xyz(AtomID(5,jr)); if( CB11.distance_squared(CB12) < 49.0 ) cbc++; if( CB21.distance_squared(CB12) < 49.0 ) cbc++; if( CB31.distance_squared(CB12) < 49.0 ) cbc++; if( CB11.distance_squared(CB22) < 49.0 ) cbc++; if( CB21.distance_squared(CB22) < 49.0 ) cbc++; if( CB31.distance_squared(CB22) < 49.0 ) cbc++; if( CB11.distance_squared(CB32) < 49.0 ) cbc++; if( CB21.distance_squared(CB32) < 49.0 ) cbc++; if( CB31.distance_squared(CB32) < 49.0 ) cbc++; } } if( cbc < 30 ) continue; for(Size ir = 1; ir <= pose.n_residue(); ++ir) { for(Size ia = 1; ia <= 5; ++ia) { if( ! ifc3.clash_check( ( R2 * ( (pose.xyz(AtomID(ia,ir)))-HG) + HG ) ) ) goto cont5; if( ! ifc3.clash_check( ( R2 * ( R3a * (pose.xyz(AtomID(ia,ir)))-HG) + HG ) ) ) goto cont5; if( ! ifc3.clash_check( ( R2 * ( R3b * (pose.xyz(AtomID(ia,ir)))-HG) + HG ) ) ) goto cont5; if( ! ifc3.clash_check( R3a * ( R2 * ( (pose.xyz(AtomID(ia,ir)))-HG) + HG ) ) ) goto cont5; if( ! ifc3.clash_check( R3a * ( R2 * ( R3a * (pose.xyz(AtomID(ia,ir)))-HG) + HG ) ) ) goto cont5; if( ! ifc3.clash_check( R3a * ( R2 * ( R3b * (pose.xyz(AtomID(ia,ir)))-HG) + HG ) ) ) goto cont5; if( ! ifc3.clash_check( R3b * ( R2 * ( (pose.xyz(AtomID(ia,ir)))-HG) + HG ) ) ) goto cont5; if( ! ifc3.clash_check( R3b * ( R2 * ( R3a * (pose.xyz(AtomID(ia,ir)))-HG) + HG ) ) ) goto cont5; if( ! ifc3.clash_check( R3b * ( R2 * ( R3b * (pose.xyz(AtomID(ia,ir)))-HG) + HG ) ) ) goto cont5; } } goto done5; cont5: continue; done5: Mat R3[3]; R3[0] = Mat::identity(); R3[1] = R3a; R3[2] = R3b; { vector1<Vec> clash_olap; { Vec chk( pose.xyz(AtomID(1,1)) ); clash_olap.push_back( chk); clash_olap.push_back(R3a*chk); clash_olap.push_back(R3b*chk); } for(Size i3a = 0; i3a < 3; i3a++) { for(Size i2a = 0; i2a < 2; i2a++) { for(Size j3a = 0; j3a < 3; j3a++) { for(Size j2a = 0; j2a < 2; j2a++) { for(Size k3a = 0; k3a < 3; k3a++) { for(Size k2a = 0; k2a < 2; k2a++) { for(Size l3a = 0; l3a < 3; l3a++) { for(Size l2a = 0; l2a < 2; l2a++) { for(Size m3a = 0; m3a < 3; m3a++) { for(Size m2a = 0; m2a < 2; m2a++) { for(Size n3a = 0; n3a < 3; n3a++) { for(Size n2a = 0; n2a < 2; n2a++) { Vec chk( pose.xyz(AtomID(1,1)) ); Vec chk0 = chk; chk = R3[i3a] * chk; if(i2a) chk = R2*(chk-HG)+HG; chk = R3[j3a] * chk; if(j2a) chk = R2*(chk-HG)+HG; chk = R3[k3a] * chk; if(k2a) chk = R2*(chk-HG)+HG; chk = R3[l3a] * chk; if(l2a) chk = R2*(chk-HG)+HG; chk = R3[m3a] * chk; if(m2a) chk = R2*(chk-HG)+HG; chk = R3[n3a] * chk; if(n2a) chk = R2*(chk-HG)+HG; for(vector1<Vec>::const_iterator i = clash_olap.begin(); i != clash_olap.end(); ++i) { if( i->distance_squared(chk) < 1.0 ) goto cont6; } goto done6; cont6: continue; done6: clash_olap.push_back(chk); if( chk.distance_squared(chk0) > 30000 ) continue; for(Size ir = 1; ir <= pose.n_residue(); ++ir) { for(Size ia = 1; ia <= 5; ++ia) { Vec chk( pose.xyz(AtomID(ia,ir)) ); chk = R3[i3a] * chk; if(i2a) chk = R2*(chk-HG)+HG; chk = R3[j3a] * chk; if(j2a) chk = R2*(chk-HG)+HG; chk = R3[k3a] * chk; if(k2a) chk = R2*(chk-HG)+HG; chk = R3[l3a] * chk; if(l2a) chk = R2*(chk-HG)+HG; chk = R3[m3a] * chk; if(m2a) chk = R2*(chk-HG)+HG; chk = R3[n3a] * chk; if(n2a) chk = R2*(chk-HG)+HG; if( ! ifc3.clash_check(chk) ) goto cont7; } } } } } } } } } } } } } } goto done7; cont7: continue; done7: if(clash_olap.size() < 25) continue; } TR << "HIT " << irsd << " " << ch1 << " " << ch2 << " " << iaxs << " " << ANG << std::endl; seen_cen.push_back(R2*(com-HG)+HG); seen_axs.push_back(axs1); //dumpsym6( pose, R2, R3a, R3b, HG, fname, irsd, ch1, ch2, ANG); Hit h; h.rsd = irsd; h.cbc = cbc; h.axs = axs1; h.cen = HG; h.chi1 = ch1; h.chi2 = ch2; h.sym = true; hits.push_back(h); foundhit = true; // std::cerr << "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" << std::endl; // return std::pair<vector1<Hit>,vector1<Hit> > (hits,allhits); //pose.set_xyz( AtomID(pose.residue(irsd).atom_index("HG"),irsd), SG+axs1 ); // for(Size i3a = 0; i3a < 3; i3a++) { // for(Size i2a = 0; i2a < 2; i2a++) { // Pose tmp(pose); // rot_pose(tmp,R3[i3a]); if(i2a) rot_pose(tmp,R2,HG); // string fn = utility::file_basename(fname) +"_"+ F(4,1,ANG)+"_"+ lzs(irsd,3)+"_" // + lzs((Size)ch1,3)+"_"+ lzs((Size)ch2,3)+"_"+ lzs(i3a,1)+"_"+lzs(i2a,1)+".pdb"; // tmp.dump_pdb( fn ); // } // } //utility_exit_with_message("foo"); } } } } } pose.replace_residue(irsd,*rprev,false); } return std::pair<vector1<Hit>,vector1<Hit> > (hits,allhits); } void design(Pose & pose, ScoreFunctionOP sf, Size Ntri ){ using namespace core::pack::task; //TR << "design" << std::endl; // sasa Pose psasa(pose); for(Size ir = 1; ir <= psasa.total_residue(); ++ir) { if(psasa.residue(ir).name3()!="GLY") { if(!psasa.residue(ir).is_protein()) continue; Vec CA = psasa.residue(ir).xyz("CA"); Vec CB = psasa.residue(ir).xyz("CB"); psasa.set_xyz( AtomID(5,ir), CA + 2.3*(CB-CA).normalized() ); } } core::id::AtomID_Map< bool > atom_map; core::pose::initialize_atomid_map( atom_map, psasa, false ); for( Size ir = 1; ir <= psasa.total_residue(); ++ir ) { if(!psasa.residue(ir).is_protein()) continue; atom_map.set(AtomID(1,ir),true); atom_map.set(AtomID(2,ir),true); atom_map.set(AtomID(3,ir),true); atom_map.set(AtomID(4,ir),true); if(psasa.residue(ir).name3()!="GLY") atom_map.set(AtomID(5,ir), true ); //else atom_map.set(AtomID(2,ir), true ); //for( Size ia = 1; ia <= min(Size(5),psasa.residue(ir).nheavyatoms()); ++ia ) { //atom_map.set(AtomID(ia,ir) , true ); //} } core::id::AtomID_Map<Real> atom_sasa; utility::vector1<Real> sasa; core::scoring::calc_per_atom_sasa( psasa, atom_sasa, sasa, 3.0, false, atom_map ); for(Size ir = 1; ir <= Ntri; ++ir) { if(psasa.residue(ir).name3()=="GLY") sasa[ir] = 0; else sasa[ir] = atom_sasa[AtomID(5,ir)]; } // std::cout << "select bur=resi "; // for(Size i = 1; i <= Ntri; ++i) if(sasa[i] < 10.0) std::cout << i << "+"; // std::cout << std::endl; // std::cout << "color white, chain A; color grey, chain B; color red, bur" << std::endl; // pose.dump_pdb("test.pdb"); // utility_exit_with_message("dbg sasa"); Size nres = pose.n_residue(); PackerTaskOP task = TaskFactory::create_packer_task(pose); // task->initialize_extra_rotamer_flags_from_command_line(); vector1< bool > aac(20,false); aac[core::chemical::aa_ala] = true; //aac[core::chemical::aa_cys] = true; //aac[core::chemical::aa_asp] = true; //aac[core::chemical::aa_glu] = true; aac[core::chemical::aa_phe] = true; //aac[core::chemical::aa_gly] = true; //aac[core::chemical::aa_his] = true; aac[core::chemical::aa_ile] = true; //aac[core::chemical::aa_lys] = true; aac[core::chemical::aa_leu] = true; aac[core::chemical::aa_met] = true; aac[core::chemical::aa_asn] = true; //aac[core::chemical::aa_pro] = true; //aac[core::chemical::aa_gln] = true; //aac[core::chemical::aa_arg] = true; //aac[core::chemical::aa_ser] = true; //aac[core::chemical::aa_thr] = true; aac[core::chemical::aa_val] = true; //aac[core::chemical::aa_trp] = true; //aac[core::chemical::aa_tyr] = true; vector1< bool > aap(20,false); //aap[core::chemical::aa_ala] = true; //aap[core::chemical::aa_cys] = true; aap[core::chemical::aa_asp] = true; aap[core::chemical::aa_glu] = true; //aap[core::chemical::aa_phe] = true; //aap[core::chemical::aa_gly] = true; aap[core::chemical::aa_his] = true; //aap[core::chemical::aa_ile] = true; aap[core::chemical::aa_lys] = true; //aap[core::chemical::aa_leu] = true; //aap[core::chemical::aa_met] = true; aap[core::chemical::aa_asn] = true; //aap[core::chemical::aa_pro] = true; aap[core::chemical::aa_gln] = true; aap[core::chemical::aa_arg] = true; aap[core::chemical::aa_ser] = true; aap[core::chemical::aa_thr] = true; //aap[core::chemical::aa_val] = true; aap[core::chemical::aa_trp] = true; aap[core::chemical::aa_tyr] = true; vector1<Size> iface(Ntri,0); for( Size ir = 1; ir <= Ntri; ++ir) { if( pose.residue(ir).name3()=="CYS" || pose.residue(ir).name3()=="GLY" || pose.residue(ir).name3()=="PRO") { iface[ir] = 3; continue; } Real closestcb = 9e9; for( Size jr = Ntri+1; jr <= 2*Ntri; ++jr) { if( pose.residue(jr).name3()=="GLY" ) continue; Real d = pose.xyz(AtomID(5,ir)).distance( pose.xyz(AtomID(5,jr)) ); closestcb = min(closestcb,d); } if(closestcb < 11.0) { if ( sasa[ir] > 10.0 ) iface[ir] = 1; // if exposed, is priphery else if(closestcb < 7.0 ) iface[ir] = 2; else iface[ir] = 0; } } // std::cout << "select priph=resi "; // for(Size i = 1; i <= Ntri; ++i) if(iface[i]==1) std::cout << i << "+"; // std::cout << std::endl; // std::cout << "select iface=resi "; // for(Size i = 1; i <= Ntri; ++i) if(iface[i]==2) std::cout << i << "+"; // std::cout << std::endl; // std::cout << "color white, chain A; color grey, chain B; color blue, priph; color red, iface" << std::endl; // pose.dump_pdb("test.pdb"); // utility_exit_with_message("dbg iface sel"); for(Size i = 1; i <= Ntri; ++i) { if ( iface[i] == 3 ) { task->nonconst_residue_task(i).prevent_repacking(); } else if( iface[i] == 2 ) { bool tmp = aac[pose.residue(i).aa()]; aac[pose.residue(i).aa()] = true; task->nonconst_residue_task(i).restrict_absent_canonical_aas(aac); aac[pose.residue(i).aa()] = tmp; task->nonconst_residue_task(i).initialize_extra_rotamer_flags_from_command_line(); } else if( iface[i] == 1 ) { bool tmp = aap[pose.residue(i).aa()]; aap[pose.residue(i).aa()] = true; task->nonconst_residue_task(i).restrict_absent_canonical_aas(aap); aap[pose.residue(i).aa()] = tmp; task->nonconst_residue_task(i).initialize_extra_rotamer_flags_from_command_line(); } else if( iface[i] == 0 ) { task->nonconst_residue_task(i).restrict_to_repacking(); task->nonconst_residue_task(i).or_include_current(true); task->nonconst_residue_task(i).initialize_extra_rotamer_flags_from_command_line(); } } Real rorig = sf->get_weight(core::scoring::fa_rep); sf->set_weight(core::scoring::fa_rep,rorig/4.0); Real worig = sf->get_weight(core::scoring::res_type_constraint); if( worig == 0.0 ) sf->set_weight(core::scoring::res_type_constraint,1.0); utility::vector1< core::scoring::constraints::ConstraintCOP > res_cst = add_favor_native_cst(pose); protocols::moves::symmetry::SymPackRotamersMover repack( sf, task ); repack.apply(pose); // REMOVE SER NOT HBONDED ACROSS IFACE // cleanup 2 pose.remove_constraints( res_cst ); sf->set_weight(core::scoring::res_type_constraint,worig); sf->set_weight(core::scoring::fa_rep,rorig); //TR << "sc min" << std::endl; core::kinematics::MoveMapOP movemap = new core::kinematics::MoveMap; movemap->set_jump(false); movemap->set_bb(false); movemap->set_chi(true); core::pose::symmetry::make_symmetric_movemap( pose, *movemap ); protocols::moves::symmetry::SymMinMover m( movemap, sf, "dfpmin_armijo_nonmonotone", 1e-5, true, false, false ); m.apply(pose); //TR << "done" << std::endl; } void repack_iface(Pose & pose, ScoreFunctionOP sf, Size Ntri ){ using namespace core::pack::task; PackerTaskOP task = TaskFactory::create_packer_task(pose); vector1<Size> iface(Ntri,0); for( Size ir = 1; ir <= Ntri; ++ir) { if( pose.residue(ir).name3()=="CYS" || pose.residue(ir).name3()=="GLY" || pose.residue(ir).name3()=="PRO") { iface[ir] = 3; continue; } Real closestcb = 9e9; for( Size jr = Ntri+1; jr <= 2*Ntri; ++jr) { if( pose.residue(jr).name3()=="GLY" ) continue; Real d = pose.xyz(AtomID(5,ir)).distance( pose.xyz(AtomID(5,jr)) ); closestcb = min(closestcb,d); } if(closestcb < 11.0) { iface[ir] = 1; } } for(Size i = 1; i <= Ntri; ++i) { if ( iface[i] == 3 ) { task->nonconst_residue_task(i).prevent_repacking(); } else if( iface[i] == 1 ) { task->nonconst_residue_task(i).restrict_to_repacking(); task->nonconst_residue_task(i).or_include_current(true); task->nonconst_residue_task(i).initialize_extra_rotamer_flags_from_command_line(); } else if( iface[i] == 0 ) { task->nonconst_residue_task(i).prevent_repacking(); } } protocols::moves::symmetry::SymPackRotamersMover repack( sf, task ); repack.apply(pose); } void repack_all(Pose & pose, ScoreFunctionOP sf, Size Ntri ){ using namespace core::pack::task; PackerTaskOP task = TaskFactory::create_packer_task(pose); vector1<Size> iface(Ntri,0); for( Size ir = 1; ir <= Ntri; ++ir) { if( pose.residue(ir).name3()=="CYS" || pose.residue(ir).name3()=="GLY" || pose.residue(ir).name3()=="PRO") { iface[ir] = 3; continue; } } for(Size i = 1; i <= Ntri; ++i) { if ( iface[i] == 3 ) { task->nonconst_residue_task(i).prevent_repacking(); } else { task->nonconst_residue_task(i).restrict_to_repacking(); task->nonconst_residue_task(i).or_include_current(true); task->nonconst_residue_task(i).initialize_extra_rotamer_flags_from_command_line(); } } protocols::moves::symmetry::SymPackRotamersMover repack( sf, task ); repack.apply(pose); core::kinematics::MoveMapOP movemap = new core::kinematics::MoveMap; movemap->set_jump(false); movemap->set_bb(false); movemap->set_chi(true); core::pose::symmetry::make_symmetric_movemap( pose, *movemap ); protocols::moves::symmetry::SymMinMover m( movemap, sf, "dfpmin_armijo_nonmonotone", 1e-5, true, false, false ); m.apply(pose); } void design_hits(Pose & p, string fn, vector1<Hit> h, vector1<Hit> allh) { using namespace basic::options::OptionKeys; TR << "design_hits " << h.size() << " " << allh.size() << std::endl; // select hits //vector1<Size> nhit(p.n_residue(),0); //for(Size ih = 1; ih <= h.size(); ++ih) nhit[ h[ih].rsd ]++; core::chemical::ResidueTypeSetCAP rs = core::chemical::ChemicalManager::get_instance()->residue_type_set( core::chemical::FA_STANDARD ); Pose cys,ala; make_pose_from_sequence(cys,"C","fa_standard",false); make_pose_from_sequence(ala,"A","fa_standard",false); remove_lower_terminus_type_from_pose_residue(cys,1); remove_upper_terminus_type_from_pose_residue(cys,1); remove_lower_terminus_type_from_pose_residue(ala,1); remove_upper_terminus_type_from_pose_residue(ala,1); // add_variant_type_to_pose_residue(cys,"DISULF_PARTNER",1); for(Size ih = 1; ih <= h.size(); ++ih) { Hit & hit(h[ih]); if(!hit.sym) continue; Mat R2 = rotation_matrix_degrees(hit.axs,180.0); Mat R3a = rotation_matrix_degrees(Vec(0,0,1), 120.0); Mat R3b = rotation_matrix_degrees(Vec(0,0,1),-120.0); Mat R3[3]; R3[0] = Mat::identity(); R3[1] = R3a; R3[2] = R3b; Pose psym; Size allcnt = 0; for(Size jh = 1; jh <= allh.size(); ++jh) if(allh[jh].rsd==hit.rsd) allcnt++; TR << "Real hit " << hit.rsd << ", alt. cfg. " << allcnt << std::endl; for(Size i3a = 0; i3a < 3; i3a++) { Pose tmp(p); tmp.replace_residue(hit.rsd,ala.residue(1),true); //tmp.set_chi(1,hit.rsd,hit.chi1); //tmp.set_chi(2,hit.rsd,hit.chi2); rot_pose(tmp,R3[i3a]); psym.append_residue_by_jump(tmp.residue(1),1); for(Size ir = 2; ir <= tmp.n_residue(); ++ir) psym.append_residue_by_bond(tmp.residue(ir)); } string d = "./"; if( option[out::file::o].user() ) d = option[out::file::o]()+"/"; string tag = utility::file_basename(fn) +"_"+ lzs(hit.rsd,3) +"_"+ lzs(ih,5); //psym.dump_pdb("test0.pdb"); trans_pose(psym,-hit.cen); alignaxis(psym,Vec(0,0,1),hit.axs); core::pose::symmetry::make_symmetric_pose(psym); ScoreFunctionOP sf = core::scoring::getScoreFunction(); //psym.dump_pdb(tag+"_0.pdb"); design( psym, sf, 3*p.n_residue() ); Real Sd = sf->score(psym); repack_all(psym,sf,3*p.n_residue() ); //psym.dump_pdb("test1.pdb"); Real Si = sf->score(psym); core::kinematics::Jump j = psym.jump(5); Vec t0 = j.get_translation(); j.set_translation( Vec(999,999,999) ); psym.set_jump(5,j); repack_all(psym,sf,3*p.n_residue() ); Real S0 = sf->score(psym); //TR << "ddG " << tag << " " << Sd << " " << Si << " " << S0 << " " << Si - S0 << std::endl; j.set_translation(t0); psym.set_jump(5,j); if( Si - S0 > 0.0 ) continue; vector1<Real> altsc; Real bestalt = -9e9; for(Size jh = 1; jh <= allh.size(); ++jh) { if( allh[jh].rsd == hit.rsd ) { if( allh[jh].axs.dot(hit.axs) > 0.99 && allh[jh].cen.distance_squared(hit.cen) < 0.5 ) continue; Pose pasm; core::pose::symmetry::extract_asymmetric_unit(psym,pasm); alignaxis (pasm,h[ih].axs,Vec(0,0,1),Vec(0,0,0)); trans_pose(pasm,h[ih].cen-allh[jh].cen); alignaxis (pasm,Vec(0,0,1),allh[jh].axs,Vec(0,0,0)); core::pose::symmetry::make_symmetric_pose(pasm); repack_all(pasm,sf,3*p.n_residue() ); Real tmp = Si - sf->score(pasm); altsc.push_back( sf->score(pasm) ); //TR << "DSF_BOLTZ " << tmp << std::endl; if( tmp > bestalt) bestalt = tmp; //if(tmp > 0) { //pasm.dump_pdb("test2.pdb"); //utility_exit_with_message("arst"); //} } } if( bestalt > 0.0 ) continue; TR << "ddG " << tag << " " << Sd << " " << Si << " " << S0 << " " << Si - S0 << " bestalt: " << bestalt << std::endl; core::io::silent::SilentStructOP ss_out_all( new core::io::silent::ScoreFileSilentStruct ); ss_out_all->fill_struct(psym,tag); ss_out_all->add_energy( "bind", Si-S0 ); ss_out_all->add_energy( "dsfalt", bestalt ); sfd.write_silent_struct( *ss_out_all, d+utility::file_basename(fn)+".sc" ); dumpsym(p,R2,R3a,R3b,hit.cen,d+tag+"_xtal.pdb"); psym.replace_residue(hit.rsd,cys.residue(1),true); psym.set_chi(1,hit.rsd,hit.chi1); psym.set_chi(2,hit.rsd,hit.chi2); core::pose::symmetry::make_asymmetric_pose(psym); alignaxis(psym,hit.axs,Vec(0,0,1)); trans_pose(psym,hit.cen); psym.dump_pdb(d+tag+".pdb"); //utility_exit_with_message("arst"); //for(Syize jh = 1; jh <= h.size(); ++jh) { //if( ih == //} // rot_pose(psym,Vec(0,0,1),180); //psym.dump_pdb(tag+"_2.pdb"); } } int main (int argc, char *argv[]) { core::init(argc,argv); using namespace basic::options::OptionKeys; for(Size ifn = 1; ifn <= option[in::file::s]().size(); ++ifn) { string fn = option[in::file::s]()[ifn]; Pose pnat; core::import_pose::pose_from_pdb(pnat,fn); if( pnat.n_residue() > 300 ) continue; for(Size ir = 2; ir <= pnat.n_residue()-1; ++ir) { if(!pnat.residue(ir).is_protein()) goto cont1; if(pnat.residue(ir).is_lower_terminus()) goto cont1; if(pnat.residue(ir).is_upper_terminus()) goto cont1; if(pnat.residue(ir).name3()=="CYS") goto cont1; } goto done1; cont1: TR << "skipping " << fn << std::endl; continue; done1: //continue; Pose pala(pnat); std::pair<vector1<Hit>,vector1<Hit> > hts = dock(pala,fn); design_hits(pnat,fn,hts.first,hts.second); } }
[ "will@sheffler.me" ]
will@sheffler.me
3ab03dca868233f04e7d0c0565097b9dc42dd1ab
ebac0e7cfa81ee591bcf7cea465947ec778c7fd6
/sty/pp.cc
cd59356feeff556dd1ec7c986ca136e0b48be258
[ "Apache-2.0" ]
permissive
zhangruichang/Asenal
76f4dc78c65d504f0e91cb0685dff8bbbd9b70ac
9e58f61e0e74ff7a6156587cc7fcb00355be252a
refs/heads/master
2021-01-23T15:16:21.874701
2017-05-23T16:01:39
2017-05-23T16:01:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,379
cc
#include <iostream> #include <cstdio> #include <algorithm> #include <cstring> #include <string> #include <cmath> #include <vector> #include <queue> #include <map> #include <ctime> #include <set> #include <cstdlib> #include "xdebug.h" typedef long long lld; using namespace std; #ifdef DEBUG #define debug(x) cout<<__LINE__<<" "<<#x<<"="<<x<<endl; #else #define debug(x) #endif #define here cout<<__LINE__<< " " << "_______________here" <<endl; #define clr(NAME,VALUE) memset(NAME,VALUE,sizeof(NAME)) #define MAX 0x7f7f7f7f #define N 2000 #define PRIME 999983 struct node { int r, ii, iv; }res[N]; int max_len = 0; int step = 400; int main(int argc, char **argv) { string fname = argv[1]; clr(res, 0); for (int j = 0; j < 100; j++) { char cname[100]; snprintf(cname, sizeof(cname), "%s%d", fname.c_str(), j); freopen(cname, "r", stdin); string tmp; getline(std::cin, tmp); int a, b, c, d; int i = 0; while (scanf("%d\t%d\t%d\t%d", &a, &b, &c, &d) != EOF) { res[i].r += b; res[i].ii += c; res[i].iv += d; i++; max_len = max(max_len, i); } while (i < step) { res[i].r += b; res[i].ii += c; res[i].iv += d; i++; } } for (int i = 0; i < max_len; i++) { printf("%d\t%d\t%d\t%d\n", i, res[i].r / 100, res[i].ii / 100, res[i].iv / 100); } return 0; }
[ "baotiao@gmail.com" ]
baotiao@gmail.com
2fea55f2e0493d7fdc442462be4b54cecc12bb34
fae8d039fcc05b986c5771901834deee1aa3b916
/BOJ/BruteFroce/2503. 숫자 야구.cpp
f92dca4ec7bea89a25225117c7e8c63cebe2ba6a
[]
no_license
eastgerm/eastgerm-algo
558ce3dd7fa7bbf51ffe9210197a76e947afb634
3b4552e2dff860345ffabd6ffa6ab07bab968634
refs/heads/master
2020-09-02T16:44:14.273204
2020-05-12T10:35:20
2020-05-12T10:35:20
219,261,135
1
0
null
null
null
null
UTF-8
C++
false
false
1,600
cpp
// // Created by kimdong on 2019-06-24. // #include <iostream> #include <vector> using namespace std; int T; int N,S,B; vector<int> nums; void inputT(); void input(); bool baseball(int target, int value); void check(); void output(); int main() { ios::sync_with_stdio(false), cin.tie(NULL); inputT(); for(int tc=0; tc<T; tc++) { input(); check(); } output(); return 0; } void inputT() { cin >> T; for(int i=100; i<=999; i++) { int n1 = i/100, n2 = i/10 - 10*n1, n3 = i%10; if(n1 && n2 && n3 && n1 != n2 && n2 != n3 && n3 != n1) nums.push_back(i); } } void input() { cin >> N >> S >> B; } bool baseball(int target, int value) { int strike = 0, ball = 0; int t1 = target/100, t2 = target/10 - 10*t1, t3 = target%10; int v1 = value/100, v2 = value/10 - 10*v1, v3 = value%10; bool poss1 = true, poss2 = true, poss3 = true; if(t1 == v1) strike++, poss1 = false; if(t2 == v2) strike++, poss2 = false; if(t3 == v3) strike++, poss3 = false; vector<int> digit(10,0); if(poss1) digit[t1] += 10, digit[v1] += 1; if(poss2) digit[t2] += 10, digit[v2] += 1; if(poss3) digit[t3] += 10, digit[v3] += 1; for(int i=1; i<=9; i++) { int n1 = digit[i]/10, n2 = digit[i]%10; if(n1 && n2) ball += (n1 < n2 ? n1 : n2); } return strike == S && ball == B; } void check() { vector<int> temp = nums; nums.clear(); int len = temp.size(); for(int i=0; i<len; i++) if(baseball(N,temp[i])) nums.push_back(temp[i]); } void output() { cout << nums.size() << '\n'; }
[ "dowk0331@gmail.com" ]
dowk0331@gmail.com
646997c00d57ef8bab4e46dfedb5dc804179073b
502f965de13cf5cd92e885185d8943957d0d03db
/modules/ocl/cv_base_class.h
b7e9999e19f88b7601d9a97601f5fe4b09cd8d04
[ "Apache-2.0" ]
permissive
JosephTsai75/libxcam
0ceefdacb30f4dd14235afce336cf43d0e76663f
e06c745d4a88fe4a59e7fa1bc7a0c7c024f79fca
refs/heads/master
2021-07-05T06:40:48.688521
2017-09-30T06:22:46
2017-09-30T07:20:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,622
h
/* * cv_base_class.h - base class for all OpenCV related features * * Copyright (c) 2016-2017 Intel Corporation * * 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. * * Author: Andrey Parfenov <a1994ndrey@gmail.com> * Author: Wind Yuan <feng.yuan@intel.com> */ #ifndef XCAM_CV_BASE_CLASS_H #define XCAM_CV_BASE_CLASS_H #include "cl_utils.h" #include <base/xcam_common.h> #include <base/xcam_buffer.h> #include <dma_video_buffer.h> #include <smartptr.h> #include "xcam_obj_debug.h" #include "image_file_handle.h" #include "cv_context.h" #include <ocl/cl_context.h> #include <ocl/cl_device.h> #include <ocl/cl_memory.h> #include <opencv2/opencv.hpp> #include <opencv2/core/ocl.hpp> namespace XCam { class CVBaseClass { public: explicit CVBaseClass (); void set_ocl (bool use_ocl) { _use_ocl = use_ocl; } bool is_ocl_path () { return _use_ocl; } bool convert_to_mat (SmartPtr<VideoBuffer> buffer, cv::Mat &image); protected: XCAM_DEAD_COPY (CVBaseClass); SmartPtr<CLContext> _context; bool _use_ocl; }; } #endif // XCAM_CV_BASE_CLASS_H
[ "feng.yuan@intel.com" ]
feng.yuan@intel.com
600441c296b8c7666b81547c71bbcf2ad7d92c85
b28305dab0be0e03765c62b97bcd7f49a4f8073d
/chrome/browser/ui/views/nav_button_provider.h
50f3f2b22c23bac733549caef062ea16560a9436
[ "BSD-3-Clause" ]
permissive
svarvel/browser-android-tabs
9e5e27e0a6e302a12fe784ca06123e5ce090ced5
bd198b4c7a1aca2f3e91f33005d881f42a8d0c3f
refs/heads/base-72.0.3626.105
2020-04-24T12:16:31.442851
2019-08-02T19:15:36
2019-08-02T19:15:36
171,950,555
1
2
NOASSERTION
2019-08-02T19:15:37
2019-02-21T21:47:44
null
UTF-8
C++
false
false
1,998
h
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_UI_VIEWS_NAV_BUTTON_PROVIDER_H_ #define CHROME_BROWSER_UI_VIEWS_NAV_BUTTON_PROVIDER_H_ #include "build/buildflag.h" #include "ui/views/controls/button/button.h" #include "ui/views/features.h" #if !BUILDFLAG(ENABLE_NATIVE_WINDOW_NAV_BUTTONS) #error "Include not allowed." #endif namespace chrome { enum class FrameButtonDisplayType; } namespace gfx { class ImageSkia; class Insets; } // namespace gfx namespace views { class NavButtonProvider { public: virtual ~NavButtonProvider() {} // Redraws all images and updates all size state. |top_area_height| // is the total available height to render the buttons, and buttons // may be drawn larger when more height is available. |active| // indicates if the window the buttons reside in has activation. virtual void RedrawImages(int top_area_height, bool maximized, bool active) = 0; // Gets the cached button image corresponding to |type| and |state|. virtual gfx::ImageSkia GetImage(chrome::FrameButtonDisplayType type, views::Button::ButtonState state) const = 0; // Gets the external margin around each button. The left inset // represents the leading margin, and the right inset represents the // trailing margin. virtual gfx::Insets GetNavButtonMargin( chrome::FrameButtonDisplayType type) const = 0; // Gets the internal spacing (padding + border) of the top area. // The left inset represents the leading spacing, and the right // inset represents the trailing spacing. virtual gfx::Insets GetTopAreaSpacing() const = 0; // Gets the spacing to be used to separate buttons. virtual int GetInterNavButtonSpacing() const = 0; }; } // namespace views #endif // CHROME_BROWSER_UI_VIEWS_NAV_BUTTON_PROVIDER_H_
[ "artem@brave.com" ]
artem@brave.com
a43e510b9fe638099a1821821c70a34ecfb269ae
90aeda1b0f5308c5327801702193a39c692a0485
/YP/labwork_3/project_3/main.cpp
2164f1889a0ab8399aeeec50b2b968c5b7b701fa
[]
no_license
OlshOlga/MyRepo
7ca6d70a657e3d5d9c856920152643743ec500c4
69cedf4e86427bbdd92ade93f500f02302647182
refs/heads/master
2020-05-14T09:07:48.668758
2019-06-18T14:11:58
2019-06-18T14:11:58
181,734,587
0
0
null
null
null
null
UTF-8
C++
false
false
1,459
cpp
/* Программа для подсчта количества цифр, букв и прочих символов. * Язык программирования: С++ * Автор: Ольшевская О.И., гр. 18ПИ1 */ #include <iostream> #include <string> #include <cctype> using namespace std; int main() { int i, j, l, len = 0, tz = 0, byk= 0, sim = 0; string s[] = {"deb http://mirror.mephi.ru/debian/ stretch main contrib non-free", "deb-src http://mirror.mephi.ru/debian/ stretch main contrib non-free", "deb http://security.debian.org/ stretch/updates main contrib non-free","deb-src http://security.debian.org/ stretch/updates main contrib non-free","deb http://mirror.mephi.ru/debian/ stretch-updates main contrib non-free","deb-src http://mirror.mephi.ru/debian/ stretch-updates main contrib non-free","deb http://mirror.mephi.ru/debian stretch-backports main contrib non-free", "deb-src http://mirror.mephi.ru/debian stretch-backports main contrib non-free"}; for (i=0; i < 8; i++) { l = s[i].size(); for (j=0; j<l; j++) { if (isdigit(s[i][j])) { tz = tz +1; } else if (isalpha(s[i][j])) { byk = byk +1; } else if (ispunct(s[i][j])) { sim = sim +1; } } len = len + tz; } cout << "Длина текста: " << len << endl; cout << "Кол-во цифр: " << tz << endl; cout << "Кол-во букв: " << byk << endl; cout << "Кол-во символов: " << sim << endl; return 0; }
[ "lelya.ol.28@mail.ru" ]
lelya.ol.28@mail.ru
f72d53f6a0ac6134e866cad6c0b5503e4032cbbd
fa74435c33c7c2387b82b214d1bc7a9308557dca
/MotorController/include/encoder.h
e065367c28bf7087c4d742a341f9fb05c403d43e
[]
no_license
munsailbot/munsailbot
34f232f3e63ecc1f3edc8833b890a7f4c6ecaaee
5caad0fb46ef380cb0f4a84fbd71540a29374f20
refs/heads/master
2020-05-21T04:45:01.561250
2018-06-16T21:13:36
2018-06-16T21:13:36
43,016,839
2
2
null
2017-10-20T17:12:13
2015-09-23T17:42:07
C
UTF-8
C++
false
false
545
h
/* * encoder.h * * Created on: 2010-06-15 * Author: brianclaus */ #ifndef ENCODER_H_ #define ENCODER_H_ #include <Arduino.h> #include <avr/io.h> #include <avr/interrupt.h> #include "common.h" class Encoder{ int pinCHA; int pinCHB; int direction; long position; int pinCHAlast; int pinCHBlast; int error; public: void init(); Encoder(int,int,int); Encoder(); long getPosition(void); void setPosition(int); int getDirection(void); int getErrors(void); void encoderISR(void); ~Encoder(); }; #endif /* ENCODER_H_ */
[ "bryan@okplus.ca" ]
bryan@okplus.ca
d1c8f79acd2ebde5b4a28bf18a9cacbc123a5901
4536dfb68a78f1e7e48f46387abf0c0108ff001c
/massageTechniques.h
038e38d10208d0dcc21abd0a84fc28c7c1cd3de3
[]
no_license
HenryFOCUS/Massage-Robot
3755cf7d8e795aedaefb4408ce24993bc5acf3b6
b3f3a34b321136eb29830241f04cb492f4487dfd
refs/heads/master
2021-11-23T02:36:29.597884
2017-05-04T14:15:07
2017-05-04T14:15:07
null
0
0
null
null
null
null
BIG5
C++
false
false
878
h
#include "SystemParameter.h" #include "tcp6D.h" #include "jointSpace.h" class massageTechniques { public: Eigen::Vector3d cornerPosition[2][2]; Eigen::Vector3d massagePosition[2][5]; Eigen::Vector3d viaPosition[2]; Eigen::Vector3d virtualPoint[2]; massageTechniques(); void teachMotion(Eigen::Vector3d &currentPosR,Eigen::Vector3d &currentPosL,char &jKey , int &Control_Mode); //教stroking的動作,順便記錄最上和最下的點然後內插 void Pressing(Eigen::Vector3d &targetPosR,Eigen::Vector3d &targetPosL, int &Control_Mode, int &timeIndex); void Rubbing(Eigen::Vector3d &targetPosR,Eigen::Vector3d &targetPosL, int &Control_Mode); void Stroking(Eigen::Vector3d &targetPosR,Eigen::Vector3d &targetPosL, int &Control_Mode,char &jKey,bool &jointPlayDone); void teachPosition_for_tapping(); // cp void play_tapping(); // cp };
[ "noreply@github.com" ]
noreply@github.com
fca8cb1081e268983162e7be1a248f214e1ed75b
bb6ebff7a7f6140903d37905c350954ff6599091
/v8/src/codegen.cc
c039e40c93317668b25bed72c6c743a4e40abba7
[ "BSD-3-Clause", "bzip2-1.0.6" ]
permissive
PDi-Communication-Systems-Inc/lollipop_external_chromium_org
faa6602bd6bfd9b9b6277ce3cd16df0bd26e7f2f
ccadf4e63dd34be157281f53fe213d09a8c66d2c
refs/heads/master
2022-12-23T18:07:04.568931
2016-04-11T16:03:36
2016-04-11T16:03:36
53,677,925
0
1
BSD-3-Clause
2022-12-09T23:46:46
2016-03-11T15:49:07
C++
UTF-8
C++
false
false
8,193
cc
// Copyright 2012 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/v8.h" #include "src/bootstrapper.h" #include "src/codegen.h" #include "src/compiler.h" #include "src/cpu-profiler.h" #include "src/debug.h" #include "src/prettyprinter.h" #include "src/rewriter.h" #include "src/runtime.h" #include "src/stub-cache.h" namespace v8 { namespace internal { #if defined(_WIN64) typedef double (*ModuloFunction)(double, double); static ModuloFunction modulo_function = NULL; // Defined in codegen-x64.cc. ModuloFunction CreateModuloFunction(); void init_modulo_function() { modulo_function = CreateModuloFunction(); } double modulo(double x, double y) { // Note: here we rely on dependent reads being ordered. This is true // on all architectures we currently support. return (*modulo_function)(x, y); } #elif defined(_WIN32) double modulo(double x, double y) { // Workaround MS fmod bugs. ECMA-262 says: // dividend is finite and divisor is an infinity => result equals dividend // dividend is a zero and divisor is nonzero finite => result equals dividend if (!(std::isfinite(x) && (!std::isfinite(y) && !std::isnan(y))) && !(x == 0 && (y != 0 && std::isfinite(y)))) { x = fmod(x, y); } return x; } #else // POSIX double modulo(double x, double y) { return std::fmod(x, y); } #endif // defined(_WIN64) #define UNARY_MATH_FUNCTION(name, generator) \ static UnaryMathFunction fast_##name##_function = NULL; \ void init_fast_##name##_function() { \ fast_##name##_function = generator; \ } \ double fast_##name(double x) { \ return (*fast_##name##_function)(x); \ } UNARY_MATH_FUNCTION(exp, CreateExpFunction()) UNARY_MATH_FUNCTION(sqrt, CreateSqrtFunction()) #undef UNARY_MATH_FUNCTION void lazily_initialize_fast_exp() { if (fast_exp_function == NULL) { init_fast_exp_function(); } } #define __ ACCESS_MASM(masm_) #ifdef DEBUG Comment::Comment(MacroAssembler* masm, const char* msg) : masm_(masm), msg_(msg) { __ RecordComment(msg); } Comment::~Comment() { if (msg_[0] == '[') __ RecordComment("]"); } #endif // DEBUG #undef __ void CodeGenerator::MakeCodePrologue(CompilationInfo* info, const char* kind) { bool print_source = false; bool print_ast = false; const char* ftype; if (info->isolate()->bootstrapper()->IsActive()) { print_source = FLAG_print_builtin_source; print_ast = FLAG_print_builtin_ast; ftype = "builtin"; } else { print_source = FLAG_print_source; print_ast = FLAG_print_ast; ftype = "user-defined"; } if (FLAG_trace_codegen || print_source || print_ast) { PrintF("[generating %s code for %s function: ", kind, ftype); if (info->IsStub()) { const char* name = CodeStub::MajorName(info->code_stub()->MajorKey(), true); PrintF("%s", name == NULL ? "<unknown>" : name); } else { PrintF("%s", info->function()->debug_name()->ToCString().get()); } PrintF("]\n"); } #ifdef DEBUG if (!info->IsStub() && print_source) { PrintF("--- Source from AST ---\n%s\n", PrettyPrinter(info->zone()).PrintProgram(info->function())); } if (!info->IsStub() && print_ast) { PrintF("--- AST ---\n%s\n", AstPrinter(info->zone()).PrintProgram(info->function())); } #endif // DEBUG } Handle<Code> CodeGenerator::MakeCodeEpilogue(MacroAssembler* masm, Code::Flags flags, CompilationInfo* info) { Isolate* isolate = info->isolate(); // Allocate and install the code. CodeDesc desc; bool is_crankshafted = Code::ExtractKindFromFlags(flags) == Code::OPTIMIZED_FUNCTION || info->IsStub(); masm->GetCode(&desc); Handle<Code> code = isolate->factory()->NewCode(desc, flags, masm->CodeObject(), false, is_crankshafted, info->prologue_offset(), info->is_debug() && !is_crankshafted); isolate->counters()->total_compiled_code_size()->Increment( code->instruction_size()); isolate->heap()->IncrementCodeGeneratedBytes(is_crankshafted, code->instruction_size()); return code; } void CodeGenerator::PrintCode(Handle<Code> code, CompilationInfo* info) { #ifdef ENABLE_DISASSEMBLER AllowDeferredHandleDereference allow_deference_for_print_code; bool print_code = info->isolate()->bootstrapper()->IsActive() ? FLAG_print_builtin_code : (FLAG_print_code || (info->IsStub() && FLAG_print_code_stubs) || (info->IsOptimizing() && FLAG_print_opt_code)); if (print_code) { // Print the source code if available. FunctionLiteral* function = info->function(); bool print_source = code->kind() == Code::OPTIMIZED_FUNCTION || code->kind() == Code::FUNCTION; CodeTracer::Scope tracing_scope(info->isolate()->GetCodeTracer()); if (print_source) { Handle<Script> script = info->script(); if (!script->IsUndefined() && !script->source()->IsUndefined()) { PrintF(tracing_scope.file(), "--- Raw source ---\n"); ConsStringIteratorOp op; StringCharacterStream stream(String::cast(script->source()), &op, function->start_position()); // fun->end_position() points to the last character in the stream. We // need to compensate by adding one to calculate the length. int source_len = function->end_position() - function->start_position() + 1; for (int i = 0; i < source_len; i++) { if (stream.HasMore()) { PrintF(tracing_scope.file(), "%c", stream.GetNext()); } } PrintF(tracing_scope.file(), "\n\n"); } } if (info->IsOptimizing()) { if (FLAG_print_unopt_code) { PrintF(tracing_scope.file(), "--- Unoptimized code ---\n"); info->closure()->shared()->code()->Disassemble( function->debug_name()->ToCString().get(), tracing_scope.file()); } PrintF(tracing_scope.file(), "--- Optimized code ---\n"); PrintF(tracing_scope.file(), "optimization_id = %d\n", info->optimization_id()); } else { PrintF(tracing_scope.file(), "--- Code ---\n"); } if (print_source) { PrintF(tracing_scope.file(), "source_position = %d\n", function->start_position()); } if (info->IsStub()) { CodeStub::Major major_key = info->code_stub()->MajorKey(); code->Disassemble(CodeStub::MajorName(major_key, false), tracing_scope.file()); } else { code->Disassemble(function->debug_name()->ToCString().get(), tracing_scope.file()); } PrintF(tracing_scope.file(), "--- End code ---\n"); } #endif // ENABLE_DISASSEMBLER } bool CodeGenerator::RecordPositions(MacroAssembler* masm, int pos, bool right_here) { if (pos != RelocInfo::kNoPosition) { masm->positions_recorder()->RecordStatementPosition(pos); masm->positions_recorder()->RecordPosition(pos); if (right_here) { return masm->positions_recorder()->WriteRecordedPositions(); } } return false; } void ArgumentsAccessStub::Generate(MacroAssembler* masm) { switch (type_) { case READ_ELEMENT: GenerateReadElement(masm); break; case NEW_SLOPPY_FAST: GenerateNewSloppyFast(masm); break; case NEW_SLOPPY_SLOW: GenerateNewSloppySlow(masm); break; case NEW_STRICT: GenerateNewStrict(masm); break; } } int CEntryStub::MinorKey() { int result = (save_doubles_ == kSaveFPRegs) ? 1 : 0; ASSERT(result_size_ == 1 || result_size_ == 2); #ifdef _WIN64 return result | ((result_size_ == 1) ? 0 : 2); #else return result; #endif } } } // namespace v8::internal
[ "mrobbeloth@pdiarm.com" ]
mrobbeloth@pdiarm.com
a8be7bf20483fda0817e1c16fc4b89f89922ac14
a92b18defb50c5d1118a11bc364f17b148312028
/src/prod/src/Management/ClusterManager/StoreDataServiceManifest.h
17036dfb2609f259132b07d80dff67eeb735a023
[ "MIT" ]
permissive
KDSBest/service-fabric
34694e150fde662286e25f048fb763c97606382e
fe61c45b15a30fb089ad891c68c893b3a976e404
refs/heads/master
2023-01-28T23:19:25.040275
2020-11-30T11:11:58
2020-11-30T11:11:58
301,365,601
1
0
MIT
2020-11-30T11:11:59
2020-10-05T10:05:53
null
UTF-8
C++
false
false
2,545
h
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #pragma once namespace Management { namespace ClusterManager { class StoreDataServiceManifest : public Store::StoreData { public: StoreDataServiceManifest(); StoreDataServiceManifest( ServiceModelTypeName const &, ServiceModelVersion const &); StoreDataServiceManifest( ServiceModelTypeName const &, ServiceModelVersion const &, std::vector<ServiceModelServiceManifestDescription> && ); void TrimDuplicateManifestsAndPackages(std::vector<StoreDataServiceManifest> const &); std::wstring GetTypeNameKeyPrefix() const; __declspec (property(get=get_Type)) std::wstring const & Type; virtual std::wstring const & get_Type() const; virtual void WriteTo(Common::TextWriter & w, Common::FormatOptions const &) const; __declspec(property(get=get_ApplicationTypeName)) ServiceModelTypeName const & ApplicationTypeName; ServiceModelTypeName const & get_ApplicationTypeName() const { return applicationTypeName_; } __declspec(property(get=get_ApplicationTypeVersion)) ServiceModelVersion const & ApplicationTypeVersion; ServiceModelVersion const & get_ApplicationTypeVersion() const { return applicationTypeVersion_; } __declspec(property(put=set_ServiceManifests, get=get_ServiceManifests)) std::vector<ServiceModelServiceManifestDescription> const & ServiceManifests; std::vector<ServiceModelServiceManifestDescription> const & get_ServiceManifests() const { return serviceManifests_; } void set_ServiceManifests(std::vector<ServiceModelServiceManifestDescription> const && manifests) { serviceManifests_ = move(manifests); } FABRIC_FIELDS_03(applicationTypeName_, applicationTypeVersion_, serviceManifests_); protected: virtual std::wstring ConstructKey() const; private: ServiceModelTypeName applicationTypeName_; ServiceModelVersion applicationTypeVersion_; std::vector<ServiceModelServiceManifestDescription> serviceManifests_; }; } }
[ "noreply-sfteam@microsoft.com" ]
noreply-sfteam@microsoft.com
b624ea927a29f62db1cc9885245bd6a0ca2839d2
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_2755486_0/C++/bilbo/C-small.cpp
c8870e30d1799aa618f8163f18707081ce1e9ecf
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
11,921
cpp
#include <vector> #include <list> #include <map> #include <set> #include <deque> #include <queue> #include <stack> #include <bitset> #include <algorithm> #include <functional> #include <numeric> #include <utility> #include <sstream> #include <iostream> #include <iomanip> #include <cstdio> #include <cmath> #include <cstdlib> #include <cctype> #include <string> #include <cstring> #include <cstdio> #include <cmath> #include <cstdlib> #include <ctime> #include <string.h> #include <tuple> using namespace std; //BEGINTEMPLATE_BY_ACRUSH_TOPCODER #define SIZE(X) ((int)(X.size()))//NOTES:SIZE( #define LENGTH(X) ((int)(X.length()))//NOTES:LENGTH( #define MP(X,Y) make_pair(X,Y)//NOTES:MP( typedef long long int64;//NOTES:int64 typedef unsigned long long uint64;//NOTES:uint64 #define two(X) (1<<(X))//NOTES:two( #define twoL(X) (((int64)(1))<<(X))//NOTES:twoL( #define contain(S,X) (((S)&two(X))!=0)//NOTES:contain( #define containL(S,X) (((S)&twoL(X))!=0)//NOTES:containL( const double pi=acos(-1.0);//NOTES:pi const double eps=1e-11;//NOTES:eps template<class T> inline void swapval(T &a,T &b){a=(a=a+b)-(b=a-b);} template<class T> inline bool checkmin(T &a,T b){if(b<a) {a=b;return true;}return false;}//NOTES:checkmin( template<class T> inline bool checkmax(T &a,T b){if(b>a) {a=b;return true;}return false;}//NOTES:checkmax( template<class T> inline T sqr(T x){return x*x;}//NOTES:sqr typedef pair<int,int> ipair;//NOTES:ipair template<class T> inline T lowbit(T n){return (n^(n-1))&n;}//NOTES:lowbit( template<class T> inline int countbit(T n){return (n==0)?0:(1+countbit(n&(n-1)));}//NOTES:countbit( //Numberic Functions template<class T> inline T gcd(T a,T b)//NOTES:gcd( {if(a<0)return gcd(-a,b);if(b<0)return gcd(a,-b);return (b==0)?a:gcd(b,a%b);} template<class T> inline T lcm(T a,T b)//NOTES:lcm( {if(a<0)return lcm(-a,b);if(b<0)return lcm(a,-b);return a*(b/gcd(a,b));} template<class T> inline T euclide(T a,T b,T &x,T &y)//NOTES:euclide( {if(a<0){T d=euclide(-a,b,x,y);x=-x;return d;} if(b<0){T d=euclide(a,-b,x,y);y=-y;return d;} if(b==0){x=1;y=0;return a;}else{T d=euclide(b,a%b,x,y);T t=x;x=y;y=t-(a/b)*y;return d;}} template<class T> inline vector<pair<T,int> > factorize(T n)//NOTES:factorize( {vector<pair<T,int> > R;for (T i=2;n>1;){if (n%i==0){int C=0;for (;n%i==0;C++,n/=i);R.push_back(make_pair(i,C));} i++;if (i>n/i) i=n;}if (n>1) R.push_back(make_pair(n,1));return R;} template<class T> inline bool isPrimeNumber(T n)//NOTES:isPrimeNumber( {if(n<=1)return false;for (T i=2;i*i<=n;i++) if (n%i==0) return false;return true;} template<class T> inline T eularFunction(T n)//NOTES:eularFunction( {vector<pair<T,int> > R=factorize(n);T r=n;for (int i=0;i<R.size();i++)r=r/R[i].first*(R[i].first-1);return r;} //Matrix Operations const int MaxMatrixSize=40;//NOTES:MaxMatrixSize template<class T> inline void showMatrix(int n,T A[MaxMatrixSize][MaxMatrixSize])//NOTES:showMatrix( {for (int i=0;i<n;i++){for (int j=0;j<n;j++)cout<<A[i][j];cout<<endl;}} template<class T> inline T checkMod(T n,T m) {return (n%m+m)%m;}//NOTES:checkMod( template<class T> inline void identityMatrix(int n,T A[MaxMatrixSize][MaxMatrixSize])//NOTES:identityMatrix( {for (int i=0;i<n;i++) for (int j=0;j<n;j++) A[i][j]=(i==j)?1:0;} template<class T> inline void addMatrix(int n,T C[MaxMatrixSize][MaxMatrixSize],T A[MaxMatrixSize][MaxMatrixSize],T B[MaxMatrixSize][MaxMatrixSize])//NOTES:addMatrix( {for (int i=0;i<n;i++) for (int j=0;j<n;j++) C[i][j]=A[i][j]+B[i][j];} template<class T> inline void subMatrix(int n,T C[MaxMatrixSize][MaxMatrixSize],T A[MaxMatrixSize][MaxMatrixSize],T B[MaxMatrixSize][MaxMatrixSize])//NOTES:subMatrix( {for (int i=0;i<n;i++) for (int j=0;j<n;j++) C[i][j]=A[i][j]-B[i][j];} template<class T> inline void mulMatrix(int n,T C[MaxMatrixSize][MaxMatrixSize],T _A[MaxMatrixSize][MaxMatrixSize],T _B[MaxMatrixSize][MaxMatrixSize])//NOTES:mulMatrix( { T A[MaxMatrixSize][MaxMatrixSize],B[MaxMatrixSize][MaxMatrixSize]; for (int i=0;i<n;i++) for (int j=0;j<n;j++) A[i][j]=_A[i][j],B[i][j]=_B[i][j],C[i][j]=0; for (int i=0;i<n;i++) for (int j=0;j<n;j++) for (int k=0;k<n;k++) C[i][j]+=A[i][k]*B[k][j];} template<class T> inline void addModMatrix(int n,T m,T C[MaxMatrixSize][MaxMatrixSize],T A[MaxMatrixSize][MaxMatrixSize],T B[MaxMatrixSize][MaxMatrixSize])//NOTES:addModMatrix( {for (int i=0;i<n;i++) for (int j=0;j<n;j++) C[i][j]=checkMod(A[i][j]+B[i][j],m);} template<class T> inline void subModMatrix(int n,T m,T C[MaxMatrixSize][MaxMatrixSize],T A[MaxMatrixSize][MaxMatrixSize],T B[MaxMatrixSize][MaxMatrixSize])//NOTES:subModMatrix( {for (int i=0;i<n;i++) for (int j=0;j<n;j++) C[i][j]=checkMod(A[i][j]-B[i][j],m);} template<class T> inline T multiplyMod(T a,T b,T m) {return (T)((((int64)(a)*(int64)(b)%(int64)(m))+(int64)(m))%(int64)(m));}//NOTES:multiplyMod( template<class T> inline void mulModMatrix(int n,T m,T C[MaxMatrixSize][MaxMatrixSize],T _A[MaxMatrixSize][MaxMatrixSize],T _B[MaxMatrixSize][MaxMatrixSize])//NOTES:mulModMatrix( { T A[MaxMatrixSize][MaxMatrixSize],B[MaxMatrixSize][MaxMatrixSize]; for (int i=0;i<n;i++) for (int j=0;j<n;j++) A[i][j]=_A[i][j],B[i][j]=_B[i][j],C[i][j]=0; for (int i=0;i<n;i++) for (int j=0;j<n;j++) for (int k=0;k<n;k++) C[i][j]=(C[i][j]+multiplyMod(A[i][k],B[k][j],m))%m;} template<class T> inline T powerMod(T p,int e,T m)//NOTES:powerMod( {if(e==0)return 1%m;else if(e%2==0){T t=powerMod(p,e/2,m);return multiplyMod(t,t,m);}else return multiplyMod(powerMod(p,e-1,m),p,m);} //Point&Line double dist(double x1,double y1,double x2,double y2){return sqrt(sqr(x1-x2)+sqr(y1-y2));}//NOTES:dist( double distR(double x1,double y1,double x2,double y2){return sqr(x1-x2)+sqr(y1-y2);}//NOTES:distR( template<class T> T cross(T x0,T y0,T x1,T y1,T x2,T y2){return (x1-x0)*(y2-y0)-(x2-x0)*(y1-y0);}//NOTES:cross( int crossOper(double x0,double y0,double x1,double y1,double x2,double y2)//NOTES:crossOper( {double t=(x1-x0)*(y2-y0)-(x2-x0)*(y1-y0);if (fabs(t)<=eps) return 0;return (t<0)?-1:1;} bool isIntersect(double x1,double y1,double x2,double y2,double x3,double y3,double x4,double y4)//NOTES:isIntersect( {return crossOper(x1,y1,x2,y2,x3,y3)*crossOper(x1,y1,x2,y2,x4,y4)<0 && crossOper(x3,y3,x4,y4,x1,y1)*crossOper(x3,y3,x4,y4,x2,y2)<0;} bool isMiddle(double s,double m,double t){return fabs(s-m)<=eps || fabs(t-m)<=eps || (s<m)!=(t<m);}//NOTES:isMiddle( //Translator bool isUpperCase(char c){return c>='A' && c<='Z';}//NOTES:isUpperCase( bool isLowerCase(char c){return c>='a' && c<='z';}//NOTES:isLowerCase( bool isLetter(char c){return (c>='A' && c<='Z') || (c>='a' && c<='z');}//NOTES:isLetter( bool isDigit(char c){return c>='0' && c<='9';}//NOTES:isDigit( char toLowerCase(char c){return (isUpperCase(c))?(c+32):c;}//NOTES:toLowerCase( char toUpperCase(char c){return (isLowerCase(c))?(c-32):c;}//NOTES:toUpperCase( template<class T> string toString(T n){ostringstream ost;ost<<n;ost.flush();return ost.str();}//NOTES:toString( int toInt(string s){int r=0;istringstream sin(s);sin>>r;return r;}//NOTES:toInt( int64 toInt64(string s){int64 r=0;istringstream sin(s);sin>>r;return r;}//NOTES:toInt64( double toDouble(string s){double r=0;istringstream sin(s);sin>>r;return r;}//NOTES:toDouble( template<class T> void stoa(string s,int &n,T A[]){n=0;istringstream sin(s);for(T v;sin>>v;A[n++]=v);}//NOTES:stoa( template<class T> void atos(int n,T A[],string &s){ostringstream sout;for(int i=0;i<n;i++){if(i>0)sout<<' ';sout<<A[i];}s=sout.str();}//NOTES:atos( template<class T> void atov(int n,T A[],vector<T> &vi){vi.clear();for (int i=0;i<n;i++) vi.push_back(A[i]);}//NOTES:atov( template<class T> void vtoa(vector<T> vi,int &n,T A[]){n=vi.size();for (int i=0;i<n;i++)A[i]=vi[i];}//NOTES:vtoa( template<class T> void stov(string s,vector<T> &vi){vi.clear();istringstream sin(s);for(T v;sin>>v;vi.push_bakc(v));}//NOTES:stov( template<class T> void vtos(vector<T> vi,string &s){ostringstream sout;for (int i=0;i<vi.size();i++){if(i>0)sout<<' ';sout<<vi[i];}s=sout.str();}//NOTES:vtos( //Fraction template<class T> struct Fraction{T a,b;Fraction(T a=0,T b=1);string toString();};//NOTES:Fraction template<class T> Fraction<T>::Fraction(T a,T b){T d=gcd(a,b);a/=d;b/=d;if (b<0) a=-a,b=-b;this->a=a;this->b=b;} template<class T> string Fraction<T>::toString(){ostringstream sout;sout<<a<<"/"<<b;return sout.str();} template<class T> Fraction<T> operator+(Fraction<T> p,Fraction<T> q){return Fraction<T>(p.a*q.b+q.a*p.b,p.b*q.b);} template<class T> Fraction<T> operator-(Fraction<T> p,Fraction<T> q){return Fraction<T>(p.a*q.b-q.a*p.b,p.b*q.b);} template<class T> Fraction<T> operator*(Fraction<T> p,Fraction<T> q){return Fraction<T>(p.a*q.a,p.b*q.b);} template<class T> Fraction<T> operator/(Fraction<T> p,Fraction<T> q){return Fraction<T>(p.a*q.b,p.b*q.a);} //ENDTEMPLATE_BY_ACRUSH_TOPCODER #define FORN(i, n) for (int i = 0; i < (int)(n); i++) #define FORAB(i, a, b) for (int i = (int)(a); i <= (int)(b); i++) #define FORBA(i, b, a) for (int i = (int)(b); i >= (int)(a); i--) #define FORIT(i, a) for (__typeof((a).begin()) i = (a).begin(); i != (a).end(); i++) #define FORITR(i, a) for (__typeof((a).rbegin()) i = (a).rbegin(); i != (a).rend(); i++) #define WHILEIT(i, a) for (__typeof((a).begin()) i = (a).begin(); i != (a).end();) #define WHILEITR(i, a) for (__typeof((a).rbegin()) i = (a).rbegin(); i != (a).rend();) #define PB push_back //#define MP make_pair #define ST first #define ND second #define ZERO(a) memset(a, 0, sizeof(a)) #define ALL(a) (a).begin(), (a).end() #define CLR(x) memset((x), 0, sizeof(x)) //[range] int64: 9.2e18(2^63-1) <> uint64: 1.8e19(2^64-1) <> double: 2.23e-308~1.79e308(2^-1022~2^1023) //[precision] double: 16 digit, 17th may round //[setf] cout.setf(ios::fixed); cout.precision(10); //[int64 input] cin>>a; scanf("%lld",&a); scanf("%I64d",&a); const int most=1002; int make() { int N; cin>>N; int d[N],n[N],w[N],e[N],s[N],del_d[N],del_p[N],del_s[N]; int hw[2*most],he[2*most]; int nhw[2*most],nhe[2*most]; ZERO(hw);ZERO(he); ZERO(nhw);ZERO(nhe); FORN(i,N) { cin>>d[i]>>n[i]>>w[i]>>e[i]>>s[i]>>del_d[i]>>del_p[i]>>del_s[i]; } int today=0; int ans=0; while(1) { FORN(i,N) { bool breach=false; if(d[i]==today && n[i]>0) { FORAB(p,2*w[i],2*e[i]) { if(p>=0) { if(he[p]<s[i]) { breach=true; nhe[p]=max(s[i],nhe[p]); } } else { if(hw[-p]<s[i]) { breach=true; nhw[-p]=max(s[i],nhw[-p]); } } } d[i]+=del_d[i]; s[i]+=del_s[i]; w[i]+=del_p[i]; e[i]+=del_p[i]; --n[i]; } if(breach) ++ans; } int cnt=0; FORN(j,N)cnt+=n[j]; if(cnt==0)break; FORN(j,most) { he[j]=nhe[j]; hw[j]=nhw[j]; } ++today; } cout<<ans<<endl; } int main(int argc,char **args) { freopen("input.in","r",stdin); freopen("output.out","w",stdout); int testcase; scanf("%d\n",&testcase); for (int caseId=1;caseId<=testcase;caseId++) { printf("Case #%d: ",caseId); cerr<<caseId<<endl; //if(caseId==15) // cerr<<endl; make(); fflush(stdout); } return 0; }
[ "eewestman@gmail.com" ]
eewestman@gmail.com
843c320519165920b00378cfa04edc74b0ca3e50
bde250a5bd97435abf0ffa505ba3da1f129720d8
/security/cryptoapi/pki/activex/capicom/envelopeddata.cpp
0fc3d0e3784cd5ba5d085c7f67aacfbb5d38d982
[]
no_license
KernelPanic-OpenSource/Win2K3_NT_ds
f45afd1a1243e42a8ccb489048f4a73946dad99f
0d97393773ee5ecdc29aae15023492e383f7ee7f
refs/heads/master
2023-04-04T00:34:51.876505
2021-04-14T04:49:28
2021-04-14T04:49:28
357,774,650
1
0
null
null
null
null
UTF-8
C++
false
false
51,232
cpp
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Microsoft Windows, Copyright (C) Microsoft Corporation, 2000 File: EnvelopedData.cpp Content: Implementation of CEnvelopedData. History: 11-15-99 dsie created ------------------------------------------------------------------------------*/ #include "StdAfx.h" #include "CAPICOM.h" #include "EnvelopedData.h" #include "Common.h" #include "Convert.h" #include "CertHlpr.h" #include "MsgHlpr.h" #include "SignHlpr.h" #include "Settings.h" //////////////////////////////////////////////////////////////////////////////// // // Local functions. // /*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Function : SelectRecipientCertCallback Synopsis : Callback routine for CryptUIDlgSelectCertificateW() API for recipient's cert selection. Parameter: See CryptUI.h for defination. Remark : Filter out any cert that is not time valid. ------------------------------------------------------------------------------*/ static BOOL WINAPI SelectRecipientCertCallback (PCCERT_CONTEXT pCertContext, BOOL * pfInitialSelectedCert, void * pvCallbackData) { int nValidity = 0; // // Check cert time validity. // if (0 != (nValidity = ::CertVerifyTimeValidity(NULL, pCertContext->pCertInfo))) { DebugTrace("Info: SelectRecipientCertCallback() - invalid time (%s).\n", nValidity < 0 ? "not yet valid" : "expired"); return FALSE; } return TRUE; } //////////////////////////////////////////////////////////////////////////////// // // CEnvelopedData // /*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Function : SetKeyLength Synopsis : Setup the symetric encryption key length. Parameter: HCRYPTPROV hCryptProv - CSP handle. CRYPT_ALGORITHM_IDENTIFIER EncryptAlgorithm - Encryption algorithm. CAPICOM_ENCRYPTION_KEY_LENGTH KeyLength - Key length. void ** pAuxInfo - Receive NULL or allocated and initialized aux info structure. Remark : ------------------------------------------------------------------------------*/ static HRESULT SetKeyLength ( HCRYPTPROV hCryptProv, CRYPT_ALGORITHM_IDENTIFIER EncryptAlgorithm, CAPICOM_ENCRYPTION_KEY_LENGTH KeyLength, void ** ppAuxInfo) { HRESULT hr = S_OK; ALG_ID AlgID = 0; PROV_ENUMALGS_EX peex; CMSG_RC2_AUX_INFO * pRC2AuxInfo = NULL; CMSG_RC4_AUX_INFO * pRC4AuxInfo = NULL; DebugTrace("Entering SetKeyLength().\n"); // // Sanity check. // ATLASSERT(hCryptProv); ATLASSERT(ppAuxInfo); // // Initialize. // *ppAuxInfo = (void *) NULL; // // Get ALG_ID. // if (FAILED(hr = ::OIDToAlgID(EncryptAlgorithm.pszObjId, &AlgID))) { DebugTrace("Error [%#x]: OIDToAlgID() failed.\n", hr); goto ErrorExit; } // // Get algorithm capability from CSP. // if (FAILED(::IsAlgSupported(hCryptProv, AlgID, &peex))) { hr = CAPICOM_E_NOT_SUPPORTED; DebugTrace("Error: requested encryption algorithm is not available.\n"); goto ErrorExit; } // // Setup AuxInfo for RC2. // if (CALG_RC2 == AlgID) { // // Allocate and intialize memory for RC2 AuxInfo structure. // if (!(pRC2AuxInfo = (CMSG_RC2_AUX_INFO *) ::CoTaskMemAlloc(sizeof(CMSG_RC2_AUX_INFO)))) { hr = E_OUTOFMEMORY; DebugTrace("Error: out of memory.\n"); goto ErrorExit; } ::ZeroMemory(pRC2AuxInfo, sizeof(CMSG_RC2_AUX_INFO)); pRC2AuxInfo->cbSize = sizeof(CMSG_RC2_AUX_INFO); // // Determine key length requested. // if (CAPICOM_ENCRYPTION_KEY_LENGTH_MAXIMUM == KeyLength) { pRC2AuxInfo->dwBitLen = peex.dwMaxLen; } else if (CAPICOM_ENCRYPTION_KEY_LENGTH_40_BITS == KeyLength) { if (peex.dwMinLen <= 40 && 40 <= peex.dwMaxLen) { pRC2AuxInfo->dwBitLen = 40; } else { hr = CAPICOM_E_NOT_SUPPORTED; DebugTrace("Error [%#x]: 40-bits encryption is not available.\n", hr); goto ErrorExit; } } else if (CAPICOM_ENCRYPTION_KEY_LENGTH_56_BITS == KeyLength) { if (peex.dwMinLen <= 56 && 56 <= peex.dwMaxLen) { pRC2AuxInfo->dwBitLen = 56; } else { hr = CAPICOM_E_NOT_SUPPORTED; DebugTrace("Error [%#x]: 56-bits encryption is not available.\n", hr); goto ErrorExit; } } else if (CAPICOM_ENCRYPTION_KEY_LENGTH_128_BITS == KeyLength) { if (peex.dwMinLen <= 128 && 128 <= peex.dwMaxLen) { pRC2AuxInfo->dwBitLen = 128; } else { hr = CAPICOM_E_NOT_SUPPORTED; DebugTrace("Error [%#x]: 128-bits encryption is not available.\n", hr); goto ErrorExit; } } else { // // Should never get to here. // hr = CAPICOM_E_INTERNAL; DebugTrace("Error [%#x]: Unknown key length (%d).\n", hr, KeyLength); goto ErrorExit; } // // Return RC2 AuxInfo pointer to caller. // *ppAuxInfo = (void *) pRC2AuxInfo; } else if (CALG_RC4 == AlgID) { // // Allocate and intialize memory for RC4 AuxInfo structure. // if (!(pRC4AuxInfo = (CMSG_RC4_AUX_INFO *) ::CoTaskMemAlloc(sizeof(CMSG_RC4_AUX_INFO)))) { hr = E_OUTOFMEMORY; DebugTrace("Error: out of memory.\n"); goto ErrorExit; } ::ZeroMemory(pRC4AuxInfo, sizeof(CMSG_RC4_AUX_INFO)); pRC4AuxInfo->cbSize = sizeof(CMSG_RC4_AUX_INFO); // // Determine key length requested. // if (CAPICOM_ENCRYPTION_KEY_LENGTH_MAXIMUM == KeyLength) { pRC4AuxInfo->dwBitLen = peex.dwMaxLen; } else if (CAPICOM_ENCRYPTION_KEY_LENGTH_40_BITS == KeyLength) { if (peex.dwMinLen <= 40 && 40 <= peex.dwMaxLen) { pRC4AuxInfo->dwBitLen = 40; } else { hr = CAPICOM_E_NOT_SUPPORTED; DebugTrace("Error [%#x]: 40-bits encryption is not available.\n", hr); goto ErrorExit; } } else if (CAPICOM_ENCRYPTION_KEY_LENGTH_56_BITS == KeyLength) { if (peex.dwMinLen <= 56 && 56 <= peex.dwMaxLen) { pRC4AuxInfo->dwBitLen = 56; } else { hr = CAPICOM_E_NOT_SUPPORTED; DebugTrace("Error [%#x]: 56-bits encryption is not available.\n", hr); goto ErrorExit; } } else if (CAPICOM_ENCRYPTION_KEY_LENGTH_128_BITS == KeyLength) { if (peex.dwMinLen <= 128 && 128 <= peex.dwMaxLen) { pRC4AuxInfo->dwBitLen = 128; } else { hr = CAPICOM_E_NOT_SUPPORTED; DebugTrace("Error [%#x]: 128-bits encryption is not available.\n", hr); goto ErrorExit; } } else { // // Should never get to here. // hr = CAPICOM_E_INTERNAL; DebugTrace("Error [%#x]: Unknown key length (%d).\n", hr, KeyLength); goto ErrorExit; } // // Return RC4 AuxInfo pointer to caller. // *ppAuxInfo = (void *) pRC4AuxInfo; } CommonExit: DebugTrace("Leaving SetKeyLength().\n"); return hr; ErrorExit: // // Sanity check. // ATLASSERT(FAILED(hr)); // // Free resource. // if (pRC2AuxInfo) { ::CoTaskMemFree(pRC2AuxInfo); } if (pRC4AuxInfo) { ::CoTaskMemFree(pRC4AuxInfo); } goto CommonExit; } /*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Function : SetEncryptionAlgorithm Synopsis : Setup the encryption algorithm structure. Parameter: CAPICOM_ENCRYPTION_ALGORITHM AlgoName - Algorithm ID enum name. CAPICOM_ENCRYPTION_KEY_LENGTH KeyLength - Key length enum name. CRYPT_ALGORITHM_IDENTIFIER * pEncryptAlgorithm - Pointer to the structure. Remark : ------------------------------------------------------------------------------*/ static HRESULT SetEncryptionAlgorithm (CAPICOM_ENCRYPTION_ALGORITHM AlgoName, CAPICOM_ENCRYPTION_KEY_LENGTH KeyLength, CRYPT_ALGORITHM_IDENTIFIER * pEncryptAlgorithm) { HRESULT hr = S_OK; ALG_ID AlgID = 0; DebugTrace("Entering SetEncryptionAlgorithm().\n"); // // Sanity check. // ATLASSERT(pEncryptAlgorithm); // // Initialize structure. // ::ZeroMemory(pEncryptAlgorithm, sizeof(CRYPT_ALGORITHM_IDENTIFIER)); // // Convert to LPSTR. // if (FAILED(hr = ::EnumNameToAlgID(AlgoName, KeyLength, &AlgID))) { DebugTrace("Error: EnumNameToAlgID() failed.\n"); goto ErrorExit; } if (FAILED(hr = ::AlgIDToOID(AlgID, &pEncryptAlgorithm->pszObjId))) { DebugTrace("Error: AlgIDToOID() failed.\n"); goto ErrorExit; } CommonExit: DebugTrace("Leaving SetEncryptionAlgorithm().\n"); return hr; ErrorExit: // // Sanity check. // ATLASSERT(FAILED(hr)); // // Free resource. // if (pEncryptAlgorithm->pszObjId) { ::CoTaskMemFree(pEncryptAlgorithm->pszObjId); } goto CommonExit; } //////////////////////////////////////////////////////////////////////////////// // // CEnvelopedData // /*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Function : CEnvelopedData::get_Content Synopsis : Return the content. Parameter: BSTR * pVal - Pointer to BSTR to receive the content. Remark : ------------------------------------------------------------------------------*/ STDMETHODIMP CEnvelopedData::get_Content (BSTR * pVal) { HRESULT hr = S_OK; DebugTrace("Entering CEnvelopedData::get_Content().\n"); // // Lock access to this object. // m_Lock.Lock(); try { // // Check parameters. // if (NULL == pVal) { hr = E_INVALIDARG; DebugTrace("Error [%#x]: Parameter pVal is NULL.\n", hr); goto ErrorExit; } // // Make sure content is already initialized. // if (0 == m_ContentBlob.cbData) { hr = CAPICOM_E_ENVELOP_NOT_INITIALIZED; DebugTrace("Error [%#x]: Enveloped object has not been initialized.\n", hr); goto ErrorExit; } // // Sanity check. // ATLASSERT(m_ContentBlob.pbData); // // Return content. // if (FAILED(hr = ::BlobToBstr(&m_ContentBlob, pVal))) { DebugTrace("Error [%#x]: BlobToBstr() failed.\n", hr); goto ErrorExit; } } catch(...) { hr = E_POINTER; DebugTrace("Exception: invalid parameter.\n"); goto ErrorExit; } UnlockExit: // // Unlock access to this object. // m_Lock.Unlock(); DebugTrace("Leaving CEnvelopedData::get_Content().\n"); return hr; ErrorExit: // // Sanity check. // ATLASSERT(FAILED(hr)); ReportError(hr); goto UnlockExit; } /*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Function : CEnvelopedData::put_Content Synopsis : Initialize the object with content to be enveloped. Parameter: BSTR newVal - BSTR containing the content to be enveloped. Remark : ------------------------------------------------------------------------------*/ STDMETHODIMP CEnvelopedData::put_Content (BSTR newVal) { HRESULT hr = S_OK; DebugTrace("Entering CEnvelopedData::put_Content().\n"); // // Lock access to this object. // m_Lock.Lock(); try { // // Make sure parameters are valid. // if (0 == ::SysStringByteLen(newVal)) { hr = E_INVALIDARG; DebugTrace("Error [%#x]: Parameter newVal is NULL or empty.\n", hr); goto ErrorExit; } // // Update content. // if (FAILED(hr = ::BstrToBlob(newVal, &m_ContentBlob))) { DebugTrace("Error [%#x]: BstrToBlob() failed.\n", hr); goto ErrorExit; } } catch(...) { hr = E_POINTER; DebugTrace("Exception: invalid parameter.\n"); goto ErrorExit; } UnlockExit: // // Unlock access to this object. // m_Lock.Unlock(); DebugTrace("Leaving CEnvelopedData::put_Content().\n"); return hr; ErrorExit: // // Sanity check. // ATLASSERT(FAILED(hr)); ReportError(hr); goto UnlockExit; } /*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Function : CEnvelopedData::get_Algorithm Synopsis : Property to return the algorithm object. Parameter: IAlgorithm ** pVal - Pointer to pointer to IAlgorithm to receive the interfcae pointer. Remark : ------------------------------------------------------------------------------*/ STDMETHODIMP CEnvelopedData::get_Algorithm (IAlgorithm ** pVal) { HRESULT hr = S_OK; DebugTrace("Entering CEnvelopedData::get_Algorithm().\n"); // // Lock access to this object. // m_Lock.Lock(); try { // // Check parameters. // if (NULL == pVal) { hr = E_INVALIDARG; DebugTrace("Error [%#x]: Parameter pVal is NULL.\n", hr); goto ErrorExit; } // // Sanity check. // ATLASSERT(m_pIAlgorithm); // // Return interface pointer to caller. // if (FAILED(hr = m_pIAlgorithm->QueryInterface(pVal))) { DebugTrace("Unexpected error [%#x]: m_pIAlgorithm->QueryInterface() failed.\n", hr); goto ErrorExit; } } catch(...) { hr = E_POINTER; DebugTrace("Exception: invalid parameter.\n"); goto ErrorExit; } UnlockExit: // // Unlock access to this object. // m_Lock.Unlock(); DebugTrace("Leaving CEnvelopedData::get_Algorithm().\n"); return hr; ErrorExit: // // Sanity check. // ATLASSERT(FAILED(hr)); ReportError(hr); goto UnlockExit; } /*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Function : CEnvelopedData::get_Recipients Synopsis : Property to return the IRecipients collection object. Parameter: IRecipients ** pVal - Pointer to pointer to IRecipietns to receive the interface pointer. Remark : ------------------------------------------------------------------------------*/ STDMETHODIMP CEnvelopedData::get_Recipients (IRecipients ** pVal) { HRESULT hr = S_OK; DebugTrace("Entering CEnvelopedData::get_Recipients().\n"); // // Lock access to this object. // m_Lock.Lock(); try { // // Check parameters. // if (NULL == pVal) { hr = E_INVALIDARG; DebugTrace("Error [%#x]: Parameter pVal is NULL.\n", hr); goto ErrorExit; } // // Sanity check. // ATLASSERT(m_pIRecipients); // // Return interface pointer to caller. // if (FAILED(hr = m_pIRecipients->QueryInterface(pVal))) { DebugTrace("Unexpected error [%#x]: m_pIRecipients->QueryInterface() failed.\n", hr); goto ErrorExit; } } catch(...) { hr = E_POINTER; DebugTrace("Exception: invalid parameter.\n"); goto ErrorExit; } UnlockExit: // // Unlock access to this object. // m_Lock.Unlock(); DebugTrace("Leaving CEnvelopedData::get_Recipients().\n"); return hr; ErrorExit: // // Sanity check. // ATLASSERT(FAILED(hr)); ReportError(hr); goto UnlockExit; } /*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Function : CEnvelopedData::Encrypt Synopsis : Envelop the content. Parameter: CAPICOM_ENCODING_TYPE EncodingType - Encoding type. BSTR * pVal - Pointer to BSTR to receive the enveloped message. Remark : ------------------------------------------------------------------------------*/ STDMETHODIMP CEnvelopedData::Encrypt (CAPICOM_ENCODING_TYPE EncodingType, BSTR * pVal) { HRESULT hr = S_OK; HCRYPTMSG hMsg = NULL; HCRYPTPROV hCryptProv = NULL; CRYPT_DATA_BLOB MessageBlob = {0, NULL}; DebugTrace("Entering CEnvelopedData::Encrypt().\n"); // // Lock access to this object. // m_Lock.Lock(); try { // // Check parameters. // if (NULL == pVal) { hr = E_INVALIDARG; DebugTrace("Error [%#x]: Parameter pVal is NULL.\n", hr); goto ErrorExit; } // // Make sure we do have content to envelop. // if (0 == m_ContentBlob.cbData) { hr = CAPICOM_E_ENVELOP_NOT_INITIALIZED; DebugTrace("Error [%#x]: envelop object has not been initialized.\n", hr); goto ErrorExit; } // // Open a new message to encode. // if (FAILED(hr = OpenToEncode(&hMsg, &hCryptProv))) { DebugTrace("Error [%#x]: CEnvelopedData::OpenToEncode() failed.\n", hr); goto ErrorExit; } // // Update envelop content. // if(!::CryptMsgUpdate(hMsg, m_ContentBlob.pbData, m_ContentBlob.cbData, TRUE)) { hr = HRESULT_FROM_WIN32(::GetLastError()); DebugTrace("Error [%#x]: CryptMsgUpdate() failed.\n", hr); goto ErrorExit; } // // Retrieve enveloped message. // if (FAILED(hr = ::GetMsgParam(hMsg, CMSG_CONTENT_PARAM, 0, (void **) &MessageBlob.pbData, &MessageBlob.cbData))) { hr = HRESULT_FROM_WIN32(::GetLastError()); DebugTrace("Error [%#x]: GetMsgParam() failed to get message content.\n", hr); goto ErrorExit; } // // Now export the enveloped message. // if (FAILED(hr = ::ExportData(MessageBlob, EncodingType, pVal))) { DebugTrace("Error [%#x]: ExportData() failed.\n", hr); goto ErrorExit; } // // Write encoded blob to file, so we can use offline tool such as // ASN parser to analyze message. // // The following line will resolve to void for non debug build, and // thus can be safely removed if desired. // DumpToFile("Enveloped.asn", MessageBlob.pbData, MessageBlob.cbData); } catch(...) { hr = E_POINTER; DebugTrace("Exception: invalid parameter.\n"); goto ErrorExit; } UnlockExit: // // Free resource. // if (MessageBlob.pbData) { ::CoTaskMemFree(MessageBlob.pbData); } if (hCryptProv) { ::ReleaseContext(hCryptProv); } if (hMsg) { ::CryptMsgClose(hMsg); } // // Unlock access to this object. // m_Lock.Unlock(); DebugTrace("Leaving CEnvelopedData::Encrypt().\n"); return hr; ErrorExit: // // Sanity check. // ATLASSERT(FAILED(hr)); ReportError(hr); goto UnlockExit; } /*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Function : CEnvelopedData::Decrypt Synopsis : Decrypt the enveloped message. Parameter: BSTR EnvelopedMessage - BSTR containing the enveloped message. Remark : If called from web environment, UI will be displayed, if has not been prevously disabled, to warn the user of accessing the private key for decrypting. ------------------------------------------------------------------------------*/ STDMETHODIMP CEnvelopedData::Decrypt (BSTR EnvelopedMessage) { HRESULT hr = S_OK; HRESULT hr2 = S_OK; HCERTSTORE hCertStores[2] = {NULL, NULL}; HCRYPTMSG hMsg = NULL; PCCERT_CONTEXT pCertContext = NULL; HCRYPTPROV hCryptProv = NULL; DWORD dwKeySpec = 0; BOOL bReleaseContext = FALSE; BOOL bUserPrompted = FALSE; DWORD dwNumRecipients = 0; DWORD cbNumRecipients = sizeof(dwNumRecipients); CRYPT_DATA_BLOB ContentBlob = {0, NULL}; DWORD dwIndex; CComBSTR bstrContent; DebugTrace("Entering CEnvelopedData::Decrypt().\n"); // // Lock access to this object. // m_Lock.Lock(); try { // // Reset member variables. // if (FAILED(hr = m_pIRecipients->Clear())) { DebugTrace("Error [%#x]: m_pIRecipients->Clear() failed.\n", hr); goto ErrorExit; } // // Make sure parameters are valid. // if (0 == ::SysStringByteLen(EnvelopedMessage)) { hr = E_INVALIDARG; DebugTrace("Error [%#x]: Parameter EnvelopedMessage is NULL or empty.\n", hr); goto ErrorExit; } // // Open current user and local machine MY stores. // hCertStores[0] = ::CertOpenStore(CERT_STORE_PROV_SYSTEM, CAPICOM_ASN_ENCODING, NULL, CERT_SYSTEM_STORE_CURRENT_USER | CERT_STORE_OPEN_EXISTING_FLAG, L"My"); hCertStores[1] = ::CertOpenStore(CERT_STORE_PROV_SYSTEM, CAPICOM_ASN_ENCODING, NULL, CERT_SYSTEM_STORE_LOCAL_MACHINE | CERT_STORE_OPEN_EXISTING_FLAG, L"My"); // // Did we manage to open any of the MY store? // if (NULL == hCertStores[0] && NULL == hCertStores[1]) { hr = HRESULT_FROM_WIN32(::GetLastError()); DebugTrace("Error [%#x]: CertOpenStore() failed.\n", hr); goto ErrorExit; } // // Open the message for decode. // if (FAILED(hr = OpenToDecode(NULL, EnvelopedMessage, &hMsg))) { DebugTrace("Error [%#x]: CEnvelopedData::OpenToDecode() failed.\n", hr); goto ErrorExit; } // // Determine number of recipients. // if (!::CryptMsgGetParam(hMsg, CMSG_RECIPIENT_COUNT_PARAM, 0, (void *) &dwNumRecipients, &cbNumRecipients)) { hr = HRESULT_FROM_WIN32(::GetLastError()); DebugTrace("Error [%#x]: CryptMsgGetParam() failed for CMSG_RECIPIENT_COUNT_PARAM.\n", hr); goto ErrorExit; } // // Find recipient. // for (dwIndex = 0; dwIndex < dwNumRecipients; dwIndex++) { BOOL bFound = FALSE; DATA_BLOB CertInfoBlob = {0, NULL}; // // Get RecipientInfo. // if (FAILED(hr = ::GetMsgParam(hMsg, CMSG_RECIPIENT_INFO_PARAM, dwIndex, (void **) &CertInfoBlob.pbData, &CertInfoBlob.cbData))) { DebugTrace("Error [%#x]: GetMsgParam() failed for CMSG_RECIPIENT_INFO_PARAM.\n", hr); goto ErrorExit; } // // Find recipient's cert in store. // if ((hCertStores[0] && (pCertContext = ::CertGetSubjectCertificateFromStore(hCertStores[0], CAPICOM_ASN_ENCODING, (CERT_INFO *) CertInfoBlob.pbData))) || (hCertStores[1] && (pCertContext = ::CertGetSubjectCertificateFromStore(hCertStores[1], CAPICOM_ASN_ENCODING, (CERT_INFO *) CertInfoBlob.pbData)))) { bFound = TRUE; } // // Free memory. // ::CoTaskMemFree(CertInfoBlob.pbData); // // Did we find the recipient? // if (bFound) { CMSG_CTRL_DECRYPT_PARA DecryptPara; // // If we are called from a web page, we need to pop up UI // to get user permission to perform decrypt operation. // if (!bUserPrompted) { if (m_dwCurrentSafety && FAILED(hr = OperationApproved(IDD_DECRYPT_SECURITY_ALERT_DLG))) { DebugTrace("Error [%#x]: OperationApproved() failed.\n", hr); goto ErrorExit; } bUserPrompted = TRUE; } // // Acquire CSP context. // if (S_OK == ::AcquireContext(pCertContext, &hCryptProv, &dwKeySpec, &bReleaseContext)) { // // Decypt the message. // ::ZeroMemory(&DecryptPara, sizeof(DecryptPara)); DecryptPara.cbSize = sizeof(DecryptPara); DecryptPara.hCryptProv = hCryptProv; DecryptPara.dwKeySpec = dwKeySpec; DecryptPara.dwRecipientIndex = dwIndex; if(::CryptMsgControl(hMsg, 0, CMSG_CTRL_DECRYPT, &DecryptPara)) { // // Get decrypted content. // if (FAILED(hr = ::GetMsgParam(hMsg, CMSG_CONTENT_PARAM, 0, (void **) &ContentBlob.pbData, &ContentBlob.cbData))) { DebugTrace("Error [%#x]: GetMsgParam() failed to get CMSG_CONTENT_PARAM.\n", hr); goto ErrorExit; } // // Update member variables. // m_ContentBlob = ContentBlob; // // We are all done, so break out of loop. // break; } else { // // Keep copy of error code. // hr2 = HRESULT_FROM_WIN32(::GetLastError()); DebugTrace("Info [%#x]: CryptMsgControl() failed to decrypt.\n", hr2); } if (bReleaseContext) { ::ReleaseContext(hCryptProv), hCryptProv = NULL; } } ::CertFreeCertificateContext(pCertContext), pCertContext = NULL; } } // // Did we find the recipient? // if (dwIndex == dwNumRecipients) { // // Retrieve previous error if any. // if (FAILED(hr2)) { hr = hr2; DebugTrace("Error [%#x]: CryptMsgControl() failed to decrypt.\n", hr); } else { hr = CAPICOM_E_ENVELOP_RECIPIENT_NOT_FOUND; DebugTrace("Error [%#x]: recipient not found.\n", hr); } goto ErrorExit; } } catch(...) { hr = E_POINTER; DebugTrace("Exception: invalid parameter.\n"); goto ErrorExit; } UnlockExit: // // Free resource. // if (hCryptProv && bReleaseContext) { ::ReleaseContext(hCryptProv); } if (pCertContext) { ::CertFreeCertificateContext(pCertContext); } if(hMsg) { ::CryptMsgClose(hMsg); } if (hCertStores[0]) { ::CertCloseStore(hCertStores[0], 0); } if (hCertStores[1]) { ::CertCloseStore(hCertStores[1], 0); } // // Unlock access to this object. // m_Lock.Unlock(); DebugTrace("Leaving CEnvelopedData::Decrypt().\n"); return hr; ErrorExit: // // Sanity check. // ATLASSERT(FAILED(hr)); // // Free resources. // if (ContentBlob.pbData) { ::CoTaskMemFree(ContentBlob.pbData); } ReportError(hr); goto UnlockExit; } //////////////////////////////////////////////////////////////////////////////// // // Private member functions. // /*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Function : CEnvelopedData::Init Synopsis : Initialize the object. Parameter: None. Remark : This method is not part of the COM interface (it is a normal C++ member function). We need it to initialize the object created internally by us. Since it is only a normal C++ member function, this function can only be called from a C++ class pointer, not an interface pointer. ------------------------------------------------------------------------------*/ STDMETHODIMP CEnvelopedData::Init () { HRESULT hr = S_OK; CComPtr<IAlgorithm> pIAlgorithm = NULL; CComPtr<IRecipients> pIRecipients = NULL; DebugTrace("Entering CEnvelopedData::Init().\n"); // // Create embeded IAlgorithm. // if (FAILED(hr = ::CreateAlgorithmObject(FALSE, FALSE, &pIAlgorithm))) { DebugTrace("Error [%#x]: CreateAlgorithmObject() failed.\n", hr); goto CommonExit; } // // Create embeded IRecipients. // if (FAILED(hr = ::CreateRecipientsObject(&pIRecipients))) { DebugTrace("Error [%#x]: CreateRecipientsObject() failed.\n", hr); goto CommonExit; } // // Update member variables. // m_bEnveloped = FALSE; m_ContentBlob.cbData = 0; m_ContentBlob.pbData = NULL; m_pIAlgorithm = pIAlgorithm; m_pIRecipients = pIRecipients; CommonExit: DebugTrace("Leaving CEnvelopedData::Init().\n"); return hr; } /*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Function : CEnvelopedData::OpenToEncode Synopsis : Create and initialize an envelop message for encoding. Parameter: HCRYPTMSG * phMsg - Pointer to HCRYPTMSG to receive message handler. HCRYPTPROV * phCryptProv - Pointer to HCRYPTPROV to receive CSP handler. Remark : ------------------------------------------------------------------------------*/ STDMETHODIMP CEnvelopedData::OpenToEncode (HCRYPTMSG * phMsg, HCRYPTPROV * phCryptProv) { HRESULT hr = S_OK; DWORD dwNumRecipients = 0; PCCERT_CONTEXT * pCertContexts = NULL; PCERT_INFO * pCertInfos = NULL; HCRYPTPROV hCryptProv = NULL; void * pEncryptionAuxInfo = NULL; CAPICOM_STORE_INFO StoreInfo = {0, L"AddressBook"}; CComPtr<ICertificate> pIRecipient = NULL; CComPtr<ICertificate2> pICertificate2 = NULL; DWORD dwIndex; CAPICOM_ENCRYPTION_ALGORITHM AlgoName; CAPICOM_ENCRYPTION_KEY_LENGTH KeyLength; CMSG_ENVELOPED_ENCODE_INFO EnvelopInfo; CRYPT_ALGORITHM_IDENTIFIER EncryptionAlgorithm; DebugTrace("Entering CEnvelopedData::OpenToEncode().\n"); // // Sanity check. // ATLASSERT(phMsg); ATLASSERT(phCryptProv); ATLASSERT(m_ContentBlob.cbData && m_ContentBlob.pbData); ATLASSERT(m_pIRecipients); // // Initialize. // ::ZeroMemory(&EnvelopInfo, sizeof(EnvelopInfo)); ::ZeroMemory(&EncryptionAlgorithm, sizeof(EncryptionAlgorithm)); // // Make sure we do have at least 1 recipient. // if (FAILED(hr = m_pIRecipients->get_Count((long *) &dwNumRecipients))) { DebugTrace("Error [%#x]: m_pIRecipients->get_Count() failed.\n", hr); goto ErrorExit; } if (0 == dwNumRecipients) { // // Prompt user to add a recipient. // if (FAILED(hr = ::SelectCertificate(StoreInfo, SelectRecipientCertCallback, &pICertificate2))) { if (hr == CAPICOM_E_STORE_EMPTY) { hr = CAPICOM_E_ENVELOP_NO_RECIPIENT; } DebugTrace("Error [%#x]: SelectCertificate() failed.\n", hr); goto ErrorExit; } if (FAILED(hr = pICertificate2->QueryInterface(__uuidof(ICertificate), (void **) &pIRecipient))) { DebugTrace("Unexpected error [%#x]: pICertificate2->QueryInterface() failed.\n", hr); goto ErrorExit; } // // Add to collection. // if (FAILED (hr = m_pIRecipients->Add(pIRecipient))) { DebugTrace("Error [%#x]: m_pIRecipients->Add() failed.\n", hr); goto ErrorExit; } // // Make sure count is 1. // if (FAILED(hr = m_pIRecipients->get_Count((long *) &dwNumRecipients))) { DebugTrace("Error [%#x]: m_pIRecipients->get_Count() failed.\n", hr); goto ErrorExit; } // // Sanity check. // ATLASSERT(1 == dwNumRecipients); } // // Allocate memory for CERT_CONTEXT array. // if (!(pCertContexts = (PCCERT_CONTEXT *) ::CoTaskMemAlloc(sizeof(PCCERT_CONTEXT) * dwNumRecipients))) { hr = E_OUTOFMEMORY; DebugTrace("Error: out of memory.\n"); goto ErrorExit; } ::ZeroMemory(pCertContexts, sizeof(PCCERT_CONTEXT) * dwNumRecipients); // // Allocate memory for CERT_INFO array. // if (!(pCertInfos = (PCERT_INFO *) ::CoTaskMemAlloc(sizeof(PCERT_INFO) * dwNumRecipients))) { hr = E_OUTOFMEMORY; DebugTrace("Error: out of memory.\n"); goto ErrorExit; } ::ZeroMemory(pCertInfos, sizeof(PCERT_INFO) * dwNumRecipients); // // Set CERT_INFO array. // for (dwIndex = 0; dwIndex < dwNumRecipients; dwIndex++) { CComVariant varRecipient; CComPtr<ICertificate> pIRecipient2 = NULL; // // Get next recipient. // if (FAILED(hr = m_pIRecipients->get_Item((long) (dwIndex + 1), &varRecipient))) { DebugTrace("Error [%#x]: m_pIRecipients->get_Item() failed.\n", hr); goto ErrorExit; } // // Get custom interface. // if (FAILED(hr = varRecipient.pdispVal->QueryInterface(IID_ICertificate, (void **) &pIRecipient2))) { DebugTrace("Error [%#x]: varRecipient.pdispVal->QueryInterface() failed.\n", hr); goto ErrorExit; } // // Get CERT_CONTEXT. // if (FAILED(hr = ::GetCertContext(pIRecipient2, &pCertContexts[dwIndex]))) { DebugTrace("Error [%#x]: GetCertContext() failed.\n", hr); goto ErrorExit; } // // Set CERT_INFO. // pCertInfos[dwIndex] = pCertContexts[dwIndex]->pCertInfo; } // // Get algorithm ID enum name. // if (FAILED(hr = m_pIAlgorithm->get_Name(&AlgoName))) { DebugTrace("Error [%#x]: m_pIAlgorithm->get_Name() failed.\n", hr); goto ErrorExit; } // // Get key length enum name. // if (FAILED(hr = m_pIAlgorithm->get_KeyLength(&KeyLength))) { DebugTrace("Error [%#x]: m_pIAlgorithm->get_KeyLength() failed.\n", hr); goto ErrorExit; } // // Get CSP context. // if (FAILED(hr = ::AcquireContext(AlgoName, KeyLength, &hCryptProv))) { DebugTrace("Error [%#x]: AcquireContext() failed.\n", hr); goto ErrorExit; } // // Set algorithm. // if (FAILED(hr = ::SetEncryptionAlgorithm(AlgoName, KeyLength, &EncryptionAlgorithm))) { DebugTrace("Error [%#x]: SetEncryptionAlgorithm() failed.\n", hr); goto ErrorExit; } // // Set key length. // if (FAILED(hr = ::SetKeyLength(hCryptProv, EncryptionAlgorithm, KeyLength, &pEncryptionAuxInfo))) { DebugTrace("Error [%#x]: SetKeyLength() failed.\n", hr); goto ErrorExit; } // // Set CMSG_ENVELOPED_ENCODE_INFO. // EnvelopInfo.cbSize = sizeof(EnvelopInfo); EnvelopInfo.ContentEncryptionAlgorithm = EncryptionAlgorithm; EnvelopInfo.hCryptProv = hCryptProv; EnvelopInfo.cRecipients = dwNumRecipients; EnvelopInfo.rgpRecipients = pCertInfos; EnvelopInfo.pvEncryptionAuxInfo = pEncryptionAuxInfo; // // Open the message for encoding. // if(!(*phMsg = ::CryptMsgOpenToEncode(CAPICOM_ASN_ENCODING, // ASN encoding type 0, // Flags CMSG_ENVELOPED, // Message type &EnvelopInfo, // Pointer to structure NULL, // Inner content OID NULL))) // Stream information (not used) { hr = HRESULT_FROM_WIN32(::GetLastError()); DebugTrace("Error [%#x]: CryptMsgOpenToEncode() failed.\n", hr); goto ErrorExit; } // // Return HCRYPTPROV to caller. // *phCryptProv = hCryptProv; CommonExit: // // Free resource. // if (pEncryptionAuxInfo) { ::CoTaskMemFree(pEncryptionAuxInfo); } if (EncryptionAlgorithm.pszObjId) { ::CoTaskMemFree(EncryptionAlgorithm.pszObjId); } if (EncryptionAlgorithm.Parameters.pbData) { ::CoTaskMemFree(EncryptionAlgorithm.Parameters.pbData); } if (pCertInfos) { ::CoTaskMemFree(pCertInfos); } if (pCertContexts) { for (dwIndex = 0; dwIndex < dwNumRecipients; dwIndex++) { if (pCertContexts[dwIndex]) { ::CertFreeCertificateContext(pCertContexts[dwIndex]); } } ::CoTaskMemFree(pCertContexts); } DebugTrace("Leaving CEnvelopedData::OpenToEncode().\n"); return hr; ErrorExit: // // Sanity check. // ATLASSERT(FAILED(hr)); // // Free resource. // if (hCryptProv) { ::ReleaseContext(hCryptProv); } goto CommonExit; } /*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Function : CEnvelopedData::OpenToDeccode Synopsis : Open an enveloped message for decoding. Parameter: HCRYPTPROV hCryptProv - CSP handle. BSTR EnvelopMessage - Enveloped message. HCRYPTMSG * phMsg - Pointer to HCRYPTMSG. Remark : ------------------------------------------------------------------------------*/ STDMETHODIMP CEnvelopedData::OpenToDecode (HCRYPTPROV hCryptProv, BSTR EnvelopedMessage, HCRYPTMSG * phMsg) { HRESULT hr = S_OK; HCRYPTMSG hMsg = NULL; DWORD dwMsgType = 0; DWORD cbMsgType = sizeof(dwMsgType); DATA_BLOB MessageBlob = {0, NULL}; DATA_BLOB AlgorithmBlob = {0, NULL}; DATA_BLOB ParametersBlob = {0, NULL}; DebugTrace("Leaving CEnvelopedData::OpenToDecode().\n"); // Sanity check. // ATLASSERT(phMsg); ATLASSERT(EnvelopedMessage); try { // // Open the message for decoding. // if (!(hMsg = ::CryptMsgOpenToDecode(CAPICOM_ASN_ENCODING, 0, 0, hCryptProv, NULL, NULL))) { hr = HRESULT_FROM_WIN32(::GetLastError()); DebugTrace("Error [%#x]: CryptMsgOpenToDecode() failed.\n", hr); goto CommonExit; } // // Import the message. // if (FAILED(hr = ::ImportData(EnvelopedMessage, CAPICOM_ENCODE_ANY, &MessageBlob))) { DebugTrace("Error [%#x]: ImportData() failed.\n", hr); goto ErrorExit; } // // Update message with enveloped content. // if (!::CryptMsgUpdate(hMsg, MessageBlob.pbData, MessageBlob.cbData, TRUE)) { hr = HRESULT_FROM_WIN32(::GetLastError()); DebugTrace("Error [%#x]: CryptMsgUpdate() failed.\n", hr); goto ErrorExit; } // // Check message type. // if (!::CryptMsgGetParam(hMsg, CMSG_TYPE_PARAM, 0, (void *) &dwMsgType, &cbMsgType)) { hr = HRESULT_FROM_WIN32(::GetLastError()); DebugTrace("Error [%#x]: CryptMsgGetParam() failed for CMSG_TYPE_PARAM.\n", hr); goto ErrorExit; } if (CMSG_ENVELOPED != dwMsgType) { hr = CAPICOM_E_ENVELOP_INVALID_TYPE; DebugTrace("Error [%#x]: Enveloped message's dwMsgType (%#x) is not CMSG_ENVELOPED.\n", hr, dwMsgType); goto ErrorExit; } // // Get algorithm ID. // if (FAILED(hr = ::GetMsgParam(hMsg, CMSG_ENVELOPE_ALGORITHM_PARAM, 0, (void **) &AlgorithmBlob.pbData, &AlgorithmBlob.cbData))) { DebugTrace("Error [%#x]: GetMsgParam() failed for CMSG_ENVELOPE_ALGORITHM_PARAM.\n", hr); goto ErrorExit; } // // Restore encryption algorithm state, as much as we can. // if (0 == lstrcmpA(szOID_RSA_RC2CBC, ((CRYPT_ALGORITHM_IDENTIFIER *) AlgorithmBlob.pbData)->pszObjId)) { CAPICOM_ENCRYPTION_KEY_LENGTH KeyLength; DebugTrace("INFO: Envelop encryption algorithm was RC2.\n"); // // Set encryption algorithm name. // if (FAILED(hr = m_pIAlgorithm->put_Name(CAPICOM_ENCRYPTION_ALGORITHM_RC2))) { DebugTrace("Error [%#x]: m_pIAlgorithm->put_Name() failed.\n", hr); goto ErrorExit; } // // Determine encryption key length. // if (((CRYPT_ALGORITHM_IDENTIFIER *) AlgorithmBlob.pbData)->Parameters.cbData) { if (FAILED(hr = ::DecodeObject(PKCS_RC2_CBC_PARAMETERS, ((CRYPT_ALGORITHM_IDENTIFIER *) AlgorithmBlob.pbData)->Parameters.pbData, ((CRYPT_ALGORITHM_IDENTIFIER *) AlgorithmBlob.pbData)->Parameters.cbData, &ParametersBlob))) { DebugTrace("Error [%#x]: DecodeObject() failed for PKCS_RC2_CBC_PARAMETERS.\n", hr); goto ErrorExit; } } // // Set encryption key length. // switch (((CRYPT_RC2_CBC_PARAMETERS *) ParametersBlob.pbData)->dwVersion) { case CRYPT_RC2_40BIT_VERSION: { KeyLength = CAPICOM_ENCRYPTION_KEY_LENGTH_40_BITS; DebugTrace("INFO: Envelop encryption key length was 40-bits.\n"); break; } case CRYPT_RC2_56BIT_VERSION: { KeyLength = CAPICOM_ENCRYPTION_KEY_LENGTH_56_BITS; DebugTrace("INFO: Envelop encryption key length was 56-bits.\n"); break; } case CRYPT_RC2_128BIT_VERSION: { KeyLength = CAPICOM_ENCRYPTION_KEY_LENGTH_128_BITS; DebugTrace("INFO: Envelop encryption key length was 128-bits.\n"); break; } default: { // // Unknown key length, so arbitrary choose one. // KeyLength = CAPICOM_ENCRYPTION_KEY_LENGTH_MAXIMUM; DebugTrace("INFO: Unknown envelop encryption key length.\n"); break; } } // // Set key length. // if (FAILED(hr = m_pIAlgorithm->put_KeyLength(KeyLength))) { DebugTrace("Error [%#x]: m_pIAlgorithm->put_KeyLength() failed.\n", hr); goto ErrorExit; } } else if (0 == lstrcmpA(szOID_RSA_RC4, ((CRYPT_ALGORITHM_IDENTIFIER *) AlgorithmBlob.pbData)->pszObjId)) { DebugTrace("INFO: Envelop encryption algorithm was RC4.\n"); // // Set encryption algorithm name. // if (FAILED(hr = m_pIAlgorithm->put_Name(CAPICOM_ENCRYPTION_ALGORITHM_RC4))) { DebugTrace("Error [%#x]: m_pIAlgorithm->put_Name() failed.\n", hr); goto ErrorExit; } // // For RC4, CAPI simply does not provide a way to retrieve the // encryption key length, so we will have to leave it alone!!! // } else if (0 == lstrcmpA(szOID_OIWSEC_desCBC, ((CRYPT_ALGORITHM_IDENTIFIER *) AlgorithmBlob.pbData)->pszObjId)) { DebugTrace("INFO: Envelop encryption algorithm was DES.\n"); // // Set encryption algorithm name. // if (FAILED(hr = m_pIAlgorithm->put_Name(CAPICOM_ENCRYPTION_ALGORITHM_DES))) { DebugTrace("Error [%#x]: m_pIAlgorithm->put_Name() failed.\n", hr); goto ErrorExit; } // // For DES, key length is fixed at 56, and should be ignored. // } else if (0 == lstrcmpA(szOID_RSA_DES_EDE3_CBC, ((CRYPT_ALGORITHM_IDENTIFIER *) AlgorithmBlob.pbData)->pszObjId)) { DebugTrace("INFO: Envelop encryption algorithm was 3DES.\n"); // // Set encryption algorithm name. // if (FAILED(hr = m_pIAlgorithm->put_Name(CAPICOM_ENCRYPTION_ALGORITHM_3DES))) { DebugTrace("Error [%#x]: m_pIAlgorithm->put_Name() failed.\n", hr); goto ErrorExit; } // // For 3DES, key length is fixed at 168, and should be ignored. // } else { DebugTrace("INFO: Unknown envelop encryption algorithm.\n"); } // // Return msg handler to caller. // *phMsg = hMsg; } catch(...) { hr = E_POINTER; DebugTrace("Exception: invalid parameter.\n"); goto ErrorExit; } CommonExit: // // Free resource. // if (ParametersBlob.pbData) { ::CoTaskMemFree(ParametersBlob.pbData); } if (AlgorithmBlob.pbData) { ::CoTaskMemFree(AlgorithmBlob.pbData); } if (MessageBlob.pbData) { ::CoTaskMemFree(MessageBlob.pbData); } DebugTrace("Leaving CEnvelopedData::OpenToDecode().\n"); return hr; ErrorExit: // // Sanity check. // ATLASSERT(FAILED(hr)); if (hMsg) { ::CryptMsgClose(hMsg); } goto CommonExit; }
[ "polarisdp@gmail.com" ]
polarisdp@gmail.com
68f6df58e3eac6320245a950c0d67ae7c9f793f3
df8ad07125499db61660bad289c655d100e5bf17
/src/GrayScaleImage.hh
908792f6a6ffcca1346e705aa9a1c7fb5a3a3b0e
[]
no_license
ericwolter/nusif
1f6845ea013343328961bc46e56d4eac0f946e01
ec0d9c701ef6434f9966846b5a74064830caa855
refs/heads/master
2021-01-01T15:51:26.459500
2013-12-18T22:28:22
2013-12-18T22:28:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,405
hh
#pragma once #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wsign-conversion" #include "Types.hh" #include "Debug.hh" #include <string> #include <vector> //******************************************************************************************************************* /*! Class for loading and storing png images * * Very simple wrapper around lodepng library. * You also have to compile and link lodepng.cc */ //******************************************************************************************************************* class GrayScaleImage { public: /// Loads a grayscale png image from the specified file GrayScaleImage(const std::string & pngFilename); GrayScaleImage(const int width, const int height); void save( const std::string & pngFilename ); GrayScaleImage getResizedImage( int newWidth, int newHeight ) const; int width() const { return size_[0]; } int height() const { return size_[1]; } int size( int coord ) const; /// Returns a value between 0 and 1 /// 0 means black - 1 means white real operator() ( int x, int y ) const; /// Returns the gray value of the specified pixel (between 0 and 255) unsigned char & getElement ( int x, int y ); unsigned char getElement ( int x, int y ) const; void setElement (int x, int y, unsigned char value); protected: GrayScaleImage() {} // required in getResizedImage int size_[2]; //< 0=width, 1=height std::vector<unsigned char> image_; //< raw pixels }; //=================================================================================================================== // // Implementation of inline functions // //=================================================================================================================== inline unsigned char & GrayScaleImage::getElement ( int x, int y ) { ASSERT( x >= 0 && y >= 0 ); ASSERT( x < size_[0] ); ASSERT( y < size_[1] ); return image_[ y * size_[0] + x ]; } inline unsigned char GrayScaleImage::getElement ( int x, int y ) const { return const_cast<GrayScaleImage*> ( this )->getElement(x,y); } inline void GrayScaleImage::setElement (int x, int y, unsigned char value) { image_[y * size_[0] + x] = value; } inline int GrayScaleImage::size( int coord ) const { ASSERT(coord < 2); return size_[coord]; } #pragma GCC diagnostic pop
[ "eric.wolter@gmx.de" ]
eric.wolter@gmx.de
094cebb1f67299f04fb049946866e4fdd479479a
23254f37fb5662815a20e6c374def95c4a9e96ed
/output/application.KafkaEcho/BuildConfig/src/operator/Custom_2.cpp
db65c1a97b0ef546ed3ca220d5fb3af469d4b7a2
[]
no_license
jms90h5/KafkaEcho
1f7c3fbe85c7236ab9a2c915a16889d9647874c7
dd2b80b60addeb35361f19308b07ee13c31876b8
refs/heads/main
2023-03-26T03:43:23.699344
2021-03-25T17:55:42
2021-03-25T17:55:42
351,524,564
0
1
null
null
null
null
UTF-8
C++
false
false
5,684
cpp
// eJyFjz1vwkAMhuU1vwIhhrLkDoYOx1RaGFqQggID4zW45HS5D50d0bTqfycKtGvtycPzPn4pNnnLpjHcKfXcEgcHM5D9zmCc54K7iGKJr5e0LcP8yz7y5uW92Jey3dvPYrl76mh3bPJ6PDAg6uBQECfUjvTJGS8uIVmKukLxpj_0sXlV1ECfNGnzweBNJMDEknkgoi41S_1_0rAQBp839moH6UGbN36ik3wpNTht1FMxnPjH_07500X2kwHMwWIHqX_1T_0DM4JNJn_1LvlFfWGFbq #include "./Custom_2.h" using namespace SPL::_Operator; #include <SPL/Runtime/Function/SPLFunctions.h> #include <SPL/Runtime/Operator/Port/Punctuation.h> #define MY_OPERATOR_SCOPE SPL::_Operator #define MY_BASE_OPERATOR Custom_2_Base #define MY_OPERATOR Custom_2$OP static SPL::Operator * initer() { return new MY_OPERATOR_SCOPE::MY_OPERATOR(); } bool MY_BASE_OPERATOR::globalInit_ = MY_BASE_OPERATOR::globalIniter(); bool MY_BASE_OPERATOR::globalIniter() { instantiators_.insert(std::make_pair("Custom_2",&initer)); return true; } template<class T> static void initRTC (SPL::Operator& o, T& v, const char * n) { SPL::ValueHandle vh = v; o.getContext().getRuntimeConstantValue(vh, n); } MY_BASE_OPERATOR::MY_BASE_OPERATOR() : Operator() { uint32_t index = getIndex(); (void) getParameters(); // ensure thread safety by initializing here OperatorMetrics& om = getContext().getMetrics(); metrics_[0] = &(om.createCustomMetric("nExceptionsCaughtPort0", "Number of exceptions caught on port 0", Metric::Counter)); } MY_BASE_OPERATOR::~MY_BASE_OPERATOR() { for (ParameterMapType::const_iterator it = paramValues_.begin(); it != paramValues_.end(); it++) { const ParameterValueListType& pvl = it->second; for (ParameterValueListType::const_iterator it2 = pvl.begin(); it2 != pvl.end(); it2++) { delete *it2; } } } void MY_BASE_OPERATOR::tupleLogic(Tuple const & tuple, uint32_t port) { IPort0Type const & iport$0 = static_cast<IPort0Type const &>(tuple); AutoPortMutex $apm($svMutex, *this); { ::SPL::Functions::Utility::println(iport$0); } } void MY_BASE_OPERATOR::processRaw(Tuple const & tuple, uint32_t port) { try { tupleLogic (tuple, port); static_cast<MY_OPERATOR_SCOPE::MY_OPERATOR*>(this)->MY_OPERATOR::process(tuple, port); } catch (const SPL::SPLRuntimeException& e) { metrics_[port]->incrementValue(); unrecoverableExceptionShutdown(e.getExplanation()); } catch (const std::exception& e) { metrics_[port]->incrementValue(); unrecoverableExceptionShutdown(e.what()); } catch (...) { metrics_[port]->incrementValue(); unrecoverableExceptionShutdown("Unknown exception"); } } void MY_BASE_OPERATOR::punctLogic(Punctuation const & punct, uint32_t port) { } void MY_BASE_OPERATOR::punctPermitProcessRaw(Punctuation const & punct, uint32_t port) { { punctNoPermitProcessRaw(punct, port); } } void MY_BASE_OPERATOR::punctNoPermitProcessRaw(Punctuation const & punct, uint32_t port) { switch(punct) { case Punctuation::WindowMarker: try { punctLogic(punct, port); process(punct, port); } catch (const SPL::SPLRuntimeException& e) { metrics_[port]->incrementValue(); unrecoverableExceptionShutdown(e.getExplanation()); } catch (const std::exception& e) { metrics_[port]->incrementValue(); unrecoverableExceptionShutdown(e.what()); } catch (...) { metrics_[port]->incrementValue(); unrecoverableExceptionShutdown("Unknown exception"); } break; case Punctuation::FinalMarker: try { punctLogic(punct, port); process(punct, port); } catch (const SPL::SPLRuntimeException& e) { metrics_[port]->incrementValue(); unrecoverableExceptionShutdown(e.getExplanation()); } catch (const std::exception& e) { metrics_[port]->incrementValue(); unrecoverableExceptionShutdown(e.what()); } catch (...) { metrics_[port]->incrementValue(); unrecoverableExceptionShutdown("Unknown exception"); } break; case Punctuation::DrainMarker: case Punctuation::ResetMarker: case Punctuation::ResumeMarker: break; case Punctuation::SwitchMarker: break; case Punctuation::WatermarkMarker: break; default: break; } } void MY_BASE_OPERATOR::processRaw(Punctuation const & punct, uint32_t port) { switch(port) { case 0: punctNoPermitProcessRaw(punct, port); break; } } void MY_BASE_OPERATOR::checkpointStateVariables(NetworkByteBuffer & opstate) const { } void MY_BASE_OPERATOR::restoreStateVariables(NetworkByteBuffer & opstate) { } void MY_BASE_OPERATOR::checkpointStateVariables(Checkpoint & ckpt) { } void MY_BASE_OPERATOR::resetStateVariables(Checkpoint & ckpt) { } void MY_BASE_OPERATOR::resetStateVariablesToInitialState() { } bool MY_BASE_OPERATOR::hasStateVariables() const { return false; } void MY_BASE_OPERATOR::resetToInitialStateRaw() { AutoMutex $apm($svMutex); StateHandler *sh = getContext().getStateHandler(); if (sh != NULL) { sh->resetToInitialState(); } resetStateVariablesToInitialState(); } void MY_BASE_OPERATOR::checkpointRaw(Checkpoint & ckpt) { AutoMutex $apm($svMutex); StateHandler *sh = getContext().getStateHandler(); if (sh != NULL) { sh->checkpoint(ckpt); } checkpointStateVariables(ckpt); } void MY_BASE_OPERATOR::resetRaw(Checkpoint & ckpt) { AutoMutex $apm($svMutex); StateHandler *sh = getContext().getStateHandler(); if (sh != NULL) { sh->reset(ckpt); } resetStateVariables(ckpt); }
[ "jms@sharpe.com" ]
jms@sharpe.com
3e897429a8c84de8b98232485efe1741e939d5e1
385cfbb27ee3bcc219ec2ac60fa22c2aa92ed8a0
/ThirdParty/fbxsdk/2009.3/include/fbxfilesdk/kfbxmodules/kfbxscopedloadingfilename.h
97645821ea6e3361b6e2cedab73b1a1c964b0967
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
palestar/medusa
edbddf368979be774e99f74124b9c3bc7bebb2a8
7f8dc717425b5cac2315e304982993354f7cb27e
refs/heads/develop
2023-05-09T19:12:42.957288
2023-05-05T12:43:35
2023-05-05T12:43:35
59,434,337
35
18
MIT
2018-01-21T01:34:01
2016-05-22T21:05:17
C++
UTF-8
C++
false
false
3,943
h
#ifndef FBXFILESDK_KFBXMODULES_KFBXSCOPEDLOADINGFILENAME_H #define FBXFILESDK_KFBXMODULES_KFBXSCOPEDLOADINGFILENAME_H /************************************************************************************** Copyright ?2001 - 2006 Autodesk, Inc. and/or its licensors. All Rights Reserved. The coded instructions, statements, computer programs, and/or related material (collectively the "Data") in these files contain unpublished information proprietary to Autodesk, Inc. and/or its licensors, which is protected by Canada and United States of America federal copyright law and by international treaties. The Data may not be disclosed or distributed to third parties, in whole or in part, without the prior written consent of Autodesk, Inc. ("Autodesk"). THE DATA IS PROVIDED "AS IS" AND WITHOUT WARRANTY. ALL WARRANTIES ARE EXPRESSLY EXCLUDED AND DISCLAIMED. AUTODESK MAKES NO WARRANTY OF ANY KIND WITH RESPECT TO THE DATA, EXPRESS, IMPLIED OR ARISING BY CUSTOM OR TRADE USAGE, AND DISCLAIMS ANY IMPLIED WARRANTIES OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE OR USE. WITHOUT LIMITING THE FOREGOING, AUTODESK DOES NOT WARRANT THAT THE OPERATION OF THE DATA WILL BE UNINTERRUPTED OR ERROR FREE. IN NO EVENT SHALL AUTODESK, ITS AFFILIATES, PARENT COMPANIES, LICENSORS OR SUPPLIERS ("AUTODESK GROUP") BE LIABLE FOR ANY LOSSES, DAMAGES OR EXPENSES OF ANY KIND (INCLUDING WITHOUT LIMITATION PUNITIVE OR MULTIPLE DAMAGES OR OTHER SPECIAL, DIRECT, INDIRECT, EXEMPLARY, INCIDENTAL, LOSS OF PROFITS, REVENUE OR DATA, COST OF COVER OR CONSEQUENTIAL LOSSES OR DAMAGES OF ANY KIND), HOWEVER CAUSED, AND REGARDLESS OF THE THEORY OF LIABILITY, WHETHER DERIVED FROM CONTRACT, TORT (INCLUDING, BUT NOT LIMITED TO, NEGLIGENCE), OR OTHERWISE, ARISING OUT OF OR RELATING TO THE DATA OR ITS USE OR ANY OTHER PERFORMANCE, WHETHER OR NOT AUTODESK HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH LOSS OR DAMAGE. **************************************************************************************/ #include <fbxfilesdk/components/kbaselib/kaydaradef_h.h> // Local includes #include <fbxfilesdk/kfbxmodules/kfbxloadingstrategy.h> // FBX includes #include <fbxfilesdk/components/kbaselib/klib/kstring.h> // FBX begin namespace #include <fbxfilesdk/fbxfilesdk_nsbegin.h> ///////////////////////////////////////////////////////////////////////////////////////// // TODO: todonamespace // Every FBX module should have a namespace but for consistency, // you have, for this version of fbx, to use the fbx object without namespace //namespace kfbxmodules //{ /** \class KFbxScopedLoadingFileName * * \brief Implementation a loading strategy. This loading strategy load a single dll and release it when the * the strategy goes out of scope. */ class KFBX_DLL KFbxScopedLoadingFileName : public KFbxLoadingStrategy { public: /** *\name Public interface */ //@{ /** Constructor * \param pPath The file path. */ explicit KFbxScopedLoadingFileName(const char* pPath); /** Destructor */ virtual ~KFbxScopedLoadingFileName(); //@} private: /////////////////////////////////////////////////////////////////////////////// // // WARNING! // // Anything beyond these lines may not be documented accurately and is // subject to change without notice. // /////////////////////////////////////////////////////////////////////////////// #ifndef DOXYGEN_SHOULD_SKIP_THIS void* mInstance; KString mPath; // From KFbxLoadingStrategy virtual bool SpecificLoad(KFbxPluginData& pData); virtual void SpecificUnload(); #endif }; //} // FBX end namespace #include <fbxfilesdk/fbxfilesdk_nsend.h> #endif // FBXFILESDK_KFBXMODULES_KFBXSCOPEDLOADINGFILENAME_H
[ "rlyle@palestar.com" ]
rlyle@palestar.com
f299784192740517fa6a0e04a8a7aecb8ff4af88
4418f86b56eb89e0bf83d1cb61d67e30fbf0cab9
/helperfiles/misc/QuadControl-cpp-master/Ground_station/src/joystick.h
c7611e3c22995aa4e8d1f908b7f2e7095f12bfa6
[]
no_license
nadurthi/ros_roverbot_ws
95441893610d64010e4f4c44b94dc6300e77c6fb
9f1330d30c170b817a8df3d229d63082eec6697d
refs/heads/master
2020-12-29T21:53:00.650936
2020-02-10T16:41:02
2020-02-10T16:41:02
238,745,801
0
0
null
null
null
null
UTF-8
C++
false
false
3,245
h
/** * @file joystick.cpp * @brief Acquire data from joystick.\n * Copyright (c) 2013 Smart Laboratory at SUNY at Buffalo * This computer program includes confidential, proprietary * information and is a trade secret of the Author. All * use, disclosure, and/or reproduction is prohibited unless * expressly authorized in writing. * All rights reserved. * @author mdiz * @version $Header$ * FLAG REASON DATE WHO DESCRIPTION \n * ---- ---- ------- ------ -------- -------------------------------------\n * @bug 0001 Created Mar 23, 2012 mdiz File creation\n * @bug 0002 x42pro Jun 06, 2013 mdiz Size change in data containers to use saitek x52 pro */ #ifndef JOYSTICK_H_ #define JOYSTICK_H_ #include <pthread.h> #include <linux/joystick.h> #include <string> void* update(void *ptr); #define Stopbit 0 #define handledownbit 1 #define handlemidbit 2 #define handleleftbit 3 #define handlerightbit 4 #define leftupbit 5 #define leftdownbit 6 #define midleftbit 7 #define mid rightbit 8 #define rightdownbit 9 #define rightupbit 10 /// @brief Hold \b ALL joystick information struct stjoystick{ /// @brief Hold description of joystick. struct { /// amount of axis int axis; /// amount of buttons int button; /// Joystick name char name[256]; /// File name for joystick only for linux char* file; /// IF only for windows int id; }info; /// Normalize all axis in range [-1 1] double axisNorm[11]; /// State of each button press or unpress int button[39],buttonflags[11],axisflags[3]; /// The joystick state is updated bool update; /// Which axis is throttle int thtl; /// Linux custom descriptions int fd; struct { pthread_t thread; }thread; js_event event; int axis[11]; int axisOld[11]; }; ///@brief Small and simple class to acquire joystick information class joystick { private: public: /// Joystick information stjoystick joy; /** * Custom constructor * @param file_ */ joystick(std::string file_="/dev/input/js0"); /** * Initialize the device * @return true if success */ bool start(); double getaxis(int axisno); void getbuttons(int * Dbutt); /* * if buttno >=11 clear all 11 button flags */ void ClearButtonFlag(int buttno); int GetButtonFlag(int buttno); bool CheckifEmergencyStopRequest(); void ClearAxisFlag(int axisno); int GetAxisFlag(int axisno); void GetReMapAxis(double * Daxis,double * lb,double * ub); /* * Re,ap the value D in [-1,1] to a value in [lu,ub] linearly */ double ReMapValue(double D, double lb, double ub); /** * Initialize the device * @param file_ set the joystick before start * @return true if success */ bool checkif_eventoccured(); bool checkif_Axiseventoccured(); bool checkif_Buttoneventoccured(); bool start(char* file_); /* * increments the val with rate whenever the button is pressed * returns the incremented val */ double IncrementVal_Button(double val,double rate, double lb, double ub); double DecrementVal_Button(double val,double rate, double lb, double ub); /** * Standard destructor */ virtual ~joystick(); }; #endif /* JOYSTICK_H_ */
[ "n.adurthi@gmail.com" ]
n.adurthi@gmail.com
a06c75e9d16870c5e024f6ff469c292c40fac1b5
26cf4ff96cfb7e970feb98be931549a879f3f4a4
/code/ClassSelectionWindow.h
2f3101a26899e9a49a6672529475ec9b85c9bda9
[]
no_license
HaikuArchives/Finance
ec573b8d8ac87c48dd8b1c7546249d4e3292a6a7
6c7281ea410c5dbb759e98d45128c5a7dfe349e8
refs/heads/master
2021-01-22T11:59:11.618399
2017-12-06T14:05:57
2017-12-06T16:21:41
11,803,829
2
6
null
2017-12-06T16:21:42
2013-07-31T23:49:20
C++
UTF-8
C++
false
false
83
h
#include "StringInputWindow.h" class CatSelectionWindow : public StringInputWindow
[ "plfiorini@fa5accb0-463b-4a10-a226-9995dc1be018" ]
plfiorini@fa5accb0-463b-4a10-a226-9995dc1be018
3557163b2abd145fcc3e530ffa89ae8fd70145c5
d5ebc2990b64d557a7df9e76e3b3e3f2726cdc2e
/src/Position.hpp
4910ba66df65188840e28e7d7d8387ff106f2a97
[]
no_license
vmstavens/sokoban_solver
b1f2bc9ed87e916a1e63bc1c45ad21ffbfbb85ce
db8e84cbf64b11b8b4236180dd595dbd3c0cfdc1
refs/heads/main
2023-07-12T03:23:21.898903
2021-08-16T07:51:34
2021-08-16T07:51:34
371,096,607
0
0
null
null
null
null
UTF-8
C++
false
false
452
hpp
#pragma once #include <string> class Position { private: public: int y = 0; int x = 0; Position(); Position(int x, int y); ~Position(); Position operator+(const Position& pos); Position operator-(const Position& pos); bool operator==(const Position& pos); bool operator!=(const Position& pos); Position operator+=(const Position& pos); Position operator-=(const Position& pos); Position operator*(int scale); std::string str(); };
[ "victorstaven@protonmail.com" ]
victorstaven@protonmail.com
b2caf3510da44a6ce437c420ed331cbc482bbfcf
c6f61d1b7802d4d366d1770e67cac2555e382fe3
/AutoYams/AutoYams/include/AutoYams/opencv/graphic/VideoOpenCV.h
74d5410e29769beef920a4587be43656920e62f9
[ "MIT" ]
permissive
TrueAbastien/AutoYams
4e2f4fde051650d712bdecaabfd482af6ec0764e
3fc566ae9df62a79a53e7988610c687d354f6c1f
refs/heads/master
2022-07-03T04:25:29.219372
2020-05-15T19:40:14
2020-05-15T19:40:14
263,786,534
0
0
null
null
null
null
UTF-8
C++
false
false
3,384
h
#pragma once #include <AutoYams\opencv\graphic\ImageOpenCV.h> #include "opencv2/videoio.hpp" #include <QTimer> #include <QLabel> #include <ctime> #include <iostream> /** * \class VideoOpenCV * \brief Object updating ImageOpenCV object * \author Bastien LEGOY * \version 1.0.0 * \date $Date: 2020/05/15 $ * * Depending on framerate, update ImageOpenCV stored object from current Capture device output. */ class VideoOpenCV : public QObject { Q_OBJECT public: /** * \brief Default constructor * \param lab Reference of the Label used to create ImageOpenCV instance and set pixmap in * \param cap Video Capture device reference outputing the current webcam recorded image * \param fps Default framerate for timer instantiation * * Initialize object propreties, timed image processing & events connections. */ VideoOpenCV(QLabel* lab, cv::VideoCapture* cap = nullptr, int fps = 30); public slots: /** * \brief Change max framerate of Image * \param fps New max framerate * * Change max framerate per second of the current Camera Device config. */ void setMaxFPS(int fps); /** * \brief Change capture device through device Index * \param capIndex Specific device Index * * Change current device if specified in Devices list. */ void setCapture(int capIndex); /** * \brief Change current image brightness * \param val New image brightness * * Change current brightness in both image and current configuration. */ void setBrightness(int val); /** * \brief Change current image contrast * \param val New image contrast * * Change current contrast in both image and current configuration. */ void setContrast(int val); /** * \brief Change current image zoom/scale * \param val New image zoom/scale * * Change current zoom/scale in both image and current configuration. */ void setZoom(double val); /** * \brief Disable image display * * Display a white Pixmap wherever the output image was previously displayed. */ void turnOff(); private: /** * Capture device reference (from main application). */ cv::VideoCapture* capture; /** * Current max framerate. */ int frameRate; /** * Current image contrast. */ double contrast; /** * Current image brightness. */ int brightness; /** * Current OpenCV image model (cv::Mat). */ cv::Mat currentImage; /** * Video Player object: update Timer called 'framerate' times per second at max. */ QTimer* player; /** * Image OpenCV object to display the capture output in. */ ImageOpenCV image; /** * Reference of the container for autoscaling purposes. */ QLabel* container; /** * List of all dices founds by algorithm by frame. */ QList<int> latestDiceList; /** * List of all dices saved if the 'latestDiceList' remains unchanged for at least 1 second. */ QList<int> savedDiceList; /** * Amount of ticks requiered for the 'savedDiceList' to be updated. * Should be the same as max framerate. */ int waitingTicks; /** * Current amount of ticks passed with 'latestDiceList' remaining unchanged. */ int currentTicks; signals: /** * \brief Signal sent when new dices have been detected long enough * \param dices Value list of all detected dices * * Whenever the dices have been detected and unchanged for more than 1 second, * this signal will trigger through the EventThrowDice (Event Redirector). */ void DiceChanged(QList<int>& dices); };
[ "bastien.legoy@gmail.com" ]
bastien.legoy@gmail.com
692b91c0e0125d8df73461940bb9e6e5ba8b2845
6fac50aa19020566f2e01595a6a0632a42ba3da3
/UVA/DFS/11518.cpp
8b2dba2f8f685ce7eeb8014234202b519f84aec5
[]
no_license
sayemimtiaz/competitive-programming
c36905ee99b1cfeb578c2b47367eff901a5e444f
58ff86e0d3804bd072d733e5fa491d6c192e4345
refs/heads/master
2023-01-27T14:47:06.767566
2023-01-08T21:50:49
2023-01-08T21:50:49
36,745,247
0
0
null
null
null
null
UTF-8
C++
false
false
858
cpp
#include<cstdio> #include<vector> #include<cstdlib> #define SIZE 500000 using namespace std; typedef vector<long> vi; vi gr[SIZE]; long n,count; bool vis[SIZE]; void init() { long i; for(i=0; i<=n; i++) { gr[i].clear(); } memset(vis,0,sizeof(vis)); } void dfs(long a) { long next,i; vis[a]=1; for( i=0;i<gr[a].size();i++) { next=gr[a][i]; if(!vis[next]) { count++; dfs(next); } } } int main() { long i,a,b,edge,t,k,l; scanf("%ld",&t); for(k=1;k<=t;k++) { scanf("%ld %ld %ld",&n,&edge,&l); init(); for(i=0;i<edge;i++) { scanf("%ld %ld",&a,&b); gr[a-1].push_back(b-1); } count=0; for(i=0;i<l;i++) { scanf("%ld",&a); if(!vis[a-1]) count++; dfs(a-1); } printf("%ld\n",count); } return 0; }
[ "imtiaz.cuet@gmail.com" ]
imtiaz.cuet@gmail.com
f989fbdf659b5e421e44208b2f089ab034d0993e
9ad96c4e6b08beebfa0dc7e22fa4db08bbc68fba
/lib/SCLAW/SCLAW.cpp
84304e59f80572a81f7d7f0defc123a2a5d0fbbb
[]
no_license
Arrakark/V2FC
2ac3477025eb207a44f17dd35f71a5a79fa1816e
1aaef6e2155b3168f6da8e7e64e34442805e9b2f
refs/heads/master
2020-04-22T02:24:42.405690
2018-08-06T23:07:07
2018-08-06T23:07:07
170,047,559
1
0
null
2019-02-11T01:15:50
2019-02-11T01:15:50
null
UTF-8
C++
false
false
474
cpp
#include "SCLAW.h" SCLAW::SCLAW(int _pincer_servo_pin, int _support_servo_pin, int _pickup_pin){ pincer_servo_pin = _pincer_servo_pin; support_servo_pin = _support_servo_pin; pickup_pin = _pickup_pin; } void SCLAW::init() { pincer_servo.attach(pincer_servo_pin); support_servo.attach(support_servo_pin); pinMode(pickup_pin,INPUT_PULLUP); } void SCLAW::hug() { } void SCLAW::open() { } void SCLAW::pickup() { } void SCLAW::dropoff() { }
[ "novakovic.vladimir@alumni.ubc.ca" ]
novakovic.vladimir@alumni.ubc.ca
1eb9b7192b3399c0ee136e6979587d73ebc76cb0
7b6785d57e92fab5a929bd61621f97feecc47913
/MySnmp/src/DeleteHostModule.cpp
309a2b0e654d4f9d600c55d5847fc92ce25ffda7
[]
no_license
core2duoe6420/MySnmp
97dcd7139cd5a63a58adc6a1e4298b58c7dbe533
796d02f6eac2ad20791a64b81c4ec7049a222f30
refs/heads/master
2021-01-16T18:19:13.195621
2014-04-23T09:01:28
2014-04-23T09:01:28
18,564,052
1
0
null
null
null
null
GB18030
C++
false
false
702
cpp
#include <MySnmp/View/Module.h> #include <MySnmp/View/TopoCanvas.h> #include <MySnmp/Command/HostCommand.h> #include <wx/wx.h> #include <MySnmp/debug.h> using namespace mysnmp; void DeleteHostModule::OnMenuItemClick(wxCommandEvent& event) { TopoHost * topoHost = canvas->GetChosenHost(); int hostId = topoHost->GetHostId(); wxMessageDialog * dialog = new wxMessageDialog(canvas->GetParent(), L"确认删除主机" + topoHost->GetName() + L"?", L"确认删除主机", wxICON_INFORMATION | wxYES_NO); if (dialog->ShowModal() == wxID_YES) { canvas->RemoveHost(hostId); canvas->RefreshCanvas(); DeleteHostCommand command(hostId); command.Execute(); } dialog->Destroy(); }
[ "core2duoe6420@vip.qq.com" ]
core2duoe6420@vip.qq.com