blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
sequencelengths
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
sequencelengths
1
1
author
stringlengths
0
119
cb02062573ba93e710d45e739306534c72a71e88
8d52c40a3c5acc0a374198566d6b98d071aa1f86
/cppcheck/data/c_files/460.cpp
696c08c0f7a997c5d3c7da5d8184b228d1f21e04
[ "MIT" ]
permissive
awsm-research/LineVul
8f6e6a7ee34c50b2b8d7d4a2d79b680f38c141d6
e739809970189f715aef6a707c1543786e3a9ec8
refs/heads/main
2023-04-29T04:03:06.454615
2023-04-15T06:59:41
2023-04-15T06:59:41
449,643,469
51
23
null
null
null
null
UTF-8
C++
false
false
1,850
cpp
static inline ogg_uint32_t decode_packed_entry_number(codebook *book, oggpack_buffer *b){ ogg_uint32_t chase=0; int read=book->dec_maxlength; long lok = oggpack_look(b,read),i; while(lok<0 && read>1) lok = oggpack_look(b, --read); if(lok<0){ oggpack_adv(b,1); /* force eop */ return -1; } /* chase the tree with the bits we got */ switch (book->dec_method) { case 0: { /* book->dec_nodeb==1, book->dec_leafw==1 */ /* 8/8 - Used */ unsigned char *t=(unsigned char *)book->dec_table; for(i=0;i<read;i++){ chase=t[chase*2+((lok>>i)&1)]; if(chase&0x80UL)break; } chase&=0x7fUL; break; } case 1: { /* book->dec_nodeb==1, book->dec_leafw!=1 */ /* 8/16 - Used by infile2 */ unsigned char *t=(unsigned char *)book->dec_table; for(i=0;i<read;i++){ int bit=(lok>>i)&1; int next=t[chase+bit]; if(next&0x80){ chase= (next<<8) | t[chase+bit+1+(!bit || t[chase]&0x80)]; break; } chase=next; } //chase&=0x7fffUL; chase&=~0x8000UL; break; } case 2: { /* book->dec_nodeb==2, book->dec_leafw==1 */ /* 16/16 - Used */ for(i=0;i<read;i++){ chase=((ogg_uint16_t *)(book->dec_table))[chase*2+((lok>>i)&1)]; if(chase&0x8000UL)break; } //chase&=0x7fffUL; chase&=~0x8000UL; break; } case 3: { /* book->dec_nodeb==2, book->dec_leafw!=1 */ /* 16/32 - Used by infile2 */ ogg_uint16_t *t=(ogg_uint16_t *)book->dec_table; for(i=0;i<read;i++){ int bit=(lok>>i)&1; int next=t[chase+bit]; if(next&0x8000){ chase= (next<<16) | t[chase+bit+1+(!bit || t[chase]&0x8000)]; break; } chase=next; } //chase&=0x7fffffffUL; chase&=~0x80000000UL; break; } case 4: { //Output("32/32"); for(i=0;i<read;i++){ chase=((ogg_uint32_t *)(book->dec_table))[chase*2+((lok>>i)&1)]; if(chase&0x80000000UL)break; } //chase&=0x7fffffffUL; chase&=~0x80000000UL; break; } } if(i<read){ oggpack_adv(b,i+1); return chase; } oggpack_adv(b,read+1); return(-1); }
cd5b9bc6b0f57d4b67bf8e333068b3cd7faabe80
ad273708d98b1f73b3855cc4317bca2e56456d15
/aws-cpp-sdk-codestar-notifications/include/aws/codestar-notifications/model/SubscribeRequest.h
8719a1cd575172f2e196454f224bd14a1b4e3229
[ "MIT", "Apache-2.0", "JSON" ]
permissive
novaquark/aws-sdk-cpp
b390f2e29f86f629f9efcf41c4990169b91f4f47
a0969508545bec9ae2864c9e1e2bb9aff109f90c
refs/heads/master
2022-08-28T18:28:12.742810
2020-05-27T15:46:18
2020-05-27T15:46:18
267,351,721
1
0
Apache-2.0
2020-05-27T15:08:16
2020-05-27T15:08:15
null
UTF-8
C++
false
false
6,249
h
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #pragma once #include <aws/codestar-notifications/CodeStarNotifications_EXPORTS.h> #include <aws/codestar-notifications/CodeStarNotificationsRequest.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/codestar-notifications/model/Target.h> #include <utility> namespace Aws { namespace CodeStarNotifications { namespace Model { /** */ class AWS_CODESTARNOTIFICATIONS_API SubscribeRequest : public CodeStarNotificationsRequest { public: SubscribeRequest(); // Service request name is the Operation name which will send this request out, // each operation should has unique request name, so that we can get operation's name from this request. // Note: this is not true for response, multiple operations may have the same response name, // so we can not get operation's name from response. inline virtual const char* GetServiceRequestName() const override { return "Subscribe"; } Aws::String SerializePayload() const override; /** * <p>The Amazon Resource Name (ARN) of the notification rule for which you want to * create the association.</p> */ inline const Aws::String& GetArn() const{ return m_arn; } /** * <p>The Amazon Resource Name (ARN) of the notification rule for which you want to * create the association.</p> */ inline bool ArnHasBeenSet() const { return m_arnHasBeenSet; } /** * <p>The Amazon Resource Name (ARN) of the notification rule for which you want to * create the association.</p> */ inline void SetArn(const Aws::String& value) { m_arnHasBeenSet = true; m_arn = value; } /** * <p>The Amazon Resource Name (ARN) of the notification rule for which you want to * create the association.</p> */ inline void SetArn(Aws::String&& value) { m_arnHasBeenSet = true; m_arn = std::move(value); } /** * <p>The Amazon Resource Name (ARN) of the notification rule for which you want to * create the association.</p> */ inline void SetArn(const char* value) { m_arnHasBeenSet = true; m_arn.assign(value); } /** * <p>The Amazon Resource Name (ARN) of the notification rule for which you want to * create the association.</p> */ inline SubscribeRequest& WithArn(const Aws::String& value) { SetArn(value); return *this;} /** * <p>The Amazon Resource Name (ARN) of the notification rule for which you want to * create the association.</p> */ inline SubscribeRequest& WithArn(Aws::String&& value) { SetArn(std::move(value)); return *this;} /** * <p>The Amazon Resource Name (ARN) of the notification rule for which you want to * create the association.</p> */ inline SubscribeRequest& WithArn(const char* value) { SetArn(value); return *this;} inline const Target& GetTarget() const{ return m_target; } inline bool TargetHasBeenSet() const { return m_targetHasBeenSet; } inline void SetTarget(const Target& value) { m_targetHasBeenSet = true; m_target = value; } inline void SetTarget(Target&& value) { m_targetHasBeenSet = true; m_target = std::move(value); } inline SubscribeRequest& WithTarget(const Target& value) { SetTarget(value); return *this;} inline SubscribeRequest& WithTarget(Target&& value) { SetTarget(std::move(value)); return *this;} /** * <p>An enumeration token that, when provided in a request, returns the next batch * of the results.</p> */ inline const Aws::String& GetClientRequestToken() const{ return m_clientRequestToken; } /** * <p>An enumeration token that, when provided in a request, returns the next batch * of the results.</p> */ inline bool ClientRequestTokenHasBeenSet() const { return m_clientRequestTokenHasBeenSet; } /** * <p>An enumeration token that, when provided in a request, returns the next batch * of the results.</p> */ inline void SetClientRequestToken(const Aws::String& value) { m_clientRequestTokenHasBeenSet = true; m_clientRequestToken = value; } /** * <p>An enumeration token that, when provided in a request, returns the next batch * of the results.</p> */ inline void SetClientRequestToken(Aws::String&& value) { m_clientRequestTokenHasBeenSet = true; m_clientRequestToken = std::move(value); } /** * <p>An enumeration token that, when provided in a request, returns the next batch * of the results.</p> */ inline void SetClientRequestToken(const char* value) { m_clientRequestTokenHasBeenSet = true; m_clientRequestToken.assign(value); } /** * <p>An enumeration token that, when provided in a request, returns the next batch * of the results.</p> */ inline SubscribeRequest& WithClientRequestToken(const Aws::String& value) { SetClientRequestToken(value); return *this;} /** * <p>An enumeration token that, when provided in a request, returns the next batch * of the results.</p> */ inline SubscribeRequest& WithClientRequestToken(Aws::String&& value) { SetClientRequestToken(std::move(value)); return *this;} /** * <p>An enumeration token that, when provided in a request, returns the next batch * of the results.</p> */ inline SubscribeRequest& WithClientRequestToken(const char* value) { SetClientRequestToken(value); return *this;} private: Aws::String m_arn; bool m_arnHasBeenSet; Target m_target; bool m_targetHasBeenSet; Aws::String m_clientRequestToken; bool m_clientRequestTokenHasBeenSet; }; } // namespace Model } // namespace CodeStarNotifications } // namespace Aws
4dac5a840db6303ee72c34947750dcc60996e9b5
8dc31889551a9eaf567fb8af89a81bd615220c7e
/Atcoder/ABC/165/e.cpp
5e69b63f16591717f0be7462971b893b35800d32
[]
no_license
mijinko17/competitive-programming
c025cd731a227908f93b150c020a01d144b4358a
8743ef7f62aadba66c5c2f46bd199e50ce4160da
refs/heads/master
2020-07-30T07:34:23.255781
2020-05-19T15:46:16
2020-05-19T15:46:16
210,136,713
0
0
null
null
null
null
UTF-8
C++
false
false
556
cpp
#include <bits/stdc++.h> typedef long long lint; using namespace std; lint n, m; int main() { cin >> n >> m; int offset = 0; if (n % 2 != 0) { for (int i = 0; i < m; i++) { cout << i + 1 << ' ' << n - i << endl; } return 0; } else { for (int i = 0; i < m; i++) { int left = i + 1, right = n - i - offset; if (right - left == n / 2) { offset += 1; right--; } cout << left << ' ' << right << endl; } } }
00c76913aa7cf73ff8cab7c9c8d6061db817af69
191c0e5fdf8c0284e2ee81ee14333ebf84810e32
/hamerly_kmeans.cpp
b13d66a8328cee0bcec51241bfb77f7dee9cbcc7
[]
no_license
philipwhen/fasterkmeans
b92d8e34da365debf290f2db57e3a5d0cef94ece
f5ea009a539c36d1cc6163cfcdc5e571c16e1c28
refs/heads/master
2021-01-19T13:17:55.309572
2017-09-21T03:03:22
2017-09-21T03:03:22
82,394,814
0
0
null
2017-03-05T14:21:44
2017-02-18T15:10:31
C++
UTF-8
C++
false
false
6,296
cpp
/* Authors: Greg Hamerly and Jonathan Drake * Feedback: [email protected] * See: http://cs.baylor.edu/~hamerly/software/kmeans.php * Copyright 2014 */ #include "hamerly_kmeans.h" #include "general_functions.h" #include <cmath> /* Hamerly's algorithm that is a 'simplification' of Elkan's, in that it keeps * the following bounds: * - One upper bound per clustered record on the distance between the record * and its closest center. It is always greater than or equal to the true * distance between the record and its closest center. This is the same as in * Elkan's algorithm. * - *One* lower bound per clustered record on the distance between the record * and its *second*-closest center. It is always less than or equal to the * true distance between the record and its second closest center. This is * different information than Elkan's algorithm -- his algorithm keeps k * lower bounds for each record, for a total of (n*k) lower bounds. * * The basic ideas are: * - when lower(x) <= upper(x), we need to recalculate the closest centers for * the record x, and reset lower(x) and upper(x) to their boundary values * - whenever a center moves * - calculate the distance it moves 'd' * - for each record x assigned to that center, update its upper bound * - upper(x) = upper(x) + d * - after each iteration * - find the center that has moved the most (with distance 'd') * - update the lower bound for all (?) records: * - lower(x) = lower(x) - d * * Parameters: none * * Return value: the number of iterations performed (always at least 1) */ // this version only updates center locations when necessary int HamerlyKmeans::runThread(int threadId, int maxIterations) { int iterations = 0; int startNdx = start(threadId); int endNdx = end(threadId); while ((iterations < maxIterations) && ! converged) { ++iterations; // compute the inter-center distances, keeping only the closest distances update_s(threadId); synchronizeAllThreads(); // loop over all records for (int i = startNdx; i < endNdx; ++i) { unsigned short closest = assignment[i]; // if upper[i] is less than the greater of these two, then we can // ignore record i double upper_comparison_bound = std::max(s[closest], lower[i]); // first check: if u(x) <= s(c(x)) or u(x) <= lower(x), then ignore // x, because its closest center must still be closest if (upper[i] <= upper_comparison_bound) { continue; } // otherwise, compute the real distance between this record and its // closest center, and update upper double u2 = pointCenterDist2(i, closest); upper[i] = sqrt(u2); // if (u(x) <= s(c(x))) or (u(x) <= lower(x)), then ignore x if (upper[i] <= upper_comparison_bound) { continue; } // now update the lower bound by looking at all other centers double l2 = std::numeric_limits<double>::max(); // the squared lower bound for (int j = 0; j < k; ++j) { if (j == closest) { continue; } double dist2 = pointCenterDist2(i, j); if (dist2 < u2) { // another center is closer than the current assignment // change the lower bound to be the current upper bound // (since the current upper bound is the distance to the // now-second-closest known center) l2 = u2; // adjust the upper bound and the current assignment u2 = dist2; closest = j; } else if (dist2 < l2) { // we must reduce the lower bound on the distance to the // *second* closest center to x[i] l2 = dist2; } } // we have been dealing in squared distances; need to convert lower[i] = sqrt(l2); // if the assignment for i has changed, then adjust the counts and // locations of each center's accumulated mass if (assignment[i] != closest) { upper[i] = sqrt(u2); changeAssignment(i, closest, threadId); } } verifyAssignment(iterations, startNdx, endNdx); // ELKAN 4, 5, AND 6 // calculate the new center locations synchronizeAllThreads(); if (threadId == 0) { int furthestMovingCenter = move_centers(); converged = (0.0 == centerMovement[furthestMovingCenter]); } synchronizeAllThreads(); if (! converged) { update_bounds(startNdx, endNdx); } synchronizeAllThreads(); } return iterations; } /* This method does the following: * - finds the furthest-moving center * - finds the distances moved by the two furthest-moving centers * - updates the upper/lower bounds for each record * * Parameters: none */ void HamerlyKmeans::update_bounds(int startNdx, int endNdx) { int furthestMovingCenter = 0; double longest = centerMovement[furthestMovingCenter]; double secondLongest = 0.0; for (int j = 0; j < k; ++j) { if (longest < centerMovement[j]) { secondLongest = longest; longest = centerMovement[j]; furthestMovingCenter = j; } else if (secondLongest < centerMovement[j]) { secondLongest = centerMovement[j]; } } // update upper/lower bounds for (int i = startNdx; i < endNdx; ++i) { // the upper bound increases by the amount that its center moved upper[i] += centerMovement[assignment[i]]; // The lower bound decreases by the maximum amount that any center // moved, unless the furthest-moving center is the one it's assigned // to. In the latter case, the lower bound decreases by the amount // of the second-furthest-moving center. lower[i] -= (assignment[i] == furthestMovingCenter) ? secondLongest : longest; } }
daad9c1063631ba908ad58b1c417cdb4dfcfb722
1db1283e0c80cfad03826ebfee64cc9233a1d0ac
/ralgo/geom/simplex/triangle2d.h
62d1cbbb37e3d562366cd820de14adff2d00c259
[ "MIT" ]
permissive
mirmik/ralgo
34d5fd78bdf819b6992aad4501a0420148a1ce60
f0bc9328a875b819e08667b461bb143f39ae516c
refs/heads/master
2023-08-21T14:21:33.722994
2023-08-16T19:40:16
2023-08-16T19:40:16
164,855,319
0
0
null
null
null
null
UTF-8
C++
false
false
1,240
h
#ifndef RALGO_GEOM_SIMPLEX_TRIANGLE_32_H #define RALGO_GEOM_SIMPLEX_TRIANGLE_2D_H #include <ralgo/geom/vector2d.h> #include <ralgo/linalg/linalg.h> namespace ralgo { namespace geom { namespace simplex { template <class T> class triangle2d { point2d<T> _a; point2d<T> _b; point2d<T> _c; public: triangle2d(const point2d<T> &a, const point2d<T> &b, const point2d<T> &c) : _a(a), _b(b), _c(c) { } linalg::vec<T, 3> baricentric_of_point2d(const point2d<T> &p) { // https://habr.com/ru/post/249467/ auto ab = _b - _a; auto ac = _c - _a; auto pa = _a - p; auto x = linalg::vec<T, 3>{ab.x(), ac.x(), pa.x()}; auto y = linalg::vec<T, 3>{ab.y(), ac.y(), pa.y()}; auto z = linalg::cross(x, y); auto r = z / z.z; return {1 - r.x - r.y, r.x, r.y}; } }; } } } #endif
f95a1736be1ce0ccc75b8d64b6ff6ffa4f8d8ec5
ec55fdcd6422a9be12cf5167d53beed9d84c2961
/归并排序(递归版).cpp
010eed784ba9edab2e23481dab11ea984e331927
[]
no_license
hml-sason/sason
a11185e579c391e3b958063c826f4ef2338727af
8df84380c03c52b2b396c76327fbb7a8288b4d82
refs/heads/master
2020-12-31T22:59:46.649715
2020-08-14T14:12:40
2020-08-14T14:12:40
239,065,456
1
0
null
2020-03-19T02:42:21
2020-02-08T03:52:52
C++
UTF-8
C++
false
false
1,125
cpp
#include<iostream> #include<iomanip> #include<cmath> #include<cstdio> #include<float.h> #include<cstdlib> #include<ctime> #include<cstring> #include<ctype.h> #include<algorithm> #include<fstream> #include<string> #include<vector> #include<stack> #include<queue> using namespace std; int a[10] = { 31,11,49,15,36,47,5,91,88,10 }; void ms(int low, int mid, int high) { int i = low, j = mid + 1, k = 0; int* temp = new int[high - low + 1]; while (i <= mid && j <= high) { if (a[i] <= a[j]) { temp[k++] = a[i++]; } else { temp[k++] = a[j++]; } } while (i <= mid) { temp[k++] = a[i++]; } while (j <= high) { temp[k++] = a[j++]; } for (i = low, k = 0; i <= high; i++, k++) { a[i] = temp[k]; } delete[] temp; } void msort(int low,int high) { if(low < high) { int mid = (low + high) / 2; msort(low,mid); msort(mid + 1,high); ms(low,mid,high); } } int main() { msort(0,9); for(int i = 0;i < 10;i++) { cout << a[i] << " "; } cout << endl; for(int i = 9;i >= 0;i--) { cout << a[i] << " "; } return 0; }
5dead991d470156444543607e5564c049847721b
055f943f2cba917ff71f5db9f2b2b9e963ddb8f4
/company/Manager_Dev/include/ThreadPool/WorkerThread.h
a159a2b5c638b3322d28e551fd474003c4f5286e
[]
no_license
zj23564/GitProject
1c64daf39214d45b5516e48e104b015f5152bd38
b6e272d47fc68e02db5f696595d8d8c9fdb2e2d2
refs/heads/master
2021-01-18T14:02:54.088766
2013-01-30T08:11:28
2013-01-30T08:11:28
7,910,189
0
1
null
null
null
null
UTF-8
C++
false
false
995
h
#ifndef _WORKERTHREAD_H_ #define _WORKERTHREAD_H_ #include "Thread.h" #include "ThreadPool.h" #include "Job.h" //#include "../sync/sync.h" /************************************************************** *For class CThread is an abstract class,it can't be instantiated *class CWorkerThread is the actual thread that run the job,but * **************************************************************/ //class CThreadPool; class CWorkerThread:public CThread { private: CThreadPool* m_ThreadPool; //the job that associate with the workthread CJob* m_Job; void* m_JobData; CThreadMutex m_VarMutex; bool m_IsEnd; protected: public: CCondition m_JobCond; CThreadMutex m_WorkMutex; CWorkerThread(); virtual ~CWorkerThread(); void Run(); void SetJob(CJob* job,void* jobdata); CJob* GetJob(void){return m_Job;} void SetThreadPool(CThreadPool* thrpool); CThreadPool* GetThreadPool(void){return m_ThreadPool;} }; #endif
b768065b5c4da81a37398a552cea27b63c3243de
d3c75f4264bdbd7fa8bef300ff5f572a2cc69b50
/Paste.cpp
d9cf2b144a9988cfd00188b88c2034aebbd87f2f
[]
no_license
GeorgeEskandar/FlowChart
3e076c8f48095c3b65fa61ba994d3d8d151da7e5
c012d50e6fde87a65bdec91df61dea1fb51c30e6
refs/heads/master
2020-04-28T13:18:22.916538
2019-03-15T15:29:30
2019-03-15T15:29:30
175,303,252
0
0
null
null
null
null
UTF-8
C++
false
false
5,012
cpp
#include "Paste.h" #include "ApplicationManager.h" #include "GUI\Input.h" #include "GUI\Output.h" #include "Select.h" #include "Statements\Statement.h" #include "Actions\AddSmplAssign.h" #include "AddComplexAssign.h" #include "AddCondition.h" #include "AddWrite.h" #include "AddStart.h" #include "AddEnd.h" #include "AddLoop.h" #include "Actions\AddRead.h" #include "Condition.h" #include "End.h" #include "Loop.h" #include <string> using namespace std; Paste::Paste(ApplicationManager *pAppManager):Action(pAppManager) { //Clears if multi selection is set Select::UnSelectAll(pAppManager); } void Paste::ReadActionParameters() { Input *pIn = pManager->GetInput(); Output *pOut = pManager->GetOutput(); bool check = false; while(!check) { pIn->GetPointClicked(Position); if(Position.y < (UI.ASSGN_HI/2 + 3*UI.TlBrWdth) || Position.y > (UI.height-UI.ASSGN_HI/2 - UI.StBrWdth)) pOut->PrintMessage("Error, out of bounds. Please click elsewhere."); else check = true; } } void Paste::Execute() { Output *pOut = pManager->GetOutput(); ReadActionParameters(); if(pManager->pCopiedStat[0]==NULL) return; pManager->pCopiedStat[0]->setCenter(Position.x,Position.y); pManager->pCopiedStat[0]->DeterDim(); Condition* pCond=dynamic_cast<Condition*>(pManager->pCopiedStat[0]); if(pCond!=NULL) { Point P(pCond->GetNoOut()); P.x+=20; P.y+=20; pCond->getNoConnector()->setEndPoint(P); Point Q(pCond->GetYesOut()); Q.x-=20; Q.y+=20; pCond->getYesConnector()->setEndPoint(Q); pManager->AddConnector(pCond->getYesConnector()); pManager->AddConnector(pCond->getNoConnector()); } Loop* pLoop= dynamic_cast<Loop*>(pManager->pCopiedStat[0]); if(dynamic_cast<Loop*>(pManager->pCopiedStat[0])) { Point P(pLoop->GetloopPoint()); P.y+=100; pLoop->GetloopConnector()->setStartPoint(P); pLoop->GetloopConnector()->setEndPoint(pLoop->GetloopPoint()); pManager->AddConnector(pLoop->GetloopConnector()); } /*if(dynamic_cast<Loop*>(pManager->pCopiedStat[0])) { Loop* CopyStat = dynamic_cast<Loop*>(pManager->pCopiedStat[0]); string Left = CopyStat->getLHS(); string Right = CopyStat->getRHS(); Relational Operator = CopyStat->getOp(); Loop* newcopy = new Loop(Position, Left, Right, Operator); pManager->AddStatement(newcopy); }*/ /*if(dynamic_cast<SmplAssign*>(pManager->pCopiedStat[0])) { SmplAssign *CopyStat = dynamic_cast<SmplAssign*>(pManager->pCopiedStat[0]); string Left = CopyStat->getLHS(); double Right = CopyStat->getRHS(); SmplAssign *newcopy = new SmplAssign(Position, Left, Right); pManager->AddStatement(newcopy); } else if(dynamic_cast<ComplexAssign*>(pManager->pCopiedStat[0])) { ComplexAssign* CopyStat = dynamic_cast<ComplexAssign*>(pManager->pCopiedStat[0]); string Left = CopyStat->getLHS(); string Right = CopyStat->getRHS(); ComplexAssign* newcopy = new ComplexAssign(Position, Left, Right); pManager->AddStatement(newcopy); } else if(dynamic_cast<Condition*>(pManager->pCopiedStat[0])) { Condition* CopyStat = dynamic_cast<Condition*>(pManager->pCopiedStat[0]); string Left = CopyStat->getLHS(); string Right = CopyStat->getRHS(); Relational Operator = CopyStat->getOp(); Condition* newcopy = new Condition(Position, Left, Right, Operator); pManager->AddStatement(newcopy); } else if(dynamic_cast<Loop*>(pManager->pCopiedStat[0])) { Loop* CopyStat = dynamic_cast<Loop*>(pManager->pCopiedStat[0]); string Left = CopyStat->getLHS(); string Right = CopyStat->getRHS(); Relational Operator = CopyStat->getOp(); Loop* newcopy = new Loop(Position, Left, Right, Operator); pManager->AddStatement(newcopy); } else if(dynamic_cast<Start*>(pManager->pCopiedStat[0])) { Start* CopyStat = dynamic_cast<Start*>(pManager->pCopiedStat[0]); string text = CopyStat->getText(); Start* newcopy = new Start(Position,text); pManager->AddStatement(newcopy); } else if(dynamic_cast<End*>(pManager->pCopiedStat[0])) { End* CopyStat = dynamic_cast<End*>(pManager->pCopiedStat[0]); string text = CopyStat->getComment(); End* newcopy = new End(Position,text); pManager->AddStatement(newcopy); } else if(dynamic_cast<Read*>(pManager->pCopiedStat[0])) { Read* CopyStat = dynamic_cast<Read*>(pManager->pCopiedStat[0]); string Left = "Read"; string Right = CopyStat->getRHS(); Read* newcopy = new Read(Position, Left, Right); pManager->AddStatement(newcopy); } else if(dynamic_cast<Write*>(pManager->pCopiedStat[0])) { Write* CopyStat = dynamic_cast<Write*>(pManager->pCopiedStat[0]); string Left = "Write"; string Right = CopyStat->getRHS(); Write* newcopy = new Write(Position, Left, Right); pManager->AddStatement(newcopy); }*/ pManager->AddStatement(pManager->pCopiedStat[0]); pManager->pCopiedStat[0]=NULL; pOut->PrintMessage("The Statement has been pasted"); pOut->ClearStatusBar(); }
369881f641f1f0e014b84abeebc7afa75971f1eb
7ce35b45b636a466a904ac0304fed5fc77dec7d0
/CGlassTD/CGlassTD/BillboardSprite.cpp
ae03dcdeadd3b988d4a92673b04f7f1115297cd1
[]
no_license
kidsang/GlassTD2
d29e337e66f126250ff03ce58c0bebd94ba5e067
2fd1163c34ff9afbb8d3e954b61316ffe6170ee9
refs/heads/master
2021-01-15T10:19:15.208419
2012-07-03T07:54:27
2012-07-03T07:54:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,014
cpp
#include "BillboardSprite.h" #include "SceneManagerContainer.h" BillboardSprite::BillboardSprite(SceneNode* node, BillboardSet* bs, int row, int col, int unitWidth, int unitHeight) : mNode(node), mBillboards(bs), mRow(row), mCol(col), mUnitWidth(unitWidth), mUnitHeight(unitHeight), mIsFinished(false) { mWidth = row * unitWidth; mHeight = col * unitHeight; Billboard* b = mBillboards->getBillboard(0); if (b) b->setTexcoordRect(0, 0, 1 / (float)mRow, 1 / (float)mCol); } BillboardSprite::~BillboardSprite(void) { if (mNode) { auto objIter = mNode->getAttachedObjectIterator(); SceneManager* mgr = SceneManagerContainer::getSceneManager(); while (objIter.hasMoreElements()) mgr->destroyMovableObject(objIter.getNext()); mgr->destroySceneNode(mNode); } } void BillboardSprite::addAnimator( Animator<BillboardSprite>* ani ) { mAniMgr.addAnimator(ani); } void BillboardSprite::animate( float timeSinceLastFrame, BillboardSprite* object ) { mAniMgr.animate(timeSinceLastFrame, object); }
d731051666761d7a2637b485eb9656cf2bdda92f
24221ab2cbbc5605e7c2648633fb009d3901ccd1
/src/libdrt/search/commandref.cpp
794128357ddc5fb312520b1b05d067dad7378c7b
[ "MIT" ]
permissive
leecbaker/datareftool
843565a18283bfefbb26954bd74fa7d62e2c818a
a2b238838a130b8d0df1908c72300b22fb837323
refs/heads/master
2022-11-15T20:00:30.812405
2022-10-24T05:24:57
2022-10-24T05:24:57
29,484,885
143
41
MIT
2022-09-18T20:25:35
2015-01-19T18:23:22
C
UTF-8
C++
false
false
685
cpp
#include "commandref.h" #include "allrefs.h" int CommandRefRecord::cr_callback(XPLMCommandRef /*inCommand*/, XPLMCommandPhase phase, void * inRefcon) { CommandRefRecord * record = reinterpret_cast<CommandRefRecord *>(inRefcon); std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); record->last_updated = now; record->last_updated_big = now; switch(phase) { case xplm_CommandBegin: record->activated = true; break; case xplm_CommandContinue: record->activated = true; break; case xplm_CommandEnd: record->activated = false; break; } record->all_records.addUpdatedCommandThisFrame(record); return 1; }
282b3e776acb9cd813f7723b5fc56a459cf8d5e0
fbbe424559f64e9a94116a07eaaa555a01b0a7bb
/Tensorflow_Pandas_Numpy/source3.6/tensorflow/include/tensorflow/core/util/guarded_philox_random.h
5b94a76777b25e0aea29ae0898e1a5e8d7fab80e
[ "MIT" ]
permissive
ryfeus/lambda-packs
6544adb4dec19b8e71d75c24d8ed789b785b0369
cabf6e4f1970dc14302f87414f170de19944bac2
refs/heads/master
2022-12-07T16:18:52.475504
2022-11-29T13:35:35
2022-11-29T13:35:35
71,386,735
1,283
263
MIT
2022-11-26T05:02:14
2016-10-19T18:22:39
Python
UTF-8
C++
false
false
2,802
h
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #ifndef TENSORFLOW_KERNELS_GUARDED_PHILOX_RANDOM_H_ #define TENSORFLOW_KERNELS_GUARDED_PHILOX_RANDOM_H_ #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/lib/random/philox_random.h" #include "tensorflow/core/platform/macros.h" #include "tensorflow/core/platform/mutex.h" #include "tensorflow/core/platform/types.h" namespace tensorflow { // A thread safe wrapper around a Philox generator. Example usage: // // GuardedRandomPhilox generator; // generator.Init(context); // // // In thread safe code // const int samples = ...; // auto local_generator = generator.ReserveSamples128(samples); // for (int i = 0; i < samples; i++) // Array<uint32, 4> sample = local_generator(); // // Use sample // } // class GuardedPhiloxRandom { public: // Must call Init to finish initialization GuardedPhiloxRandom() : initialized_(false) {} // Initialize the generator from attributes "seed" and "seed2". // If both seeds are unspecified, use random seeds. // Must be called exactly once. Status Init(OpKernelConstruction* context); // Initialize with given seeds. void Init(int64 seed, int64 seed2); // Reserve a certain number of 128-bit samples. // This function is thread safe. The returned generator is valid for the // given number of samples, and can be used without a lock. random::PhiloxRandom ReserveSamples128(int64 samples); // Reserve a certain number of 32-bit samples. random::PhiloxRandom ReserveSamples32(int64 samples) { return ReserveSamples128((samples + 3) / 4); } // Reserve enough random samples in the generator for the given output count. random::PhiloxRandom ReserveRandomOutputs(int64 output_count, int multiplier) { int64 conservative_sample_count = output_count * multiplier; return ReserveSamples128(conservative_sample_count); } private: mutex mu_; random::PhiloxRandom generator_ GUARDED_BY(mu_); bool initialized_; TF_DISALLOW_COPY_AND_ASSIGN(GuardedPhiloxRandom); }; } // namespace tensorflow #endif // TENSORFLOW_KERNELS_GUARDED_PHILOX_RANDOM_H_
f8b138c7d86dc28b211cae90be9b23ff5ec30b9a
522eb32044bd2dd01aea5e89e428da43ae901988
/cbtest.cpp
59ff1005517d08512e79a46e7920dcbed3ee0cd5
[]
no_license
vikas0799/DSA-using-CPP
fb9328f248bff6b260fc22a11c7a6a2d1ee72cbe
a80585ca0725ff0e4325b1b3b90d8273521dd666
refs/heads/master
2023-07-10T09:18:19.928850
2021-08-18T23:14:22
2021-08-18T23:14:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
341
cpp
#include<bits/stdc++.h> using namespace std; int main() { int n;cin>>n; int i,j,k=1; for(i=1;i<=n;i++) { for(j=1;j<2*n;j++) { if(i<=j||j>=2*n-i) { if(j<=n) { if(i<=j) cout<<j<<" "; } if(j>n) { if(j>2*n-i) cout<<"chutiya"<<" "; } cout<<endl; } } cout<<endl; } }
0883e4bfcfc88f580ec6f3ec8e737812aec292fd
f7e865a3186bb7fe8ec96a417506391d0265d5b5
/structure.cpp
f68d443a8019ab6ba8373756005ca4a538d80233
[]
no_license
acadien/BasinPave
d2d1b690efb755af66367e7d4a35fb60e3b10518
51498e2dcd05f0eb3f6dcef19c68215df2a94e67
refs/heads/master
2020-05-09T20:33:25.002545
2012-11-18T21:39:42
2012-11-18T21:39:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,780
cpp
#include "math.h" #include "structure.h" #include "state.h" #include "constants.h" #include "localMin.h" #include "random.h" using namespace std; using namespace Struc; //Distance between 2 points float dist(float *a, float* b){ strucx=a[0]-b[0]; strucy=a[1]-b[1]; strucz=a[2]-b[2]; return sqrt(strucx*strucx + strucy*strucy + strucz*strucz); } //Distance between point and origin float origDist(float *a){ return sqrt(a[0]*a[0]+a[1]*a[1]+a[2]*a[2]); } //Calculate the com void com(state* s){ //First re-center about the center of mass. float com[3]={0.0,0.0,0.0}; for(int i=0;i<s->N;i++){ com[0]+=s->x[3*i+1]; com[1]+=s->x[3*i+2]; com[2]+=s->x[3*i+3]; } for(int i=0;i<3;i++) s->com[i]=com[i]/s->N; } void recenter(state* s){ com(s); float *com=s->com; for(int i=0;i<s->N;i++){ s->x[3*i+1]-=com[0]; s->x[3*i+2]-=com[1]; s->x[3*i+3]-=com[2]; } for(int i=0;i<3;i++) s->com[i]=0.; } float msd(state* a, state* b){ float d=0,m=0; float* xa=a->x; float* xb=b->x; int N=a->N; for(int i=0;i<N;i++){ d=dist(&xa[3*i+1],&xb[3*i+1]); m+=d*d; } return sqrt(m/(float)N); } //Move atoms from outside the sphere... inside sphere somewhere float salt(state* s){ int N = s->N,cnt,outcount=0; float *x=s->x; float r,theta,phi; ARGST args; args.N=N; for(int i=0;i<N;i++){ if( origDist(&(x[3*i+1])) > boundr ){ outcount++; cnt=0; args.d=i; while(true){ cnt++; r=boundr*mnormrand(1.0); while(r>boundr) r-=boundr; while(r<-boundr) r+=boundr; theta=2*M_PI*mrand(); phi=acos(2.0*mrand()-1.0); x[i*3+1]=r*sin(theta)*cos(phi); x[i*3+2]=r*sin(theta)*sin(phi); x[i*3+3]=r*cos(theta); int a=LJpot(x,(void*)&args); if(a - s->E < 5.) break; else printf("???? salt fail %f ????\n",a-s->E); if(cnt>10000){ printf("Error:unable to salt atom!\n"); exit(0); } } } } if(outcount>0) printf("salt cnt=%d\n",outcount); } //compresses axes that are greater than the average boundary width //intended to be used during initialization void cubify(state *s){ mnx=1E10; mny=1E10; mnz=1E10; mxx=-1E10; mxy=-1E10; mxz=-1E10; float *xs=s->x; for(int i=0;i<s->N;i++){ if(xs[3*i+1]<mnx) mnx=xs[3*i+1]; if(xs[3*i+1]>mxx) mxx=xs[3*i+1]; if(xs[3*i+2]<mny) mny=xs[3*i+2]; if(xs[3*i+2]>mxy) mxy=xs[3*i+2]; if(xs[3*i+3]<mnz) mnz=xs[3*i+3]; if(xs[3*i+3]>mxz) mxz=xs[3*i+3]; } strucx=mxx-mnx; strucy=mxy-mny; strucz=mxz-mnz; float avgwidth=(strucx+strucy+strucz)/3.0; strucx=0.5*(1.+avgwidth/strucx); strucy=0.5*(1.+avgwidth/strucy); strucz=0.5*(1.+avgwidth/strucz); for(int i=0;i<s->N;i++){ xs[3*i+1]*=strucx; xs[3*i+2]*=strucy; xs[3*i+3]*=strucz; } }
2cbcd15033e54c177d93102a5c12b854d003cce2
7712e63123fdcaf0396f6c2d6ad6cd6b198f9aa3
/Learn34-Win32_粒子系统(SSBO)/Timer.h
424067e985338076c4637112d3424700774f4e46
[]
no_license
YzlCoder/LearnOpengl
c151aeed63b0b949c87a32d490f8979ebe025a86
f128f71728952668cb1a14de1d6b3bcc4536c1c9
refs/heads/master
2021-08-23T05:05:44.698503
2017-12-03T14:13:07
2017-12-03T14:13:07
107,639,295
1
0
null
null
null
null
UTF-8
C++
false
false
263
h
#pragma once #include <Windows.h> class Timer { public: HANDLE mCurrentThread; LARGE_INTEGER mStart; LARGE_INTEGER mEnd; LARGE_INTEGER mCPUFrequency; DWORD_PTR mProcessAffinityMask; Timer(); void Start(); int GetPssedTicks(); float GetPassTime(); };
0b47025beb5c398ee32c263da91b08c7e6bd5551
6204e206bd811baaedfa5d87a48dad7058b1543f
/class_Matrix.cpp
501377480d7ce8858d3e172b0eafea4ea8d1eb0c
[]
no_license
anmolkaur18/C-Programs
c277c0dd4d37be4a550a75d40855a18f2626569a
a12f66c4ec4e8d4396502e2d43bc6e6f97e31a1f
refs/heads/master
2022-04-11T11:34:02.043793
2020-03-28T17:08:21
2020-03-28T17:08:21
216,167,737
0
0
null
null
null
null
UTF-8
C++
false
false
1,903
cpp
#include<iostream> using namespace std; class Matrix{ int r1,r2; int a[10][10]; int b[10][10]; int c[10][10]; int c1,c2; public: void values(){ cout<<"sum and differnce operation is valid only when rows of matrix1 = rows of matrix 2 and columns of 1 = columns of 2\n"; cout<<"enter r1 ,c1,r2,c2\n"; cin>>r1>>c1>>r2>>c2; if(r1==r2 && c1==c2) { cout<<"enter values for matrix 1\n"; for(int i=0;i<r1;i++) {for (int j=0;j<c1;j++) cin>>a[i][j]; } cout<<"enter values for matrix 2\n"; for(int i=0;i<r2;i++) {for (int j=0;j<c2;j++) cin>>b[i][j]; } } } void sum() { for(int i=0;i<r1;i++) { for(int j=0;j<c1;j++) {c[i][j]=a[i][j]+b[i][j]; cout<<c[i][j]<<" "; } cout<<endl; } } void differnce() { for(int i=0;i<r1;i++) { for(int j=0;j<c1;j++) {c[i][j]=a[i][j]-b[i][j]; cout<<c[i][j]<<" "; } cout<<endl; } } void product() { int k[r1][c1]={0}; for(int i=0;i<r1;i++) { for(int j=0;j<c2;j++) { for(int l=0;l<c1;l++) k[i][j]+=a[i][l]*b[l][j]; cout<<k[i][j]<<" "; } cout<<endl; } } void transpose() { cout<<"\ntranspose of matrix a is as follows\n"; for(int i=0;i<r1;i++) { for(int j=0;j<c1;j++) cout<<a[j][i]<<" "; cout<<endl; } cout<<"\ntranspose of matrix b is as follows\n"; for(int i=0;i<r2;i++) { for(int j=0;j<c2;j++) cout<<b[j][i]<<" "; cout<<endl; } } }; int main() { int choice; Matrix M; M.values(); cout<<"enter tour choice\n"; cout<<" 1 for addition\n 2 for differnce\n 3 for product\n 4 for transpose\n"; cin>>choice; switch(choice) { case 1: M.sum(); break; case 2:M.differnce(); break; case 3:M.product(); break; case 4:M.transpose(); break; default: cout<<"enter a valid choice\n"; } return 0; }
625dfc9966b6581505a1c51e55c6797f8d7ec10e
dd4e67eb95b8a276d66cf607acfad519ed82f251
/EnumClass/EnumClass.hpp
d52c81caa82d62f0a058c9fc7571814b621a8236
[]
no_license
ZSShen/ModernCpp
a95ee3a16eca8f6b122ccb396da3a87041a98ca8
65f7739c84a20aecd4504e0d69ddd5837de3a7ce
refs/heads/master
2021-01-11T04:55:36.318457
2017-01-14T07:52:52
2017-01-14T07:52:52
77,625,055
0
0
null
null
null
null
UTF-8
C++
false
false
843
hpp
#pragma once template <typename T, T Begin = T::Begin, T End = T::End> class Enum { public: Enum() {} ~Enum() {} Enum(const Enum&) = delete; Enum(Enum&&) = delete; Enum& operator=(const Enum&) = delete; Enum& operator=(Enum&&) = delete; class Iterator { public: Iterator(int value) : value_(value) {} T operator*() const { return static_cast<T>(value_); } void operator++() { ++value_; } bool operator!=(const Iterator& rhs) { return value_ != rhs.value_; } private: int value_; }; Iterator begin() { return Iterator(static_cast<int>(Begin)); } Iterator end() { return Iterator(static_cast<int>(End) + 1); } };
55ff007d3b683d515400d57a104482c2a0e297db
d5706e390454571163f9e90d46dd99329c53d696
/catkin_ws/src/kylinbot_core/include/viz/inc/MarkerDetection.h
8adce645f76b12fe344f8e43cd30ee86d108bd95
[]
no_license
jetbang/gnd-ros
1f1ac487e5b3b6b3182c1b9485813c1156cf6b22
a90b85e6332679fee89626e2b32f95c00f359934
refs/heads/master
2021-01-01T15:27:15.241718
2017-07-18T17:44:00
2017-07-18T17:44:00
97,621,031
0
0
null
null
null
null
UTF-8
C++
false
false
1,118
h
/** * Copyright (c) 2016, Jack Mo ([email protected]). * * 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 __MARKER_DETECTION_H__ #define __MARKER_DETECTION_H__ #include <opencv2/opencv.hpp> typedef struct { float x; float y; float z; }Vec3_t; typedef struct { Vec3_t t; // Translation Vec3_t r; // Rotation }Viz_t; class MarkerDetecter { public: MarkerDetecter(); ~MarkerDetecter(); bool detectMarker(cv::Mat& img, std::vector<std::vector<cv::Point>> squares); bool locateMarker(cv::Mat& img, Viz_t& viz); protected: std::vector<std::vector<cv::Point>> squares; } #endif
73ad2194da6c56b959f5d3425a926b362f9f12ac
3d6836659f270b41267c0cd5c710fcf08fa4a166
/moba_server/netbus/netbus.h
279510a9bf3af8766a22c89b366d0bd551bae8f4
[]
no_license
jinzt/moba_game_server
4b9d33d618f2d5f5820f3b7e3d848f3fc245a6ec
341d3acebe8d907011760358b1594667d4e086d3
refs/heads/master
2021-10-27T12:27:35.469670
2019-04-17T09:34:53
2019-04-17T09:34:53
null
0
0
null
null
null
null
GB18030
C++
false
false
607
h
/* 1: netbus: 提供一个全局的对象, instance(); 2: start_tcp_server: 提供启动tcp_server接口; 3: start_ws_server: 提供启动ws server接口;websocket服务器 4: run接口来开启事件循环; */ #ifndef __NETBUS_H #define __NETBUS_H #include "session.h" class netbus { public: static netbus* instance(); public: void init(); void tcp_listen(int port,const char* ip); void ws_listen(int port,const char* ip); void udp_listen(int port,const char* ip); void run(); void tcp_connect(const char* server_ip,int port,void(*connected)(int err,session*s,void* udata),void* udata); }; #endif
0e09aad9462518eb1daae470ae40a48b2f790c5b
41ab6b8bbeb03958c59350ae6da2887a4bf8e144
/third_party/v8/src/builtins/builtins-test-gen.h
5412beb9bdad6890731d2155536162bfcacfcf7b
[ "SunPro", "BSD-3-Clause", "bzip2-1.0.6", "Apache-2.0" ]
permissive
ofrobots/no-bazel
6472b0bb1b3309d8613ee97c6526a3fa46060eab
f7eb147044dc35aac86df8bd9bec2cc55863ce17
refs/heads/master
2020-04-07T14:21:40.305137
2018-12-08T00:53:07
2018-12-08T00:53:07
158,443,929
4
0
Apache-2.0
2018-12-13T01:54:59
2018-11-20T19:56:42
C++
UTF-8
C++
false
false
633
h
// Copyright 2018 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. #ifndef V8_BUILTINS_BUILTINS_TEST_GEN_H_ #define V8_BUILTINS_BUILTINS_TEST_GEN_H_ #include "torque-generated/builtins-base-from-dsl-gen.h" namespace v8 { namespace internal { class TestBuiltinsAssembler : public BaseBuiltinsFromDSLAssembler { public: explicit TestBuiltinsAssembler(compiler::CodeAssemblerState* state) : BaseBuiltinsFromDSLAssembler(state) {} }; } // namespace internal } // namespace v8 #endif // V8_BUILTINS_BUILTINS_TEST_GEN_H_
c7ad0c10f51eb94c86f10a073f4caadf2f05fa3b
97bef09236161448fe8713d20030325c5b2364de
/src/api/wayfire/nonstd/safe-list.hpp
2dbfcac46d788e7ebad1cdfe8a4d490142321853
[ "MIT" ]
permissive
paullinuxthemer/wayfire
682a7528c0144c50239d9d239dda89db8d54ad87
b2e244949783e92e97f5197b0e29ae2ca2868b29
refs/heads/master
2021-06-14T06:04:51.479486
2020-04-09T13:34:09
2020-04-09T13:34:09
254,478,460
1
0
MIT
2020-04-09T21:06:34
2020-04-09T21:06:34
null
UTF-8
C++
false
false
6,863
hpp
#ifndef WF_SAFE_LIST_HPP #define WF_SAFE_LIST_HPP #include <list> #include <memory> #include <algorithm> #include <functional> #include <wayland-server.h> #include "reverse.hpp" /* This is a trimmed-down wrapper of std::list<T>. * * It supports safe iteration over all elements in the collection, where any * element can be deleted from the list at any given time (i.e even in a * for-each-like loop) */ namespace wf { /* The object type depends on the safe list type, and the safe list type * needs access to the event loop. However, the event loop is typically * available from core.hpp. Because we can't resolve this circular dependency, * we provide a link to the event loop specially for the safe list */ namespace _safe_list_detail { /* In main.cpp, and initialized there */ extern wl_event_loop* event_loop; void idle_cleanup_func(void *data); } template<class T> class safe_list_t { std::list<std::unique_ptr<T>> list; wl_event_source *idle_cleanup_source = NULL; /* Remove all invalidated elements in the list */ std::function<void()> do_cleanup = [&] () { auto it = list.begin(); while (it != list.end()) { if (*it) { ++it; } else { it = list.erase(it); } } idle_cleanup_source = NULL; }; /* Return whether the list has invalidated elements */ bool is_dirty() const { return idle_cleanup_source; } public: safe_list_t() {}; /* Copy the not-erased elements from other, but do not copy the idle source */ safe_list_t(const safe_list_t& other) { *this = other; } safe_list_t& operator = (const safe_list_t& other) { this->idle_cleanup_source = NULL; other.for_each([&] (auto& el) { this->push_back(el); }); } safe_list_t(safe_list_t&& other) = default; safe_list_t& operator = (safe_list_t&& other) = default; ~safe_list_t() { if (idle_cleanup_source) wl_event_source_remove(idle_cleanup_source); } T& back() { /* No invalidated elements */ if (!is_dirty()) return *list.back(); auto it = list.rbegin(); while (it != list.rend() && (*it) == nullptr) ++it; if (it == list.rend()) throw std::out_of_range("back() called on an empty list!"); return **it; } size_t size() const { if (!is_dirty()) return list.size(); /* Count non-null elements, because that's the real size */ size_t sz = 0; for (auto& it : list) sz += (it != nullptr); return sz; } /* Push back by copying */ void push_back(T value) { list.push_back(std::make_unique<T> (std::move(value))); } /* Push back by moving */ void emplace_back(T&& value) { list.push_back(std::make_unique<T> (value)); } enum insert_place_t { INSERT_BEFORE, INSERT_AFTER, INSERT_NONE, }; /* Insert the given value at a position in the list, determined by the * check function. The value is inserted at the first position that * check indicates, or at the end of the list otherwise */ void emplace_at(T&& value, std::function<insert_place_t(T&)> check) { auto it = list.begin(); while (it != list.end()) { /* Skip empty elements */ if (*it == nullptr) { ++it; continue; } auto place = check(**it); switch (place) { case INSERT_AFTER: /* We can safely increment it, because it points to an * element in the list */ ++it; // fall through case INSERT_BEFORE: list.emplace(it, std::make_unique<T>(value)); return; default: break; } ++it; } /* If no place found, insert at the end */ emplace_back(std::move(value)); } void insert_at(T value, std::function<insert_place_t(T&)> check) { emplace_at(std::move(value), check); } /* Call func for each non-erased element of the list */ void for_each(std::function<void(T&)> func) const { /* Go through all elements currently in the list */ auto it = list.begin(); for (int size = list.size(); size > 0; size--, it++) { if (*it) func(**it); } } /* Call func for each non-erased element of the list in reversed order */ void for_each_reverse(std::function<void(T&)> func) const { auto it = list.rbegin(); for (int size = list.size(); size > 0; size--, it++) { if (*it) func(**it); } } /* Safely remove all elements equal to value */ void remove_all(const T& value) { remove_if([=] (const T& el) { return el == value; }); } /* Remove all elements satisfying a given condition. * This function resets their pointers and scheduling a cleanup operation */ void remove_if(std::function<bool(const T&)> predicate) { bool actually_removed = false; for (auto& it : list) { if (it && predicate(*it)) { actually_removed = true; /* First reset the element in the list, and then free resources */ auto copy = std::move(it); it = nullptr; /* Now copy goes out of scope */ } } /* Schedule a clean-up, but be careful to not schedule it twice */ if (!idle_cleanup_source && actually_removed) { idle_cleanup_source = wl_event_loop_add_idle(_safe_list_detail::event_loop, _safe_list_detail::idle_cleanup_func, &do_cleanup); } } }; } #endif /* end of include guard: WF_SAFE_LIST_HPP */
8755db0e9a9925f1258c4c0f42eb184347e4702a
5dd99f7b55867527c9aaab80a017b3463014e520
/clients/gtest/syevd_heevd_gtest.cpp
5361411506006044fc8aa0ba1b7dcacfe9b49562
[ "BSD-2-Clause" ]
permissive
pavahora/rocSOLVER
1f63babea61837ec99ff246564ec82738b9e75e6
0c7f93731501a805beed3edb2f600e9854a590a7
refs/heads/master
2023-08-26T18:15:32.936261
2021-10-27T19:13:06
2021-10-27T19:13:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,929
cpp
/* ************************************************************************ * Copyright (c) 2021 Advanced Micro Devices, Inc. * * ************************************************************************ */ #include "testing_syevd_heevd.hpp" using ::testing::Combine; using ::testing::TestWithParam; using ::testing::Values; using ::testing::ValuesIn; using namespace std; typedef std::tuple<vector<int>, vector<rocsolver_op_char>> syevd_heevd_tuple; // each size_range vector is a {n, lda} // each op_range vector is a {evect, uplo} // case when n == 0, evect == N, and uplo = L will also execute the bad arguments test // (null handle, null pointers and invalid values) const vector<vector<rocsolver_op_char>> op_range = {{'N', 'L'}, {'N', 'U'}, {'V', 'L'}, {'V', 'U'}}; // for checkin_lapack tests const vector<vector<int>> size_range = { // quick return {0, 1}, // invalid {-1, 1}, {10, 5}, // normal (valid) samples {1, 1}, {12, 12}, {20, 30}, {35, 35}, {50, 60}}; // for daily_lapack tests const vector<vector<int>> large_size_range = {{192, 192}, {256, 270}, {300, 300}}; Arguments syevd_heevd_setup_arguments(syevd_heevd_tuple tup) { vector<int> size = std::get<0>(tup); vector<rocsolver_op_char> op = std::get<1>(tup); Arguments arg; arg.set<rocblas_int>("n", size[0]); arg.set<rocblas_int>("lda", size[1]); arg.set<char>("evect", op[0]); arg.set<char>("uplo", op[1]); // only testing standard use case/defaults for strides arg.timing = 0; return arg; } class SYEVD_HEEVD : public ::TestWithParam<syevd_heevd_tuple> { protected: SYEVD_HEEVD() {} virtual void SetUp() {} virtual void TearDown() {} template <bool BATCHED, bool STRIDED, typename T> void run_tests() { Arguments arg = syevd_heevd_setup_arguments(GetParam()); if(arg.peek<rocblas_int>("n") == 0 && arg.peek<char>("evect") == 'N' && arg.peek<char>("uplo") == 'L') testing_syevd_heevd_bad_arg<BATCHED, STRIDED, T>(); arg.batch_count = (BATCHED || STRIDED ? 3 : 1); testing_syevd_heevd<BATCHED, STRIDED, T>(arg); } }; class SYEVD : public SYEVD_HEEVD { }; class HEEVD : public SYEVD_HEEVD { }; // non-batch tests TEST_P(SYEVD, __float) { run_tests<false, false, float>(); } TEST_P(SYEVD, __double) { run_tests<false, false, double>(); } TEST_P(HEEVD, __float_complex) { run_tests<false, false, rocblas_float_complex>(); } TEST_P(HEEVD, __double_complex) { run_tests<false, false, rocblas_double_complex>(); } // batched tests TEST_P(SYEVD, batched__float) { run_tests<true, true, float>(); } TEST_P(SYEVD, batched__double) { run_tests<true, true, double>(); } TEST_P(HEEVD, batched__float_complex) { run_tests<true, true, rocblas_float_complex>(); } TEST_P(HEEVD, batched__double_complex) { run_tests<true, true, rocblas_double_complex>(); } // strided_batched tests TEST_P(SYEVD, strided_batched__float) { run_tests<false, true, float>(); } TEST_P(SYEVD, strided_batched__double) { run_tests<false, true, double>(); } TEST_P(HEEVD, strided_batched__float_complex) { run_tests<false, true, rocblas_float_complex>(); } TEST_P(HEEVD, strided_batched__double_complex) { run_tests<false, true, rocblas_double_complex>(); } // daily_lapack tests normal execution with medium to large sizes INSTANTIATE_TEST_SUITE_P(daily_lapack, SYEVD, Combine(ValuesIn(large_size_range), ValuesIn(op_range))); INSTANTIATE_TEST_SUITE_P(daily_lapack, HEEVD, Combine(ValuesIn(large_size_range), ValuesIn(op_range))); // checkin_lapack tests normal execution with small sizes, invalid sizes, // quick returns, and corner cases INSTANTIATE_TEST_SUITE_P(checkin_lapack, SYEVD, Combine(ValuesIn(size_range), ValuesIn(op_range))); INSTANTIATE_TEST_SUITE_P(checkin_lapack, HEEVD, Combine(ValuesIn(size_range), ValuesIn(op_range)));
8d7251fd6ca8b75792b4f3c6f372058243608b7d
64f0f468cce53891fe536b1e2f5d92b0c7119adf
/Mazes/src/Maze_Dense.cpp
26027d0b51aad0d7219f6182cc3c0bd233cd5a20
[]
no_license
Bryce-Summers/Randomized_Acyclic_Connected_Sub_Graphs
4ac4e0c688e432a33d20d9c320ef6942c6470990
a77d1784338952bf64d9c40c19469e272365c45d
refs/heads/master
2020-12-25T19:04:16.378986
2015-05-14T22:21:28
2015-05-14T22:21:28
33,847,225
0
0
null
null
null
null
UTF-8
C++
false
false
1,338
cpp
#include "../include/Maze_Dense.h" Maze_Dense::Maze_Dense(int size) { this -> size = size; } Maze_Dense::~Maze_Dense() { //dtor } /* This should return the number "nodes" in the maze. */ int Maze_Dense::getNumberOfVertices() { return size; } // Returns the characteristic Edge List containing all possible edges. // Returns a complete graph on size vertices for Maze_Dense. EdgeList * Maze_Dense::populateEdgeList() { EdgeList * output = new EdgeList(); // Add an edge for every pair of edges. for(int a = 0; a < size; a++) for(int b = a + 1; b < size; b++) { output->addEdge(a, b); } return output; } /* * This method returns a pointer to a map from Edges to those Edges that intersect it. * * FIXME : Implement actual conlicts if they are desired. */ std::map<Edge, EdgeList *> * Maze_Dense::getConflicts() { auto * output_map = new std::map<Edge, EdgeList *>(); // Go Through all of the Edges in this lattice and set their conflict lists to only contain themselves. EdgeList * edges = populateEdgeList(); std::vector<Edge> edge_vector = edges->edges; for(auto iter = edge_vector.begin(); iter != edge_vector.end(); ++iter) { Edge edge = *iter; EdgeList * edgeList = new EdgeList(); edgeList->addEdge(edge); (*output_map)[edge] = edgeList; } return output_map; }
f0a0e7550f2b855e44712b9807098b36e75a1da2
3188d2b4e8e9869c80819e8a3d99ebace8adfd06
/Practice/Find the Longest Substring Containing Vowels in Even Counts.cpp
331af99f7ec126f25eef07eb3c82c55b6b61c5b7
[]
no_license
Divyalok123/LeetCode_Practice
78ce9ba0deb8719b71111e17ae65422d76d2a306
2ac1dd229e7154e5ddddb0c72b9bfbb9c897d825
refs/heads/master
2023-06-30T08:55:33.369349
2021-08-01T06:17:06
2021-08-01T06:17:06
256,864,709
0
0
null
null
null
null
UTF-8
C++
false
false
998
cpp
/* https://leetcode.com/problems/find-the-longest-substring-containing-vowels-in-even-counts/ */ #include <iostream> #include <vector> #include <unordered_map> using namespace std; static int xx = [](){ios_base::sync_with_stdio(false);cin.tie(0);return 0;}(); class Solution { public: int findTheLongestSubstring(string s) { int i = 0, j = 0, n = s.size(); int ans = 0, mask = 0; unordered_map<char, int> um; um['a'] = 1; um['e'] = 2; um['i'] = 3; um['o'] = 4; um['u'] = 5; int found[100] = {0}; for(int i = 0; i < n; i++) { if(um[s[i]]) mask ^= (1 << um[s[i]]); if(mask == 0) ans = i + 1; else { if(found[mask]) ans = max(ans, i-found[mask] + 1); else found[mask] = i+1; } } return ans; } };
60de4421777bf6a9910c572ebd5200d990e7c119
8e479d7986af5ac7ff2bdd00e7277f0c9b4d40ef
/Kernel/disk/IDE/IdeCtrl.cpp
fbd45bbb231c4a36043ce7504211dcc4b753bf79
[]
no_license
zartech22/Brokenos
9fd62692fa4a3129d38c0c3478d1c25ff40707c8
ad90cb4e1166b846a6a7149e01d647f0393e5c14
refs/heads/master
2023-02-04T04:35:41.139026
2020-12-27T13:05:33
2020-12-27T13:05:33
58,419,447
0
0
null
null
null
null
UTF-8
C++
false
false
2,300
cpp
#include <disk/IDE/IdeCtrl.h> #include <video/Screen.h> #include <pci/pci.h> #include <disk/IDE/IdeDrive.h> Vector<IdeCtrl*> *IdeCtrl::IdeList = nullptr; IdeCtrl::IdeCtrl(u8 bus, u8 device, u8 function) : _bus(bus), _device(device), _function(function) { _primaryPorts[0] = 0x1F0; _primaryPorts[1] = 0x3F6; _secundaryPorts[0] = 0x170; _secundaryPorts[1] = 0x376; checkPorts(); _drives[0] = new IdeDrive(_primaryPorts[0], _primaryPorts[1], Master); _drives[1] = new IdeDrive(_primaryPorts[0], _primaryPorts[1], Slave); _drives[2] = new IdeDrive(_secundaryPorts[0], _secundaryPorts[1], Master); _drives[3] = new IdeDrive(_secundaryPorts[0], _secundaryPorts[1], Slave); for(int i = 0; i < 4; ++i) _connetedDevice[i] = _drives[i]->isConnected(); } IdeDrive& IdeCtrl::getDrive(BusRole bus, DriveRole drive) { unsigned int index = (bus == SecundaryBus) ? 1 : 0; // 0 if primary, else 1 index *= 2; index += (drive == Slave); return *_drives[index]; } void IdeCtrl::displayModelNames() { for(int i = 0; i < 4; i++) if(_connetedDevice[i]) Screen::getScreen().printk("IDE Device : %s\n", _drives[i]->getModelName()); } void IdeCtrl::displayTree() { sScreen.println("Ide controller: PCI(%u, %u, %u)", _bus, _device, _function); sScreen.putcar(0xB3); sScreen.putcar(0x0A); sScreen.putcar(0xC3); sScreen.printk(" Primary master : %s\n", _drives[0]->getModelName()); sScreen.putcar(0xC3); sScreen.printk(" Primary slave : %s\n", _drives[1]->getModelName()); sScreen.putcar(0xC3); sScreen.printk(" Secundary master : %s\n", _drives[2]->getModelName()); sScreen.putcar(0xC0); sScreen.printk(" Secundary slave : %s\n", _drives[3]->getModelName()); } void IdeCtrl::checkPorts() { u8 progIf = pciConfigReadByte(_bus, _device, _function, 0x09); if(!(progIf & 0x1)) return; else { _primaryPorts[0] = 0xFFFC & pciConfigReadWord(_bus, _device, _function, 0x10); _primaryPorts[1] = 0xFFFC & pciConfigReadByte(_bus, _device, _function, 0x14); _secundaryPorts[0] = 0xFFFC & pciConfigReadWord(_bus, _device, _function, 0x18); _secundaryPorts[1] = 0xFFFC & pciConfigReadByte(_bus, _device, _function, 0x1C); } }
0fb8bf236637b9cdd5e9c32aa48c50c93b7365a0
e1609af218c77d5ab063ed1518ae95c4b5545699
/oopprogram4Extreame/Plugin_hybrid.h
60ec2641ad3c12a941b1dd7eb81e779df6786c85
[]
no_license
CaptainMax/backup
ec83886cf673143d48ce4926e0e1b1ccee38a0f2
b96ef7b892cbf9d6f4f0844c35b0f9531a082a26
refs/heads/master
2020-03-29T08:18:20.004319
2018-09-21T03:18:39
2018-09-21T03:18:39
149,703,687
0
0
null
null
null
null
UTF-8
C++
false
false
220
h
// headfile ==> child from both Electric and Gas #ifndef PLUGIN_HYBRID_H #define PLUGIN_HYBRID_H #include "Electric_vehicle.h" #include "Gas_vehicle.h" class Plugin_hybrid : public Electric_vehicle : Gas_vehicle{ }
d3183e075b3f62c79c18369c4a8abd91e8e6c5bb
be9917c9cf688edcd2adddf3107c3cdcc5b8cd1c
/CPP/agents.h
4a3b039fdf87de1157a1cb1a2ea1d0c242fbbf75
[]
no_license
An-Cockrell/IIRABM_MRM_GA
350545ae04274cad3264c30c4a7f9776528c0f33
5f7a808e1aba2b31e2305a2d64a5e03bcf896d7c
refs/heads/master
2022-09-17T04:37:28.382416
2022-09-08T19:06:08
2022-09-08T19:06:08
209,343,818
0
0
null
null
null
null
UTF-8
C++
false
false
4,548
h
#ifndef AGENTS_H #define AGENTS_H #include<vector> #include <stdlib.h> #include <iostream> using namespace std; struct EC{ public: int xLoc; int yLoc; int id; bool alive; float oxy; int ec_activation; int ec_roll; //rolling int ec_stick; //sticking int ec_migrate; //migration float cytotox; //o2rads and enzymes float infection; //infectious vector float endotoxin; float PAF; float TNF; float sTNFr; float IL1; float sIL1r; float IL1ra; float IFNg; float IL4; float IL6; float IL8; float IL10; float IL12; float GCSF; float tempSignal; int neighbors[8]; EC(int x, int y, int id); EC(); void ECfunction(float oxyHeal); void inj_function(int infectSpread, int numInfectRepeat); void getNeighbors(); void diffuse(); void activate(); void patch_inj_spread(float oxyHeal); }; struct pmn{ public: int xLoc; int yLoc; int wbc_roll; //selectins int wbc_stick; //integrens int wbc_migrate; //diapedesis int pmn_age; //life span float pmn_pcd; //programmed cell death float TNFr; float IL_1r; float activation; int orientation; pmn(int x, int y); pmn(int x, int y, int age); void pmn_function(int pmnID); void pmn_burst(int pmnID); void pmn_sniff(); }; struct pmn_marrow{ public: int xLoc; int yLoc; float wbc_roll; //selectins float wbc_stick; //integrens float wbc_migrate; //diapedesis int pmn_age; //life span float pmn_pcd; //programmed cell death int mono_age; //life span float TNFr; float IL_1r; float activation; pmn_marrow(int x, int y); void pmn_marrow_function(); int orientation; }; struct mono{ public: int xLoc; int yLoc; int wbc_roll; //selectins int wbc_stick; //integrens int wbc_migrate; //diapedesis int mono_age; //life span float TNFr; float IL_1r; float activation; int orientation; mono(int x, int y); mono(int x, int y, int age, int iTNFr, int iIL1r); void mono_function(int monoID); void mono_sniff(); }; struct mono_marrow{ public: int xLoc; int yLoc; float wbc_roll; //selectins float wbc_stick; //integrens float wbc_migrate; //diapedesis int pmn_age; //life span float pmn_pcd; //programmed cell death int mono_age; //life span float TNFr; float IL_1r; float activation; mono_marrow(int x, int y); void mono_marrow_function(); int orientation; }; struct TH0{ public: int xLoc; int yLoc; float wbc_roll; //selectins float wbc_stick; //integrens float wbc_migrate; //diapedesis int pmn_age; //life span float pmn_pcd; //programmed cell death int mono_age; //life span float TNFr; float IL_1r; int TH0_age; float activation; float proTH1; float proTH2; float rTH1; //random holder for pro-TH1 float rTH2; //random holder for pro-TH2 int orientation; TH0(int x, int y); TH0(int x, int y, int age); void TH0function(int index); }; struct TH1{ public: int xLoc; int yLoc; float wbc_roll; //selectins float wbc_stick; //integrens float wbc_migrate; //diapedesis int pmn_age; //life span float pmn_pcd; //programmed cell death int mono_age; //life span float TNFr; float IL_1r; int TH1_age; float activation; float pro_TH1; float pro_TH2; float rTH1; //random holder for pro-TH1 float rTH2; //random holder for pro-TH2 int orientation; TH1(int x, int y); TH1(int x, int y, int age); void TH1function(int index); }; struct TH2{ public: int xLoc; int yLoc; float wbc_roll; //selectins float wbc_stick; //integrens float wbc_migrate; //diapedesis int pmn_age; //life span float pmn_pcd; //programmed cell death int mono_age; //life span float TNFr; float IL_1r; int TH2_age; float activation; float pro_TH1; float pro_TH2; float rTH1; //random holder for pro-TH1 float rTH2; //random holder for pro-TH2 int orientation; TH2(int x, int y); TH2(int x, int y, int age); void TH2function(int index); }; struct TH0_germ{ public: int xLoc; int yLoc; int orientation; TH0_germ(int x, int y); void TH0_germ_function(); }; struct TH1_germ{ public: int xLoc; int yLoc; int orientation; TH1_germ(int x, int y); void TH1_germ_function(); }; struct TH2_germ{ public: int xLoc; int yLoc; int orientation; TH2_germ(int x, int y); void TH2_germ_function(); }; #endif
88607795a77a9ed15395a34d51c499f4b94d0b6e
a62342d6359a88b0aee911e549a4973fa38de9ea
/0.6.0.3/External/SDK/ST_Quest_ItemsToPickFrom_functions.cpp
71b912eaf3aef0a013f0e72c2d0fd2def18ad4e6
[]
no_license
zanzo420/Medieval-Dynasty-SDK
d020ad634328ee8ee612ba4bd7e36b36dab740ce
d720e49ae1505e087790b2743506921afb28fc18
refs/heads/main
2023-06-20T03:00:17.986041
2021-07-15T04:51:34
2021-07-15T04:51:34
386,165,085
0
0
null
null
null
null
UTF-8
C++
false
false
506
cpp
// Name: Medieval Dynasty, Version: 0.6.0.3 #include "../pch.h" /*!!DEFINE!!*/ /*!!HELPER_DEF!!*/ /*!!HELPER_INC!!*/ #ifdef _MSC_VER #pragma pack(push, 0x01) #endif namespace CG { //--------------------------------------------------------------------------- // Functions //--------------------------------------------------------------------------- void FST_Quest_ItemsToPickFrom::AfterRead() { } void FST_Quest_ItemsToPickFrom::BeforeDelete() { } } #ifdef _MSC_VER #pragma pack(pop) #endif
c6020a4265e3cdbee527b21f8241f9505d3fbdee
347718e3822e250855d0e64cb5757d216d6bdaa9
/ch11/11-2/q1_1.cpp
0e07a844c61783104204feb4085c2a86740f5fe3
[]
no_license
yoowonsuk/cpp
5fc47711e1babcf881064185f5d70e0dde24bc0d
17ac29accbbbc5d6346ca47b8e4f2f2123ce50ec
refs/heads/master
2020-06-23T05:15:57.423755
2019-08-14T01:57:58
2019-08-14T01:57:58
198,526,354
0
0
null
null
null
null
UTF-8
C++
false
false
1,597
cpp
// BoundCheckPointPtrArray overloading #include <iostream> #include <cstdlib> using namespace std; class Point { private: int xpos, ypos; public: Point(int x=0, int y=0) : xpos(x), ypos(y) { } friend ostream& operator<<(ostream& os, const Point& pos); }; ostream& operator<<(ostream& os, const Point& pos) { os<<'['<<pos.xpos<<", "<<pos.ypos<<']'<<endl; return os; } typedef Point * POINT_PTR; class BoundCheckPointPtrArray { private: POINT_PTR * arr; int arrlen; BoundCheckPointPtrArray(const BoundCheckPointPtrArray& arr) { } BoundCheckPointPtrArray& operator=(const BoundCheckPointPtrArray& arr) { } public: BoundCheckPointPtrArray(int len) :arrlen(len) { arr=new POINT_PTR[len]; } POINT_PTR& operator[] (int idx) { if(idx<0 || idx>=arrlen) { cout<<"Array index out of bound exception"<<endl; exit(1); } return arr[idx]; } POINT_PTR operator[] (int idx) const { if(idx<0 || idx>=arrlen) { cout<<"Array index out of bound exception"<<endl; exit(1); } return arr[idx]; } int GetArrLen() const { return arrlen; } ~BoundCheckPointPtrArray() { delete []arr; } friend ostream& operator<<(ostream& os, const POINT_PTR &arr); }; ostream& operator<<(ostream& os, const POINT_PTR &arr) { os<<*arr; return os; } int main(void) { BoundCheckPointPtrArray arr(3); arr[0]=new Point(3, 4); arr[1]=new Point(5, 6); arr[2]=new Point(7, 8); // for(int i=0; i<arr.GetArrLen(); i++) // cout<<*(arr[i]); for(int i = 0; i<arr.GetArrLen(); i++) cout<<arr[i]; delete arr[0]; delete arr[1]; delete arr[2]; return 0; }
e7c84b803e93355607b34967013066ae8dd5dfd2
79a66affc9fa8bc6dee087d96f079e1c24d15067
/linux/my_application.cc
796af3aa862d0e2040470ff0303fcde838a8ff46
[]
no_license
fear404-png/synt
48d40aa3a5e77d53e0a0c96115dda9ad110d8c3d
c2d568a45a11726cffbfb37ca13b8c24d20350de
refs/heads/main
2023-07-08T03:03:17.602018
2021-08-09T01:09:39
2021-08-09T01:09:39
384,312,612
1
0
null
null
null
null
UTF-8
C++
false
false
3,706
cc
#include "my_application.h" #include <flutter_linux/flutter_linux.h> #ifdef GDK_WINDOWING_X11 #include <gdk/gdkx.h> #endif #include "flutter/generated_plugin_registrant.h" struct _MyApplication { GtkApplication parent_instance; char** dart_entrypoint_arguments; }; G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION) // Implements GApplication::activate. static void my_application_activate(GApplication* application) { MyApplication* self = MY_APPLICATION(application); GtkWindow* window = GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application))); // Use a header bar when running in GNOME as this is the common style used // by applications and is the setup most users will be using (e.g. Ubuntu // desktop). // If running on X and not using GNOME then just use a traditional title bar // in case the window manager does more exotic layout, e.g. tiling. // If running on Wayland assume the header bar will work (may need changing // if future cases occur). gboolean use_header_bar = TRUE; #ifdef GDK_WINDOWING_X11 GdkScreen* screen = gtk_window_get_screen(window); if (GDK_IS_X11_SCREEN(screen)) { const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen); if (g_strcmp0(wm_name, "GNOME Shell") != 0) { use_header_bar = FALSE; } } #endif if (use_header_bar) { GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new()); gtk_widget_show(GTK_WIDGET(header_bar)); gtk_header_bar_set_title(header_bar, "synt"); gtk_header_bar_set_show_close_button(header_bar, TRUE); gtk_window_set_titlebar(window, GTK_WIDGET(header_bar)); } else { gtk_window_set_title(window, "synt"); } gtk_window_set_default_size(window, 1280, 720); gtk_widget_show(GTK_WIDGET(window)); g_autoptr(FlDartProject) project = fl_dart_project_new(); fl_dart_project_set_dart_entrypoint_arguments(project, self->dart_entrypoint_arguments); FlView* view = fl_view_new(project); gtk_widget_show(GTK_WIDGET(view)); gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view)); fl_register_plugins(FL_PLUGIN_REGISTRY(view)); gtk_widget_grab_focus(GTK_WIDGET(view)); } // Implements GApplication::local_command_line. static gboolean my_application_local_command_line(GApplication* application, gchar*** arguments, int* exit_status) { MyApplication* self = MY_APPLICATION(application); // Strip out the first argument as it is the binary name. self->dart_entrypoint_arguments = g_strdupv(*arguments + 1); g_autoptr(GError) error = nullptr; if (!g_application_register(application, nullptr, &error)) { g_warning("Failed to register: %s", error->message); *exit_status = 1; return TRUE; } g_application_activate(application); *exit_status = 0; return TRUE; } // Implements GObject::dispose. static void my_application_dispose(GObject* object) { MyApplication* self = MY_APPLICATION(object); g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev); G_OBJECT_CLASS(my_application_parent_class)->dispose(object); } static void my_application_class_init(MyApplicationClass* klass) { G_APPLICATION_CLASS(klass)->activate = my_application_activate; G_APPLICATION_CLASS(klass)->local_command_line = my_application_local_command_line; G_OBJECT_CLASS(klass)->dispose = my_application_dispose; } static void my_application_init(MyApplication* self) {} MyApplication* my_application_new() { return MY_APPLICATION(g_object_new(my_application_get_type(), "application-id", APPLICATION_ID, "flags", G_APPLICATION_NON_UNIQUE, nullptr)); }
33397c5a4eb278c517d1a0b00f61512225bb7f4b
63a27c3b09cec84533cd4300be96eb625bbd566f
/knapsack/Code/Actor.h
2a5796d49fc64e277df10427dcfee990c1f6831a
[ "Apache-2.0" ]
permissive
derekmpeterson/knapsack
0db751d1378df3c3041d323540ddbc55da55356f
bc96ba50e4a44c8649f9f52376991e3f05b4968e
refs/heads/master
2020-05-18T11:19:49.043797
2015-07-21T05:22:03
2015-07-21T05:22:03
39,353,326
0
0
null
null
null
null
UTF-8
C++
false
false
1,557
h
// // Actor.h // knapsack // // Created by Derek Peterson on 5/7/15. // Copyright (c) 2015 Derek Peterson. All rights reserved. // #ifndef __knapsack__Actor__ #define __knapsack__Actor__ #include <stdio.h> #include "SDL2/SDL.h" #include "SDL2_Image/SDL_Image.h" #include "ext/Vector2d.cpp" #include <vector> #include <string> #include "Gadget.h" #include "LuaScript.h" typedef int ActorHandle; class Actor { private: Vector2d m_pos; Vector2d m_acceleration; float m_speed; SDL_Texture* m_texture; int m_textureWidth; int m_textureHeight; std::string m_name; public: Actor( ActorHandle i_actorHandle, std::string i_name, std::string i_imageName, Vector2d i_pos ); ~Actor(); ActorHandle m_actorHandle; std::vector<Gadget*> m_gadgets; void SetPos( Vector2d i_pos ) { m_pos = i_pos; }; void SetAcceleration( Vector2d i_acceleration ) { m_acceleration = i_acceleration; }; void SetSpeed( int i_speed ) { m_speed = i_speed; }; void SetTexture( SDL_Texture* i_texture ) { m_texture = i_texture; }; Vector2d GetPos() { return m_pos; }; Vector2d GetAcceleration() { return m_acceleration; }; float GetSpeed() { return m_speed; }; SDL_Texture* GetTexture() { return m_texture; }; std::string GetName() { return m_name; }; void Update( float dt ); void Draw(); void AttachGadget( std::string i_gadgetType ); void AttachGadgetWithDNA( std::string i_gadgetType, LuaScript& i_script ); }; #endif /* defined(__knapsack__Actor__) */
3982de166bf068b012731b7814ab3f821d5fbbda
234b36576d6efc4a83dec64130e95f6e4cf5db29
/workspace/catkin_ws/devel/include/rll_msgs/JobStatus.h
1e81d96c1fb22b6db1130b25d4b66d82a1eb704a
[]
no_license
anupamkaul/robotarm_pnp_maze
c812a821c0cb72ee299211501ba06c01d373f03d
f203118714c7c32b750d1ac14c5e4e8776d9a820
refs/heads/master
2020-07-01T08:02:24.327673
2019-08-29T00:32:44
2019-08-29T00:32:44
201,099,922
0
0
null
null
null
null
UTF-8
C++
false
false
5,598
h
// Generated by gencpp from file rll_msgs/JobStatus.msg // DO NOT EDIT! #ifndef RLL_MSGS_MESSAGE_JOBSTATUS_H #define RLL_MSGS_MESSAGE_JOBSTATUS_H #include <string> #include <vector> #include <map> #include <ros/types.h> #include <ros/serialization.h> #include <ros/builtin_message_traits.h> #include <ros/message_operations.h> namespace rll_msgs { template <class ContainerAllocator> struct JobStatus_ { typedef JobStatus_<ContainerAllocator> Type; JobStatus_() : status(0) , status_detail() { } JobStatus_(const ContainerAllocator& _alloc) : status(0) , status_detail(_alloc) { (void)_alloc; } typedef uint8_t _status_type; _status_type status; typedef std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > _status_detail_type; _status_detail_type status_detail; enum { SUCCESS = 0u, FAILURE = 1u, INTERNAL_ERROR = 2u, }; typedef boost::shared_ptr< ::rll_msgs::JobStatus_<ContainerAllocator> > Ptr; typedef boost::shared_ptr< ::rll_msgs::JobStatus_<ContainerAllocator> const> ConstPtr; }; // struct JobStatus_ typedef ::rll_msgs::JobStatus_<std::allocator<void> > JobStatus; typedef boost::shared_ptr< ::rll_msgs::JobStatus > JobStatusPtr; typedef boost::shared_ptr< ::rll_msgs::JobStatus const> JobStatusConstPtr; // constants requiring out of line definition template<typename ContainerAllocator> std::ostream& operator<<(std::ostream& s, const ::rll_msgs::JobStatus_<ContainerAllocator> & v) { ros::message_operations::Printer< ::rll_msgs::JobStatus_<ContainerAllocator> >::stream(s, "", v); return s; } } // namespace rll_msgs namespace ros { namespace message_traits { // BOOLTRAITS {'IsFixedSize': False, 'IsMessage': True, 'HasHeader': False} // {'geometry_msgs': ['/opt/ros/kinetic/share/geometry_msgs/cmake/../msg'], 'actionlib_msgs': ['/opt/ros/kinetic/share/actionlib_msgs/cmake/../msg'], 'std_msgs': ['/opt/ros/kinetic/share/std_msgs/cmake/../msg'], 'rll_msgs': ['/home/anupam/robotarm_pnp_maze/workspace/catkin_ws/src/rll_sdk/rll_msgs/msg', '/home/anupam/robotarm_pnp_maze/workspace/catkin_ws/devel/share/rll_msgs/msg']} // !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types'] template <class ContainerAllocator> struct IsFixedSize< ::rll_msgs::JobStatus_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct IsFixedSize< ::rll_msgs::JobStatus_<ContainerAllocator> const> : FalseType { }; template <class ContainerAllocator> struct IsMessage< ::rll_msgs::JobStatus_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::rll_msgs::JobStatus_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::rll_msgs::JobStatus_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct HasHeader< ::rll_msgs::JobStatus_<ContainerAllocator> const> : FalseType { }; template<class ContainerAllocator> struct MD5Sum< ::rll_msgs::JobStatus_<ContainerAllocator> > { static const char* value() { return "ded0e6920d3687094231ffc64e57394c"; } static const char* value(const ::rll_msgs::JobStatus_<ContainerAllocator>&) { return value(); } static const uint64_t static_value1 = 0xded0e6920d368709ULL; static const uint64_t static_value2 = 0x4231ffc64e57394cULL; }; template<class ContainerAllocator> struct DataType< ::rll_msgs::JobStatus_<ContainerAllocator> > { static const char* value() { return "rll_msgs/JobStatus"; } static const char* value(const ::rll_msgs::JobStatus_<ContainerAllocator>&) { return value(); } }; template<class ContainerAllocator> struct Definition< ::rll_msgs::JobStatus_<ContainerAllocator> > { static const char* value() { return "uint8 status\n\ uint8 SUCCESS = 0\n\ uint8 FAILURE = 1\n\ uint8 INTERNAL_ERROR = 2\n\ string status_detail\n\ "; } static const char* value(const ::rll_msgs::JobStatus_<ContainerAllocator>&) { return value(); } }; } // namespace message_traits } // namespace ros namespace ros { namespace serialization { template<class ContainerAllocator> struct Serializer< ::rll_msgs::JobStatus_<ContainerAllocator> > { template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m) { stream.next(m.status); stream.next(m.status_detail); } ROS_DECLARE_ALLINONE_SERIALIZER }; // struct JobStatus_ } // namespace serialization } // namespace ros namespace ros { namespace message_operations { template<class ContainerAllocator> struct Printer< ::rll_msgs::JobStatus_<ContainerAllocator> > { template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::rll_msgs::JobStatus_<ContainerAllocator>& v) { s << indent << "status: "; Printer<uint8_t>::stream(s, indent + " ", v.status); s << indent << "status_detail: "; Printer<std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > >::stream(s, indent + " ", v.status_detail); } }; } // namespace message_operations } // namespace ros #endif // RLL_MSGS_MESSAGE_JOBSTATUS_H
9a3d745cde6943416f620a30a6957775db48b480
c849fa997c2a41d27af1d7aa21e3f0c7d7b4523b
/Saclay/saclay.cpp
875dbc3788343005f9bd69d83a23a706a33f91dc
[]
no_license
kinuskia/Heavy-Ion-Collision-Analysis
8045ce9969872006f4f59a8d6938409658e5adb6
47ae07a9b219d9873975b30c89ac6da18652e526
refs/heads/master
2021-06-25T00:33:16.942994
2020-11-01T15:04:10
2020-11-01T15:04:10
154,057,951
1
0
null
null
null
null
UTF-8
C++
false
false
4,479
cpp
#include <iostream> #include <vector> //#include <gsl/gsl_vector.h> #include "model.hpp" #include "../auxiliary/fbdecomposition.hpp" // load after (!) model.hpp #include "../auxiliary/to_file.hpp" #include "../auxiliary/to_size_t.hpp" #include <ctime> /* Idea: In the file "model.hpp" one specifies the position space one-point and two-point correlation function of an arbitrary initial-state model. Here, t */ int main (int argc, char* argv[]) // comand-line input: centrality_min, centrality_max, # grid points for r-integration, # gridpoints azimuthal direction, output location, infrared cutoff { typedef std::size_t size_type; typedef double number_type; size_type centrality_min = to_size_t(argv[1]); size_type centrality_max = to_size_t(argv[2]); size_type n_grid = to_size_t(argv[3]); size_type n_azim = to_size_t(argv[4]); std::string destination = argv[5]; number_type m_IR = std::stod(argv[6]); std::string centrality = std::to_string(centrality_min) + "-" + std::to_string(centrality_max); // Set up initial-state model Model<number_type> model(m_IR, 6.624, 0.549, 0.); model.initialize_W("../Saclay_simplified/output/"+centrality+"/weight_functions_magma_"+centrality+".txt"); model.initialize_T(); // const gsl_interp2d_type* xy_interpolation_method = gsl_interp2d_bicubic; // model.initialize_OnePoint("../output/profiles_averaged_"+centrality+".txt", 100, xy_interpolation_method, 10, 0.2); // Set up Fourier-Bessel decomposition object // with rMax = 10 as maximal radial integration length FBDecomposition<number_type> decomposition(model, 9.604+0*1.*8.604, centrality_min); decomposition.get_impact_parameter_distribution("../output/percentiles_b.txt"); decomposition.initialize(); // set number of radial grid points per dimension decomposition.set_N_discret(n_grid); // set # gridpoints for FFT decomposition.set_Nm_(n_azim); // Compute <e_l1^(m)e_l2^(-m)> as a function of l int mMax = 10; //4 int lMax = 20; //10 decomposition.fill_background_bar_for(mMax, lMax); decomposition.print_background_bar(destination + "/background_coeffs_CGC_" + centrality + ".txt"); number_type counter = 0; number_type progress_steps = 100; std::time_t start = std::time(nullptr); bool estimate_given = false; size_type nb_steps = (mMax+1)*lMax*lMax; // number_type current = decomposition.TwoMode_fast(1, 9, -1, 9); // std::cout << current << "\n"; for (int m = mMax; m >= 0; --m) { // if ((m != 1)) // DELETE AFTERWARDS // { // continue; // } // save result in matrix gsl_matrix* result = gsl_matrix_alloc(lMax, lMax); for (int l1 = 1; l1 <= lMax; ++l1) { for (int l2 = 1; l2 <= lMax; ++l2) { // /////////////////////////////////////////////////////// // if ( (m <= 4) && (l1 < 10 && l2 < 10) ) // { // gsl_matrix_set(result, l1-1, l2-1, 0.0); // continue; // } // /////////////////////////////////////////////////////// // if (l1 != l2) // { // gsl_matrix_set(result, l1-1, l2-1, 0.0); // continue; // } if (l1 > l2) // make use of symmetry { continue; } std::cout << "m=" << m << ", l1= " << l1 << ", l2=" << l2 << "\n"; // Print progress for (size_type i = 1; i < progress_steps; ++i) { if (counter == size_type(i*nb_steps/progress_steps)) { std::cout << "Progress: " << size_type(i*100./progress_steps) << "%" << "\n"; } } // After 60 s: estimate total computation time: std::time_t end = std::time(nullptr); number_type diff = end - start; if ( (diff > 60) && !estimate_given) { number_type expected_duration = 1.0*nb_steps * diff / counter / 60; std::cout << "Computation time in min: " << expected_duration << "\n"; estimate_given = true; } number_type current = decomposition.TwoMode_fast2(m, l1, -m, l2, centrality_min); gsl_matrix_set(result, l1-1, l2-1, current); // make use of symmetry gsl_matrix_set(result, l2-1, l1-1, current); counter++; } } // save result to text file std::string filename = destination + "/two_point_random_connected_m_"; filename += std::to_string(m); //filename += "_test"; filename += ".txt"; to_file(filename, result); gsl_matrix_free(result); } // report total calculation time std::time_t end = std::time(nullptr); number_type diff = 1.0*(end - start)/60; std::cout << "Total calculation time in min : " << diff << "\n"; return 0; }
e7c986747d79c7e218d65795efa33b6c431c421e
0577a46d8d28e1fd8636893bbdd2b18270bb8eb8
/update_notifier/thirdparty/wxWidgets/src/common/ftp.cpp
bb90ebaea3ef30b431f40a72269a51777891cd61
[ "BSD-3-Clause" ]
permissive
ric2b/Vivaldi-browser
388a328b4cb838a4c3822357a5529642f86316a5
87244f4ee50062e59667bf8b9ca4d5291b6818d7
refs/heads/master
2022-12-21T04:44:13.804535
2022-12-17T16:30:35
2022-12-17T16:30:35
86,637,416
166
41
BSD-3-Clause
2021-03-31T18:49:30
2017-03-29T23:09:05
null
UTF-8
C++
false
false
29,127
cpp
///////////////////////////////////////////////////////////////////////////// // Name: src/common/ftp.cpp // Purpose: FTP protocol // Author: Guilhem Lavaux // Modified by: Mark Johnson, [email protected] // 20000917 : RmDir, GetLastResult, GetList // Vadim Zeitlin (numerous fixes and rewrites to all part of the // code, support ASCII/Binary modes, better error reporting, more // robust Abort(), support for arbitrary FTP commands, ...) // Randall Fox (support for active mode) // Created: 07/07/1997 // Copyright: (c) 1997, 1998 Guilhem Lavaux // (c) 1998-2004 wxWidgets team // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// // ============================================================================ // declarations // ============================================================================ // ---------------------------------------------------------------------------- // headers // ---------------------------------------------------------------------------- // For compilers that support precompilation, includes "wx.h". #include "wx/wxprec.h" #if wxUSE_PROTOCOL_FTP #ifndef WX_PRECOMP #include <stdlib.h> #include "wx/string.h" #include "wx/utils.h" #include "wx/log.h" #include "wx/intl.h" #include "wx/wxcrtvararg.h" #endif // WX_PRECOMP #include "wx/sckaddr.h" #include "wx/socket.h" #include "wx/url.h" #include "wx/sckstrm.h" #include "wx/protocol/protocol.h" #include "wx/protocol/ftp.h" #include <memory.h> // ---------------------------------------------------------------------------- // constants // ---------------------------------------------------------------------------- // the length of FTP status code (3 digits) static const size_t LEN_CODE = 3; // ---------------------------------------------------------------------------- // macros // ---------------------------------------------------------------------------- wxIMPLEMENT_DYNAMIC_CLASS(wxFTP, wxProtocol); IMPLEMENT_PROTOCOL(wxFTP, wxT("ftp"), wxT("ftp"), true) // ============================================================================ // implementation // ============================================================================ // ---------------------------------------------------------------------------- // wxFTP constructor and destructor // ---------------------------------------------------------------------------- wxFTP::wxFTP() { m_streaming = false; m_currentTransfermode = NONE; m_username = wxT("anonymous"); m_password << wxGetUserId() << wxT('@') << wxGetFullHostName(); m_bPassive = true; m_bEncounteredError = false; } wxFTP::~wxFTP() { if ( m_streaming ) { // if we are streaming, this will issue // an FTP ABORT command, to tell the server we are aborting (void)Abort(); } // now this issues a "QUIT" command to tell the server we are Close(); } // ---------------------------------------------------------------------------- // wxFTP connect and login methods // ---------------------------------------------------------------------------- bool wxFTP::Connect(const wxSockAddress& addr, bool WXUNUSED(wait)) { if ( !wxProtocol::Connect(addr) ) { m_lastError = wxPROTO_NETERR; return false; } if ( !m_username ) { m_lastError = wxPROTO_CONNERR; return false; } // we should have 220 welcome message if ( !CheckResult('2') ) { Close(); return false; } wxString command; command.Printf(wxT("USER %s"), m_username.c_str()); char rc = SendCommand(command); if ( rc == '2' ) { // 230 return: user accepted without password m_lastError = wxPROTO_NOERR; return true; } if ( rc != '3' ) { m_lastError = wxPROTO_CONNERR; Close(); return false; } command.Printf(wxT("PASS %s"), m_password.c_str()); if ( !CheckCommand(command, '2') ) { m_lastError = wxPROTO_CONNERR; Close(); return false; } m_lastError = wxPROTO_NOERR; return true; } bool wxFTP::Connect(const wxString& host, unsigned short port) { wxIPV4address addr; addr.Hostname(host); if ( port ) addr.Service(port); else if (!addr.Service(wxT("ftp"))) addr.Service(21); return Connect(addr); } bool wxFTP::Close() { if ( m_streaming ) { m_lastError = wxPROTO_STREAMING; return false; } if ( IsConnected() ) { if ( !CheckCommand(wxT("QUIT"), '2') ) { m_lastError = wxPROTO_CONNERR; wxLogDebug(wxT("Failed to close connection gracefully.")); } } return wxSocketClient::Close(); } // ============================================================================ // low level methods // ============================================================================ wxSocketBase *wxFTP::AcceptIfActive(wxSocketBase *sock) { if ( m_bPassive ) return sock; // now wait for a connection from server wxSocketServer *sockSrv = (wxSocketServer *)sock; if ( !sockSrv->WaitForAccept() ) { m_lastError = wxPROTO_CONNERR; wxLogError(_("Timeout while waiting for FTP server to connect, try passive mode.")); wxDELETE(sock); } else { m_lastError = wxPROTO_NOERR; sock = sockSrv->Accept(true); delete sockSrv; } return sock; } bool wxFTP::Abort() { if ( !m_streaming ) return true; m_streaming = false; if ( !CheckCommand(wxT("ABOR"), '4') ) return false; return CheckResult('2'); } // ---------------------------------------------------------------------------- // Send command to FTP server // ---------------------------------------------------------------------------- char wxFTP::SendCommand(const wxString& command) { if ( m_streaming ) { m_lastError = wxPROTO_STREAMING; return 0; } wxString tmp_str = command + wxT("\r\n"); const wxWX2MBbuf tmp_buf = tmp_str.mb_str(); if ( Write(static_cast<const char *>(tmp_buf), strlen(tmp_buf)).Error()) { m_lastError = wxPROTO_NETERR; return 0; } // don't show the passwords in the logs (even in debug ones) wxString cmd, password; if ( command.Upper().StartsWith(wxT("PASS "), &password) ) { cmd << wxT("PASS ") << wxString(wxT('*'), password.length()); } else { cmd = command; } LogRequest(cmd); m_lastError = wxPROTO_NOERR; return GetResult(); } // ---------------------------------------------------------------------------- // Receive servers reply // ---------------------------------------------------------------------------- char wxFTP::GetResult() { // if we've already had a read or write timeout error, the connection is // probably toast, so don't bother, it just wastes the users time if ( m_bEncounteredError ) return 0; wxString code; // m_lastResult will contain the entire server response, possibly on // multiple lines m_lastResult.clear(); // we handle multiline replies here according to RFC 959: it says that a // reply may either be on 1 line of the form "xyz ..." or on several lines // in whuch case it looks like // xyz-... // ... // xyz ... // and the intermeidate lines may start with xyz or not bool badReply = false; bool firstLine = true; bool endOfReply = false; while ( !endOfReply && !badReply ) { wxString line; m_lastError = ReadLine(this,line); if ( m_lastError ) { m_bEncounteredError = true; return 0; } LogResponse(line); if ( !m_lastResult.empty() ) { // separate from last line m_lastResult += wxT('\n'); } m_lastResult += line; // unless this is an intermediate line of a multiline reply, it must // contain the code in the beginning and '-' or ' ' following it if ( line.Len() < LEN_CODE + 1 ) { if ( firstLine ) { badReply = true; } } else // line has at least 4 chars { // this is the char which tells us what we're dealing with wxChar chMarker = line.GetChar(LEN_CODE); if ( firstLine ) { code = wxString(line, LEN_CODE); switch ( chMarker ) { case wxT(' '): endOfReply = true; break; case wxT('-'): firstLine = false; break; default: // unexpected badReply = true; } } else // subsequent line of multiline reply { if ( line.compare(0, LEN_CODE, code) == 0 ) { if ( chMarker == wxT(' ') ) { endOfReply = true; } } } } } if ( badReply ) { wxLogDebug(wxT("Broken FTP server: '%s' is not a valid reply."), m_lastResult.c_str()); m_lastError = wxPROTO_PROTERR; return 0; } else m_lastError = wxPROTO_NOERR; // if we got here we must have a non empty code string return (char)code[0u]; } // ---------------------------------------------------------------------------- // wxFTP simple commands // ---------------------------------------------------------------------------- bool wxFTP::SetTransferMode(TransferMode transferMode) { if ( transferMode == m_currentTransfermode ) { // nothing to do return true; } wxString mode; switch ( transferMode ) { default: wxFAIL_MSG(wxT("unknown FTP transfer mode")); wxFALLTHROUGH; case BINARY: mode = wxT('I'); break; case ASCII: mode = wxT('A'); break; } if ( !DoSimpleCommand(wxT("TYPE"), mode) ) { wxLogError(_("Failed to set FTP transfer mode to %s."), (transferMode == ASCII ? _("ASCII") : _("binary"))); return false; } // If we get here the operation has been successfully completed // Set the status-member m_currentTransfermode = transferMode; return true; } bool wxFTP::DoSimpleCommand(const wxChar *command, const wxString& arg) { wxString fullcmd = command; if ( !arg.empty() ) { fullcmd << wxT(' ') << arg; } if ( !CheckCommand(fullcmd, '2') ) { wxLogDebug(wxT("FTP command '%s' failed."), fullcmd.c_str()); m_lastError = wxPROTO_NETERR; return false; } m_lastError = wxPROTO_NOERR; return true; } bool wxFTP::ChDir(const wxString& dir) { // some servers might not understand ".." if they use different directory // tree conventions, but they always understand CDUP - should we use it if // dir == ".."? OTOH, do such servers (still) exist? return DoSimpleCommand(wxT("CWD"), dir); } bool wxFTP::MkDir(const wxString& dir) { return DoSimpleCommand(wxT("MKD"), dir); } bool wxFTP::RmDir(const wxString& dir) { return DoSimpleCommand(wxT("RMD"), dir); } wxString wxFTP::Pwd() { wxString path; if ( CheckCommand(wxT("PWD"), '2') ) { // the result is at least that long if CheckCommand() succeeded wxString::const_iterator p = m_lastResult.begin() + LEN_CODE + 1; const wxString::const_iterator end = m_lastResult.end(); if ( p == end || *p != wxT('"') ) { wxLogDebug(wxT("Missing starting quote in reply for PWD: %s"), wxString(p, end)); } else { for ( ++p; p != end; ++p ) { if ( *p == wxT('"') ) { // check if the quote is doubled ++p; if ( p == end || *p != wxT('"') ) { // no, this is the end break; } //else: yes, it is: this is an embedded quote in the // filename, treat as normal char } path += *p; } if ( p != end ) { wxLogDebug(wxT("Missing ending quote in reply for PWD: %s"), m_lastResult.c_str() + LEN_CODE + 1); } } } else { m_lastError = wxPROTO_PROTERR; wxLogDebug(wxT("FTP PWD command failed.")); } return path; } bool wxFTP::Rename(const wxString& src, const wxString& dst) { wxString str; str = wxT("RNFR ") + src; if ( !CheckCommand(str, '3') ) return false; str = wxT("RNTO ") + dst; return CheckCommand(str, '2'); } bool wxFTP::RmFile(const wxString& path) { wxString str; str = wxT("DELE ") + path; return CheckCommand(str, '2'); } // ---------------------------------------------------------------------------- // wxFTP port methods // ---------------------------------------------------------------------------- wxSocketBase *wxFTP::GetPort() { /* PASSIVE: Client sends a "PASV" to the server. The server responds with an address and port number which it will be listening on. Then the client connects to the server at the specified address and port. ACTIVE: Client sends the server a PORT command which includes an address and port number which the client will be listening on. The server then connects to the client at that address and port. */ wxSocketBase *socket = m_bPassive ? GetPassivePort() : GetActivePort(); if ( !socket ) { m_bEncounteredError = true; return NULL; } // Now set the time for the new socket to the default or user selected // timeout period socket->SetTimeout(m_uiDefaultTimeout); return socket; } wxString wxFTP::GetPortCmdArgument(const wxIPV4address& addrLocal, const wxIPV4address& addrNew) { // Just fills in the return value with the local IP // address of the current socket. Also it fill in the // PORT which the client will be listening on wxString addrIP = addrLocal.IPAddress(); int portNew = addrNew.Service(); // We need to break the PORT number in bytes addrIP.Replace(wxT("."), wxT(",")); addrIP << wxT(',') << wxString::Format(wxT("%d"), portNew >> 8) << wxT(',') << wxString::Format(wxT("%d"), portNew & 0xff); // Now we have a value like "10,0,0,1,5,23" return addrIP; } wxSocketBase *wxFTP::GetActivePort() { // we need an address to listen on wxIPV4address addrNew, addrLocal; GetLocal(addrLocal); addrNew.AnyAddress(); addrNew.Service(0); // pick an open port number. wxSocketServer* const sockSrv = new wxSocketServer ( addrNew, wxSocketServer::GetBlockingFlagIfNeeded() ); if (!sockSrv->IsOk()) { // We use IsOk() here to see if everything is ok m_lastError = wxPROTO_PROTERR; delete sockSrv; return NULL; } //gets the new address, actually it is just the port number sockSrv->GetLocal(addrNew); // Now we create the argument of the PORT command, we send in both // addresses because the addrNew has an IP of "0.0.0.0", so we need the // value in addrLocal wxString port = GetPortCmdArgument(addrLocal, addrNew); if ( !DoSimpleCommand(wxT("PORT"), port) ) { m_lastError = wxPROTO_PROTERR; delete sockSrv; wxLogError(_("The FTP server doesn't support the PORT command.")); return NULL; } m_lastError = wxPROTO_NOERR; sockSrv->Notify(false); // Don't send any events return sockSrv; } wxSocketBase *wxFTP::GetPassivePort() { if ( !DoSimpleCommand(wxT("PASV")) ) { m_lastError = wxPROTO_PROTERR; wxLogError(_("The FTP server doesn't support passive mode.")); return NULL; } size_t addrStart = m_lastResult.find(wxT('(')); size_t addrEnd = (addrStart == wxString::npos) ? wxString::npos : m_lastResult.find(wxT(')'), addrStart); if ( addrEnd == wxString::npos ) { m_lastError = wxPROTO_PROTERR; return NULL; } // get the port number and address int a[6]; wxString straddr(m_lastResult, addrStart + 1, addrEnd - (addrStart + 1)); wxSscanf(straddr, wxT("%d,%d,%d,%d,%d,%d"), &a[2],&a[3],&a[4],&a[5],&a[0],&a[1]); wxUint32 hostaddr = (wxUint16)a[2] << 24 | (wxUint16)a[3] << 16 | (wxUint16)a[4] << 8 | a[5]; wxUint16 port = (wxUint16)(a[0] << 8 | a[1]); wxIPV4address addr; addr.Hostname(hostaddr); addr.Service(port); // If we're used from a worker thread or can't dispatch events even though // we're in the main one, we can't use non-blocking sockets. wxSocketClient* const client = new wxSocketClient(wxSocketClient::GetBlockingFlagIfNeeded()); if ( !client->Connect(addr) ) { m_lastError = wxPROTO_CONNERR; delete client; return NULL; } client->Notify(false); m_lastError = wxPROTO_NOERR; return client; } // ---------------------------------------------------------------------------- // wxFTP download and upload // ---------------------------------------------------------------------------- class wxInputFTPStream : public wxSocketInputStream { public: wxInputFTPStream(wxFTP *ftp, wxSocketBase *sock) : wxSocketInputStream(*sock) { m_ftp = ftp; // socket timeout automatically set in GetPort function } virtual ~wxInputFTPStream() { delete m_i_socket; // keep at top // when checking the result, the stream will // almost always show an error, even if the file was // properly transferred, thus, let's just grab the result // we are looking for "226 transfer completed" char code = m_ftp->GetResult(); if ('2' == code) { // it was a good transfer. // we're done! m_ftp->m_streaming = false; return; } // did we timeout? if (0 == code) { // the connection is probably toast. issue an abort, and // then a close. there won't be any more waiting // for this connection m_ftp->Abort(); m_ftp->Close(); return; } // There was a problem with the transfer and the server // has acknowledged it. If we issue an "ABORT" now, the user // would get the "226" for the abort and think the xfer was // complete, thus, don't do anything here, just return } wxFTP *m_ftp; wxDECLARE_NO_COPY_CLASS(wxInputFTPStream); }; class wxOutputFTPStream : public wxSocketOutputStream { public: wxOutputFTPStream(wxFTP *ftp_clt, wxSocketBase *sock) : wxSocketOutputStream(*sock), m_ftp(ftp_clt) { } virtual ~wxOutputFTPStream() { if ( IsOk() ) { // close data connection first, this will generate "transfer // completed" reply delete m_o_socket; // read this reply m_ftp->GetResult(); // save result so user can get to it m_ftp->m_streaming = false; } else { // abort data connection first m_ftp->Abort(); // and close it after delete m_o_socket; } } wxFTP *m_ftp; wxDECLARE_NO_COPY_CLASS(wxOutputFTPStream); }; wxInputStream *wxFTP::GetInputStream(const wxString& path) { if ( ( m_currentTransfermode == NONE ) && !SetTransferMode(BINARY) ) { m_lastError = wxPROTO_CONNERR; return NULL; } wxSocketBase *sock = GetPort(); if ( !sock ) { m_lastError = wxPROTO_NETERR; return NULL; } wxString tmp_str = wxT("RETR ") + wxURI::Unescape(path); if ( !CheckCommand(tmp_str, '1') ) { delete sock; return NULL; } sock = AcceptIfActive(sock); if ( !sock ) { m_lastError = wxPROTO_CONNERR; return NULL; } m_streaming = true; wxInputFTPStream *in_stream = new wxInputFTPStream(this, sock); m_lastError = wxPROTO_NOERR; return in_stream; } wxOutputStream *wxFTP::GetOutputStream(const wxString& path) { if ( ( m_currentTransfermode == NONE ) && !SetTransferMode(BINARY) ) { m_lastError = wxPROTO_CONNERR; return NULL; } wxSocketBase *sock = GetPort(); wxString tmp_str = wxT("STOR ") + path; if ( !CheckCommand(tmp_str, '1') ) { delete sock; return NULL; } sock = AcceptIfActive(sock); m_streaming = true; m_lastError = wxPROTO_NOERR; return new wxOutputFTPStream(this, sock); } // ---------------------------------------------------------------------------- // FTP directory listing // ---------------------------------------------------------------------------- bool wxFTP::GetList(wxArrayString& files, const wxString& wildcard, bool details) { wxSocketBase *sock = GetPort(); if (!sock) { m_lastError = wxPROTO_NETERR; return false; } // NLST : List of Filenames (including Directory's !) // LIST : depending on BS of FTP-Server // - Unix : result like "ls" command // - Windows : like "dir" command // - others : ? wxString line(details ? wxT("LIST") : wxT("NLST")); if ( !wildcard.empty() ) { line << wxT(' ') << wildcard; } if ( !CheckCommand(line, '1') ) { m_lastError = wxPROTO_PROTERR; wxLogDebug(wxT("FTP 'LIST' command returned unexpected result from server")); delete sock; return false; } sock = AcceptIfActive(sock); if ( !sock ) { m_lastError = wxPROTO_CONNERR; return false; } files.Empty(); while (ReadLine(sock, line) == wxPROTO_NOERR ) { files.Add(line); } delete sock; // the file list should be terminated by "226 Transfer complete"" m_lastError = wxPROTO_NOERR; return CheckResult('2'); } bool wxFTP::FileExists(const wxString& fileName) { // This function checks if the file specified in fileName exists in the // current dir. It does so by simply doing an NLST (via GetList). // If this succeeds (and the list is not empty) the file exists. bool retval = false; wxArrayString fileList; if ( GetList(fileList, fileName, false) ) { // Some ftp-servers (Ipswitch WS_FTP Server 1.0.5 does this) // displays this behaviour when queried on a nonexistent file: // NLST this_file_does_not_exist // 150 Opening ASCII data connection for directory listing // (no data transferred) // 226 Transfer complete // Here wxFTP::GetList(...) will succeed but it will return an empty // list. retval = !fileList.IsEmpty(); } return retval; } // ---------------------------------------------------------------------------- // FTP GetSize // ---------------------------------------------------------------------------- int wxFTP::GetFileSize(const wxString& fileName) { // return the filesize of the given file if possible // return -1 otherwise (predominantly if file doesn't exist // in current dir) int filesize = -1; // Check for existence of file via wxFTP::FileExists(...) if ( FileExists(fileName) ) { wxString command; // First try "SIZE" command using BINARY(IMAGE) transfermode // Especially UNIX ftp-servers distinguish between the different // transfermodes and reports different filesizes accordingly. // The BINARY size is the interesting one: How much memory // will we need to hold this file? TransferMode oldTransfermode = m_currentTransfermode; SetTransferMode(BINARY); command << wxT("SIZE ") << fileName; bool ok = CheckCommand(command, '2'); if ( ok ) { // The answer should be one line: "213 <filesize>\n" // 213 is File Status (STD9) // "SIZE" is not described anywhere..? It works on most servers int statuscode; if ( wxSscanf(GetLastResult().c_str(), wxT("%i %i"), &statuscode, &filesize) == 2 ) { // We've gotten a good reply. ok = true; } else { // Something bad happened.. A "2yz" reply with no size // Fallback ok = false; } } // Set transfermode back to the original. Only the "SIZE"-command // is dependent on transfermode if ( oldTransfermode != NONE ) { SetTransferMode(oldTransfermode); } // this is not a direct else clause.. The size command might return an // invalid "2yz" reply if ( !ok ) { // The server didn't understand the "SIZE"-command or it // returned an invalid reply. // We now try to get details for the file with a "LIST"-command // and then parse the output from there.. wxArrayString fileList; if ( GetList(fileList, fileName, true) ) { if ( !fileList.IsEmpty() ) { // We _should_ only get one line in return, but just to be // safe we run through the line(s) returned and look for a // substring containing the name we are looking for. We // stop the iteration at the first occurrence of the // filename. The search is not case-sensitive. const size_t numFiles = fileList.size(); size_t i; for ( i = 0; i < fileList.GetCount(); i++ ) { if ( fileList[i].Upper().Contains(fileName.Upper()) ) break; } if ( i != numFiles ) { // The index i points to the first occurrence of // fileName in the array Now we have to find out what // format the LIST has returned. There are two // "schools": Unix-like // // '-rw-rw-rw- owner group size month day time filename' // // or Windows-like // // 'date size filename' // check if the first character is '-'. This would // indicate Unix-style (this also limits this function // to searching for files, not directories) if ( fileList[i].Mid(0, 1) == wxT("-") ) { if ( wxSscanf(fileList[i].c_str(), wxT("%*s %*s %*s %*s %i %*s %*s %*s %*s"), &filesize) != 9 ) { // Hmm... Invalid response wxLogDebug(wxT("Invalid LIST response")); } } else // Windows-style response (?) { if ( wxSscanf(fileList[i].c_str(), wxT("%*s %*s %i %*s"), &filesize) != 4 ) { // something bad happened..? wxLogDebug(wxT("Invalid or unknown LIST response")); } } } } } } } // filesize might still be -1 when exiting return filesize; } #endif // wxUSE_PROTOCOL_FTP
34c24756645ee4b39527dde248fb69aa61c0e009
c894cd35c59ac6166f2fea40e18e6aa65333ce2e
/MysqlSP/MysqlSP/main.cpp
d330b09559df4f86b06253f29009f8999c524eb2
[]
no_license
skdn159/GameServerLearning
49ac9fb9db87ee926a61a3972aabb16873c8b8c3
e01dd1ad3c14337664eaca6d6aa391ac5e91211c
refs/heads/master
2020-04-06T07:02:41.021719
2016-09-07T02:01:41
2016-09-07T02:01:41
61,171,206
0
0
null
null
null
null
UHC
C++
false
false
2,454
cpp
#pragma once #include "MainForm.h" // #include "Windows.h" // #include "iostream" // using namespace std; // // #include "sql.h" // #include "sqlext.h" // #include <tchar.h> // #include <sqltypes.h> // // int _tmain(int argc, _TCHAR* argv[]) { // // int ret; // SQLHENV hEnv; // SQLHDBC hDbc; // SQLHSTMT hStmt; // // //SQL과 연결 // ret = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &hEnv); // ret = SQLSetEnvAttr(hEnv, SQL_ATTR_ODBC_VERSION, // (SQLPOINTER)SQL_OV_ODBC3, SQL_IS_INTEGER); // ret = SQLAllocHandle(SQL_HANDLE_DBC, hEnv, &hDbc); // // // ret = SQLConnect(hDbc, (SQLWCHAR*)L"MYODBC", SQL_NTS, // (SQLWCHAR*)L"root", SQL_NTS, // (SQLWCHAR*)L"1q2w3e4r", SQL_NTS); // if (ret == SQL_SUCCESS || ret == SQL_SUCCESS_WITH_INFO) // printf("SQL Connect Ok \n"); // else { // display error code when we get error… SQLGetDiagRec 참고 // printf("sqlconnect error .\n"); return(1); // } // // // // 명령핸들 // ret = SQLAllocHandle(SQL_HANDLE_STMT, hDbc, &hStmt); // //ret = SQLExecDirect(hStmt, (SQLWCHAR*)L"SELECT * FROM Users", SQL_NTS); // ret = SQLExecDirect(hStmt, (SQLWCHAR*)L"call SP_SearchUID ('testId', 'asdf1234', @ret);", SQL_NTS); // if (ret == SQL_SUCCESS) { // int iCount = 0; // // //SQLLEN iAuthorLen, iTitleLen, iPriceLen, iPrice; // SQLLEN UID, UIDLen, UserIDLen, PassWordLen; // char UserID[100], PassWord[100]; // // while (TRUE) { // ret = SQLFetch(hStmt); // 값을 얻어올때 // if (ret == SQL_ERROR || ret == SQL_SUCCESS_WITH_INFO) // printf("An error occured\n"); // // if (ret == SQL_SUCCESS || ret == SQL_SUCCESS_WITH_INFO) { // SQLGetData(hStmt, 1, SQL_C_WCHAR, &UID, 0, &UIDLen); // SQLGetData(hStmt, 2, SQL_C_WCHAR, UserID, 100, &UserIDLen); // SQLGetData(hStmt, 3, SQL_C_ULONG, &PassWord, 100, &PassWordLen); // /* Print the row of data */ // _tprintf(_T(" Row %d : "), iCount++); // _tprintf(_T(" %ls %ls %d \n"), UID, UserID, PassWord); // } // } // } // else // printf("An error occured during excuting query!! \n"); // //접속 종료 및 반환 // if (hStmt) SQLFreeHandle(SQL_HANDLE_STMT, hStmt); // if (hDbc) SQLDisconnect(hDbc); // if (hDbc) SQLFreeHandle(SQL_HANDLE_DBC, hDbc); // if (hEnv) SQLFreeHandle(SQL_HANDLE_ENV, hEnv); // return 0; // } int main() { MainForm mainform; mainform.Init(); mainform.CreateGUI(); mainform.ShowModal(); getchar(); return 0; }
d35561616ce977bc3967a6363d4cf470fb9f2fc0
7bcc51362468098bbb9ddd241230e02cdbeea6e4
/engine/src/C4GameSave.cpp
67775aa4ecd4291f95d15ba01c81ed74c93101d3
[ "ISC" ]
permissive
Marko10-000/clonk-rage
af4ac62b7227c00874ecd49431a29a984a417fbb
230e715f2abe65966d5e5467cb18382062d1dec6
refs/heads/master
2021-01-18T07:29:38.108084
2015-09-07T01:34:56
2015-09-07T01:34:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
17,763
cpp
/* by Sven2, 2004 */ // game saving functionality #include <C4Include.h> #include <C4GameSave.h> #include <C4Version.h> #ifndef BIG_C4INCLUDE #include <C4Components.h> #include <C4Game.h> #include <C4Console.h> #include <C4Log.h> #include <C4Player.h> #endif // *** C4GameSave main class bool C4GameSave::SaveCreateGroup(const char *szFilename, C4Group &hUseGroup) { // erase any previous item (2do: work in C4Groups?) EraseItem(szFilename); // copy from previous group? if (GetCopyScenario()) if (!ItemIdentical(Game.ScenarioFilename, szFilename)) if (!C4Group_CopyItem(Game.ScenarioFilename, szFilename)) { LogF(LoadResStr("IDS_CNS_SAVEASERROR"), szFilename); return false; } // open it if (!hUseGroup.Open(szFilename, !GetCopyScenario())) { EraseItem(szFilename); LogF(LoadResStr("IDS_CNS_SAVEASERROR"), szFilename); return false; } // done, success return true; } bool C4GameSave::SaveCore() { // base on original, current core rC4S = Game.C4S; // Always mark current engine version rC4S.Head.C4XVer[0]=C4XVER1; rC4S.Head.C4XVer[1]=C4XVER2; rC4S.Head.C4XVer[2]=C4XVER3; rC4S.Head.C4XVer[3]=C4XVER4; // Some flags are not to be set for initial settings: // They depend on whether specific runtime data is present, which may simply not be stored into initial // saves, because they rely on any data present and up-to-date within the scenario! if (!fInitial) { // NoInitialize: Marks whether object data is contained and not to be created from core rC4S.Head.NoInitialize = TRUE; // the SaveGame-value, despite it's name, marks whether exact runtime data is contained // the flag must not be altered for pure rC4S.Head.SaveGame = GetSaveRuntimeData() && IsExact(); } // reset some network flags rC4S.Head.NetworkGame=0; // Title in language game was started in (not: save scenarios and net references) if (!GetKeepTitle()) SCopy(Game.ScenarioTitle.getData(), rC4S.Head.Title, C4MaxTitle); // some adjustments for everything but saved scenarios if (IsExact()) { // Store used definitions rC4S.Definitions.SetModules(Game.DefinitionFilenames,Config.General.ExePath, Config.General.DefinitionPath); // Save game parameters if(!Game.Parameters.Save(*pSaveGroup, &Game.C4S)) return false; } // clear MissionAccess in save games and records (sulai) *rC4S.Head.MissionAccess = 0; // clear shareware release for non-initial saves if (!fInitial) rC4S.Head.EnableUnregisteredAccess = FALSE; // OldGfx is no longer supported // checks for IsExact() || ExactLandscape wouldn't catch scenarios using more than 23 materials, so let's make it easy rC4S.Head.ForcedGfxMode = C4SGFXMODE_NEWGFX; // store origin if (GetSaveOrigin()) { // keep if assigned already (e.g., when doing a record of a savegame) if (!rC4S.Head.Origin.getLength()) { rC4S.Head.Origin.Copy(Game.ScenarioFilename); Config.ForceRelativePath(&rC4S.Head.Origin); } } else if (GetClearOrigin()) rC4S.Head.Origin.Clear(); // adjust specific values (virtual call) AdjustCore(rC4S); // Save scenario core return !!rC4S.Save(*pSaveGroup); } bool C4GameSave::SaveScenarioSections() { // any scenario sections? if (!Game.pScenarioSections) return true; // prepare section filename int iWildcardPos = SCharPos('*', C4CFN_ScenarioSections); char fn[_MAX_FNAME+1]; // save all modified sections for(C4ScenarioSection *pSect = Game.pScenarioSections; pSect; pSect = pSect->pNext) { // compose section filename SCopy(C4CFN_ScenarioSections, fn); SDelete(fn, 1, iWildcardPos); SInsert(fn, pSect->szName, iWildcardPos); // do not save self, because that is implied in CurrentScenarioSection and the main landscape/object data if (pSect == Game.pCurrentScenarioSection) pSaveGroup->DeleteEntry(fn); else if (pSect->fModified) { // modified section: delete current pSaveGroup->DeleteEntry(fn); // replace by new pSaveGroup->Add(pSect->szTempFilename, fn); } } // done, success return true; } bool C4GameSave::SaveLandscape() { // exact? if (Game.Landscape.Mode == C4LSC_Exact || GetForceExactLandscape()) { C4DebugRecOff DBGRECOFF; // Landscape Game.Objects.RemoveSolidMasks(); bool fSuccess; if(Game.Landscape.Mode == C4LSC_Exact) fSuccess = !!Game.Landscape.Save(*pSaveGroup); else fSuccess = !!Game.Landscape.SaveDiff(*pSaveGroup, !IsSynced()); Game.Objects.PutSolidMasks(); if (!fSuccess) return false; DBGRECOFF.Clear(); // PXS if (!Game.PXS.Save(*pSaveGroup)) return false; // MassMover (create copy, may not modify running data) C4MassMoverSet MassMoverSet; MassMoverSet.Copy(Game.MassMover); if (!MassMoverSet.Save(*pSaveGroup)) return false; // Material enumeration if (!Game.Material.SaveEnumeration(*pSaveGroup)) return false; } // static / dynamic if (Game.Landscape.Mode == C4LSC_Static) { // static map // remove old-style landscape.bmp pSaveGroup->DeleteEntry(C4CFN_Landscape); // save materials if not already done if(!GetForceExactLandscape()) { // save map if (!Game.Landscape.SaveMap(*pSaveGroup)) return FALSE; // save textures (if changed) if (!Game.Landscape.SaveTextures(*pSaveGroup)) return FALSE; } } else if (Game.Landscape.Mode != C4LSC_Exact) { // dynamic map by landscape.txt or scenario core: nothing to save // in fact, it doesn't even make much sense to save the Objects.txt // but the user pressed save after all... } return true; } bool C4GameSave::SaveRuntimeData() { // scenario sections (exact only) if (IsExact()) if (!SaveScenarioSections()) { Log(LoadResStr("IDS_ERR_SAVE_SCENSECTIONS")); return false; } // landscape if (!SaveLandscape()) { Log(LoadResStr("IDS_ERR_SAVE_LANDSCAPE")); return false; } // Strings Game.ScriptEngine.Strings.EnumStrings(); if(!Game.ScriptEngine.Strings.Save((*pSaveGroup))) { Log(LoadResStr("IDS_ERR_SAVE_SCRIPTSTRINGS")); return false; } // Objects if (!Game.Objects.Save((*pSaveGroup),IsExact(),true)) { Log(LoadResStr("IDS_ERR_SAVE_OBJECTS")); return false; } // Round results if (GetSaveUserPlayers()) if (!Game.RoundResults.Save(*pSaveGroup)) { Log(LoadResStr("IDS_ERR_ERRORSAVINGROUNDRESULTS")); return false; } // Teams if (!Game.Teams.Save(*pSaveGroup)) { Log(LoadResStr(LoadResStr("IDS_ERR_ERRORSAVINGTEAMS"))); return false; } // some scenario components possiby modified in console mode // such modifications cannot possibly be done before game start // so it's runtime data // Script if (!Game.Script.Save((*pSaveGroup))) Log(LoadResStr("IDS_ERR_SAVE_SCRIPT")); /* nofail */ // Title - unexact only, because in savegames, the title will be set in core if (!IsExact()) if (!Game.Title.Save((*pSaveGroup))) Log(LoadResStr("IDS_ERR_SAVE_TITLE")); /* nofail */ // Info if (!Game.Info.Save((*pSaveGroup))) Log(LoadResStr("IDS_ERR_SAVE_INFO")); /* nofail */ if (GetSaveUserPlayers() || GetSaveScriptPlayers()) { // player infos // the stored player info filenames will point into the scenario file, and no ressource information // will be saved. PlayerInfo must be saved first, because those will generate the storage filenames to be used by // C4PlayerList C4PlayerInfoList RestoreInfos; RestoreInfos.SetAsRestoreInfos(Game.PlayerInfos, GetSaveUserPlayers(), GetSaveScriptPlayers(), GetSaveUserPlayerFiles(), GetSaveScriptPlayerFiles()); if (!RestoreInfos.Save(*pSaveGroup, C4CFN_SavePlayerInfos)) { Log(LoadResStr("IDS_ERR_SAVE_RESTOREPLAYERINFOS")); return false; } // Players // this will save the player files to the savegame scenario group only // synchronization to the original player files will be done in global game // synchronization (via control queue) if (GetSaveUserPlayerFiles() || GetSaveScriptPlayerFiles()) { if (!Game.Players.Save((*pSaveGroup), GetCreateSmallFile(), RestoreInfos)) { Log(LoadResStr("IDS_ERR_SAVE_PLAYERS")); return false; } } } else { // non-exact runtime data: remove any exact files // No Game.txt pSaveGroup->Delete(C4CFN_Game); // No player files pSaveGroup->Delete(C4CFN_PlayerInfos); pSaveGroup->Delete(C4CFN_SavePlayerInfos); } // done, success return true; } bool C4GameSave::SaveDesc(C4Group &hToGroup) { // Unfortunately, there's no way to prealloc the buffer in an appropriate size StdStrBuf sBuffer; // Header sBuffer.AppendFormat("{\\rtf1\\ansi\\ansicpg1252\\deff0\\deflang1031{\\fonttbl {\\f0\\fnil\\fcharset%d Times New Roman;}}", GetCharsetCode(Config.General.LanguageCharset)); sBuffer.Append(LineFeed); // Scenario title sBuffer.AppendFormat("\\uc1\\pard\\ulnone\\b\\f0\\fs20 %s\\par",Game.ScenarioTitle.getData()); sBuffer.Append(LineFeed "\\b0\\fs16\\par" LineFeed); // OK; each specializations has its own desc format WriteDesc(sBuffer); // End of file sBuffer.Append(LineFeed "}" LineFeed EndOfFile); // Generate Filename StdStrBuf sFilename; char szLang[3]; SCopyUntil(Config.General.Language, szLang, ',', 2); sFilename.Format(C4CFN_ScenarioDesc,szLang); // Save to file return !!hToGroup.Add(sFilename.getData(),sBuffer,false,true); } void C4GameSave::WriteDescLineFeed(StdStrBuf &sBuf) { // paragraph end + cosmetics sBuf.Append("\\par" LineFeed); } void C4GameSave::WriteDescDate(StdStrBuf &sBuf, bool fRecord) { // write local time/date time_t tTime; time(&tTime); struct tm *pLocalTime; pLocalTime=localtime(&tTime); sBuf.AppendFormat(LoadResStr(fRecord ? "IDS_DESC_DATEREC" : (Game.Network.isEnabled() ? "IDS_DESC_DATENET" : "IDS_DESC_DATE")), pLocalTime->tm_mday, pLocalTime->tm_mon+1, pLocalTime->tm_year+1900, pLocalTime->tm_hour, pLocalTime->tm_min); WriteDescLineFeed(sBuf); } void C4GameSave::WriteDescGameTime(StdStrBuf &sBuf) { // Write game duration if (Game.Time) { sBuf.AppendFormat(LoadResStr("IDS_DESC_DURATION"), Game.Time/3600,(Game.Time%3600)/60,Game.Time%60); WriteDescLineFeed(sBuf); } } void C4GameSave::WriteDescEngine(StdStrBuf &sBuf) { char ver[5]; sprintf(ver, "%03d", (int) C4XVERBUILD); sBuf.AppendFormat(LoadResStr("IDS_DESC_VERSION"), ver); WriteDescLineFeed(sBuf); } void C4GameSave::WriteDescLeague(StdStrBuf &sBuf, bool fLeague, const char *strLeagueName) { if (fLeague) { sBuf.AppendFormat(LoadResStr("IDS_PRC_LEAGUE"), strLeagueName); WriteDescLineFeed(sBuf); } } void C4GameSave::WriteDescDefinitions(StdStrBuf &sBuf) { // Definition specs if (Game.DefinitionFilenames[0]) { char szDef[_MAX_PATH+1]; // Desc sBuf.Append(LoadResStr("IDS_DESC_DEFSPECS")); // Get definition modules for (int cnt=0; SGetModule(Game.DefinitionFilenames,cnt,szDef); cnt++) { // Get exe relative path StdStrBuf sDefFilename; sDefFilename.Copy(Config.AtExeRelativePath(szDef)); // Convert rtf backslashes sDefFilename.Replace("\\", "\\\\"); // Append comma if (cnt>0) sBuf.Append(", "); // Apend to desc sBuf.Append(sDefFilename); } // End of line WriteDescLineFeed(sBuf); } } void C4GameSave::WriteDescNetworkClients(StdStrBuf &sBuf) { // Desc sBuf.Append(LoadResStr("IDS_DESC_CLIENTS")); // Client names for (C4Network2Client *pClient=Game.Network.Clients.GetNextClient(NULL); pClient; pClient=Game.Network.Clients.GetNextClient(pClient)) { sBuf.Append(", "); sBuf.Append(pClient->getName()); } // End of line WriteDescLineFeed(sBuf); } void C4GameSave::WriteDescPlayers(StdStrBuf &sBuf, bool fByTeam, int32_t idTeam) { // write out all players; only if they match the given team if specified C4PlayerInfo *pPlr; bool fAnyPlrWritten = false; for (int i = 0; pPlr = Game.PlayerInfos.GetPlayerInfoByIndex(i); i++) if (pPlr->HasJoined() && !pPlr->IsRemoved() && !pPlr->IsInvisible()) { if (fByTeam) if (idTeam) { // match team if (pPlr->GetTeam() != idTeam) continue; } else { // must be in no known team if (Game.Teams.GetTeamByID(pPlr->GetTeam())) continue; } if (fAnyPlrWritten) sBuf.Append(", "); else if (fByTeam && idTeam) { C4Team *pTeam = Game.Teams.GetTeamByID(idTeam); if (pTeam) sBuf.AppendFormat("%s: ", pTeam->GetName()); } sBuf.Append(pPlr->GetName()); fAnyPlrWritten = true; } if (fAnyPlrWritten) WriteDescLineFeed(sBuf); } void C4GameSave::WriteDescPlayers(StdStrBuf &sBuf) { // New style using Game.PlayerInfos if (Game.PlayerInfos.GetPlayerCount()) { sBuf.Append(LoadResStr("IDS_DESC_PLRS")); if (Game.Teams.IsMultiTeams() && !Game.Teams.IsAutoGenerateTeams()) { // Teams defined: Print players sorted by teams WriteDescLineFeed(sBuf); C4Team *pTeam; int32_t i=0; while (pTeam = Game.Teams.GetTeamByIndex(i++)) { WriteDescPlayers(sBuf, true, pTeam->GetID()); } // Finally, print out players outside known teams (those can only be achieved by script using SetPlayerTeam) WriteDescPlayers(sBuf, true, 0); } else { // No teams defined: Print all players that have ever joined WriteDescPlayers(sBuf, false, 0); } } } bool C4GameSave::Save(const char *szFilename) { // close any previous Close(); // create group C4Group *pLSaveGroup = new C4Group(); if (!SaveCreateGroup(szFilename, *pLSaveGroup)) { LogF(LoadResStr("IDS_ERR_SAVE_TARGETGRP"), szFilename ? szFilename : "NULL!"); delete pLSaveGroup; return false; } // save to it return Save(*pLSaveGroup, true); } bool C4GameSave::Save(C4Group &hToGroup, bool fKeepGroup) { // close any previous Close(); // set group pSaveGroup = &hToGroup; fOwnGroup = fKeepGroup; // PreSave-actions (virtual call) if (!OnSaving()) return false; // always save core if (!SaveCore()) { Log(LoadResStr("IDS_ERR_SAVE_CORE")); return false; } // cleanup group pSaveGroup->Delete(C4CFN_PlayerFiles); // remove: Title text, image and icon if specified if (!GetKeepTitle()) { pSaveGroup->Delete(C4CFN_ScenarioTitle); pSaveGroup->Delete(C4CFN_ScenarioIcon); sprintf(OSTR,C4CFN_ScenarioDesc,"*"); pSaveGroup->Delete(OSTR); pSaveGroup->Delete(C4CFN_Titles); pSaveGroup->Delete(C4CFN_Info); } // Always save Game.txt; even for saved scenarios, because global effects need to be saved if(!Game.SaveData(*pSaveGroup, false, fInitial, IsExact())) { Log(LoadResStr("IDS_ERR_SAVE_RUNTIMEDATA")); return false; } // save additional runtime data if (GetSaveRuntimeData()) if (!SaveRuntimeData()) return false; // Desc if (GetSaveDesc()) if (!SaveDesc(*pSaveGroup)) Log(LoadResStr("IDS_ERR_SAVE_DESC")); /* nofail */ // save specialized components (virtual call) if (!SaveComponents()) return false; // done, success return true; } bool C4GameSave::Close() { bool fSuccess = true; // any group open? if (pSaveGroup) { // sort group const char *szSortOrder = GetSortOrder(); if (szSortOrder) pSaveGroup->Sort(szSortOrder); // close if owned group if (fOwnGroup) { fSuccess = !!pSaveGroup->Close(); delete pSaveGroup; fOwnGroup = false; } pSaveGroup = NULL; } return fSuccess; } // *** C4GameSaveSavegame bool C4GameSaveSavegame::OnSaving() { if (!Game.IsRunning) return true; // synchronization to sync player files on all clients // this resets playing times and stores them in the players? // but doing so would be too late when the queue is executed! // TODO: remove it? (-> PeterW ;)) if (Game.Network.isEnabled()) Game.Input.Add(CID_Synchronize, new C4ControlSynchronize(TRUE)); else Game.Players.SynchronizeLocalFiles(); // OK; save now return true; } void C4GameSaveSavegame::AdjustCore(C4Scenario &rC4S) { // Determine save game index from trailing number in group file name int iSaveGameIndex = GetTrailingNumber(GetFilenameOnly(pSaveGroup->GetFullName().getData())); // Looks like a decent index: set numbered icon if (Inside(iSaveGameIndex, 1, 10)) rC4S.Head.Icon = 2 + (iSaveGameIndex - 1); // Else: set normal script icon else rC4S.Head.Icon = 29; } bool C4GameSaveSavegame::SaveComponents() { // special for savegames: save a screenshot if (!Game.SaveGameTitle((*pSaveGroup))) Log(LoadResStr("IDS_ERR_SAVE_GAMETITLE")); /* nofail */ // done, success return true; } bool C4GameSaveSavegame::WriteDesc(StdStrBuf &sBuf) { // compose savegame desc WriteDescDate(sBuf); WriteDescGameTime(sBuf); WriteDescDefinitions(sBuf); if (Game.Network.isEnabled()) WriteDescNetworkClients(sBuf); WriteDescPlayers(sBuf); // done, success return true; } // *** C4GameSaveRecord void C4GameSaveRecord::AdjustCore(C4Scenario &rC4S) { // specific recording flags rC4S.Head.Replay=TRUE; if (!rC4S.Head.Film) rC4S.Head.Film=C4SFilm_Normal; /* default to film */ rC4S.Head.Icon=29; // unregistered replay OK rC4S.Head.EnableUnregisteredAccess = TRUE; // default record title char buf[1024 + 1]; sprintf(buf, "%03i %s [%d]", iNum, Game.ScenarioTitle.getData(), (int) C4XVERBUILD); SCopy(buf, rC4S.Head.Title, C4MaxTitle); } bool C4GameSaveRecord::SaveComponents() { // special: records need player infos even if done initially if (fInitial) Game.PlayerInfos.Save((*pSaveGroup), C4CFN_PlayerInfos); // for !fInitial, player infos will be saved as regular runtime data // done, success return true; } bool C4GameSaveRecord::WriteDesc(StdStrBuf &sBuf) { // compose record desc WriteDescDate(sBuf, true); WriteDescGameTime(sBuf); WriteDescEngine(sBuf); WriteDescDefinitions(sBuf); WriteDescLeague(sBuf, fLeague, Game.Parameters.League.getData()); if (Game.Network.isEnabled()) WriteDescNetworkClients(sBuf); WriteDescPlayers(sBuf); // done, success return true; } // *** C4GameSaveNetwork void C4GameSaveNetwork::AdjustCore(C4Scenario &rC4S) { // specific dynamic flags rC4S.Head.NetworkGame=TRUE; rC4S.Head.NetworkRuntimeJoin = !fInitial; }
d5c19adab23019150641791c2c245e8077a86e87
0ecf2d067e8fe6cdec12b79bfd68fe79ec222ffd
/ui/chromeos/search_box/search_box_view_base.h
f5c46590dfe384463c38b0eedf2b8a6f2cf020cc
[ "BSD-3-Clause" ]
permissive
yachtcaptain23/browser-android-tabs
e5144cee9141890590d6d6faeb1bdc5d58a6cbf1
a016aade8f8333c822d00d62738a922671a52b85
refs/heads/master
2021-04-28T17:07:06.955483
2018-09-26T06:22:11
2018-09-26T06:22:11
122,005,560
0
0
NOASSERTION
2019-05-17T19:37:59
2018-02-19T01:00:10
null
UTF-8
C++
false
false
7,857
h
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_CHOMEOS_SEARCH_BOX_SEARCH_BOX_VIEW_BASE_H_ #define UI_CHOMEOS_SEARCH_BOX_SEARCH_BOX_VIEW_BASE_H_ #include <vector> #include "base/macros.h" #include "base/strings/string16.h" #include "ui/chromeos/search_box/search_box_constants.h" #include "ui/chromeos/search_box/search_box_export.h" #include "ui/events/event_constants.h" #include "ui/views/controls/button/image_button.h" #include "ui/views/controls/textfield/textfield_controller.h" #include "ui/views/widget/widget_delegate.h" namespace gfx { class ImageSkia; } // namespace gfx namespace views { class BoxLayout; class ImageView; class Textfield; class View; } // namespace views namespace search_box { class SearchBoxViewDelegate; class SearchBoxBackground; class SearchBoxImageButton; // These are used in histograms, do not remove/renumber entries. If you're // adding to this enum with the intention that it will be logged, update the // SearchBoxActivationSource enum listing in tools/metrics/histograms/enums.xml. enum class ActivationSource { kMousePress = 0, kKeyPress = 1, kGestureTap = 2, kMaxValue = kGestureTap, }; // TODO(wutao): WidgetDelegateView owns itself and cannot be deleted from the // views hierarchy automatically. Make SearchBoxViewBase a subclass of View // instead of WidgetDelegateView. // SearchBoxViewBase consists of icons and a Textfield. The Textfiled is for // inputting queries and triggering callbacks. The icons include a search icon, // a close icon and a back icon for different functionalities. This class // provides common functions for the search box view across Chrome OS. class SEARCH_BOX_EXPORT SearchBoxViewBase : public views::WidgetDelegateView, public views::TextfieldController, public views::ButtonListener { public: explicit SearchBoxViewBase(SearchBoxViewDelegate* delegate); ~SearchBoxViewBase() override; void Init(); bool HasSearch() const; // Returns the bounds to use for the view (including the shadow) given the // desired bounds of the search box contents. gfx::Rect GetViewBoundsForSearchBoxContentsBounds( const gfx::Rect& rect) const; views::ImageButton* back_button(); views::ImageButton* close_button(); views::Textfield* search_box() { return search_box_; } void set_contents_view(views::View* contents_view) { contents_view_ = contents_view; } // Swaps the google icon with the back button. void ShowBackOrGoogleIcon(bool show_back_button); // Setting the search box active left aligns the placeholder text, changes // the color of the placeholder text, and enables cursor blink. Setting the // search box inactive center aligns the placeholder text, sets the color, and // disables cursor blink. void SetSearchBoxActive(bool active, ui::EventType event_type); // Handles Gesture and Mouse Events sent from |search_box_|. bool OnTextfieldEvent(ui::EventType type); // Overridden from views::View: gfx::Size CalculatePreferredSize() const override; bool OnMouseWheel(const ui::MouseWheelEvent& event) override; void OnEnabledChanged() override; const char* GetClassName() const override; void OnGestureEvent(ui::GestureEvent* event) override; void OnMouseEvent(ui::MouseEvent* event) override; // Overridden from views::WidgetDelegate: ax::mojom::Role GetAccessibleWindowRole() const override; bool ShouldAdvanceFocusToTopLevelWidget() const override; // Overridden from views::ButtonListener: void ButtonPressed(views::Button* sender, const ui::Event& event) override; // Called when tablet mode starts and ends. void OnTabletModeChanged(bool started); // Used only in the tests to get the current search icon. views::ImageView* get_search_icon_for_test() { return search_icon_; } // Whether the search box is active. bool is_search_box_active() const { return is_search_box_active_; } void OnOnSearchBoxFocusedChanged(); // Whether the trimmed query in the search box is empty. bool IsSearchBoxTrimmedQueryEmpty() const; virtual void ClearSearch(); // Returns selected view in contents view. virtual views::View* GetSelectedViewInContentsView(); protected: // Fires query change notification. void NotifyQueryChanged(); // Nofifies the active status change. void NotifyActiveChanged(); // Sets the background color. void SetBackgroundColor(SkColor light_vibrant); SkColor background_color() const { return background_color_; } // Sets the search box color. void SetSearchBoxColor(SkColor color); SkColor search_box_color() const { return search_box_color_; } // Updates the visibility of close button. void UpdateCloseButtonVisisbility(); // Overridden from views::TextfieldController: void ContentsChanged(views::Textfield* sender, const base::string16& new_contents) override; bool HandleMouseEvent(views::Textfield* sender, const ui::MouseEvent& mouse_event) override; bool HandleGestureEvent(views::Textfield* sender, const ui::GestureEvent& gesture_event) override; views::BoxLayout* box_layout() { return box_layout_; } views::View* contents_view() { return contents_view_; } void set_is_tablet_mode(bool is_tablet_mode) { is_tablet_mode_ = is_tablet_mode; } bool is_tablet_mode() const { return is_tablet_mode_; } void SetSearchBoxBackgroundCornerRadius(int corner_radius); void SetSearchBoxBackgroundColor(SkColor color); void SetSearchIconImage(gfx::ImageSkia image); // Detects |ET_MOUSE_PRESSED| and |ET_GESTURE_TAP| events on the white // background of the search box. virtual void HandleSearchBoxEvent(ui::LocatedEvent* located_event); // Updates the search box's background color. virtual void UpdateBackgroundColor(SkColor color); private: virtual void ModelChanged() = 0; // Shows/hides the virtual keyboard if the search box is active. virtual void UpdateKeyboardVisibility() = 0; // Updates model text and selection model with current Textfield info. virtual void UpdateModel(bool initiated_by_user) = 0; // Updates the search icon. virtual void UpdateSearchIcon() = 0; // Update search box border based on whether the search box is activated. virtual void UpdateSearchBoxBorder() = 0; // Setup button's image, accessible name, and tooltip text etc. virtual void SetupCloseButton() = 0; virtual void SetupBackButton() = 0; // Records in histograms the activation of the searchbox. virtual void RecordSearchBoxActivationHistogram(ui::EventType event_type){}; // Gets the search box background. SearchBoxBackground* GetSearchBoxBackground() const; SearchBoxViewDelegate* delegate_; // Not owned. // Owned by views hierarchy. views::View* content_container_; views::ImageView* search_icon_ = nullptr; SearchBoxImageButton* back_button_ = nullptr; SearchBoxImageButton* close_button_ = nullptr; views::Textfield* search_box_; views::View* search_box_right_space_ = nullptr; views::View* contents_view_ = nullptr; // Owned by |content_container_|. It is deleted when the view is deleted. views::BoxLayout* box_layout_ = nullptr; // Whether the search box is active. bool is_search_box_active_ = false; // Whether tablet mode is active. bool is_tablet_mode_ = false; // The current background color. SkColor background_color_ = kSearchBoxBackgroundDefault; // The current search box color. SkColor search_box_color_ = kDefaultSearchboxColor; DISALLOW_COPY_AND_ASSIGN(SearchBoxViewBase); }; } // namespace search_box #endif // UI_CHOMEOS_SEARCH_BOX_SEARCH_BOX_VIEW_BASE_H_
fece2a411b5396df168071d48eca33aed5dac58d
6fa810261806889b7bf04414fcec2b21b68c6453
/matth_test/Window.cpp
c4092ba80ef41c92b7357a1d5234fbebc7f33296
[]
no_license
mvancompernolle/MatthLib
5d0f86643a4e5e8c839df48c807b0091f9c848e4
d757d1c7149927bf88a9664194ed7c1d132e7363
refs/heads/master
2021-01-10T06:53:05.906495
2016-03-28T02:31:08
2016-03-28T02:31:08
49,996,091
0
0
null
null
null
null
UTF-8
C++
false
false
454
cpp
#include "Window.h" #include "sfwdraw.h" bool Window::initialize( unsigned width, unsigned height, const char* title ) { if ( initialized ) return true; this->width = width; this->height = height; initialized = sfw::initContext( width, height, title ); return initialized; } bool Window::update() { INIT_ASSERT( Window ); return sfw::stepContext(); } void Window::terminate() { INIT_ASSERT( Window ); sfw::termContext(); initialized = false; }
080593cf35076742a10906ebf2bed0c317d1d550
fc2ffcfbe2e06fa408cd9c806da7c9332e9fef36
/gui/dict/dictionarydialog.cpp
49b22283cc1ad2db4b947f1d4d5dab438dd404cd
[ "MIT" ]
permissive
matoom/frostbite
01b3a60b0405ffd1884d859d2f7f1f454affaff8
57fe74b493615ecac08527c2e922008714e3da8d
refs/heads/master
2023-02-08T19:52:01.410524
2023-02-05T19:40:33
2023-02-05T19:40:33
4,841,550
27
20
null
2023-02-05T20:34:28
2012-06-30T10:00:54
C++
UTF-8
C++
false
false
5,622
cpp
#include "dictionarydialog.h" #include <QPushButton> #include <QGridLayout> #include <QLineEdit> #include <QLabel> #include <QGroupBox> #include <QVBoxLayout> #include <QRadioButton> #include <algorithm> #include "mainwindow.h" #include "dictionaryservice.h" #include "dictionarysettings.h" namespace { struct FindModifier { FindModifier(const Qt::KeyboardModifier mod) : modifier(mod) {} bool operator()(const DictionaryDialog::ButtonPair& pair) { return pair.first == modifier; } Qt::KeyboardModifier modifier; }; } // anonymous DictionaryDialog::DictionaryDialog(QWidget *parent) : QDialog(parent), settings(DictionarySettings::getInstance()) { mainWindow = (MainWindow*)qobject_cast<QObject *>(parent); setWindowTitle(tr("Dictionary settings")); QPushButton *okButton = new QPushButton(tr("Ok"), this); QPushButton *cancelButton = new QPushButton(tr("Cancel"), this); connect(okButton, SIGNAL(clicked()), this, SLOT(okPressed())); connect(cancelButton, SIGNAL(clicked()), this, SLOT(cancelPressed())); dictNameEdit = new QLineEdit("", this); dictArgumentsEdit = new QLineEdit("", this); outputOptionsBox = new QGroupBox(tr("Dictionary output type"), this); noOutputBtn = new QRadioButton(tr("Disabled"), outputOptionsBox); dictionaryWinBtn = new QRadioButton(tr("Dictionary window (double click on a word)"), outputOptionsBox); toolTipBtn = new QRadioButton(tr("Tooltip (mouse over a word)"), outputOptionsBox); connect(noOutputBtn, &QRadioButton::toggled, this, &DictionaryDialog::onToggled); connect(dictionaryWinBtn, &QRadioButton::toggled, this, &DictionaryDialog::onToggled); connect(toolTipBtn, &QRadioButton::toggled, this, &DictionaryDialog::onToggled); QVBoxLayout *vbox = new QVBoxLayout(this); vbox->addWidget(noOutputBtn); vbox->addWidget(dictionaryWinBtn); vbox->addWidget(toolTipBtn); vbox->addStretch(1); outputOptionsBox->setLayout(vbox); hotkeyOptionsBox = new QGroupBox(tr("Double-click modifiers"), this); vbox = new QVBoxLayout(this); dblClkButtons.push_back(std::make_pair(Qt::NoModifier, new QRadioButton(tr("Double click")))); dblClkButtons.push_back(std::make_pair(Qt::AltModifier, new QRadioButton(tr("Alt + Double click")))); dblClkButtons.push_back(std::make_pair(Qt::ControlModifier, new QRadioButton(tr("Ctrl + Double click")))); dblClkButtons.push_back(std::make_pair(Qt::ShiftModifier, new QRadioButton(tr("Shift + Double click")))); for (size_t i = 0; i < dblClkButtons.size(); ++ i) { vbox->addWidget(dblClkButtons[i].second); } vbox->addStretch(1); hotkeyOptionsBox->setLayout(vbox); dblClkButtons[0].second->setChecked(true); loadSettings(); QGridLayout *mainLayout = new QGridLayout(this); mainLayout->addWidget(new QLabel(tr("Dictionary program name:")), 0, 0); mainLayout->addWidget(dictNameEdit, 0, 1, 1, 3); mainLayout->addWidget(new QLabel(tr("Command line arguments:")), 1, 0); mainLayout->addWidget(dictArgumentsEdit, 1, 1, 1, 3); mainLayout->addWidget(outputOptionsBox, 2, 0, 1, 4); mainLayout->addWidget(hotkeyOptionsBox, 3, 0, 1, 4); mainLayout->addWidget(okButton, 4, 2); mainLayout->addWidget(cancelButton, 4, 3); } DictionaryDialog::~DictionaryDialog() { } void DictionaryDialog::okPressed() { this->saveSettings(); this->loadSettings(); mainWindow->getDictionaryService()->updateConnections(); this->accept(); } void DictionaryDialog::cancelPressed() { this->loadSettings(); this->reject(); } void DictionaryDialog::loadSettings() { dictNameEdit->setText(settings->getDictCommand()); dictArgumentsEdit->setText(settings->getDictArguments()); auto outType = settings->getDictOutputType(); // Enable hotkey selection only when output type is a Dictionary Window hotkeyOptionsBox->setEnabled(outType == DictionarySettings::OutputType::Window); // Select appropriate radio button switch (outType) { case DictionarySettings::OutputType::Disabled: noOutputBtn->setChecked(true); break; case DictionarySettings::OutputType::Window: dictionaryWinBtn->setChecked(true); break; case DictionarySettings::OutputType::Tooltip: toolTipBtn->setChecked(true); } ButtonVector::iterator found = std::find_if(dblClkButtons.begin(), dblClkButtons.end(), FindModifier(settings->getDoubleClickModifier())); if (found != dblClkButtons.end()) { found->second->setChecked(true); } } void DictionaryDialog::saveSettings() { Qt::KeyboardModifier modifier = Qt::NoModifier; for (size_t i = 0; i < dblClkButtons.size(); ++ i) { if (dblClkButtons[i].second->isChecked()) { modifier = dblClkButtons[i].first; } } DictionarySettings::OutputType output { DictionarySettings::OutputType::Disabled }; if (dictionaryWinBtn->isChecked()) output = DictionarySettings::OutputType::Window; else if (toolTipBtn->isChecked()) output = DictionarySettings::OutputType::Tooltip; settings->setDictCommand(dictNameEdit->text()) .setDictArguments(dictArgumentsEdit->text()) .setDictOutputType(output) .setDoubleClickModifier(modifier); } void DictionaryDialog::onToggled(bool checked) { if (checked) { QRadioButton* btn = static_cast<QRadioButton*>(sender()); hotkeyOptionsBox->setEnabled(btn == dictionaryWinBtn); } }
6d3c3cea5a088e9066beb62ba14824dcfda89a47
065c193fa4ee0b7e54abed5b8cc3748a92d0b298
/src/include/lem/solarix/action_steps.h
f25248706aea95de8fe3907133495fbed1262aa3
[ "MIT" ]
permissive
olegtarasov/GrammarEngine
f3bb08101fdd55016553e454d4e11e20a226fc2a
5de66a442e371268fce3dbaa57d518c9b9cb28a2
refs/heads/oleg_tarasov
2023-07-18T00:54:34.336097
2021-08-25T09:34:34
2021-08-25T09:34:34
116,387,386
0
0
MIT
2019-04-14T09:55:05
2018-01-05T13:22:39
C++
UTF-8
C++
false
false
9,491
h
#ifndef ACTION_STEPS__H #define ACTION_STEPS__H #pragma once #include <lem/solarix/tree_node.h> namespace Solarix { class AS_Group : public PM_ActionStep { private: CloneCollect<PM_ActionStep> list; public: AS_Group(void); AS_Group( const AS_Group &x ); virtual void operator=( const PM_ActionStep &x ); #if defined SOL_LOADTXT virtual void LoadTxt( CompilationContext &context, Macro_Parser &txtfile, Dictionary &dict ); #endif #if defined SOL_LOADBIN virtual void LoadBin( lem::Stream &bin ); virtual void Link( const TrFunctions &funs ); #endif #if defined SOL_SAVEBIN virtual void SaveBin( lem::Stream &bin ) const; #endif virtual Res_Pack* Build( Dictionary *dict #if defined SOL_CAA , bool do_deep_copy , const PM_Input &input , const PM_Yield &yield , const PM_SuperIndex *CONFIG=NULL #endif ) const; #if defined SOL_LOADTXT virtual void Optimize( SynGram &sg ); #endif virtual bool CanPrebuilt(void) const; #if defined SOL_SAVETXT virtual void SaveTxt( OFormatter &txt, const Dictionary &dict ) const; #endif virtual PM_ActionStep* clone() const; virtual bool DoesContainReferences() const; virtual void GetRefNames( IntCollect &refnames ) const; virtual int GetMaxContextLen(void) const; }; class AS_Or : public PM_ActionStep { private: lem::CloneCollect<PM_ActionStep> list; public: AS_Or(void); AS_Or( const AS_Or &x ); virtual void operator=( const PM_ActionStep &x ); #if defined SOL_LOADTXT virtual void LoadTxt( CompilationContext &context, Macro_Parser &txtfile, Dictionary &dict ); #endif #if defined SOL_LOADBIN virtual void LoadBin( lem::Stream &bin ); virtual void Link( const TrFunctions &funs ); #endif #if defined SOL_SAVEBIN virtual void SaveBin( lem::Stream &bin ) const; #endif virtual Res_Pack* Build( Dictionary *dict #if defined SOL_CAA , bool do_deep_copy , const PM_Input &input , const PM_Yield &yield , const PM_SuperIndex *CONFIG=NULL #endif ) const; #if defined SOL_LOADTXT virtual void Optimize( SynGram &sg ); #endif virtual bool CanPrebuilt(void) const; #if defined SOL_SAVETXT virtual void SaveTxt( OFormatter &txt, const Dictionary &dict ) const; #endif virtual PM_ActionStep* clone() const; virtual bool DoesContainReferences() const; virtual void GetRefNames( IntCollect &refnames ) const; virtual int GetMaxContextLen(void) const; }; class AS_Oscil : public PM_ActionStep { private: PM_ActionStep* item; public: AS_Oscil(void); AS_Oscil( const AS_Oscil &x ); virtual void operator=( const PM_ActionStep &x ); virtual ~AS_Oscil(void); #if defined SOL_LOADTXT virtual void LoadTxt( CompilationContext &context, Macro_Parser &txtfile, Dictionary &dict ); #endif #if defined SOL_LOADBIN virtual void LoadBin( lem::Stream &bin ); virtual void Link( const TrFunctions &funs ); #endif #if defined SOL_SAVEBIN virtual void SaveBin( lem::Stream &bin ) const; #endif virtual Res_Pack* Build( Dictionary *dict #if defined SOL_CAA , bool do_deep_copy , const PM_Input &input , const PM_Yield &yield , const PM_SuperIndex *CONFIG=NULL #endif ) const; #if defined SOL_LOADTXT virtual void Optimize( SynGram &sg ); #endif virtual bool CanPrebuilt(void) const; #if defined SOL_SAVETXT virtual void SaveTxt( OFormatter &txt, const Dictionary &dict ) const; #endif virtual PM_ActionStep* clone() const; virtual bool DoesContainReferences() const; virtual void GetRefNames( IntCollect &refnames ) const; virtual int GetMaxContextLen(void) const; }; class AS_Word : public PM_ActionStep { private: PlainArgumentList word; public: AS_Word(void); AS_Word( const AS_Word &x ); virtual void operator=( const PM_ActionStep &x ); virtual int GetMaxContextLen(void) const; #if defined SOL_LOADTXT virtual void LoadTxt( CompilationContext &context, Macro_Parser &txtfile, Dictionary &dict ); #endif #if defined SOL_LOADBIN virtual void LoadBin( lem::Stream &bin ); virtual void Link( const TrFunctions &funs ); #endif #if defined SOL_SAVEBIN virtual void SaveBin( lem::Stream &bin ) const; #endif virtual Res_Pack* Build( Dictionary *dict #if defined SOL_CAA , bool do_deep_copy , const PM_Input &input , const PM_Yield &yield , const PM_SuperIndex *CONFIG=NULL #endif ) const; #if defined SOL_LOADTXT virtual void Optimize( SynGram &sg ); #endif virtual bool CanPrebuilt(void) const; #if defined SOL_SAVETXT virtual void SaveTxt( OFormatter &txt, const Dictionary &dict ) const; #endif virtual PM_ActionStep* clone() const; virtual bool DoesContainReferences() const; virtual void GetRefNames( IntCollect &refnames ) const; }; class AS_Chain : public PM_ActionStep { private: PM_ActionStep *item; public: AS_Chain(void); AS_Chain( const AS_Chain &x ); virtual void operator=( const PM_ActionStep &x ); virtual ~AS_Chain(void); #if defined SOL_LOADTXT virtual void LoadTxt( CompilationContext &context, Macro_Parser &txtfile, Dictionary &dict ); #endif #if defined SOL_LOADBIN virtual void LoadBin( lem::Stream &bin ); virtual void Link( const TrFunctions &funs ); #endif #if defined SOL_SAVEBIN virtual void SaveBin( lem::Stream &bin ) const; #endif virtual Res_Pack* Build( Dictionary *dict #if defined SOL_CAA , bool do_deep_copy , const PM_Input &input , const PM_Yield &yield , const PM_SuperIndex *CONFIG=NULL #endif ) const; #if defined SOL_LOADTXT virtual void Optimize( SynGram &sg ); #endif virtual bool CanPrebuilt(void) const; #if defined SOL_SAVETXT virtual void SaveTxt( OFormatter &txt, const Dictionary &dict ) const; #endif virtual PM_ActionStep* clone() const; virtual bool DoesContainReferences() const; virtual void GetRefNames( IntCollect &refnames ) const; virtual int GetMaxContextLen(void) const; }; class PA_PredicateMaker; class AS_Predicate : public PM_ActionStep { private: PA_PredicateMaker *pred; UCString base_name; public: AS_Predicate(void); AS_Predicate( const AS_Predicate &x ); virtual ~AS_Predicate(void); virtual void operator=( const PM_ActionStep &x ); #if defined SOL_LOADTXT virtual void LoadTxt( CompilationContext &context, Macro_Parser &txtfile, Dictionary &dict ); #endif #if defined SOL_LOADBIN virtual void LoadBin( lem::Stream &bin ); virtual void Link( const TrFunctions &funs ); #endif #if defined SOL_SAVEBIN virtual void SaveBin( lem::Stream &bin ) const; #endif virtual Res_Pack* Build( Dictionary *dict #if defined SOL_CAA , bool do_deep_copy , const PM_Input &input , const PM_Yield &yield , const PM_SuperIndex *CONFIG=NULL #endif ) const; #if defined SOL_LOADTXT virtual void Optimize( SynGram &sg ); #endif virtual bool CanPrebuilt(void) const; #if defined SOL_SAVETXT virtual void SaveTxt( OFormatter &txt, const Dictionary &dict ) const; #endif virtual PM_ActionStep* clone(void) const; virtual bool DoesContainReferences(void) const; virtual void GetRefNames( IntCollect &refnames ) const; }; } #endif
0463234373060e294c6b9d68b2fa56d6f856c917
236ab5dddddef525220fdf10b1f15361ecb04f20
/cp04/ex02/TacticalMarine.cpp
5f9608391babd88a0ae75910b9f69e566714652e
[]
no_license
YatchiYa/cppModules
bb6fef53b1d946fee58d4beb77241b1341adcb8e
7bcb920be8be851db8a00e2763ca8f5f1cfaf4e6
refs/heads/master
2021-05-20T01:10:05.768925
2020-10-05T14:11:40
2020-10-05T14:11:40
252,122,078
1
0
null
null
null
null
UTF-8
C++
false
false
889
cpp
#include "TacticalMarine.hpp" TacticalMarine::TacticalMarine() { std::cout << "Tactical Marine ready for battle" << std::endl; } TacticalMarine::TacticalMarine(TacticalMarine const &other) { (void)other; std::cout << "Tactical Marine ready for battle" << std::endl; } TacticalMarine::~TacticalMarine() { std::cout << "Aaargh ..." << std::endl; } TacticalMarine &TacticalMarine::operator=(TacticalMarine const &other) { (void)other; return (*this); } ISpaceMarine *TacticalMarine::clone(void) const { TacticalMarine *cpy = new TacticalMarine(*this); return (cpy); } void TacticalMarine::battleCry(void) const { std::cout << "For the holy PLOT !" << std::endl; } void TacticalMarine::rangedAttack(void) const { std::cout << "* attacks with bolter *" << std::endl; } void TacticalMarine::meleeAttack(void) const { std::cout << "* attacks with chainsword *" << std::endl; }
cf3bae0f0f71f0421c93ef4f10aaf9abc1830f5e
c2747e220e4dd523ee82cec3b6252bfe0a00b1f4
/gr_common/mbed-gr-libs/components/esp32-driver/ESP32Stack.h
0bc29a0267872fd7b8de1e342c5b24805df9fe4b
[]
no_license
GadgetRenesas/lychee_mbed_style
cd0a57448b74538d94aa0e8abaee41e42e517b65
10a00e14aba7269ff05fcca4bd7d5a1d76bd797e
refs/heads/master
2021-05-02T14:32:31.214560
2018-02-08T06:51:30
2018-02-08T06:51:30
120,721,216
0
0
null
null
null
null
UTF-8
C++
false
false
6,090
h
/* ESP32 implementation of NetworkInterfaceAPI * Copyright (c) 2015 ARM Limited * Copyright (c) 2017 Renesas Electronics 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. */ #ifndef ESP32_STACK_H #define ESP32_STACK_H #include "mbed.h" #include "ESP32.h" /** ESP32Stack class * Implementation of the NetworkStack for the ESP32 */ class ESP32Stack : public NetworkStack { protected: /** ESP32Stack lifetime * @param tx TX pin * @param rx RX pin * @param debug Enable debugging * @param rts RTS pin * @param cts CTS pin * @param baudrate The baudrate of the serial port. */ ESP32Stack(PinName en, PinName io0, PinName tx, PinName rx, bool debug, PinName rts, PinName cts, int baudrate); protected: /** Open a socket * @param handle Handle in which to store new socket * @param proto Type of socket to open, NSAPI_TCP or NSAPI_UDP * @return 0 on success, negative on failure */ virtual int socket_open(void **handle, nsapi_protocol_t proto); /** Close the socket * @param handle Socket handle * @return 0 on success, negative on failure * @note On failure, any memory associated with the socket must still * be cleaned up */ virtual int socket_close(void *handle); /** Bind a server socket to a specific port * @param handle Socket handle * @param address Local address to listen for incoming connections on * @return 0 on success, negative on failure. */ virtual int socket_bind(void *handle, const SocketAddress &address); /** Start listening for incoming connections * @param handle Socket handle * @param backlog Number of pending connections that can be queued up at any * one time [Default: 1] * @return 0 on success, negative on failure */ virtual int socket_listen(void *handle, int backlog); /** Connects this TCP socket to the server * @param handle Socket handle * @param address SocketAddress to connect to * @return 0 on success, negative on failure */ virtual int socket_connect(void *handle, const SocketAddress &address); /** Accept a new connection. * @param handle Handle in which to store new socket * @param server Socket handle to server to accept from * @return 0 on success, negative on failure * @note This call is not-blocking, if this call would block, must * immediately return NSAPI_ERROR_WOULD_WAIT */ virtual int socket_accept(void *handle, void **socket, SocketAddress *address); /** Send data to the remote host * @param handle Socket handle * @param data The buffer to send to the host * @param size The length of the buffer to send * @return Number of written bytes on success, negative on failure * @note This call is not-blocking, if this call would block, must * immediately return NSAPI_ERROR_WOULD_WAIT */ virtual int socket_send(void *handle, const void *data, unsigned size); /** Receive data from the remote host * @param handle Socket handle * @param data The buffer in which to store the data received from the host * @param size The maximum length of the buffer * @return Number of received bytes on success, negative on failure * @note This call is not-blocking, if this call would block, must * immediately return NSAPI_ERROR_WOULD_WAIT */ virtual int socket_recv(void *handle, void *data, unsigned size); /** Send a packet to a remote endpoint * @param handle Socket handle * @param address The remote SocketAddress * @param data The packet to be sent * @param size The length of the packet to be sent * @return The number of written bytes on success, negative on failure * @note This call is not-blocking, if this call would block, must * immediately return NSAPI_ERROR_WOULD_WAIT */ virtual int socket_sendto(void *handle, const SocketAddress &address, const void *data, unsigned size); /** Receive a packet from a remote endpoint * @param handle Socket handle * @param address Destination for the remote SocketAddress or null * @param buffer The buffer for storing the incoming packet data * If a packet is too long to fit in the supplied buffer, * excess bytes are discarded * @param size The length of the buffer * @return The number of received bytes on success, negative on failure * @note This call is not-blocking, if this call would block, must * immediately return NSAPI_ERROR_WOULD_WAIT */ virtual int socket_recvfrom(void *handle, SocketAddress *address, void *buffer, unsigned size); /** Register a callback on state change of the socket * @param handle Socket handle * @param callback Function to call on state change * @param data Argument to pass to callback * @note Callback may be called in an interrupt context. */ virtual void socket_attach(void *handle, void (*callback)(void *), void *data); protected: ESP32 *_esp; }; #endif
d8871246b9b92f7cf0ba90108b98d7a209f9a8a4
a754da405bc3d2d2d1d8940d7d277c63bf2b7768
/3party/boost/boost/intrusive/unordered_set_hook.hpp
a7ef2833193009be3ff0129a8330d85cb55c7a2d
[ "BSL-1.0", "Apache-2.0" ]
permissive
icyleaf/omim
3a5a4f07890e6ad0155447ed39563a710178ec35
a1a299eb341603337bf4a22b92518d9575498c97
refs/heads/master
2020-12-28T22:53:52.624975
2015-10-09T16:30:46
2015-10-09T16:30:46
43,995,093
0
0
Apache-2.0
2019-12-12T03:19:59
2015-10-10T05:08:38
C++
UTF-8
C++
false
false
15,855
hpp
///////////////////////////////////////////////////////////////////////////// // // (C) Copyright Olaf Krzikalla 2004-2006. // (C) Copyright Ion Gaztanaga 2006-2013 // // 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/intrusive for documentation. // ///////////////////////////////////////////////////////////////////////////// #ifndef BOOST_INTRUSIVE_UNORDERED_SET_HOOK_HPP #define BOOST_INTRUSIVE_UNORDERED_SET_HOOK_HPP #include <boost/intrusive/detail/config_begin.hpp> #include <boost/intrusive/intrusive_fwd.hpp> #include <boost/intrusive/detail/utilities.hpp> #include <boost/intrusive/pointer_traits.hpp> #include <boost/intrusive/slist_hook.hpp> #include <boost/intrusive/options.hpp> #include <boost/intrusive/detail/generic_hook.hpp> namespace boost { namespace intrusive { /// @cond template<class VoidPointer, bool StoreHash, bool OptimizeMultiKey> struct unordered_node : public slist_node<VoidPointer> { typedef typename pointer_traits <VoidPointer>::template rebind_pointer < unordered_node<VoidPointer, StoreHash, OptimizeMultiKey> >::type node_ptr; node_ptr prev_in_group_; std::size_t hash_; }; template<class VoidPointer> struct unordered_node<VoidPointer, false, true> : public slist_node<VoidPointer> { typedef typename pointer_traits <VoidPointer>::template rebind_pointer < unordered_node<VoidPointer, false, true> >::type node_ptr; node_ptr prev_in_group_; }; template<class VoidPointer> struct unordered_node<VoidPointer, true, false> : public slist_node<VoidPointer> { typedef typename pointer_traits <VoidPointer>::template rebind_pointer < unordered_node<VoidPointer, true, false> >::type node_ptr; std::size_t hash_; }; template<class VoidPointer, bool StoreHash, bool OptimizeMultiKey> struct unordered_node_traits : public slist_node_traits<VoidPointer> { typedef slist_node_traits<VoidPointer> reduced_slist_node_traits; typedef unordered_node<VoidPointer, StoreHash, OptimizeMultiKey> node; typedef typename pointer_traits <VoidPointer>::template rebind_pointer < node >::type node_ptr; typedef typename pointer_traits <VoidPointer>::template rebind_pointer < const node >::type const_node_ptr; static const bool store_hash = StoreHash; static const bool optimize_multikey = OptimizeMultiKey; static node_ptr get_next(const const_node_ptr & n) { return pointer_traits<node_ptr>::static_cast_from(n->next_); } static void set_next(const node_ptr & n, const node_ptr & next) { n->next_ = next; } static node_ptr get_prev_in_group(const const_node_ptr & n) { return n->prev_in_group_; } static void set_prev_in_group(const node_ptr & n, const node_ptr & prev) { n->prev_in_group_ = prev; } static std::size_t get_hash(const const_node_ptr & n) { return n->hash_; } static void set_hash(const node_ptr & n, std::size_t h) { n->hash_ = h; } }; template<class NodeTraits> struct unordered_group_adapter { typedef typename NodeTraits::node node; typedef typename NodeTraits::node_ptr node_ptr; typedef typename NodeTraits::const_node_ptr const_node_ptr; static node_ptr get_next(const const_node_ptr & n) { return NodeTraits::get_prev_in_group(n); } static void set_next(const node_ptr & n, const node_ptr & next) { NodeTraits::set_prev_in_group(n, next); } }; template<class NodeTraits> struct unordered_algorithms : public circular_slist_algorithms<NodeTraits> { typedef circular_slist_algorithms<NodeTraits> base_type; typedef unordered_group_adapter<NodeTraits> group_traits; typedef circular_slist_algorithms<group_traits> group_algorithms; typedef NodeTraits node_traits; typedef typename NodeTraits::node node; typedef typename NodeTraits::node_ptr node_ptr; typedef typename NodeTraits::const_node_ptr const_node_ptr; static void init(typename base_type::node_ptr n) { base_type::init(n); group_algorithms::init(n); } static void init_header(typename base_type::node_ptr n) { base_type::init_header(n); group_algorithms::init_header(n); } static void unlink(typename base_type::node_ptr n) { base_type::unlink(n); group_algorithms::unlink(n); } }; template<class VoidPointer, bool StoreHash, bool OptimizeMultiKey> struct get_uset_node_algo { typedef typename detail::if_c < (StoreHash || OptimizeMultiKey) , unordered_node_traits<VoidPointer, StoreHash, OptimizeMultiKey> , slist_node_traits<VoidPointer> >::type node_traits_type; typedef typename detail::if_c < OptimizeMultiKey , unordered_algorithms<node_traits_type> , circular_slist_algorithms<node_traits_type> >::type type; }; /// @endcond //! Helper metafunction to define a \c unordered_set_base_hook that yields to the same //! type when the same options (either explicitly or implicitly) are used. #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) || defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) template<class ...Options> #else template<class O1 = void, class O2 = void, class O3 = void, class O4 = void> #endif struct make_unordered_set_base_hook { /// @cond typedef typename pack_options < hook_defaults, #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) O1, O2, O3, O4 #else Options... #endif >::type packed_options; typedef generic_hook < get_uset_node_algo<typename packed_options::void_pointer , packed_options::store_hash , packed_options::optimize_multikey > , typename packed_options::tag , packed_options::link_mode , HashBaseHookId > implementation_defined; /// @endcond typedef implementation_defined type; }; //! Derive a class from unordered_set_base_hook in order to store objects in //! in an unordered_set/unordered_multi_set. unordered_set_base_hook holds the data necessary to maintain //! the unordered_set/unordered_multi_set and provides an appropriate value_traits class for unordered_set/unordered_multi_set. //! //! The hook admits the following options: \c tag<>, \c void_pointer<>, //! \c link_mode<>, \c store_hash<> and \c optimize_multikey<>. //! //! \c tag<> defines a tag to identify the node. //! The same tag value can be used in different classes, but if a class is //! derived from more than one \c list_base_hook, then each \c list_base_hook needs its //! unique tag. //! //! \c void_pointer<> is the pointer type that will be used internally in the hook //! and the container configured to use this hook. //! //! \c link_mode<> will specify the linking mode of the hook (\c normal_link, //! \c auto_unlink or \c safe_link). //! //! \c store_hash<> will tell the hook to store the hash of the value //! to speed up rehashings. //! //! \c optimize_multikey<> will tell the hook to store a link to form a group //! with other value with the same value to speed up searches and insertions //! in unordered_multisets with a great number of with equivalent keys. #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) || defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) template<class ...Options> #else template<class O1, class O2, class O3, class O4> #endif class unordered_set_base_hook : public make_unordered_set_base_hook< #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) O1, O2, O3, O4 #else Options... #endif >::type { #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) public: //! <b>Effects</b>: If link_mode is \c auto_unlink or \c safe_link //! initializes the node to an unlinked state. //! //! <b>Throws</b>: Nothing. unordered_set_base_hook(); //! <b>Effects</b>: If link_mode is \c auto_unlink or \c safe_link //! initializes the node to an unlinked state. The argument is ignored. //! //! <b>Throws</b>: Nothing. //! //! <b>Rationale</b>: Providing a copy-constructor //! makes classes using the hook STL-compliant without forcing the //! user to do some additional work. \c swap can be used to emulate //! move-semantics. unordered_set_base_hook(const unordered_set_base_hook& ); //! <b>Effects</b>: Empty function. The argument is ignored. //! //! <b>Throws</b>: Nothing. //! //! <b>Rationale</b>: Providing an assignment operator //! makes classes using the hook STL-compliant without forcing the //! user to do some additional work. \c swap can be used to emulate //! move-semantics. unordered_set_base_hook& operator=(const unordered_set_base_hook& ); //! <b>Effects</b>: If link_mode is \c normal_link, the destructor does //! nothing (ie. no code is generated). If link_mode is \c safe_link and the //! object is stored in an unordered_set an assertion is raised. If link_mode is //! \c auto_unlink and \c is_linked() is true, the node is unlinked. //! //! <b>Throws</b>: Nothing. ~unordered_set_base_hook(); //! <b>Effects</b>: Swapping two nodes swaps the position of the elements //! related to those nodes in one or two containers. That is, if the node //! this is part of the element e1, the node x is part of the element e2 //! and both elements are included in the containers s1 and s2, then after //! the swap-operation e1 is in s2 at the position of e2 and e2 is in s1 //! at the position of e1. If one element is not in a container, then //! after the swap-operation the other element is not in a container. //! Iterators to e1 and e2 related to those nodes are invalidated. //! //! <b>Complexity</b>: Constant //! //! <b>Throws</b>: Nothing. void swap_nodes(unordered_set_base_hook &other); //! <b>Precondition</b>: link_mode must be \c safe_link or \c auto_unlink. //! //! <b>Returns</b>: true, if the node belongs to a container, false //! otherwise. This function can be used to test whether \c unordered_set::iterator_to //! will return a valid iterator. //! //! <b>Complexity</b>: Constant bool is_linked() const; //! <b>Effects</b>: Removes the node if it's inserted in a container. //! This function is only allowed if link_mode is \c auto_unlink. //! //! <b>Throws</b>: Nothing. void unlink(); #endif }; //! Helper metafunction to define a \c unordered_set_member_hook that yields to the same //! type when the same options (either explicitly or implicitly) are used. #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) || defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) template<class ...Options> #else template<class O1 = void, class O2 = void, class O3 = void, class O4 = void> #endif struct make_unordered_set_member_hook { /// @cond typedef typename pack_options < hook_defaults, #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) O1, O2, O3, O4 #else Options... #endif >::type packed_options; typedef generic_hook < get_uset_node_algo< typename packed_options::void_pointer , packed_options::store_hash , packed_options::optimize_multikey > , member_tag , packed_options::link_mode , NoBaseHookId > implementation_defined; /// @endcond typedef implementation_defined type; }; //! Put a public data member unordered_set_member_hook in order to store objects of this class in //! an unordered_set/unordered_multi_set. unordered_set_member_hook holds the data necessary for maintaining the //! unordered_set/unordered_multi_set and provides an appropriate value_traits class for unordered_set/unordered_multi_set. //! //! The hook admits the following options: \c void_pointer<>, //! \c link_mode<> and \c store_hash<>. //! //! \c void_pointer<> is the pointer type that will be used internally in the hook //! and the container configured to use this hook. //! //! \c link_mode<> will specify the linking mode of the hook (\c normal_link, //! \c auto_unlink or \c safe_link). //! //! \c store_hash<> will tell the hook to store the hash of the value //! to speed up rehashings. #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) || defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) template<class ...Options> #else template<class O1, class O2, class O3, class O4> #endif class unordered_set_member_hook : public make_unordered_set_member_hook< #if !defined(BOOST_INTRUSIVE_VARIADIC_TEMPLATES) O1, O2, O3, O4 #else Options... #endif >::type { #if defined(BOOST_INTRUSIVE_DOXYGEN_INVOKED) public: //! <b>Effects</b>: If link_mode is \c auto_unlink or \c safe_link //! initializes the node to an unlinked state. //! //! <b>Throws</b>: Nothing. unordered_set_member_hook(); //! <b>Effects</b>: If link_mode is \c auto_unlink or \c safe_link //! initializes the node to an unlinked state. The argument is ignored. //! //! <b>Throws</b>: Nothing. //! //! <b>Rationale</b>: Providing a copy-constructor //! makes classes using the hook STL-compliant without forcing the //! user to do some additional work. \c swap can be used to emulate //! move-semantics. unordered_set_member_hook(const unordered_set_member_hook& ); //! <b>Effects</b>: Empty function. The argument is ignored. //! //! <b>Throws</b>: Nothing. //! //! <b>Rationale</b>: Providing an assignment operator //! makes classes using the hook STL-compliant without forcing the //! user to do some additional work. \c swap can be used to emulate //! move-semantics. unordered_set_member_hook& operator=(const unordered_set_member_hook& ); //! <b>Effects</b>: If link_mode is \c normal_link, the destructor does //! nothing (ie. no code is generated). If link_mode is \c safe_link and the //! object is stored in an unordered_set an assertion is raised. If link_mode is //! \c auto_unlink and \c is_linked() is true, the node is unlinked. //! //! <b>Throws</b>: Nothing. ~unordered_set_member_hook(); //! <b>Effects</b>: Swapping two nodes swaps the position of the elements //! related to those nodes in one or two containers. That is, if the node //! this is part of the element e1, the node x is part of the element e2 //! and both elements are included in the containers s1 and s2, then after //! the swap-operation e1 is in s2 at the position of e2 and e2 is in s1 //! at the position of e1. If one element is not in a container, then //! after the swap-operation the other element is not in a container. //! Iterators to e1 and e2 related to those nodes are invalidated. //! //! <b>Complexity</b>: Constant //! //! <b>Throws</b>: Nothing. void swap_nodes(unordered_set_member_hook &other); //! <b>Precondition</b>: link_mode must be \c safe_link or \c auto_unlink. //! //! <b>Returns</b>: true, if the node belongs to a container, false //! otherwise. This function can be used to test whether \c unordered_set::iterator_to //! will return a valid iterator. //! //! <b>Complexity</b>: Constant bool is_linked() const; //! <b>Effects</b>: Removes the node if it's inserted in a container. //! This function is only allowed if link_mode is \c auto_unlink. //! //! <b>Throws</b>: Nothing. void unlink(); #endif }; } //namespace intrusive } //namespace boost #include <boost/intrusive/detail/config_end.hpp> #endif //BOOST_INTRUSIVE_UNORDERED_SET_HOOK_HPP
655ed4e7448a16b1bfeb3ffede71a719c37168d7
7e6a584eb9f10e525090e5b7a35e45ac262b209b
/device/fido/fido_constants.h
b3eb41948e1cb8fb101c27d0a2ae7ade57769ff5
[ "BSD-3-Clause" ]
permissive
Jongkeun/chromium
553a37b35403118cf0818debfbe7b8a22de6828c
2ce1e0340fa2c10cda3a4f499e1a13195399d0d2
refs/heads/master
2023-03-08T08:08:40.115222
2018-08-23T14:19:35
2018-08-23T14:19:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
16,143
h
// Copyright 2018 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 DEVICE_FIDO_FIDO_CONSTANTS_H_ #define DEVICE_FIDO_FIDO_CONSTANTS_H_ #include <stdint.h> #include <array> #include <vector> #include "base/component_export.h" #include "base/time/time.h" namespace device { enum class FidoReturnCode : uint8_t { kSuccess, // Response received but didn't parse/serialize properly. kAuthenticatorResponseInvalid, // The user consented to the registration operation (e.g. by touching the // authenticator), but the authenticator recognized one of the credentials // that were already registered at the relying party. kUserConsentButCredentialExcluded, // The user consented to the assertion operation (e.g. by touching the // authenticator), but none of the provided credentials were recognized by // the authenticator. kUserConsentButCredentialNotRecognized, // The user explicitly refused to provide consent. kUserConsentDenied, }; enum class ProtocolVersion { kCtap, kU2f, kUnknown, }; // Length of the U2F challenge parameter: // https://goo.gl/y75WrX#registration-request-message---u2f_register constexpr size_t kU2fChallengeParamLength = 32; // Length of the U2F application parameter: // https://goo.gl/y75WrX#registration-request-message---u2f_register constexpr size_t kU2fApplicationParamLength = 32; // Offset of the length of the U2F registration key handle: // https://goo.gl/y75WrX#registration-response-message-success constexpr size_t kU2fKeyHandleLengthOffset = 66; // Offset of the U2F registration key handle: // https://goo.gl/y75WrX#registration-response-message-success constexpr size_t kU2fKeyHandleOffset = 67; // Length of the SHA-256 hash of the JSON-serialized client data: // https://www.w3.org/TR/webauthn/#collectedclientdata-hash-of-the-serialized-client-data constexpr size_t kClientDataHashLength = 32; // Length of the SHA-256 hash of the RP ID asssociated with the credential: // https://www.w3.org/TR/webauthn/#sec-authenticator-data constexpr size_t kRpIdHashLength = 32; static_assert(kU2fApplicationParamLength == kRpIdHashLength, "kU2fApplicationParamLength must be equal to kRpIdHashLength."); // Length of the flags: // https://www.w3.org/TR/webauthn/#sec-authenticator-data constexpr size_t kFlagsLength = 1; // Length of the signature counter, 32-bit unsigned big-endian integer: // https://www.w3.org/TR/webauthn/#sec-authenticator-data constexpr size_t kSignCounterLength = 4; // Length of the AAGUID of the authenticator: // https://www.w3.org/TR/webauthn/#sec-attested-credential-data constexpr size_t kAaguidLength = 16; // Length of the byte length L of Credential ID, 16-bit unsigned big-endian // integer: https://www.w3.org/TR/webauthn/#sec-attested-credential-data constexpr size_t kCredentialIdLengthLength = 2; // CTAP protocol device response code, as specified in // https://fidoalliance.org/specs/fido-v2.0-rd-20170927/fido-client-to-authenticator-protocol-v2.0-rd-20170927.html#authenticator-api enum class CtapDeviceResponseCode : uint8_t { kSuccess = 0x00, kCtap1ErrInvalidCommand = 0x01, kCtap1ErrInvalidParameter = 0x02, kCtap1ErrInvalidLength = 0x03, kCtap1ErrInvalidSeq = 0x04, kCtap1ErrTimeout = 0x05, kCtap1ErrChannelBusy = 0x06, kCtap1ErrLockRequired = 0x0A, kCtap1ErrInvalidChannel = 0x0B, kCtap2ErrCBORParsing = 0x10, kCtap2ErrUnexpectedType = 0x11, kCtap2ErrInvalidCBOR = 0x12, kCtap2ErrInvalidCBORType = 0x13, kCtap2ErrMissingParameter = 0x14, kCtap2ErrLimitExceeded = 0x15, kCtap2ErrUnsupportedExtension = 0x16, kCtap2ErrTooManyElements = 0x17, kCtap2ErrExtensionNotSupported = 0x18, kCtap2ErrCredentialExcluded = 0x19, kCtap2ErrCredentialNotValid = 0x20, kCtap2ErrProcesssing = 0x21, kCtap2ErrInvalidCredential = 0x22, kCtap2ErrUserActionPending = 0x23, kCtap2ErrOperationPending = 0x24, kCtap2ErrNoOperations = 0x25, kCtap2ErrUnsupportedAlgorithms = 0x26, kCtap2ErrOperationDenied = 0x27, kCtap2ErrKeyStoreFull = 0x28, kCtap2ErrNotBusy = 0x29, kCtap2ErrNoOperationPending = 0x2A, kCtap2ErrUnsupportedOption = 0x2B, kCtap2ErrInvalidOption = 0x2C, kCtap2ErrKeepAliveCancel = 0x2D, kCtap2ErrNoCredentials = 0x2E, kCtap2ErrUserActionTimeout = 0x2F, kCtap2ErrNotAllowed = 0x30, kCtap2ErrPinInvalid = 0x31, kCtap2ErrPinBlocked = 0x32, kCtap2ErrPinAuthInvalid = 0x33, kCtap2ErrPinAuthBlocked = 0x34, kCtap2ErrPinNotSet = 0x35, kCtap2ErrPinRequired = 0x36, kCtap2ErrPinPolicyViolation = 0x37, kCtap2ErrPinTokenExpired = 0x38, kCtap2ErrRequestTooLarge = 0x39, kCtap2ErrOther = 0x7F, kCtap2ErrSpecLast = 0xDF, kCtap2ErrExtensionFirst = 0xE0, kCtap2ErrExtensionLast = 0xEF, kCtap2ErrVendorFirst = 0xF0, kCtap2ErrVendorLast = 0xFF }; constexpr std::array<CtapDeviceResponseCode, 51> GetCtapResponseCodeList() { return {CtapDeviceResponseCode::kSuccess, CtapDeviceResponseCode::kCtap1ErrInvalidCommand, CtapDeviceResponseCode::kCtap1ErrInvalidParameter, CtapDeviceResponseCode::kCtap1ErrInvalidLength, CtapDeviceResponseCode::kCtap1ErrInvalidSeq, CtapDeviceResponseCode::kCtap1ErrTimeout, CtapDeviceResponseCode::kCtap1ErrChannelBusy, CtapDeviceResponseCode::kCtap1ErrLockRequired, CtapDeviceResponseCode::kCtap1ErrInvalidChannel, CtapDeviceResponseCode::kCtap2ErrCBORParsing, CtapDeviceResponseCode::kCtap2ErrUnexpectedType, CtapDeviceResponseCode::kCtap2ErrInvalidCBOR, CtapDeviceResponseCode::kCtap2ErrInvalidCBORType, CtapDeviceResponseCode::kCtap2ErrMissingParameter, CtapDeviceResponseCode::kCtap2ErrLimitExceeded, CtapDeviceResponseCode::kCtap2ErrUnsupportedExtension, CtapDeviceResponseCode::kCtap2ErrTooManyElements, CtapDeviceResponseCode::kCtap2ErrExtensionNotSupported, CtapDeviceResponseCode::kCtap2ErrCredentialExcluded, CtapDeviceResponseCode::kCtap2ErrCredentialNotValid, CtapDeviceResponseCode::kCtap2ErrProcesssing, CtapDeviceResponseCode::kCtap2ErrInvalidCredential, CtapDeviceResponseCode::kCtap2ErrUserActionPending, CtapDeviceResponseCode::kCtap2ErrOperationPending, CtapDeviceResponseCode::kCtap2ErrNoOperations, CtapDeviceResponseCode::kCtap2ErrUnsupportedAlgorithms, CtapDeviceResponseCode::kCtap2ErrOperationDenied, CtapDeviceResponseCode::kCtap2ErrKeyStoreFull, CtapDeviceResponseCode::kCtap2ErrNotBusy, CtapDeviceResponseCode::kCtap2ErrNoOperationPending, CtapDeviceResponseCode::kCtap2ErrUnsupportedOption, CtapDeviceResponseCode::kCtap2ErrInvalidOption, CtapDeviceResponseCode::kCtap2ErrKeepAliveCancel, CtapDeviceResponseCode::kCtap2ErrNoCredentials, CtapDeviceResponseCode::kCtap2ErrUserActionTimeout, CtapDeviceResponseCode::kCtap2ErrNotAllowed, CtapDeviceResponseCode::kCtap2ErrPinInvalid, CtapDeviceResponseCode::kCtap2ErrPinBlocked, CtapDeviceResponseCode::kCtap2ErrPinAuthInvalid, CtapDeviceResponseCode::kCtap2ErrPinAuthBlocked, CtapDeviceResponseCode::kCtap2ErrPinNotSet, CtapDeviceResponseCode::kCtap2ErrPinRequired, CtapDeviceResponseCode::kCtap2ErrPinPolicyViolation, CtapDeviceResponseCode::kCtap2ErrPinTokenExpired, CtapDeviceResponseCode::kCtap2ErrRequestTooLarge, CtapDeviceResponseCode::kCtap2ErrOther, CtapDeviceResponseCode::kCtap2ErrSpecLast, CtapDeviceResponseCode::kCtap2ErrExtensionFirst, CtapDeviceResponseCode::kCtap2ErrExtensionLast, CtapDeviceResponseCode::kCtap2ErrVendorFirst, CtapDeviceResponseCode::kCtap2ErrVendorLast}; } // Commands supported by CTAPHID device as specified in // https://fidoalliance.org/specs/fido-v2.0-rd-20170927/fido-client-to-authenticator-protocol-v2.0-rd-20170927.html#ctaphid-commands enum class FidoHidDeviceCommand : uint8_t { kMsg = 0x03, kCbor = 0x10, kInit = 0x06, kPing = 0x01, kCancel = 0x11, kError = 0x3F, kKeepAlive = 0x3B, kWink = 0x08, kLock = 0x04, }; constexpr std::array<FidoHidDeviceCommand, 9> GetFidoHidDeviceCommandList() { return {FidoHidDeviceCommand::kMsg, FidoHidDeviceCommand::kCbor, FidoHidDeviceCommand::kInit, FidoHidDeviceCommand::kPing, FidoHidDeviceCommand::kCancel, FidoHidDeviceCommand::kError, FidoHidDeviceCommand::kKeepAlive, FidoHidDeviceCommand::kWink, FidoHidDeviceCommand::kLock}; } // BLE device command as specified in // https://fidoalliance.org/specs/fido-v2.0-rd-20170927/fido-client-to-authenticator-protocol-v2.0-rd-20170927.html#command-status-and-error-constants // U2F BLE device does not support cancel command. enum class FidoBleDeviceCommand : uint8_t { kPing = 0x81, kKeepAlive = 0x82, kMsg = 0x83, kControl = 0x84, kCancel = 0xBE, kError = 0xBF, }; // Relevant LE Discoverable Mode bits. Reference: // Bluetooth Core Specification Supplement, Part A, section 1.3 constexpr uint8_t kLeLimitedDiscoverableModeBit = 0; constexpr uint8_t kLeGeneralDiscoverableModeBit = 1; // Fido Service Data Flags as specified in // https://fidoalliance.org/specs/fido-v2.0-id-20180227/fido-client-to-authenticator-protocol-v2.0-id-20180227.html#ble-pairing-authnr-considerations enum class FidoServiceDataFlags : uint8_t { kPairingMode = 0x80, kPasskeyEntry = 0x40, }; // Authenticator API commands supported by CTAP devices, as specified in // https://fidoalliance.org/specs/fido-v2.0-rd-20170927/fido-client-to-authenticator-protocol-v2.0-rd-20170927.html#authenticator-api enum class CtapRequestCommand : uint8_t { kAuthenticatorMakeCredential = 0x01, kAuthenticatorGetAssertion = 0x02, kAuthenticatorGetNextAssertion = 0x08, kAuthenticatorGetInfo = 0x04, kAuthenticatorClientPin = 0x06, kAuthenticatorReset = 0x07, }; enum class CoseAlgorithmIdentifier : int { kCoseEs256 = -7 }; // APDU instruction code for U2F request encoding. // https://fidoalliance.org/specs/fido-u2f-v1.0-ps-20141009/fido-u2f-u2f.h-v1.0-ps-20141009.pdf enum class U2fApduInstruction : uint8_t { kRegister = 0x01, kSign = 0x02, kVersion = 0x03, kVendorFirst = 0x40, kVenderLast = 0xBF, }; enum class CredentialType { kPublicKey }; // User verification constraint passed on from the relying party as a parameter // for AuthenticatorSelectionCriteria and for CtapGetAssertion request. // https://w3c.github.io/webauthn/#enumdef-userverificationrequirement enum class UserVerificationRequirement { kRequired, kPreferred, kDiscouraged, }; // Enumerates the two types of application parameter values used: the // "primary" value is the hash of the relying party ID[1] and is always // provided. The "alternative" value is the hash of a U2F AppID, specified in // an extension[2], for compatibility with keys that were registered with the // old API. // // [1] https://w3c.github.io/webauthn/#rp-id // [2] https://w3c.github.io/webauthn/#sctn-appid-extension enum class ApplicationParameterType { kPrimary, kAlternative, }; // Parameters for fake U2F registration used to check for user presence. COMPONENT_EXPORT(DEVICE_FIDO) extern const std::array<uint8_t, 32> kBogusAppParam; COMPONENT_EXPORT(DEVICE_FIDO) extern const std::array<uint8_t, 32> kBogusChallenge; // String key values for CTAP request optional parameters and // AuthenticatorGetInfo response. COMPONENT_EXPORT(DEVICE_FIDO) extern const char kResidentKeyMapKey[]; COMPONENT_EXPORT(DEVICE_FIDO) extern const char kUserVerificationMapKey[]; COMPONENT_EXPORT(DEVICE_FIDO) extern const char kUserPresenceMapKey[]; COMPONENT_EXPORT(DEVICE_FIDO) extern const char kClientPinMapKey[]; COMPONENT_EXPORT(DEVICE_FIDO) extern const char kPlatformDeviceMapKey[]; COMPONENT_EXPORT(DEVICE_FIDO) extern const char kEntityIdMapKey[]; COMPONENT_EXPORT(DEVICE_FIDO) extern const char kEntityNameMapKey[]; COMPONENT_EXPORT(DEVICE_FIDO) extern const char kDisplayNameMapKey[]; COMPONENT_EXPORT(DEVICE_FIDO) extern const char kIconUrlMapKey[]; COMPONENT_EXPORT(DEVICE_FIDO) extern const char kCredentialTypeMapKey[]; COMPONENT_EXPORT(DEVICE_FIDO) extern const char kCredentialAlgorithmMapKey[]; // HID transport specific constants. COMPONENT_EXPORT(DEVICE_FIDO) extern const size_t kHidPacketSize; COMPONENT_EXPORT(DEVICE_FIDO) extern const uint32_t kHidBroadcastChannel; COMPONENT_EXPORT(DEVICE_FIDO) extern const size_t kHidInitPacketHeaderSize; COMPONENT_EXPORT(DEVICE_FIDO) extern const size_t kHidContinuationPacketHeader; COMPONENT_EXPORT(DEVICE_FIDO) extern const size_t kHidMaxPacketSize; COMPONENT_EXPORT(DEVICE_FIDO) extern const size_t kHidInitPacketDataSize; COMPONENT_EXPORT(DEVICE_FIDO) extern const size_t kHidContinuationPacketDataSize; COMPONENT_EXPORT(DEVICE_FIDO) extern const uint8_t kHidMaxLockSeconds; // Messages are limited to an initiation packet and 128 continuation packets. COMPONENT_EXPORT(DEVICE_FIDO) extern const size_t kHidMaxMessageSize; // U2F APDU encoding constants, as specified in // https://fidoalliance.org/specs/fido-u2f-v1.2-ps-20170411/fido-u2f-raw-message-formats-v1.2-ps-20170411.html#bib-U2FHeader COMPONENT_EXPORT(DEVICE_FIDO) extern const size_t kU2fMaxResponseSize; // P1 instructions. COMPONENT_EXPORT(DEVICE_FIDO) extern const uint8_t kP1TupRequired; COMPONENT_EXPORT(DEVICE_FIDO) extern const uint8_t kP1TupConsumed; COMPONENT_EXPORT(DEVICE_FIDO) extern const uint8_t kP1TupRequiredConsumed; // Control byte used for check-only setting. The check-only command is used to // determine if the provided key handle was originally created by this token // and whether it was created for the provided application parameter. COMPONENT_EXPORT(DEVICE_FIDO) extern const uint8_t kP1CheckOnly; // Indicates that an individual attestation certificate is acceptable to // return with this registration. COMPONENT_EXPORT(DEVICE_FIDO) extern const uint8_t kP1IndividualAttestation; COMPONENT_EXPORT(DEVICE_FIDO) extern const size_t kMaxKeyHandleLength; // Maximum wait time before client error outs on device. COMPONENT_EXPORT(DEVICE_FIDO) extern const base::TimeDelta kDeviceTimeout; // Wait time before polling device for U2F register/sign operation again when // device times out waiting for user presence. COMPONENT_EXPORT(DEVICE_FIDO) extern const base::TimeDelta kU2fRetryDelay; // Interval wait time before retrying reading on HID connection when // CTAPHID_KEEPALIVE message has been received. // https://fidoalliance.org/specs/fido-v2.0-rd-20170927/fido-client-to-authenticator-protocol-v2.0-rd-20170927.html#ctaphid_keepalive-0x3b COMPONENT_EXPORT(DEVICE_FIDO) extern const base::TimeDelta kHidKeepAliveDelay; // String key values for attestation object as a response to MakeCredential // request. COMPONENT_EXPORT(DEVICE_FIDO) extern const char kFormatKey[]; COMPONENT_EXPORT(DEVICE_FIDO) extern const char kAttestationStatementKey[]; COMPONENT_EXPORT(DEVICE_FIDO) extern const char kAuthDataKey[]; COMPONENT_EXPORT(DEVICE_FIDO) extern const char kNoneAttestationValue[]; // String representation of public key credential enum. // https://w3c.github.io/webauthn/#credentialType COMPONENT_EXPORT(DEVICE_FIDO) extern const char kPublicKey[]; const char* CredentialTypeToString(CredentialType type); // Values used to construct/validate handshake messages for Cable handshake // protocol. COMPONENT_EXPORT(DEVICE_FIDO) extern const char kCableHandshakeKeyInfo[]; COMPONENT_EXPORT(DEVICE_FIDO) extern const char kCableDeviceEncryptionKeyInfo[]; COMPONENT_EXPORT(DEVICE_FIDO) extern const char kCableAuthenticatorHelloMessage[]; COMPONENT_EXPORT(DEVICE_FIDO) extern const char kCableClientHelloMessage[]; // TODO(hongjunchoi): Add url to the official spec once it's standardized. COMPONENT_EXPORT(DEVICE_FIDO) extern const char kCtap2Version[]; COMPONENT_EXPORT(DEVICE_FIDO) extern const char kU2fVersion[]; } // namespace device #endif // DEVICE_FIDO_FIDO_CONSTANTS_H_
abd75bf4e7f4675105d002e35e66b143bf1b3ff0
4718b9b11110db8eb23980c6d12940bd5b754f34
/bench/ml2cpp-demo/DecisionTreeClassifier/BinaryClass_100/ml2cpp-demo_DecisionTreeClassifier_BinaryClass_100.cpp
0fa83aba0e1acfeabb93b0189da06fccebd36a07
[ "BSD-3-Clause" ]
permissive
ssh352/ml2cpp
74d38935256cf9d034d08ede37a7d8bdcfa25540
999eb1e7238b9ee2ee32d47ac4f12e1530a3ba6f
refs/heads/master
2023-01-27T12:07:15.929729
2020-12-07T12:26:54
2020-12-07T12:26:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,282
cpp
// ******************************************************** // This C++ code was automatically generated by ml2cpp (development version). // Copyright 2020 // https://github.com/antoinecarme/ml2cpp // Model : DecisionTreeClassifier // Dataset : BinaryClass_100 // This CPP code can be compiled using any C++-17 compiler. // g++ -Wall -Wno-unused-function -std=c++17 -g -o ml2cpp-demo_DecisionTreeClassifier_BinaryClass_100.exe ml2cpp-demo_DecisionTreeClassifier_BinaryClass_100.cpp // Model deployment code // ******************************************************** #include "../../Generic.i" namespace { std::vector<std::any> get_classes(){ std::vector<std::any> lClasses = { 0, 1 }; return lClasses; } typedef std::vector<double> tNodeData; std::map<int, tNodeData> Decision_Tree_Node_data = { { 5 , {0.0, 1.0 }} , { 6 , {1.0, 0.0 }} , { 7 , {1.0, 0.0 }} , { 8 , {0.0, 1.0 }} , { 10 , {1.0, 0.0 }} , { 11 , {0.0, 1.0 }} , { 14 , {1.0, 0.0 }} , { 15 , {0.0, 1.0 }} , { 16 , {1.0, 0.0 }} }; int get_decision_tree_node_index(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) { int lNodeIndex = (Feature_57 <= 0.034406057093292475) ? ( (Feature_17 <= 1.0863247513771057) ? ( (Feature_9 <= 1.7608928084373474) ? ( (Feature_60 <= -0.6577232480049133) ? ( (Feature_80 <= 0.2915303260087967) ? ( 5 ) : ( 6 ) ) : ( 7 ) ) : ( 8 ) ) : ( (Feature_57 <= -1.1760293245315552) ? ( 10 ) : ( 11 ) ) ) : ( (Feature_54 <= 1.471251130104065) ? ( (Feature_81 <= -1.8876248598098755) ? ( 14 ) : ( 15 ) ) : ( 16 ) ); return lNodeIndex; } std::vector<std::string> get_input_names(){ std::vector<std::string> lFeatures = { "Feature_0", "Feature_1", "Feature_2", "Feature_3", "Feature_4", "Feature_5", "Feature_6", "Feature_7", "Feature_8", "Feature_9", "Feature_10", "Feature_11", "Feature_12", "Feature_13", "Feature_14", "Feature_15", "Feature_16", "Feature_17", "Feature_18", "Feature_19", "Feature_20", "Feature_21", "Feature_22", "Feature_23", "Feature_24", "Feature_25", "Feature_26", "Feature_27", "Feature_28", "Feature_29", "Feature_30", "Feature_31", "Feature_32", "Feature_33", "Feature_34", "Feature_35", "Feature_36", "Feature_37", "Feature_38", "Feature_39", "Feature_40", "Feature_41", "Feature_42", "Feature_43", "Feature_44", "Feature_45", "Feature_46", "Feature_47", "Feature_48", "Feature_49", "Feature_50", "Feature_51", "Feature_52", "Feature_53", "Feature_54", "Feature_55", "Feature_56", "Feature_57", "Feature_58", "Feature_59", "Feature_60", "Feature_61", "Feature_62", "Feature_63", "Feature_64", "Feature_65", "Feature_66", "Feature_67", "Feature_68", "Feature_69", "Feature_70", "Feature_71", "Feature_72", "Feature_73", "Feature_74", "Feature_75", "Feature_76", "Feature_77", "Feature_78", "Feature_79", "Feature_80", "Feature_81", "Feature_82", "Feature_83", "Feature_84", "Feature_85", "Feature_86", "Feature_87", "Feature_88", "Feature_89", "Feature_90", "Feature_91", "Feature_92", "Feature_93", "Feature_94", "Feature_95", "Feature_96", "Feature_97", "Feature_98", "Feature_99" }; return lFeatures; } std::vector<std::string> get_output_names(){ std::vector<std::string> lOutputs = { "Score_0", "Score_1", "Proba_0", "Proba_1", "LogProba_0", "LogProba_1", "Decision", "DecisionProba" }; return lOutputs; } tTable compute_classification_scores(std::any Feature_0, std::any Feature_1, std::any Feature_2, std::any Feature_3, std::any Feature_4, std::any Feature_5, std::any Feature_6, std::any Feature_7, std::any Feature_8, std::any Feature_9, std::any Feature_10, std::any Feature_11, std::any Feature_12, std::any Feature_13, std::any Feature_14, std::any Feature_15, std::any Feature_16, std::any Feature_17, std::any Feature_18, std::any Feature_19, std::any Feature_20, std::any Feature_21, std::any Feature_22, std::any Feature_23, std::any Feature_24, std::any Feature_25, std::any Feature_26, std::any Feature_27, std::any Feature_28, std::any Feature_29, std::any Feature_30, std::any Feature_31, std::any Feature_32, std::any Feature_33, std::any Feature_34, std::any Feature_35, std::any Feature_36, std::any Feature_37, std::any Feature_38, std::any Feature_39, std::any Feature_40, std::any Feature_41, std::any Feature_42, std::any Feature_43, std::any Feature_44, std::any Feature_45, std::any Feature_46, std::any Feature_47, std::any Feature_48, std::any Feature_49, std::any Feature_50, std::any Feature_51, std::any Feature_52, std::any Feature_53, std::any Feature_54, std::any Feature_55, std::any Feature_56, std::any Feature_57, std::any Feature_58, std::any Feature_59, std::any Feature_60, std::any Feature_61, std::any Feature_62, std::any Feature_63, std::any Feature_64, std::any Feature_65, std::any Feature_66, std::any Feature_67, std::any Feature_68, std::any Feature_69, std::any Feature_70, std::any Feature_71, std::any Feature_72, std::any Feature_73, std::any Feature_74, std::any Feature_75, std::any Feature_76, std::any Feature_77, std::any Feature_78, std::any Feature_79, std::any Feature_80, std::any Feature_81, std::any Feature_82, std::any Feature_83, std::any Feature_84, std::any Feature_85, std::any Feature_86, std::any Feature_87, std::any Feature_88, std::any Feature_89, std::any Feature_90, std::any Feature_91, std::any Feature_92, std::any Feature_93, std::any Feature_94, std::any Feature_95, std::any Feature_96, std::any Feature_97, std::any Feature_98, std::any Feature_99) { auto lClasses = get_classes(); int lNodeIndex = get_decision_tree_node_index(Feature_0, Feature_1, Feature_2, Feature_3, Feature_4, Feature_5, Feature_6, Feature_7, Feature_8, Feature_9, Feature_10, Feature_11, Feature_12, Feature_13, Feature_14, Feature_15, Feature_16, Feature_17, Feature_18, Feature_19, Feature_20, Feature_21, Feature_22, Feature_23, Feature_24, Feature_25, Feature_26, Feature_27, Feature_28, Feature_29, Feature_30, Feature_31, Feature_32, Feature_33, Feature_34, Feature_35, Feature_36, Feature_37, Feature_38, Feature_39, Feature_40, Feature_41, Feature_42, Feature_43, Feature_44, Feature_45, Feature_46, Feature_47, Feature_48, Feature_49, Feature_50, Feature_51, Feature_52, Feature_53, Feature_54, Feature_55, Feature_56, Feature_57, Feature_58, Feature_59, Feature_60, Feature_61, Feature_62, Feature_63, Feature_64, Feature_65, Feature_66, Feature_67, Feature_68, Feature_69, Feature_70, Feature_71, Feature_72, Feature_73, Feature_74, Feature_75, Feature_76, Feature_77, Feature_78, Feature_79, Feature_80, Feature_81, Feature_82, Feature_83, Feature_84, Feature_85, Feature_86, Feature_87, Feature_88, Feature_89, Feature_90, Feature_91, Feature_92, Feature_93, Feature_94, Feature_95, Feature_96, Feature_97, Feature_98, Feature_99); std::vector<double> lNodeValue = Decision_Tree_Node_data[ lNodeIndex ]; tTable lTable; lTable["Score"] = { std::any(), std::any() } ; lTable["Proba"] = { lNodeValue [ 0 ], lNodeValue [ 1 ] } ; int lBestClass = get_arg_max( lTable["Proba"] ); auto lDecision = lClasses[lBestClass]; lTable["Decision"] = { lDecision } ; lTable["DecisionProba"] = { lTable["Proba"][lBestClass] }; recompute_log_probas( lTable ); return lTable; } tTable compute_model_outputs_from_table( tTable const & iTable) { tTable lTable = compute_classification_scores(iTable.at("Feature_0")[0], iTable.at("Feature_1")[0], iTable.at("Feature_2")[0], iTable.at("Feature_3")[0], iTable.at("Feature_4")[0], iTable.at("Feature_5")[0], iTable.at("Feature_6")[0], iTable.at("Feature_7")[0], iTable.at("Feature_8")[0], iTable.at("Feature_9")[0], iTable.at("Feature_10")[0], iTable.at("Feature_11")[0], iTable.at("Feature_12")[0], iTable.at("Feature_13")[0], iTable.at("Feature_14")[0], iTable.at("Feature_15")[0], iTable.at("Feature_16")[0], iTable.at("Feature_17")[0], iTable.at("Feature_18")[0], iTable.at("Feature_19")[0], iTable.at("Feature_20")[0], iTable.at("Feature_21")[0], iTable.at("Feature_22")[0], iTable.at("Feature_23")[0], iTable.at("Feature_24")[0], iTable.at("Feature_25")[0], iTable.at("Feature_26")[0], iTable.at("Feature_27")[0], iTable.at("Feature_28")[0], iTable.at("Feature_29")[0], iTable.at("Feature_30")[0], iTable.at("Feature_31")[0], iTable.at("Feature_32")[0], iTable.at("Feature_33")[0], iTable.at("Feature_34")[0], iTable.at("Feature_35")[0], iTable.at("Feature_36")[0], iTable.at("Feature_37")[0], iTable.at("Feature_38")[0], iTable.at("Feature_39")[0], iTable.at("Feature_40")[0], iTable.at("Feature_41")[0], iTable.at("Feature_42")[0], iTable.at("Feature_43")[0], iTable.at("Feature_44")[0], iTable.at("Feature_45")[0], iTable.at("Feature_46")[0], iTable.at("Feature_47")[0], iTable.at("Feature_48")[0], iTable.at("Feature_49")[0], iTable.at("Feature_50")[0], iTable.at("Feature_51")[0], iTable.at("Feature_52")[0], iTable.at("Feature_53")[0], iTable.at("Feature_54")[0], iTable.at("Feature_55")[0], iTable.at("Feature_56")[0], iTable.at("Feature_57")[0], iTable.at("Feature_58")[0], iTable.at("Feature_59")[0], iTable.at("Feature_60")[0], iTable.at("Feature_61")[0], iTable.at("Feature_62")[0], iTable.at("Feature_63")[0], iTable.at("Feature_64")[0], iTable.at("Feature_65")[0], iTable.at("Feature_66")[0], iTable.at("Feature_67")[0], iTable.at("Feature_68")[0], iTable.at("Feature_69")[0], iTable.at("Feature_70")[0], iTable.at("Feature_71")[0], iTable.at("Feature_72")[0], iTable.at("Feature_73")[0], iTable.at("Feature_74")[0], iTable.at("Feature_75")[0], iTable.at("Feature_76")[0], iTable.at("Feature_77")[0], iTable.at("Feature_78")[0], iTable.at("Feature_79")[0], iTable.at("Feature_80")[0], iTable.at("Feature_81")[0], iTable.at("Feature_82")[0], iTable.at("Feature_83")[0], iTable.at("Feature_84")[0], iTable.at("Feature_85")[0], iTable.at("Feature_86")[0], iTable.at("Feature_87")[0], iTable.at("Feature_88")[0], iTable.at("Feature_89")[0], iTable.at("Feature_90")[0], iTable.at("Feature_91")[0], iTable.at("Feature_92")[0], iTable.at("Feature_93")[0], iTable.at("Feature_94")[0], iTable.at("Feature_95")[0], iTable.at("Feature_96")[0], iTable.at("Feature_97")[0], iTable.at("Feature_98")[0], iTable.at("Feature_99")[0]); return lTable; } } // eof namespace int main() { score_csv_file("outputs/ml2cpp-demo/datasets/BinaryClass_100.csv"); return 0; }
278806a669ef3958c9356b0b114a504babfab566
b201ac7910ccc8072254f2594c32b0b37d1b294a
/lib/Core/Memory.h
990c7238099775d0f67e7f5cd894dd2e58f6ff93
[ "NCSA" ]
permissive
Shikhar8990/pChop
3343c2e9e703eeaa84fca5f76700c947c271b363
6a1da72db26c0f6d419c0eed5dbef8810a387701
refs/heads/master
2020-11-26T01:22:53.584230
2020-01-09T04:31:28
2020-01-09T04:31:28
228,920,184
2
0
null
null
null
null
UTF-8
C++
false
false
6,688
h
//===-- Memory.h ------------------------------------------------*- C++ -*-===// // // The KLEE Symbolic Virtual Machine // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef KLEE_MEMORY_H #define KLEE_MEMORY_H #include "Context.h" #include "klee/Expr.h" #include "llvm/ADT/StringExtras.h" #include <vector> #include <string> namespace llvm { class Value; } namespace klee { class BitArray; class MemoryManager; class Solver; class ArrayCache; class MemoryObject { friend class STPBuilder; friend class ObjectState; friend class ExecutionState; friend class AllocationRecord; private: static int counter; mutable unsigned refCount; public: unsigned id; uint64_t address; /// size in bytes unsigned size; mutable std::string name; bool isLocal; mutable bool isGlobal; bool isFixed; /// true if created by us. bool fake_object; bool isUserSpecified; MemoryManager *parent; /// "Location" for which this memory object was allocated. This /// should be either the allocating instruction or the global object /// it was allocated for (or whatever else makes sense). const llvm::Value *allocSite; /// A list of boolean expressions the user has requested be true of /// a counterexample. Mutable since we play a little fast and loose /// with allowing it to be added to during execution (although /// should sensibly be only at creation time). mutable std::vector< ref<Expr> > cexPreferences; // DO NOT IMPLEMENT MemoryObject(const MemoryObject &b); MemoryObject &operator=(const MemoryObject &b); public: // XXX this is just a temp hack, should be removed explicit MemoryObject(uint64_t _address) : refCount(0), id(counter++), address(_address), size(0), isFixed(true), parent(NULL), allocSite(0) { } MemoryObject(uint64_t _address, unsigned _size, bool _isLocal, bool _isGlobal, bool _isFixed, const llvm::Value *_allocSite, MemoryManager *_parent) : refCount(0), id(counter++), address(_address), size(_size), name("unnamed"), isLocal(_isLocal), isGlobal(_isGlobal), isFixed(_isFixed), fake_object(false), isUserSpecified(false), parent(_parent), allocSite(_allocSite) { } ~MemoryObject(); /// Get an identifying string for this allocation. void getAllocInfo(std::string &result) const; void setName(std::string name) const { this->name = name; } ref<ConstantExpr> getBaseExpr() const { return ConstantExpr::create(address, Context::get().getPointerWidth()); } ref<ConstantExpr> getSizeExpr() const { return ConstantExpr::create(size, Context::get().getPointerWidth()); } ref<Expr> getOffsetExpr(ref<Expr> pointer) const { return SubExpr::create(pointer, getBaseExpr()); } ref<Expr> getBoundsCheckPointer(ref<Expr> pointer) const { return getBoundsCheckOffset(getOffsetExpr(pointer)); } ref<Expr> getBoundsCheckPointer(ref<Expr> pointer, unsigned bytes) const { return getBoundsCheckOffset(getOffsetExpr(pointer), bytes); } ref<Expr> getBoundsCheckOffset(ref<Expr> offset) const { if (size==0) { return EqExpr::create(offset, ConstantExpr::alloc(0, Context::get().getPointerWidth())); } else { return UltExpr::create(offset, getSizeExpr()); } } ref<Expr> getBoundsCheckOffset(ref<Expr> offset, unsigned bytes) const { if (bytes<=size) { return UltExpr::create(offset, ConstantExpr::alloc(size - bytes + 1, Context::get().getPointerWidth())); } else { return ConstantExpr::alloc(0, Expr::Bool); } } }; class ObjectState { private: friend class AddressSpace; unsigned copyOnWriteOwner; // exclusively for AddressSpace friend class ObjectHolder; unsigned refCount; const MemoryObject *object; uint8_t *concreteStore; // XXX cleanup name of flushMask (its backwards or something) BitArray *concreteMask; // mutable because may need flushed during read of const mutable BitArray *flushMask; ref<Expr> *knownSymbolics; // mutable because we may need flush during read of const mutable UpdateList updates; public: unsigned size; bool readOnly; public: /// Create a new object state for the given memory object with concrete /// contents. The initial contents are undefined, it is the callers /// responsibility to initialize the object contents appropriately. ObjectState(const MemoryObject *mo); /// Create a new object state for the given memory object with symbolic /// contents. ObjectState(const MemoryObject *mo, const Array *array); ObjectState(const ObjectState &os); ~ObjectState(); const MemoryObject *getObject() const { return object; } void setReadOnly(bool ro) { readOnly = ro; } // make contents all concrete and zero void initializeToZero(); // make contents all concrete and random void initializeToRandom(); ref<Expr> read(ref<Expr> offset, Expr::Width width) const; ref<Expr> read(unsigned offset, Expr::Width width) const; ref<Expr> read8(unsigned offset) const; // return bytes written. void write(unsigned offset, ref<Expr> value); void write(ref<Expr> offset, ref<Expr> value); void write8(unsigned offset, uint8_t value); void write16(unsigned offset, uint16_t value); void write32(unsigned offset, uint32_t value); void write64(unsigned offset, uint64_t value); private: const UpdateList &getUpdates() const; void makeConcrete(); void makeSymbolic(); ref<Expr> read8(ref<Expr> offset) const; void write8(unsigned offset, ref<Expr> value); void write8(ref<Expr> offset, ref<Expr> value); void fastRangeCheckOffset(ref<Expr> offset, unsigned *base_r, unsigned *size_r) const; void flushRangeForRead(unsigned rangeBase, unsigned rangeSize) const; void flushRangeForWrite(unsigned rangeBase, unsigned rangeSize); bool isByteConcrete(unsigned offset) const; bool isByteFlushed(unsigned offset) const; bool isByteKnownSymbolic(unsigned offset) const; void markByteConcrete(unsigned offset); void markByteSymbolic(unsigned offset); void markByteFlushed(unsigned offset); void markByteUnflushed(unsigned offset); void setKnownSymbolic(unsigned offset, Expr *value); void print(); ArrayCache *getArrayCache() const; }; } // End klee namespace #endif
fc950b95794fc4f0e4b7332f312c7251a755a517
4beef014915beca63ddbc45154f1b95df2f55857
/src/folding_planner_cmake/lib/Eigen/src/SVD/JacobiSVD.h
c57f2974c539210d09760be7d40abee06d805bf8
[ "MIT" ]
permissive
Yinxiaoli/iros2015_folding
86b32a9ec0e269556212211792a3172a31b9cae2
e7bb78a31d8ff2cfa0666037b1bd5cfae337c646
refs/heads/master
2021-01-10T14:41:07.977646
2017-12-17T05:09:41
2017-12-17T05:09:41
44,642,831
19
8
MIT
2017-12-17T05:09:42
2015-10-21T00:28:33
C++
UTF-8
C++
false
false
39,345
h
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2009-2010 Benoit Jacob <[email protected]> // // This Source Code Form is subject to the terms of the Mozilla // Public License v. 2.0. If a copy of the MPL was not distributed // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. #ifndef EIGEN_JACOBISVD_H #define EIGEN_JACOBISVD_H namespace Eigen { namespace internal { // forward declaration (needed by ICC) // the empty body is required by MSVC template<typename MatrixType, int QRPreconditioner, bool IsComplex = NumTraits<typename MatrixType::Scalar>::IsComplex> struct svd_precondition_2x2_block_to_be_real {}; /*** QR preconditioners (R-SVD) *** *** Their role is to reduce the problem of computing the SVD to the case of a square matrix. *** This approach, known as R-SVD, is an optimization for rectangular-enough matrices, and is a requirement for *** JacobiSVD which by itself is only able to work on square matrices. ***/ enum { PreconditionIfMoreColsThanRows, PreconditionIfMoreRowsThanCols }; template<typename MatrixType, int QRPreconditioner, int Case> struct qr_preconditioner_should_do_anything { enum { a = MatrixType::RowsAtCompileTime != Dynamic && MatrixType::ColsAtCompileTime != Dynamic && MatrixType::ColsAtCompileTime <= MatrixType::RowsAtCompileTime, b = MatrixType::RowsAtCompileTime != Dynamic && MatrixType::ColsAtCompileTime != Dynamic && MatrixType::RowsAtCompileTime <= MatrixType::ColsAtCompileTime, ret = !( (QRPreconditioner == NoQRPreconditioner) || (Case == PreconditionIfMoreColsThanRows && bool(a)) || (Case == PreconditionIfMoreRowsThanCols && bool(b)) ) }; }; template<typename MatrixType, int QRPreconditioner, int Case, bool DoAnything = qr_preconditioner_should_do_anything<MatrixType, QRPreconditioner, Case>::ret > struct qr_preconditioner_impl {}; template<typename MatrixType, int QRPreconditioner, int Case> class qr_preconditioner_impl<MatrixType, QRPreconditioner, Case, false> { public: typedef typename MatrixType::Index Index; void allocate(const JacobiSVD<MatrixType, QRPreconditioner>&) {} bool run(JacobiSVD<MatrixType, QRPreconditioner>&, const MatrixType&) { return false; } }; /*** preconditioner using FullPivHouseholderQR ***/ template<typename MatrixType> class qr_preconditioner_impl<MatrixType, FullPivHouseholderQRPreconditioner, PreconditionIfMoreRowsThanCols, true> { public: typedef typename MatrixType::Index Index; typedef typename MatrixType::Scalar Scalar; enum { RowsAtCompileTime = MatrixType::RowsAtCompileTime, MaxRowsAtCompileTime = MatrixType::MaxRowsAtCompileTime }; typedef Matrix<Scalar, 1, RowsAtCompileTime, RowMajor, 1, MaxRowsAtCompileTime> WorkspaceType; void allocate(const JacobiSVD<MatrixType, FullPivHouseholderQRPreconditioner>& svd) { if (svd.rows() != m_qr.rows() || svd.cols() != m_qr.cols()) { m_qr.~QRType(); ::new (&m_qr) QRType(svd.rows(), svd.cols()); } if (svd.m_computeFullU) m_workspace.resize(svd.rows()); } bool run(JacobiSVD<MatrixType, FullPivHouseholderQRPreconditioner>& svd, const MatrixType& matrix) { if(matrix.rows() > matrix.cols()) { m_qr.compute(matrix); svd.m_workMatrix = m_qr.matrixQR().block(0,0,matrix.cols(),matrix.cols()).template triangularView<Upper>(); if(svd.m_computeFullU) m_qr.matrixQ().evalTo(svd.m_matrixU, m_workspace); if(svd.computeV()) svd.m_matrixV = m_qr.colsPermutation(); return true; } return false; } private: typedef FullPivHouseholderQR<MatrixType> QRType; QRType m_qr; WorkspaceType m_workspace; }; template<typename MatrixType> class qr_preconditioner_impl<MatrixType, FullPivHouseholderQRPreconditioner, PreconditionIfMoreColsThanRows, true> { public: typedef typename MatrixType::Index Index; typedef typename MatrixType::Scalar Scalar; enum { RowsAtCompileTime = MatrixType::RowsAtCompileTime, ColsAtCompileTime = MatrixType::ColsAtCompileTime, MaxRowsAtCompileTime = MatrixType::MaxRowsAtCompileTime, MaxColsAtCompileTime = MatrixType::MaxColsAtCompileTime, Options = MatrixType::Options }; typedef Matrix<Scalar, ColsAtCompileTime, RowsAtCompileTime, Options, MaxColsAtCompileTime, MaxRowsAtCompileTime> TransposeTypeWithSameStorageOrder; void allocate(const JacobiSVD<MatrixType, FullPivHouseholderQRPreconditioner>& svd) { if (svd.cols() != m_qr.rows() || svd.rows() != m_qr.cols()) { m_qr.~QRType(); ::new (&m_qr) QRType(svd.cols(), svd.rows()); } m_adjoint.resize(svd.cols(), svd.rows()); if (svd.m_computeFullV) m_workspace.resize(svd.cols()); } bool run(JacobiSVD<MatrixType, FullPivHouseholderQRPreconditioner>& svd, const MatrixType& matrix) { if(matrix.cols() > matrix.rows()) { m_adjoint = matrix.adjoint(); m_qr.compute(m_adjoint); svd.m_workMatrix = m_qr.matrixQR().block(0,0,matrix.rows(),matrix.rows()).template triangularView<Upper>().adjoint(); if(svd.m_computeFullV) m_qr.matrixQ().evalTo(svd.m_matrixV, m_workspace); if(svd.computeU()) svd.m_matrixU = m_qr.colsPermutation(); return true; } else return false; } private: typedef FullPivHouseholderQR<TransposeTypeWithSameStorageOrder> QRType; QRType m_qr; TransposeTypeWithSameStorageOrder m_adjoint; typename internal::plain_row_type<MatrixType>::type m_workspace; }; /*** preconditioner using ColPivHouseholderQR ***/ template<typename MatrixType> class qr_preconditioner_impl<MatrixType, ColPivHouseholderQRPreconditioner, PreconditionIfMoreRowsThanCols, true> { public: typedef typename MatrixType::Index Index; void allocate(const JacobiSVD<MatrixType, ColPivHouseholderQRPreconditioner>& svd) { if (svd.rows() != m_qr.rows() || svd.cols() != m_qr.cols()) { m_qr.~QRType(); ::new (&m_qr) QRType(svd.rows(), svd.cols()); } if (svd.m_computeFullU) m_workspace.resize(svd.rows()); else if (svd.m_computeThinU) m_workspace.resize(svd.cols()); } bool run(JacobiSVD<MatrixType, ColPivHouseholderQRPreconditioner>& svd, const MatrixType& matrix) { if(matrix.rows() > matrix.cols()) { m_qr.compute(matrix); svd.m_workMatrix = m_qr.matrixQR().block(0,0,matrix.cols(),matrix.cols()).template triangularView<Upper>(); if(svd.m_computeFullU) m_qr.householderQ().evalTo(svd.m_matrixU, m_workspace); else if(svd.m_computeThinU) { svd.m_matrixU.setIdentity(matrix.rows(), matrix.cols()); m_qr.householderQ().applyThisOnTheLeft(svd.m_matrixU, m_workspace); } if(svd.computeV()) svd.m_matrixV = m_qr.colsPermutation(); return true; } return false; } private: typedef ColPivHouseholderQR<MatrixType> QRType; QRType m_qr; typename internal::plain_col_type<MatrixType>::type m_workspace; }; template<typename MatrixType> class qr_preconditioner_impl<MatrixType, ColPivHouseholderQRPreconditioner, PreconditionIfMoreColsThanRows, true> { public: typedef typename MatrixType::Index Index; typedef typename MatrixType::Scalar Scalar; enum { RowsAtCompileTime = MatrixType::RowsAtCompileTime, ColsAtCompileTime = MatrixType::ColsAtCompileTime, MaxRowsAtCompileTime = MatrixType::MaxRowsAtCompileTime, MaxColsAtCompileTime = MatrixType::MaxColsAtCompileTime, Options = MatrixType::Options }; typedef Matrix<Scalar, ColsAtCompileTime, RowsAtCompileTime, Options, MaxColsAtCompileTime, MaxRowsAtCompileTime> TransposeTypeWithSameStorageOrder; void allocate(const JacobiSVD<MatrixType, ColPivHouseholderQRPreconditioner>& svd) { if (svd.cols() != m_qr.rows() || svd.rows() != m_qr.cols()) { m_qr.~QRType(); ::new (&m_qr) QRType(svd.cols(), svd.rows()); } if (svd.m_computeFullV) m_workspace.resize(svd.cols()); else if (svd.m_computeThinV) m_workspace.resize(svd.rows()); m_adjoint.resize(svd.cols(), svd.rows()); } bool run(JacobiSVD<MatrixType, ColPivHouseholderQRPreconditioner>& svd, const MatrixType& matrix) { if(matrix.cols() > matrix.rows()) { m_adjoint = matrix.adjoint(); m_qr.compute(m_adjoint); svd.m_workMatrix = m_qr.matrixQR().block(0,0,matrix.rows(),matrix.rows()).template triangularView<Upper>().adjoint(); if(svd.m_computeFullV) m_qr.householderQ().evalTo(svd.m_matrixV, m_workspace); else if(svd.m_computeThinV) { svd.m_matrixV.setIdentity(matrix.cols(), matrix.rows()); m_qr.householderQ().applyThisOnTheLeft(svd.m_matrixV, m_workspace); } if(svd.computeU()) svd.m_matrixU = m_qr.colsPermutation(); return true; } else return false; } private: typedef ColPivHouseholderQR<TransposeTypeWithSameStorageOrder> QRType; QRType m_qr; TransposeTypeWithSameStorageOrder m_adjoint; typename internal::plain_row_type<MatrixType>::type m_workspace; }; /*** preconditioner using HouseholderQR ***/ template<typename MatrixType> class qr_preconditioner_impl<MatrixType, HouseholderQRPreconditioner, PreconditionIfMoreRowsThanCols, true> { public: typedef typename MatrixType::Index Index; void allocate(const JacobiSVD<MatrixType, HouseholderQRPreconditioner>& svd) { if (svd.rows() != m_qr.rows() || svd.cols() != m_qr.cols()) { m_qr.~QRType(); ::new (&m_qr) QRType(svd.rows(), svd.cols()); } if (svd.m_computeFullU) m_workspace.resize(svd.rows()); else if (svd.m_computeThinU) m_workspace.resize(svd.cols()); } bool run(JacobiSVD<MatrixType, HouseholderQRPreconditioner>& svd, const MatrixType& matrix) { if(matrix.rows() > matrix.cols()) { m_qr.compute(matrix); svd.m_workMatrix = m_qr.matrixQR().block(0,0,matrix.cols(),matrix.cols()).template triangularView<Upper>(); if(svd.m_computeFullU) m_qr.householderQ().evalTo(svd.m_matrixU, m_workspace); else if(svd.m_computeThinU) { svd.m_matrixU.setIdentity(matrix.rows(), matrix.cols()); m_qr.householderQ().applyThisOnTheLeft(svd.m_matrixU, m_workspace); } if(svd.computeV()) svd.m_matrixV.setIdentity(matrix.cols(), matrix.cols()); return true; } return false; } private: typedef HouseholderQR<MatrixType> QRType; QRType m_qr; typename internal::plain_col_type<MatrixType>::type m_workspace; }; template<typename MatrixType> class qr_preconditioner_impl<MatrixType, HouseholderQRPreconditioner, PreconditionIfMoreColsThanRows, true> { public: typedef typename MatrixType::Index Index; typedef typename MatrixType::Scalar Scalar; enum { RowsAtCompileTime = MatrixType::RowsAtCompileTime, ColsAtCompileTime = MatrixType::ColsAtCompileTime, MaxRowsAtCompileTime = MatrixType::MaxRowsAtCompileTime, MaxColsAtCompileTime = MatrixType::MaxColsAtCompileTime, Options = MatrixType::Options }; typedef Matrix<Scalar, ColsAtCompileTime, RowsAtCompileTime, Options, MaxColsAtCompileTime, MaxRowsAtCompileTime> TransposeTypeWithSameStorageOrder; void allocate(const JacobiSVD<MatrixType, HouseholderQRPreconditioner>& svd) { if (svd.cols() != m_qr.rows() || svd.rows() != m_qr.cols()) { m_qr.~QRType(); ::new (&m_qr) QRType(svd.cols(), svd.rows()); } if (svd.m_computeFullV) m_workspace.resize(svd.cols()); else if (svd.m_computeThinV) m_workspace.resize(svd.rows()); m_adjoint.resize(svd.cols(), svd.rows()); } bool run(JacobiSVD<MatrixType, HouseholderQRPreconditioner>& svd, const MatrixType& matrix) { if(matrix.cols() > matrix.rows()) { m_adjoint = matrix.adjoint(); m_qr.compute(m_adjoint); svd.m_workMatrix = m_qr.matrixQR().block(0,0,matrix.rows(),matrix.rows()).template triangularView<Upper>().adjoint(); if(svd.m_computeFullV) m_qr.householderQ().evalTo(svd.m_matrixV, m_workspace); else if(svd.m_computeThinV) { svd.m_matrixV.setIdentity(matrix.cols(), matrix.rows()); m_qr.householderQ().applyThisOnTheLeft(svd.m_matrixV, m_workspace); } if(svd.computeU()) svd.m_matrixU.setIdentity(matrix.rows(), matrix.rows()); return true; } else return false; } private: typedef HouseholderQR<TransposeTypeWithSameStorageOrder> QRType; QRType m_qr; TransposeTypeWithSameStorageOrder m_adjoint; typename internal::plain_row_type<MatrixType>::type m_workspace; }; /*** 2x2 SVD implementation *** *** JacobiSVD consists in performing a series of 2x2 SVD subproblems ***/ template<typename MatrixType, int QRPreconditioner> struct svd_precondition_2x2_block_to_be_real<MatrixType, QRPreconditioner, false> { typedef JacobiSVD<MatrixType, QRPreconditioner> SVD; typedef typename SVD::Index Index; static void run(typename SVD::WorkMatrixType&, SVD&, Index, Index) {} }; template<typename MatrixType, int QRPreconditioner> struct svd_precondition_2x2_block_to_be_real<MatrixType, QRPreconditioner, true> { typedef JacobiSVD<MatrixType, QRPreconditioner> SVD; typedef typename MatrixType::Scalar Scalar; typedef typename MatrixType::RealScalar RealScalar; typedef typename SVD::Index Index; static void run(typename SVD::WorkMatrixType& work_matrix, SVD& svd, Index p, Index q) { using std::sqrt; Scalar z; JacobiRotation<Scalar> rot; RealScalar n = sqrt(numext::abs2(work_matrix.coeff(p,p)) + numext::abs2(work_matrix.coeff(q,p))); if(n==0) { z = abs(work_matrix.coeff(p,q)) / work_matrix.coeff(p,q); work_matrix.row(p) *= z; if(svd.computeU()) svd.m_matrixU.col(p) *= conj(z); if(work_matrix.coeff(q,q)!=Scalar(0)) { z = abs(work_matrix.coeff(q,q)) / work_matrix.coeff(q,q); work_matrix.row(q) *= z; if(svd.computeU()) svd.m_matrixU.col(q) *= conj(z); } // otherwise the second row is already zero, so we have nothing to do. } else { rot.c() = conj(work_matrix.coeff(p,p)) / n; rot.s() = work_matrix.coeff(q,p) / n; work_matrix.applyOnTheLeft(p,q,rot); if(svd.computeU()) svd.m_matrixU.applyOnTheRight(p,q,rot.adjoint()); if(work_matrix.coeff(p,q) != Scalar(0)) { Scalar z = abs(work_matrix.coeff(p,q)) / work_matrix.coeff(p,q); work_matrix.col(q) *= z; if(svd.computeV()) svd.m_matrixV.col(q) *= z; } if(work_matrix.coeff(q,q) != Scalar(0)) { z = abs(work_matrix.coeff(q,q)) / work_matrix.coeff(q,q); work_matrix.row(q) *= z; if(svd.computeU()) svd.m_matrixU.col(q) *= conj(z); } } } }; template<typename MatrixType, typename RealScalar, typename Index> void real_2x2_jacobi_svd(const MatrixType& matrix, Index p, Index q, JacobiRotation<RealScalar> *j_left, JacobiRotation<RealScalar> *j_right) { using std::sqrt; using std::abs; Matrix<RealScalar,2,2> m; m << numext::real(matrix.coeff(p,p)), numext::real(matrix.coeff(p,q)), numext::real(matrix.coeff(q,p)), numext::real(matrix.coeff(q,q)); JacobiRotation<RealScalar> rot1; RealScalar t = m.coeff(0,0) + m.coeff(1,1); RealScalar d = m.coeff(1,0) - m.coeff(0,1); if(t == RealScalar(0)) { rot1.c() = RealScalar(0); rot1.s() = d > RealScalar(0) ? RealScalar(1) : RealScalar(-1); } else { RealScalar t2d2 = numext::hypot(t,d); rot1.c() = abs(t)/t2d2; rot1.s() = d/t2d2; if(t<RealScalar(0)) rot1.s() = -rot1.s(); } m.applyOnTheLeft(0,1,rot1); j_right->makeJacobi(m,0,1); *j_left = rot1 * j_right->transpose(); } } // end namespace internal /** \ingroup SVD_Module * * * \class JacobiSVD * * \brief Two-sided Jacobi SVD decomposition of a rectangular matrix * * \param MatrixType the type of the matrix of which we are computing the SVD decomposition * \param QRPreconditioner this optional parameter allows to specify the type of QR decomposition that will be used internally * for the R-SVD step for non-square matrices. See discussion of possible values below. * * SVD decomposition consists in decomposing any n-by-p matrix \a A as a product * \f[ A = U S V^* \f] * where \a U is a n-by-n unitary, \a V is a p-by-p unitary, and \a S is a n-by-p real positive matrix which is zero outside of its main diagonal; * the diagonal entries of S are known as the \em singular \em values of \a A and the columns of \a U and \a V are known as the left * and right \em singular \em vectors of \a A respectively. * * Singular values are always sorted in decreasing order. * * This JacobiSVD decomposition computes only the singular values by default. If you want \a U or \a V, you need to ask for them explicitly. * * You can ask for only \em thin \a U or \a V to be computed, meaning the following. In case of a rectangular n-by-p matrix, letting \a m be the * smaller value among \a n and \a p, there are only \a m singular vectors; the remaining columns of \a U and \a V do not correspond to actual * singular vectors. Asking for \em thin \a U or \a V means asking for only their \a m first columns to be formed. So \a U is then a n-by-m matrix, * and \a V is then a p-by-m matrix. Notice that thin \a U and \a V are all you need for (least squares) solving. * * Here's an example demonstrating basic usage: * \include JacobiSVD_basic.cpp * Output: \verbinclude JacobiSVD_basic.out * * This JacobiSVD class is a two-sided Jacobi R-SVD decomposition, ensuring optimal reliability and accuracy. The downside is that it's slower than * bidiagonalizing SVD algorithms for large square matrices; however its complexity is still \f$ O(n^2p) \f$ where \a n is the smaller dimension and * \a p is the greater dimension, meaning that it is still of the same order of complexity as the faster bidiagonalizing R-SVD algorithms. * In particular, like any R-SVD, it takes advantage of non-squareness in that its complexity is only linear in the greater dimension. * * If the input matrix has inf or nan coefficients, the result of the computation is undefined, but the computation is guaranteed to * terminate in finite (and reasonable) time. * * The possible values for QRPreconditioner are: * \li ColPivHouseholderQRPreconditioner is the default. In practice it's very safe. It uses column-pivoting QR. * \li FullPivHouseholderQRPreconditioner, is the safest and slowest. It uses full-pivoting QR. * Contrary to other QRs, it doesn't allow computing thin unitaries. * \li HouseholderQRPreconditioner is the fastest, and less safe and accurate than the pivoting variants. It uses non-pivoting QR. * This is very similar in safety and accuracy to the bidiagonalization process used by bidiagonalizing SVD algorithms (since bidiagonalization * is inherently non-pivoting). However the resulting SVD is still more reliable than bidiagonalizing SVDs because the Jacobi-based iterarive * process is more reliable than the optimized bidiagonal SVD iterations. * \li NoQRPreconditioner allows not to use a QR preconditioner at all. This is useful if you know that you will only be computing * JacobiSVD decompositions of square matrices. Non-square matrices require a QR preconditioner. Using this option will result in * faster compilation and smaller executable code. It won't significantly speed up computation, since JacobiSVD is always checking * if QR preconditioning is needed before applying it anyway. * * \sa MatrixBase::jacobiSvd() */ template<typename _MatrixType, int QRPreconditioner> class JacobiSVD { public: typedef _MatrixType MatrixType; typedef typename MatrixType::Scalar Scalar; typedef typename NumTraits<typename MatrixType::Scalar>::Real RealScalar; typedef typename MatrixType::Index Index; enum { RowsAtCompileTime = MatrixType::RowsAtCompileTime, ColsAtCompileTime = MatrixType::ColsAtCompileTime, DiagSizeAtCompileTime = EIGEN_SIZE_MIN_PREFER_DYNAMIC(RowsAtCompileTime,ColsAtCompileTime), MaxRowsAtCompileTime = MatrixType::MaxRowsAtCompileTime, MaxColsAtCompileTime = MatrixType::MaxColsAtCompileTime, MaxDiagSizeAtCompileTime = EIGEN_SIZE_MIN_PREFER_FIXED(MaxRowsAtCompileTime,MaxColsAtCompileTime), MatrixOptions = MatrixType::Options }; typedef Matrix<Scalar, RowsAtCompileTime, RowsAtCompileTime, MatrixOptions, MaxRowsAtCompileTime, MaxRowsAtCompileTime> MatrixUType; typedef Matrix<Scalar, ColsAtCompileTime, ColsAtCompileTime, MatrixOptions, MaxColsAtCompileTime, MaxColsAtCompileTime> MatrixVType; typedef typename internal::plain_diag_type<MatrixType, RealScalar>::type SingularValuesType; typedef typename internal::plain_row_type<MatrixType>::type RowType; typedef typename internal::plain_col_type<MatrixType>::type ColType; typedef Matrix<Scalar, DiagSizeAtCompileTime, DiagSizeAtCompileTime, MatrixOptions, MaxDiagSizeAtCompileTime, MaxDiagSizeAtCompileTime> WorkMatrixType; /** \brief Default Constructor. * * The default constructor is useful in cases in which the user intends to * perform decompositions via JacobiSVD::compute(const MatrixType&). */ JacobiSVD() : m_isInitialized(false), m_isAllocated(false), m_usePrescribedThreshold(false), m_computationOptions(0), m_rows(-1), m_cols(-1), m_diagSize(0) {} /** \brief Default Constructor with memory preallocation * * Like the default constructor but with preallocation of the internal data * according to the specified problem size. * \sa JacobiSVD() */ JacobiSVD(Index rows, Index cols, unsigned int computationOptions = 0) : m_isInitialized(false), m_isAllocated(false), m_usePrescribedThreshold(false), m_computationOptions(0), m_rows(-1), m_cols(-1) { allocate(rows, cols, computationOptions); } /** \brief Constructor performing the decomposition of given matrix. * * \param matrix the matrix to decompose * \param computationOptions optional parameter allowing to specify if you want full or thin U or V unitaries to be computed. * By default, none is computed. This is a bit-field, the possible bits are #ComputeFullU, #ComputeThinU, * #ComputeFullV, #ComputeThinV. * * Thin unitaries are only available if your matrix type has a Dynamic number of columns (for example MatrixXf). They also are not * available with the (non-default) FullPivHouseholderQR preconditioner. */ JacobiSVD(const MatrixType& matrix, unsigned int computationOptions = 0) : m_isInitialized(false), m_isAllocated(false), m_usePrescribedThreshold(false), m_computationOptions(0), m_rows(-1), m_cols(-1) { compute(matrix, computationOptions); } /** \brief Method performing the decomposition of given matrix using custom options. * * \param matrix the matrix to decompose * \param computationOptions optional parameter allowing to specify if you want full or thin U or V unitaries to be computed. * By default, none is computed. This is a bit-field, the possible bits are #ComputeFullU, #ComputeThinU, * #ComputeFullV, #ComputeThinV. * * Thin unitaries are only available if your matrix type has a Dynamic number of columns (for example MatrixXf). They also are not * available with the (non-default) FullPivHouseholderQR preconditioner. */ JacobiSVD& compute(const MatrixType& matrix, unsigned int computationOptions); /** \brief Method performing the decomposition of given matrix using current options. * * \param matrix the matrix to decompose * * This method uses the current \a computationOptions, as already passed to the constructor or to compute(const MatrixType&, unsigned int). */ JacobiSVD& compute(const MatrixType& matrix) { return compute(matrix, m_computationOptions); } /** \returns the \a U matrix. * * For the SVD decomposition of a n-by-p matrix, letting \a m be the minimum of \a n and \a p, * the U matrix is n-by-n if you asked for #ComputeFullU, and is n-by-m if you asked for #ComputeThinU. * * The \a m first columns of \a U are the left singular vectors of the matrix being decomposed. * * This method asserts that you asked for \a U to be computed. */ const MatrixUType& matrixU() const { eigen_assert(m_isInitialized && "JacobiSVD is not initialized."); eigen_assert(computeU() && "This JacobiSVD decomposition didn't compute U. Did you ask for it?"); return m_matrixU; } /** \returns the \a V matrix. * * For the SVD decomposition of a n-by-p matrix, letting \a m be the minimum of \a n and \a p, * the V matrix is p-by-p if you asked for #ComputeFullV, and is p-by-m if you asked for ComputeThinV. * * The \a m first columns of \a V are the right singular vectors of the matrix being decomposed. * * This method asserts that you asked for \a V to be computed. */ const MatrixVType& matrixV() const { eigen_assert(m_isInitialized && "JacobiSVD is not initialized."); eigen_assert(computeV() && "This JacobiSVD decomposition didn't compute V. Did you ask for it?"); return m_matrixV; } /** \returns the vector of singular values. * * For the SVD decomposition of a n-by-p matrix, letting \a m be the minimum of \a n and \a p, the * returned vector has size \a m. Singular values are always sorted in decreasing order. */ const SingularValuesType& singularValues() const { eigen_assert(m_isInitialized && "JacobiSVD is not initialized."); return m_singularValues; } /** \returns true if \a U (full or thin) is asked for in this SVD decomposition */ inline bool computeU() const { return m_computeFullU || m_computeThinU; } /** \returns true if \a V (full or thin) is asked for in this SVD decomposition */ inline bool computeV() const { return m_computeFullV || m_computeThinV; } /** \returns a (least squares) solution of \f$ A x = b \f$ using the current SVD decomposition of A. * * \param b the right-hand-side of the equation to solve. * * \note Solving requires both U and V to be computed. Thin U and V are enough, there is no need for full U or V. * * \note SVD solving is implicitly least-squares. Thus, this method serves both purposes of exact solving and least-squares solving. * In other words, the returned solution is guaranteed to minimize the Euclidean norm \f$ \Vert A x - b \Vert \f$. */ template<typename Rhs> inline const internal::solve_retval<JacobiSVD, Rhs> solve(const MatrixBase<Rhs>& b) const { eigen_assert(m_isInitialized && "JacobiSVD is not initialized."); eigen_assert(computeU() && computeV() && "JacobiSVD::solve() requires both unitaries U and V to be computed (thin unitaries suffice)."); return internal::solve_retval<JacobiSVD, Rhs>(*this, b.derived()); } /** \returns the number of singular values that are not exactly 0 */ Index nonzeroSingularValues() const { eigen_assert(m_isInitialized && "JacobiSVD is not initialized."); return m_nonzeroSingularValues; } /** \returns the rank of the matrix of which \c *this is the SVD. * * \note This method has to determine which singular values should be considered nonzero. * For that, it uses the threshold value that you can control by calling * setThreshold(const RealScalar&). */ inline Index rank() const { using std::abs; eigen_assert(m_isInitialized && "JacobiSVD is not initialized."); if(m_singularValues.size()==0) return 0; RealScalar premultiplied_threshold = m_singularValues.coeff(0) * threshold(); Index i = m_nonzeroSingularValues-1; while(i>=0 && m_singularValues.coeff(i) < premultiplied_threshold) --i; return i+1; } /** Allows to prescribe a threshold to be used by certain methods, such as rank() and solve(), * which need to determine when singular values are to be considered nonzero. * This is not used for the SVD decomposition itself. * * When it needs to get the threshold value, Eigen calls threshold(). * The default is \c NumTraits<Scalar>::epsilon() * * \param threshold The new value to use as the threshold. * * A singular value will be considered nonzero if its value is strictly greater than * \f$ \vert singular value \vert \leqslant threshold \times \vert max singular value \vert \f$. * * If you want to come back to the default behavior, call setThreshold(Default_t) */ JacobiSVD& setThreshold(const RealScalar& threshold) { m_usePrescribedThreshold = true; m_prescribedThreshold = threshold; return *this; } /** Allows to come back to the default behavior, letting Eigen use its default formula for * determining the threshold. * * You should pass the special object Eigen::Default as parameter here. * \code svd.setThreshold(Eigen::Default); \endcode * * See the documentation of setThreshold(const RealScalar&). */ JacobiSVD& setThreshold(Default_t) { m_usePrescribedThreshold = false; return *this; } /** Returns the threshold that will be used by certain methods such as rank(). * * See the documentation of setThreshold(const RealScalar&). */ RealScalar threshold() const { eigen_assert(m_isInitialized || m_usePrescribedThreshold); return m_usePrescribedThreshold ? m_prescribedThreshold : (std::max<Index>)(1,m_diagSize)*NumTraits<Scalar>::epsilon(); } inline Index rows() const { return m_rows; } inline Index cols() const { return m_cols; } private: void allocate(Index rows, Index cols, unsigned int computationOptions); protected: MatrixUType m_matrixU; MatrixVType m_matrixV; SingularValuesType m_singularValues; WorkMatrixType m_workMatrix; bool m_isInitialized, m_isAllocated, m_usePrescribedThreshold; bool m_computeFullU, m_computeThinU; bool m_computeFullV, m_computeThinV; unsigned int m_computationOptions; Index m_nonzeroSingularValues, m_rows, m_cols, m_diagSize; RealScalar m_prescribedThreshold; template<typename __MatrixType, int _QRPreconditioner, bool _IsComplex> friend struct internal::svd_precondition_2x2_block_to_be_real; template<typename __MatrixType, int _QRPreconditioner, int _Case, bool _DoAnything> friend struct internal::qr_preconditioner_impl; internal::qr_preconditioner_impl<MatrixType, QRPreconditioner, internal::PreconditionIfMoreColsThanRows> m_qr_precond_morecols; internal::qr_preconditioner_impl<MatrixType, QRPreconditioner, internal::PreconditionIfMoreRowsThanCols> m_qr_precond_morerows; MatrixType m_scaledMatrix; }; template<typename MatrixType, int QRPreconditioner> void JacobiSVD<MatrixType, QRPreconditioner>::allocate(Index rows, Index cols, unsigned int computationOptions) { eigen_assert(rows >= 0 && cols >= 0); if (m_isAllocated && rows == m_rows && cols == m_cols && computationOptions == m_computationOptions) { return; } m_rows = rows; m_cols = cols; m_isInitialized = false; m_isAllocated = true; m_computationOptions = computationOptions; m_computeFullU = (computationOptions & ComputeFullU) != 0; m_computeThinU = (computationOptions & ComputeThinU) != 0; m_computeFullV = (computationOptions & ComputeFullV) != 0; m_computeThinV = (computationOptions & ComputeThinV) != 0; eigen_assert(!(m_computeFullU && m_computeThinU) && "JacobiSVD: you can't ask for both full and thin U"); eigen_assert(!(m_computeFullV && m_computeThinV) && "JacobiSVD: you can't ask for both full and thin V"); eigen_assert(EIGEN_IMPLIES(m_computeThinU || m_computeThinV, MatrixType::ColsAtCompileTime==Dynamic) && "JacobiSVD: thin U and V are only available when your matrix has a dynamic number of columns."); if (QRPreconditioner == FullPivHouseholderQRPreconditioner) { eigen_assert(!(m_computeThinU || m_computeThinV) && "JacobiSVD: can't compute thin U or thin V with the FullPivHouseholderQR preconditioner. " "Use the ColPivHouseholderQR preconditioner instead."); } m_diagSize = (std::min)(m_rows, m_cols); m_singularValues.resize(m_diagSize); if(RowsAtCompileTime==Dynamic) m_matrixU.resize(m_rows, m_computeFullU ? m_rows : m_computeThinU ? m_diagSize : 0); if(ColsAtCompileTime==Dynamic) m_matrixV.resize(m_cols, m_computeFullV ? m_cols : m_computeThinV ? m_diagSize : 0); m_workMatrix.resize(m_diagSize, m_diagSize); if(m_cols>m_rows) m_qr_precond_morecols.allocate(*this); if(m_rows>m_cols) m_qr_precond_morerows.allocate(*this); if(m_cols!=m_cols) m_scaledMatrix.resize(rows,cols); } template<typename MatrixType, int QRPreconditioner> JacobiSVD<MatrixType, QRPreconditioner>& JacobiSVD<MatrixType, QRPreconditioner>::compute(const MatrixType& matrix, unsigned int computationOptions) { using std::abs; allocate(matrix.rows(), matrix.cols(), computationOptions); // currently we stop when we reach precision 2*epsilon as the last bit of precision can require an unreasonable number of iterations, // only worsening the precision of U and V as we accumulate more rotations const RealScalar precision = RealScalar(2) * NumTraits<Scalar>::epsilon(); // limit for very small denormal numbers to be considered zero in order to avoid infinite loops (see bug 286) const RealScalar considerAsZero = RealScalar(2) * std::numeric_limits<RealScalar>::denorm_min(); // Scaling factor to reduce over/under-flows RealScalar scale = matrix.cwiseAbs().maxCoeff(); if(scale==RealScalar(0)) scale = RealScalar(1); /*** step 1. The R-SVD step: we use a QR decomposition to reduce to the case of a square matrix */ if(m_rows!=m_cols) { m_scaledMatrix = matrix / scale; m_qr_precond_morecols.run(*this, m_scaledMatrix); m_qr_precond_morerows.run(*this, m_scaledMatrix); } else { m_workMatrix = matrix.block(0,0,m_diagSize,m_diagSize) / scale; if(m_computeFullU) m_matrixU.setIdentity(m_rows,m_rows); if(m_computeThinU) m_matrixU.setIdentity(m_rows,m_diagSize); if(m_computeFullV) m_matrixV.setIdentity(m_cols,m_cols); if(m_computeThinV) m_matrixV.setIdentity(m_cols, m_diagSize); } /*** step 2. The main Jacobi SVD iteration. ***/ bool finished = false; while(!finished) { finished = true; // do a sweep: for all index pairs (p,q), perform SVD of the corresponding 2x2 sub-matrix for(Index p = 1; p < m_diagSize; ++p) { for(Index q = 0; q < p; ++q) { // if this 2x2 sub-matrix is not diagonal already... // notice that this comparison will evaluate to false if any NaN is involved, ensuring that NaN's don't // keep us iterating forever. Similarly, small denormal numbers are considered zero. using std::max; RealScalar threshold = (max)(considerAsZero, precision * (max)(abs(m_workMatrix.coeff(p,p)), abs(m_workMatrix.coeff(q,q)))); // We compare both values to threshold instead of calling max to be robust to NaN (See bug 791) if(abs(m_workMatrix.coeff(p,q))>threshold || abs(m_workMatrix.coeff(q,p)) > threshold) { finished = false; // perform SVD decomposition of 2x2 sub-matrix corresponding to indices p,q to make it diagonal internal::svd_precondition_2x2_block_to_be_real<MatrixType, QRPreconditioner>::run(m_workMatrix, *this, p, q); JacobiRotation<RealScalar> j_left, j_right; internal::real_2x2_jacobi_svd(m_workMatrix, p, q, &j_left, &j_right); // accumulate resulting Jacobi rotations m_workMatrix.applyOnTheLeft(p,q,j_left); if(computeU()) m_matrixU.applyOnTheRight(p,q,j_left.transpose()); m_workMatrix.applyOnTheRight(p,q,j_right); if(computeV()) m_matrixV.applyOnTheRight(p,q,j_right); } } } } /*** step 3. The work matrix is now diagonal, so ensure it's positive so its diagonal entries are the singular values ***/ for(Index i = 0; i < m_diagSize; ++i) { RealScalar a = abs(m_workMatrix.coeff(i,i)); m_singularValues.coeffRef(i) = a; if(computeU() && (a!=RealScalar(0))) m_matrixU.col(i) *= m_workMatrix.coeff(i,i)/a; } /*** step 4. Sort singular values in descending order and compute the number of nonzero singular values ***/ m_nonzeroSingularValues = m_diagSize; for(Index i = 0; i < m_diagSize; i++) { Index pos; RealScalar maxRemainingSingularValue = m_singularValues.tail(m_diagSize-i).maxCoeff(&pos); if(maxRemainingSingularValue == RealScalar(0)) { m_nonzeroSingularValues = i; break; } if(pos) { pos += i; std::swap(m_singularValues.coeffRef(i), m_singularValues.coeffRef(pos)); if(computeU()) m_matrixU.col(pos).swap(m_matrixU.col(i)); if(computeV()) m_matrixV.col(pos).swap(m_matrixV.col(i)); } } m_singularValues *= scale; m_isInitialized = true; return *this; } namespace internal { template<typename _MatrixType, int QRPreconditioner, typename Rhs> struct solve_retval<JacobiSVD<_MatrixType, QRPreconditioner>, Rhs> : solve_retval_base<JacobiSVD<_MatrixType, QRPreconditioner>, Rhs> { typedef JacobiSVD<_MatrixType, QRPreconditioner> JacobiSVDType; EIGEN_MAKE_SOLVE_HELPERS(JacobiSVDType,Rhs) template<typename Dest> void evalTo(Dest& dst) const { eigen_assert(rhs().rows() == dec().rows()); // A = U S V^* // So A^{-1} = V S^{-1} U^* Matrix<Scalar, Dynamic, Rhs::ColsAtCompileTime, 0, _MatrixType::MaxRowsAtCompileTime, Rhs::MaxColsAtCompileTime> tmp; Index rank = dec().rank(); tmp.noalias() = dec().matrixU().leftCols(rank).adjoint() * rhs(); tmp = dec().singularValues().head(rank).asDiagonal().inverse() * tmp; dst = dec().matrixV().leftCols(rank) * tmp; } }; } // end namespace internal /** \svd_module * * \return the singular value decomposition of \c *this computed by two-sided * Jacobi transformations. * * \sa class JacobiSVD */ template<typename Derived> JacobiSVD<typename MatrixBase<Derived>::PlainObject> MatrixBase<Derived>::jacobiSvd(unsigned int computationOptions) const { return JacobiSVD<PlainObject>(*this, computationOptions); } } // end namespace Eigen #endif // EIGEN_JACOBISVD_H
35b0c13874ef83fab19814ffc96e8e7a477e2a21
7140284b28291629fff6b582534d268dab4092d1
/include/global.h
e4ad04f4c3b8fd86c4deda4773d7abfe6c189e19
[]
no_license
snakepass/catch_data
fa4ffed5b11cff77f5a60d9ab8cc57ad60f01e51
aed51196fbc25240ab9bc35f2bcfa31357b0d5b5
refs/heads/master
2021-01-25T07:28:57.505851
2014-04-28T06:24:12
2014-04-28T06:24:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
621
h
// global.h: #ifndef VS_GLOBAL_H_ #define VS_GLOBAL_H_ #include <map> #include <vector> #include <string> #include <linux/if_packet.h> char *g_interface = 0; char *g_back_interface = 0; // 是否需要送回数据包 char *g_bpf = (char*)(""); char *g_conf = 0; // 配置文件,必须设置 char *g_cpu_profile = 0; int g_datalink_size = 14; int g_ip_len = 0; std::vector<std::map<std::string, std::string> > g_trust_ips; int g_ffmpeg_timeout; int g_back_fd; struct sockaddr_ll g_back_addr; const char *g_stream_proto_dict[] = {"todetect", "none", "udp", "rtp"}; bool g_debug = false; int g_enable_ts; #endif
[ "vobile@vobile-To-be-filled-by-O-E-M.(none)" ]
vobile@vobile-To-be-filled-by-O-E-M.(none)
7bf023cabb684833fb3b348f47be065447afb920
2af05703330b1349bdf815e9613cb03d5510f215
/cpplesson/reference/src/reference.cpp
8060d9ceb9044a3c36a90ca2736c5b351b66b441
[]
no_license
z10blog/c-plusplus
27270e02bcc3fa5d7f411da7d1108228c9b3f08e
909f2d7e19e67484bfb5da73db3411b29c469b33
refs/heads/master
2021-01-21T06:18:06.250299
2017-03-06T09:54:48
2017-03-06T09:54:48
83,203,201
0
0
null
null
null
null
UTF-8
C++
false
false
758
cpp
#include <iostream> using namespace::std; /* * 引用: 引用即别名,是为对象起了一个另外的名字 * 特点: * 1.定义引用时必须初始化 * 2.一旦定义,将不能重新绑定到另一个对象 * 3.引用智能绑定在对象上,而不能与字面值或某个表达式的计算结果绑定在一起。 * # 引用并非对象,相反的,它只是为一个已经存在的对象所起的另外一个名字。 */ int main(void) { /*int ival = 1024; int &refVal = ival; cout << "ival = " << ival << endl; cout << "refVal = " << refVal << endl; refVal = 0; cout << "refVal = " << refVal << endl; cout << "ival = " << ival << endl; */ int i, &ri = i; i = 5; ri = 10; cout << i << " " << ri << endl; return 0; }
7d685ae5bfbf59de685ae4ce2d53fe8a36a37b3b
573a66e4f4753cc0f145de8d60340b4dd6206607
/JS-CS-Detection-byExample/Dataset (ALERT 5 GB)/362855/quickfix-1.7.0/quickfix-1.7.0/src/C++/Initiator.cpp
f9cc8dec25d5e443a09760ab0d9958bbb7485258
[ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
mkaouer/Code-Smells-Detection-in-JavaScript
3919ec0d445637a7f7c5f570c724082d42248e1b
7130351703e19347884f95ce6d6ab1fb4f5cfbff
refs/heads/master
2023-03-09T18:04:26.971934
2022-03-23T22:04:28
2022-03-23T22:04:28
73,915,037
8
3
null
2023-02-28T23:00:07
2016-11-16T11:47:44
null
UTF-8
C++
false
false
6,611
cpp
/* ==================================================================== * The QuickFIX Software License, Version 1.0 * * Copyright (c) 2001 ThoughtWorks, Inc. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by * ThoughtWorks, Inc. (http://www.thoughtworks.com/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "QuickFIX" and "ThoughtWorks, Inc." must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "QuickFIX", * nor may "QuickFIX" appear in their name, without prior written * permission of ThoughtWorks, Inc. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THOUGHTWORKS INC OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== */ #ifdef _MSC_VER #include "stdafx.h" #else #include "config.h" #endif #include "CallStack.h" #include "Initiator.h" #include "Utility.h" #include "Session.h" #include "SessionFactory.h" #include <algorithm> #include <fstream> namespace FIX { Initiator::Initiator( Application& application, MessageStoreFactory& messageStoreFactory, const SessionSettings& settings ) throw( ConfigError& ) : m_threadid( 0 ), m_application( application ), m_messageStoreFactory( messageStoreFactory ), m_settings( settings ), m_pLogFactory( 0 ) { initialize(); } Initiator::Initiator( Application& application, MessageStoreFactory& messageStoreFactory, const SessionSettings& settings, LogFactory& logFactory ) throw( ConfigError& ) : m_threadid( 0 ), m_application( application ), m_messageStoreFactory( messageStoreFactory ), m_settings( settings ), m_pLogFactory( &logFactory ) { initialize(); } void Initiator::initialize() throw ( ConfigError& ) { QF_STACK_PUSH(Initiator::initialize) std::set < SessionID > sessions = m_settings.getSessions(); std::set < SessionID > ::iterator i; if ( !sessions.size() ) throw ConfigError( "No sessions defined" ); SessionFactory factory( m_application, m_messageStoreFactory, m_pLogFactory ); for ( i = sessions.begin(); i != sessions.end(); ++i ) { if ( m_settings.get( *i ).getString( "ConnectionType" ) == "initiator" ) { m_sessions[ *i ] = factory.create( *i, m_settings.get( *i ) ); setConnected( *i, false ); } } if ( !m_sessions.size() ) throw ConfigError( "No sessions defined for initiator" ); QF_STACK_POP } Initiator::~Initiator() { QF_STACK_IGNORE_BEGIN Sessions::iterator i; for ( i = m_sessions.begin(); i != m_sessions.end(); ++i ) delete i->second; QF_STACK_IGNORE_END } Session* Initiator::getSession( const SessionID& sessionID, Responder& responder ) { QF_STACK_PUSH(Initiator::getSession) Sessions::iterator i = m_sessions.find( sessionID ); if ( i != m_sessions.end() ) { i->second->setResponder( &responder ); return i->second; } return 0; QF_STACK_POP } void Initiator::connect() { QF_STACK_PUSH(Initiator::connect) SessionIDs disconnected = m_disconnected; SessionIDs::iterator i = disconnected.begin(); for ( ; i != disconnected.end(); ++i ) { Session* pSession = Session::lookupSession( *i ); if ( pSession->isSessionTime() ) setConnected( *i, doConnect( *i, m_settings.get( *i ) ) ); } QF_STACK_POP } void Initiator::setConnected( const SessionID& sessionID, bool connected ) { QF_STACK_PUSH(Initiator::setConnected) if ( connected ) { m_connected.insert( sessionID ); m_disconnected.erase( sessionID ); } else { m_disconnected.insert( sessionID ); m_connected.erase( sessionID ); } QF_STACK_POP } bool Initiator::isConnected( const SessionID& sessionID ) { QF_STACK_PUSH(Initiator::isConnected) return m_connected.find( sessionID ) != m_connected.end(); QF_STACK_POP } void Initiator::start() throw ( ConfigError&, RuntimeError& ) { QF_STACK_PUSH(Initiator::start) onConfigure( m_settings ); onInitialize( m_settings ); if( !thread_spawn( &startThread, this, m_threadid ) ) throw RuntimeError("Unable to spawn thread"); QF_STACK_POP } void Initiator::block() throw ( ConfigError&, RuntimeError& ) { QF_STACK_PUSH(Initiator::block) onConfigure( m_settings ); onInitialize( m_settings ); startThread(this); QF_STACK_POP } bool Initiator::poll() throw ( ConfigError&, RuntimeError& ) { QF_STACK_PUSH(Initiator::poll) if( m_firstPoll ) { onConfigure( m_settings ); onInitialize( m_settings ); m_firstPoll = false; } return onPoll(); QF_STACK_POP } void Initiator::stop() { QF_STACK_PUSH(Initiator::stop) if( !m_threadid ) return; onStop(); thread_join( m_threadid ); QF_STACK_POP } THREAD_PROC Initiator::startThread( void* p ) { QF_STACK_TRY QF_STACK_PUSH(Initiator::startThread) Initiator * pInitiator = static_cast < Initiator* > ( p ); pInitiator->onStart(); return 0; QF_STACK_POP QF_STACK_CATCH } }
19d2dee81efa5d07d061f825332ca55a11b61d80
8bbee45512e6bf827f38caa02d5d6643db186798
/lista ERE 4/2.cpp
c5f0f9e26924b7cf224d427691a2a8d6d94a50c5
[]
no_license
ohenriquesilvar/IALG---20-1
1bd35659ed539f12958c4bc21dcda390388b07d1
8dfba0e3a46100f3e3597e93b0918dfe520dc9fd
refs/heads/master
2022-12-25T14:48:00.960710
2020-09-10T13:08:36
2020-09-10T13:08:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
974
cpp
#include <iostream> #include <vector> using namespace std; void shell_sort(vector<int> vetor, vector<int> gaps) { int size = vetor.size(); int pos_gap = gaps.size() - 1; int aux = 0; aux++; while (gaps[pos_gap] > size) { pos_gap--; aux++; } int value; int j; aux++; while (pos_gap >= 0) { int gap = gaps[pos_gap]; aux++; for (int i = gap; i < size; i++) { value = vetor[i]; j = i; aux++; while ((j >= gap) and (value > vetor[j - gap])) { vetor[j] = vetor[j - gap]; j = j - gap; aux++; } vetor[j] = value; aux++; } pos_gap--; aux++; } cout << aux; } int main() { int qtde, gap; cin >> qtde; vector<int> vetor(qtde); for (int k = 0; k < qtde; k++) { cin >> vetor.at(k); } cin >> gap; vector<int> gaps(gap); for (int m = 0; m < gap; m++) { cin >> gaps.at(m); } shell_sort(vetor, gaps); return 0; }
76763a0dc2efbbc11f0e65ffd891ed1d8872e1b8
d2b8b0172ee1c0e0f9dfd9c552fe61c7c3a24aae
/dp/Strategy/Strategy.cpp
4a68bf6aab11ec959125a03b4b7417fbef53273c
[]
no_license
familymrfan/fanfei
b7cc47eedcadd55418ddc8f22c688d62922a81e3
c8fd4e8d35a01bacfae948f11a8671167c919aa1
refs/heads/master
2016-09-06T15:58:12.617690
2015-12-04T05:43:28
2015-12-04T05:43:28
7,419,359
0
0
null
null
null
null
UTF-8
C++
false
false
1,110
cpp
#include <iostream> using namespace std; class FlyBehavior { public: virtual void Fly() = 0; //pure virtual function }; class FlyBehavior0 : public FlyBehavior //can not fly { public: virtual void Fly() override { cout<<"I can not fly."<<endl; } }; class FlyBehavior1 : public FlyBehavior //fly: ^%^ { public: virtual void Fly() override { cout<<"I can fly with ^%^."<<endl; } }; class FlyBehavior2 : public FlyBehavior //fly: ^&^ { public: virtual void Fly() override { cout<<"I can fly with ^&^."<<endl; } }; class FlyBehavior3 : public FlyBehavior //fly: ^@^ { public: virtual void Fly() override { cout<<"I can fly with ^@^."<<endl; } }; class Duck { public: Duck(FlyBehavior *behavior) : behavior_(behavior) { } void Fly() { behavior_->Fly(); } private: FlyBehavior *behavior_; }; int main() { Duck duck1(new FlyBehavior0); Duck duck2(new FlyBehavior1); Duck duck3(new FlyBehavior2); Duck duck4(new FlyBehavior3); duck1.Fly(); duck2.Fly(); duck3.Fly(); duck4.Fly(); return 0; }
8515a1f7de8c3ff29fedc0d91ed59f4c92ce6f88
d899c8e5edcb95c614f22c53cbe8cadd452d1462
/codeforces/1284/B.cpp
47de0d2180e2346b8f2919ffeba26c39cf70626a
[]
no_license
calgagi/competitive_programming
b99d321690c811c29d8ef39025549a7fa58d9b00
9986779baaf3486e82391a2b8b2e5bec74f2df11
refs/heads/master
2021-07-05T23:52:14.457183
2020-08-13T06:44:21
2020-08-13T06:44:21
149,514,638
1
1
null
null
null
null
UTF-8
C++
false
false
1,294
cpp
// Calvin Gagliano // @calgagi // Oregon State University // Competitive Programming Template #include <bits/stdc++.h> using namespace std; int MX_i = 1e6 + 10; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); srand(chrono::steady_clock::now().time_since_epoch().count()); int n; cin >> n; vector<int> amx, ami; for (int i = 0; i < n; i++) { int sz; cin >> sz; int mi = INT_MAX, mx = INT_MIN, prev = INT_MAX; bool decreasing = true; for (int j = 0; j < sz; j++) { int s; cin >> s; mi = min(mi, s); mx = max(mx, s); if (prev < s) decreasing = false; prev = s; } if (decreasing) { ami.push_back(mi); amx.push_back(mx); } } sort(amx.begin(), amx.end()); long long ans = (n * 1LL * n); for (auto& minimum : ami) { int l = 0, r = amx.size()-1; int index = -1; while (l <= r) { int m = l + (r-l)/2; if (amx[m] <= minimum) { index = max(index, m); l = m+1; } else { r = m-1; } } ans -= index+1; } cout << ans << endl; return 0; }
2481ed2a4d865b55f2ed14595c07c7291013f23c
da49945efb639f996c18c52fdf7e4754e3305f05
/42-Imp-Small-factorials.cpp
4aed2274802e2b888e48859ee0de8a12058c28d6
[]
no_license
AdityaSinghShekhawat/CPP-spoj
ba140a8614f5900ac12f2f85c7010f8515076936
94f00dfd5e4000e75ebda3b2ead630452ff61a85
refs/heads/main
2023-02-23T23:27:28.478865
2021-01-19T12:32:52
2021-01-19T12:32:52
330,576,698
0
0
null
null
null
null
UTF-8
C++
false
false
1,011
cpp
#include <iostream> using namespace std; #define MAX 500 int multiply(int x, int res[], int res_size) { int carry = 0; // Initialize carry // One by one multiply n with individual digits of res[] for (int i = 0; i < res_size; i++) { int prod = res[i] * x + carry; // Store last digit of 'prod' in res[] res[i] = prod % 10; // Put rest in carry carry = prod / 10; } // Put carry in res and increase result size while (carry) { res[res_size] = carry % 10; carry = carry / 10; res_size++; } return res_size; } void fact(int n) { int res[MAX]; res[0] = 1; int res_size = 1; for (int x = 2; x <= n; x++) res_size = multiply(x, res, res_size); for (int i = res_size - 1; i >= 0; i--) cout << res[i]; } int main() { int t; cin >> t; for (int i = 0; i < t; i++) { int n; cin >> n; fact(n); cout << "\n"; } return 0; }
e530f1d9e7ceb37d7c7f6840bef464afd09c5b7e
834475cec2d606cc18e3f31dcdb160d33e032328
/06/DX12Tutorial2_06/Src/Animation.cpp
0b8b5e4af6ec0d1e2869180e65f4522777b2bd0a
[ "MIT" ]
permissive
tn-mai/DX12Tutorial2
803449f55084036928b7ef9827b3ee85b41bb043
340b74901680bb7f77b083401e2fc12638462289
refs/heads/master
2021-01-20T01:13:45.874361
2017-07-27T01:07:49
2017-07-27T01:07:49
89,241,111
1
0
null
null
null
null
SHIFT_JIS
C++
false
false
5,824
cpp
/** * @file Animation.cpp */ #include "Animation.h" #include "Json.h" #include <windows.h> #include <map> #include <vector> #include <string> /** * コンストラクタ. * * @param al 設定するアニメーションリスト. */ AnimationController::AnimationController(const AnimationList& al) : list(al) , seqIndex(0) , cellIndex(0) , time(0.0f) { } /** * アニメーションシーケンスのインデックスを設定する. * * @param idx 設定するシーケンスインデックス. */ void AnimationController::SetSeqIndex(uint32_t idx) { if (idx >= list.list.size()) { return; } seqIndex = idx; cellIndex = 0; time = 0.0f; } /** * アニメーションの状態を更新する. * * @param delta 経過時間. */ void AnimationController::Update(double delta) { if (seqIndex >= list.list.size() || list.list[seqIndex].empty()) { return; } time += delta; for (;;) { const float targetTime = list.list[seqIndex][cellIndex].time; if (targetTime <= 0.0f || time < targetTime) { break; } time -= targetTime; ++cellIndex; if (cellIndex >= list.list[seqIndex].size()) { cellIndex = 0; } } } /** * アニメーションデータを取得する. * * @return アニメーションデータ. */ const AnimationData& AnimationController::GetData() const { if (seqIndex >= list.list.size() || list.list[seqIndex].empty()) { static const AnimationData dummy{}; return dummy; } return list.list[seqIndex][cellIndex]; } /** * リスト内のアニメーションシーケンスの数を取得する. * * @return アニメーションシーケンスの数. */ size_t AnimationController::GetSeqCount() const { return list.list.size(); } /** * アニメーションが終了しているか調べる. * * @retval true 終了している. * @retval false 再生中. */ bool AnimationController::IsFinished() const { if (seqIndex >= list.list.size() || list.list[seqIndex].empty()) { return true; } return list.list[seqIndex][cellIndex].time < 0; } /** * ファイルからアニメーションリストを読み込む. * * @param list 読み込み先オブジェクト. * @param filename ファイル名. * * @retval true 読み込み成功. * @retval false 読み込み失敗. * * [ * { * "name" : animation list name string * "list" : * [ * [ * { * "cell" : cell index, * "time" : duration time, * "rotation" : rotation radian, * "scale" : [x, y], * "color" : [r, g, b, a] * }, * ... * ], * ... * ] * }, * ... * ] */ AnimationFile LoadAnimationFromJsonFile(const wchar_t* filename) { struct HandleHolder { explicit HandleHolder(HANDLE h) : handle(h) {} ~HandleHolder() { if (handle != INVALID_HANDLE_VALUE) { CloseHandle(handle); } } HANDLE handle; operator HANDLE() { return handle; } operator HANDLE() const { return handle; } }; HandleHolder h(CreateFileW(filename, GENERIC_READ, 0, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr)); if (h == INVALID_HANDLE_VALUE) { return {}; } LARGE_INTEGER size; if (!GetFileSizeEx(h, &size)) { return {}; } if (size.QuadPart > std::numeric_limits<size_t>::max()) { return {}; } std::vector<char> buffer; buffer.resize(static_cast<size_t>(size.QuadPart)); DWORD readBytes; if (!ReadFile(h, &buffer[0], buffer.size(), &readBytes, nullptr)) { return {}; } const Json::Result result = Json::Parse(buffer.data(), buffer.data() + buffer.size()); if (!result.error.empty()) { OutputDebugStringA(result.error.c_str()); return {}; } AnimationFile af; const Json::Array& json = result.value.AsArray(); for (const Json::Value& e : json) { const Json::Object& object = e.AsObject(); AnimationList al; const Json::Object::const_iterator itrName = object.find("name"); if (itrName != object.end()) { al.name = itrName->second.AsString(); } const Json::Object::const_iterator itrList = object.find("list"); if (itrList == object.end()) { break; } for (const Json::Value& seq : itrList->second.AsArray()) { AnimationSequence as; for (const Json::Value& data : seq.AsArray()) { const Json::Object& obj = data.AsObject(); AnimationData ad; ad.cellIndex = static_cast<uint32_t>(obj.find("cell")->second.AsNumber()); ad.time = static_cast<float>(obj.find("time")->second.AsNumber()); ad.rotation = static_cast<float>(obj.find("rotation")->second.AsNumber()); { auto itr = obj.find("scale"); if (itr == obj.end()) { return af; } const Json::Array& scale = itr->second.AsArray(); if (scale.size() < 2) { return af; } ad.scale.x = static_cast<float>(scale[0].AsNumber()); ad.scale.y = static_cast<float>(scale[1].AsNumber()); } { auto itr = obj.find("color"); if (itr == obj.end()) { return af; } const Json::Array& color = itr->second.AsArray(); if (color.size() < 4) { return af; } ad.color.x = static_cast<float>(color[0].AsNumber()); ad.color.y = static_cast<float>(color[1].AsNumber()); ad.color.z = static_cast<float>(color[2].AsNumber()); ad.color.w = static_cast<float>(color[3].AsNumber()); } as.push_back(ad); } al.list.push_back(as); } af.push_back(al); } return af; } /** * アニメーションリストを取得する. * * @return アニメーションリスト. */ const AnimationList& GetAnimationList() { static AnimationFile af; if (af.empty()) { af = LoadAnimationFromJsonFile(L"Res/Anm/Animation.json"); } return af[0]; }
f8b1ac2bf8dc8f4bd4538454c8596d45ad147cd7
3ff1fe3888e34cd3576d91319bf0f08ca955940f
/tione/src/v20211111/model/NotebookDetail.cpp
65ec1a9b738544d05f2b61ee45203281ab09df3c
[ "Apache-2.0" ]
permissive
TencentCloud/tencentcloud-sdk-cpp
9f5df8220eaaf72f7eaee07b2ede94f89313651f
42a76b812b81d1b52ec6a217fafc8faa135e06ca
refs/heads/master
2023-08-30T03:22:45.269556
2023-08-30T00:45:39
2023-08-30T00:45:39
188,991,963
55
37
Apache-2.0
2023-08-17T03:13:20
2019-05-28T08:56:08
C++
UTF-8
C++
false
false
42,127
cpp
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/tione/v20211111/model/NotebookDetail.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Tione::V20211111::Model; using namespace std; NotebookDetail::NotebookDetail() : m_idHasBeenSet(false), m_nameHasBeenSet(false), m_lifecycleScriptIdHasBeenSet(false), m_podNameHasBeenSet(false), m_updateTimeHasBeenSet(false), m_directInternetAccessHasBeenSet(false), m_resourceGroupIdHasBeenSet(false), m_tagsHasBeenSet(false), m_autoStoppingHasBeenSet(false), m_additionalCodeRepoIdsHasBeenSet(false), m_automaticStopTimeHasBeenSet(false), m_resourceConfHasBeenSet(false), m_defaultCodeRepoIdHasBeenSet(false), m_endTimeHasBeenSet(false), m_logEnableHasBeenSet(false), m_logConfigHasBeenSet(false), m_vpcIdHasBeenSet(false), m_subnetIdHasBeenSet(false), m_statusHasBeenSet(false), m_runtimeInSecondsHasBeenSet(false), m_createTimeHasBeenSet(false), m_startTimeHasBeenSet(false), m_chargeStatusHasBeenSet(false), m_rootAccessHasBeenSet(false), m_billingInfosHasBeenSet(false), m_volumeSizeInGBHasBeenSet(false), m_failureReasonHasBeenSet(false), m_chargeTypeHasBeenSet(false), m_instanceTypeAliasHasBeenSet(false), m_resourceGroupNameHasBeenSet(false), m_volumeSourceTypeHasBeenSet(false), m_volumeSourceCFSHasBeenSet(false), m_dataConfigsHasBeenSet(false), m_messageHasBeenSet(false), m_dataSourceHasBeenSet(false), m_imageInfoHasBeenSet(false), m_imageTypeHasBeenSet(false) { } CoreInternalOutcome NotebookDetail::Deserialize(const rapidjson::Value &value) { string requestId = ""; if (value.HasMember("Id") && !value["Id"].IsNull()) { if (!value["Id"].IsString()) { return CoreInternalOutcome(Core::Error("response `NotebookDetail.Id` IsString=false incorrectly").SetRequestId(requestId)); } m_id = string(value["Id"].GetString()); m_idHasBeenSet = true; } if (value.HasMember("Name") && !value["Name"].IsNull()) { if (!value["Name"].IsString()) { return CoreInternalOutcome(Core::Error("response `NotebookDetail.Name` IsString=false incorrectly").SetRequestId(requestId)); } m_name = string(value["Name"].GetString()); m_nameHasBeenSet = true; } if (value.HasMember("LifecycleScriptId") && !value["LifecycleScriptId"].IsNull()) { if (!value["LifecycleScriptId"].IsString()) { return CoreInternalOutcome(Core::Error("response `NotebookDetail.LifecycleScriptId` IsString=false incorrectly").SetRequestId(requestId)); } m_lifecycleScriptId = string(value["LifecycleScriptId"].GetString()); m_lifecycleScriptIdHasBeenSet = true; } if (value.HasMember("PodName") && !value["PodName"].IsNull()) { if (!value["PodName"].IsString()) { return CoreInternalOutcome(Core::Error("response `NotebookDetail.PodName` IsString=false incorrectly").SetRequestId(requestId)); } m_podName = string(value["PodName"].GetString()); m_podNameHasBeenSet = true; } if (value.HasMember("UpdateTime") && !value["UpdateTime"].IsNull()) { if (!value["UpdateTime"].IsString()) { return CoreInternalOutcome(Core::Error("response `NotebookDetail.UpdateTime` IsString=false incorrectly").SetRequestId(requestId)); } m_updateTime = string(value["UpdateTime"].GetString()); m_updateTimeHasBeenSet = true; } if (value.HasMember("DirectInternetAccess") && !value["DirectInternetAccess"].IsNull()) { if (!value["DirectInternetAccess"].IsBool()) { return CoreInternalOutcome(Core::Error("response `NotebookDetail.DirectInternetAccess` IsBool=false incorrectly").SetRequestId(requestId)); } m_directInternetAccess = value["DirectInternetAccess"].GetBool(); m_directInternetAccessHasBeenSet = true; } if (value.HasMember("ResourceGroupId") && !value["ResourceGroupId"].IsNull()) { if (!value["ResourceGroupId"].IsString()) { return CoreInternalOutcome(Core::Error("response `NotebookDetail.ResourceGroupId` IsString=false incorrectly").SetRequestId(requestId)); } m_resourceGroupId = string(value["ResourceGroupId"].GetString()); m_resourceGroupIdHasBeenSet = true; } if (value.HasMember("Tags") && !value["Tags"].IsNull()) { if (!value["Tags"].IsArray()) return CoreInternalOutcome(Core::Error("response `NotebookDetail.Tags` is not array type")); const rapidjson::Value &tmpValue = value["Tags"]; for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr) { Tag item; CoreInternalOutcome outcome = item.Deserialize(*itr); if (!outcome.IsSuccess()) { outcome.GetError().SetRequestId(requestId); return outcome; } m_tags.push_back(item); } m_tagsHasBeenSet = true; } if (value.HasMember("AutoStopping") && !value["AutoStopping"].IsNull()) { if (!value["AutoStopping"].IsBool()) { return CoreInternalOutcome(Core::Error("response `NotebookDetail.AutoStopping` IsBool=false incorrectly").SetRequestId(requestId)); } m_autoStopping = value["AutoStopping"].GetBool(); m_autoStoppingHasBeenSet = true; } if (value.HasMember("AdditionalCodeRepoIds") && !value["AdditionalCodeRepoIds"].IsNull()) { if (!value["AdditionalCodeRepoIds"].IsArray()) return CoreInternalOutcome(Core::Error("response `NotebookDetail.AdditionalCodeRepoIds` is not array type")); const rapidjson::Value &tmpValue = value["AdditionalCodeRepoIds"]; for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr) { m_additionalCodeRepoIds.push_back((*itr).GetString()); } m_additionalCodeRepoIdsHasBeenSet = true; } if (value.HasMember("AutomaticStopTime") && !value["AutomaticStopTime"].IsNull()) { if (!value["AutomaticStopTime"].IsInt64()) { return CoreInternalOutcome(Core::Error("response `NotebookDetail.AutomaticStopTime` IsInt64=false incorrectly").SetRequestId(requestId)); } m_automaticStopTime = value["AutomaticStopTime"].GetInt64(); m_automaticStopTimeHasBeenSet = true; } if (value.HasMember("ResourceConf") && !value["ResourceConf"].IsNull()) { if (!value["ResourceConf"].IsObject()) { return CoreInternalOutcome(Core::Error("response `NotebookDetail.ResourceConf` is not object type").SetRequestId(requestId)); } CoreInternalOutcome outcome = m_resourceConf.Deserialize(value["ResourceConf"]); if (!outcome.IsSuccess()) { outcome.GetError().SetRequestId(requestId); return outcome; } m_resourceConfHasBeenSet = true; } if (value.HasMember("DefaultCodeRepoId") && !value["DefaultCodeRepoId"].IsNull()) { if (!value["DefaultCodeRepoId"].IsString()) { return CoreInternalOutcome(Core::Error("response `NotebookDetail.DefaultCodeRepoId` IsString=false incorrectly").SetRequestId(requestId)); } m_defaultCodeRepoId = string(value["DefaultCodeRepoId"].GetString()); m_defaultCodeRepoIdHasBeenSet = true; } if (value.HasMember("EndTime") && !value["EndTime"].IsNull()) { if (!value["EndTime"].IsString()) { return CoreInternalOutcome(Core::Error("response `NotebookDetail.EndTime` IsString=false incorrectly").SetRequestId(requestId)); } m_endTime = string(value["EndTime"].GetString()); m_endTimeHasBeenSet = true; } if (value.HasMember("LogEnable") && !value["LogEnable"].IsNull()) { if (!value["LogEnable"].IsBool()) { return CoreInternalOutcome(Core::Error("response `NotebookDetail.LogEnable` IsBool=false incorrectly").SetRequestId(requestId)); } m_logEnable = value["LogEnable"].GetBool(); m_logEnableHasBeenSet = true; } if (value.HasMember("LogConfig") && !value["LogConfig"].IsNull()) { if (!value["LogConfig"].IsObject()) { return CoreInternalOutcome(Core::Error("response `NotebookDetail.LogConfig` is not object type").SetRequestId(requestId)); } CoreInternalOutcome outcome = m_logConfig.Deserialize(value["LogConfig"]); if (!outcome.IsSuccess()) { outcome.GetError().SetRequestId(requestId); return outcome; } m_logConfigHasBeenSet = true; } if (value.HasMember("VpcId") && !value["VpcId"].IsNull()) { if (!value["VpcId"].IsString()) { return CoreInternalOutcome(Core::Error("response `NotebookDetail.VpcId` IsString=false incorrectly").SetRequestId(requestId)); } m_vpcId = string(value["VpcId"].GetString()); m_vpcIdHasBeenSet = true; } if (value.HasMember("SubnetId") && !value["SubnetId"].IsNull()) { if (!value["SubnetId"].IsString()) { return CoreInternalOutcome(Core::Error("response `NotebookDetail.SubnetId` IsString=false incorrectly").SetRequestId(requestId)); } m_subnetId = string(value["SubnetId"].GetString()); m_subnetIdHasBeenSet = true; } if (value.HasMember("Status") && !value["Status"].IsNull()) { if (!value["Status"].IsString()) { return CoreInternalOutcome(Core::Error("response `NotebookDetail.Status` IsString=false incorrectly").SetRequestId(requestId)); } m_status = string(value["Status"].GetString()); m_statusHasBeenSet = true; } if (value.HasMember("RuntimeInSeconds") && !value["RuntimeInSeconds"].IsNull()) { if (!value["RuntimeInSeconds"].IsUint64()) { return CoreInternalOutcome(Core::Error("response `NotebookDetail.RuntimeInSeconds` IsUint64=false incorrectly").SetRequestId(requestId)); } m_runtimeInSeconds = value["RuntimeInSeconds"].GetUint64(); m_runtimeInSecondsHasBeenSet = true; } if (value.HasMember("CreateTime") && !value["CreateTime"].IsNull()) { if (!value["CreateTime"].IsString()) { return CoreInternalOutcome(Core::Error("response `NotebookDetail.CreateTime` IsString=false incorrectly").SetRequestId(requestId)); } m_createTime = string(value["CreateTime"].GetString()); m_createTimeHasBeenSet = true; } if (value.HasMember("StartTime") && !value["StartTime"].IsNull()) { if (!value["StartTime"].IsString()) { return CoreInternalOutcome(Core::Error("response `NotebookDetail.StartTime` IsString=false incorrectly").SetRequestId(requestId)); } m_startTime = string(value["StartTime"].GetString()); m_startTimeHasBeenSet = true; } if (value.HasMember("ChargeStatus") && !value["ChargeStatus"].IsNull()) { if (!value["ChargeStatus"].IsString()) { return CoreInternalOutcome(Core::Error("response `NotebookDetail.ChargeStatus` IsString=false incorrectly").SetRequestId(requestId)); } m_chargeStatus = string(value["ChargeStatus"].GetString()); m_chargeStatusHasBeenSet = true; } if (value.HasMember("RootAccess") && !value["RootAccess"].IsNull()) { if (!value["RootAccess"].IsBool()) { return CoreInternalOutcome(Core::Error("response `NotebookDetail.RootAccess` IsBool=false incorrectly").SetRequestId(requestId)); } m_rootAccess = value["RootAccess"].GetBool(); m_rootAccessHasBeenSet = true; } if (value.HasMember("BillingInfos") && !value["BillingInfos"].IsNull()) { if (!value["BillingInfos"].IsArray()) return CoreInternalOutcome(Core::Error("response `NotebookDetail.BillingInfos` is not array type")); const rapidjson::Value &tmpValue = value["BillingInfos"]; for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr) { m_billingInfos.push_back((*itr).GetString()); } m_billingInfosHasBeenSet = true; } if (value.HasMember("VolumeSizeInGB") && !value["VolumeSizeInGB"].IsNull()) { if (!value["VolumeSizeInGB"].IsUint64()) { return CoreInternalOutcome(Core::Error("response `NotebookDetail.VolumeSizeInGB` IsUint64=false incorrectly").SetRequestId(requestId)); } m_volumeSizeInGB = value["VolumeSizeInGB"].GetUint64(); m_volumeSizeInGBHasBeenSet = true; } if (value.HasMember("FailureReason") && !value["FailureReason"].IsNull()) { if (!value["FailureReason"].IsString()) { return CoreInternalOutcome(Core::Error("response `NotebookDetail.FailureReason` IsString=false incorrectly").SetRequestId(requestId)); } m_failureReason = string(value["FailureReason"].GetString()); m_failureReasonHasBeenSet = true; } if (value.HasMember("ChargeType") && !value["ChargeType"].IsNull()) { if (!value["ChargeType"].IsString()) { return CoreInternalOutcome(Core::Error("response `NotebookDetail.ChargeType` IsString=false incorrectly").SetRequestId(requestId)); } m_chargeType = string(value["ChargeType"].GetString()); m_chargeTypeHasBeenSet = true; } if (value.HasMember("InstanceTypeAlias") && !value["InstanceTypeAlias"].IsNull()) { if (!value["InstanceTypeAlias"].IsString()) { return CoreInternalOutcome(Core::Error("response `NotebookDetail.InstanceTypeAlias` IsString=false incorrectly").SetRequestId(requestId)); } m_instanceTypeAlias = string(value["InstanceTypeAlias"].GetString()); m_instanceTypeAliasHasBeenSet = true; } if (value.HasMember("ResourceGroupName") && !value["ResourceGroupName"].IsNull()) { if (!value["ResourceGroupName"].IsString()) { return CoreInternalOutcome(Core::Error("response `NotebookDetail.ResourceGroupName` IsString=false incorrectly").SetRequestId(requestId)); } m_resourceGroupName = string(value["ResourceGroupName"].GetString()); m_resourceGroupNameHasBeenSet = true; } if (value.HasMember("VolumeSourceType") && !value["VolumeSourceType"].IsNull()) { if (!value["VolumeSourceType"].IsString()) { return CoreInternalOutcome(Core::Error("response `NotebookDetail.VolumeSourceType` IsString=false incorrectly").SetRequestId(requestId)); } m_volumeSourceType = string(value["VolumeSourceType"].GetString()); m_volumeSourceTypeHasBeenSet = true; } if (value.HasMember("VolumeSourceCFS") && !value["VolumeSourceCFS"].IsNull()) { if (!value["VolumeSourceCFS"].IsObject()) { return CoreInternalOutcome(Core::Error("response `NotebookDetail.VolumeSourceCFS` is not object type").SetRequestId(requestId)); } CoreInternalOutcome outcome = m_volumeSourceCFS.Deserialize(value["VolumeSourceCFS"]); if (!outcome.IsSuccess()) { outcome.GetError().SetRequestId(requestId); return outcome; } m_volumeSourceCFSHasBeenSet = true; } if (value.HasMember("DataConfigs") && !value["DataConfigs"].IsNull()) { if (!value["DataConfigs"].IsArray()) return CoreInternalOutcome(Core::Error("response `NotebookDetail.DataConfigs` is not array type")); const rapidjson::Value &tmpValue = value["DataConfigs"]; for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr) { DataConfig item; CoreInternalOutcome outcome = item.Deserialize(*itr); if (!outcome.IsSuccess()) { outcome.GetError().SetRequestId(requestId); return outcome; } m_dataConfigs.push_back(item); } m_dataConfigsHasBeenSet = true; } if (value.HasMember("Message") && !value["Message"].IsNull()) { if (!value["Message"].IsString()) { return CoreInternalOutcome(Core::Error("response `NotebookDetail.Message` IsString=false incorrectly").SetRequestId(requestId)); } m_message = string(value["Message"].GetString()); m_messageHasBeenSet = true; } if (value.HasMember("DataSource") && !value["DataSource"].IsNull()) { if (!value["DataSource"].IsString()) { return CoreInternalOutcome(Core::Error("response `NotebookDetail.DataSource` IsString=false incorrectly").SetRequestId(requestId)); } m_dataSource = string(value["DataSource"].GetString()); m_dataSourceHasBeenSet = true; } if (value.HasMember("ImageInfo") && !value["ImageInfo"].IsNull()) { if (!value["ImageInfo"].IsObject()) { return CoreInternalOutcome(Core::Error("response `NotebookDetail.ImageInfo` is not object type").SetRequestId(requestId)); } CoreInternalOutcome outcome = m_imageInfo.Deserialize(value["ImageInfo"]); if (!outcome.IsSuccess()) { outcome.GetError().SetRequestId(requestId); return outcome; } m_imageInfoHasBeenSet = true; } if (value.HasMember("ImageType") && !value["ImageType"].IsNull()) { if (!value["ImageType"].IsString()) { return CoreInternalOutcome(Core::Error("response `NotebookDetail.ImageType` IsString=false incorrectly").SetRequestId(requestId)); } m_imageType = string(value["ImageType"].GetString()); m_imageTypeHasBeenSet = true; } return CoreInternalOutcome(true); } void NotebookDetail::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const { if (m_idHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Id"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_id.c_str(), allocator).Move(), allocator); } if (m_nameHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Name"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_name.c_str(), allocator).Move(), allocator); } if (m_lifecycleScriptIdHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "LifecycleScriptId"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_lifecycleScriptId.c_str(), allocator).Move(), allocator); } if (m_podNameHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "PodName"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_podName.c_str(), allocator).Move(), allocator); } if (m_updateTimeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "UpdateTime"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_updateTime.c_str(), allocator).Move(), allocator); } if (m_directInternetAccessHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "DirectInternetAccess"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_directInternetAccess, allocator); } if (m_resourceGroupIdHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "ResourceGroupId"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_resourceGroupId.c_str(), allocator).Move(), allocator); } if (m_tagsHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Tags"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator); int i=0; for (auto itr = m_tags.begin(); itr != m_tags.end(); ++itr, ++i) { value[key.c_str()].PushBack(rapidjson::Value(rapidjson::kObjectType).Move(), allocator); (*itr).ToJsonObject(value[key.c_str()][i], allocator); } } if (m_autoStoppingHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "AutoStopping"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_autoStopping, allocator); } if (m_additionalCodeRepoIdsHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "AdditionalCodeRepoIds"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator); for (auto itr = m_additionalCodeRepoIds.begin(); itr != m_additionalCodeRepoIds.end(); ++itr) { value[key.c_str()].PushBack(rapidjson::Value().SetString((*itr).c_str(), allocator), allocator); } } if (m_automaticStopTimeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "AutomaticStopTime"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_automaticStopTime, allocator); } if (m_resourceConfHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "ResourceConf"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(rapidjson::kObjectType).Move(), allocator); m_resourceConf.ToJsonObject(value[key.c_str()], allocator); } if (m_defaultCodeRepoIdHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "DefaultCodeRepoId"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_defaultCodeRepoId.c_str(), allocator).Move(), allocator); } if (m_endTimeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "EndTime"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_endTime.c_str(), allocator).Move(), allocator); } if (m_logEnableHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "LogEnable"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_logEnable, allocator); } if (m_logConfigHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "LogConfig"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(rapidjson::kObjectType).Move(), allocator); m_logConfig.ToJsonObject(value[key.c_str()], allocator); } if (m_vpcIdHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "VpcId"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_vpcId.c_str(), allocator).Move(), allocator); } if (m_subnetIdHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "SubnetId"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_subnetId.c_str(), allocator).Move(), allocator); } if (m_statusHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Status"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_status.c_str(), allocator).Move(), allocator); } if (m_runtimeInSecondsHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "RuntimeInSeconds"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_runtimeInSeconds, allocator); } if (m_createTimeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "CreateTime"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_createTime.c_str(), allocator).Move(), allocator); } if (m_startTimeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "StartTime"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_startTime.c_str(), allocator).Move(), allocator); } if (m_chargeStatusHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "ChargeStatus"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_chargeStatus.c_str(), allocator).Move(), allocator); } if (m_rootAccessHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "RootAccess"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_rootAccess, allocator); } if (m_billingInfosHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "BillingInfos"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator); for (auto itr = m_billingInfos.begin(); itr != m_billingInfos.end(); ++itr) { value[key.c_str()].PushBack(rapidjson::Value().SetString((*itr).c_str(), allocator), allocator); } } if (m_volumeSizeInGBHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "VolumeSizeInGB"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_volumeSizeInGB, allocator); } if (m_failureReasonHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "FailureReason"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_failureReason.c_str(), allocator).Move(), allocator); } if (m_chargeTypeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "ChargeType"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_chargeType.c_str(), allocator).Move(), allocator); } if (m_instanceTypeAliasHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "InstanceTypeAlias"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_instanceTypeAlias.c_str(), allocator).Move(), allocator); } if (m_resourceGroupNameHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "ResourceGroupName"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_resourceGroupName.c_str(), allocator).Move(), allocator); } if (m_volumeSourceTypeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "VolumeSourceType"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_volumeSourceType.c_str(), allocator).Move(), allocator); } if (m_volumeSourceCFSHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "VolumeSourceCFS"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(rapidjson::kObjectType).Move(), allocator); m_volumeSourceCFS.ToJsonObject(value[key.c_str()], allocator); } if (m_dataConfigsHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "DataConfigs"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator); int i=0; for (auto itr = m_dataConfigs.begin(); itr != m_dataConfigs.end(); ++itr, ++i) { value[key.c_str()].PushBack(rapidjson::Value(rapidjson::kObjectType).Move(), allocator); (*itr).ToJsonObject(value[key.c_str()][i], allocator); } } if (m_messageHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Message"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_message.c_str(), allocator).Move(), allocator); } if (m_dataSourceHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "DataSource"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_dataSource.c_str(), allocator).Move(), allocator); } if (m_imageInfoHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "ImageInfo"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(rapidjson::kObjectType).Move(), allocator); m_imageInfo.ToJsonObject(value[key.c_str()], allocator); } if (m_imageTypeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "ImageType"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_imageType.c_str(), allocator).Move(), allocator); } } string NotebookDetail::GetId() const { return m_id; } void NotebookDetail::SetId(const string& _id) { m_id = _id; m_idHasBeenSet = true; } bool NotebookDetail::IdHasBeenSet() const { return m_idHasBeenSet; } string NotebookDetail::GetName() const { return m_name; } void NotebookDetail::SetName(const string& _name) { m_name = _name; m_nameHasBeenSet = true; } bool NotebookDetail::NameHasBeenSet() const { return m_nameHasBeenSet; } string NotebookDetail::GetLifecycleScriptId() const { return m_lifecycleScriptId; } void NotebookDetail::SetLifecycleScriptId(const string& _lifecycleScriptId) { m_lifecycleScriptId = _lifecycleScriptId; m_lifecycleScriptIdHasBeenSet = true; } bool NotebookDetail::LifecycleScriptIdHasBeenSet() const { return m_lifecycleScriptIdHasBeenSet; } string NotebookDetail::GetPodName() const { return m_podName; } void NotebookDetail::SetPodName(const string& _podName) { m_podName = _podName; m_podNameHasBeenSet = true; } bool NotebookDetail::PodNameHasBeenSet() const { return m_podNameHasBeenSet; } string NotebookDetail::GetUpdateTime() const { return m_updateTime; } void NotebookDetail::SetUpdateTime(const string& _updateTime) { m_updateTime = _updateTime; m_updateTimeHasBeenSet = true; } bool NotebookDetail::UpdateTimeHasBeenSet() const { return m_updateTimeHasBeenSet; } bool NotebookDetail::GetDirectInternetAccess() const { return m_directInternetAccess; } void NotebookDetail::SetDirectInternetAccess(const bool& _directInternetAccess) { m_directInternetAccess = _directInternetAccess; m_directInternetAccessHasBeenSet = true; } bool NotebookDetail::DirectInternetAccessHasBeenSet() const { return m_directInternetAccessHasBeenSet; } string NotebookDetail::GetResourceGroupId() const { return m_resourceGroupId; } void NotebookDetail::SetResourceGroupId(const string& _resourceGroupId) { m_resourceGroupId = _resourceGroupId; m_resourceGroupIdHasBeenSet = true; } bool NotebookDetail::ResourceGroupIdHasBeenSet() const { return m_resourceGroupIdHasBeenSet; } vector<Tag> NotebookDetail::GetTags() const { return m_tags; } void NotebookDetail::SetTags(const vector<Tag>& _tags) { m_tags = _tags; m_tagsHasBeenSet = true; } bool NotebookDetail::TagsHasBeenSet() const { return m_tagsHasBeenSet; } bool NotebookDetail::GetAutoStopping() const { return m_autoStopping; } void NotebookDetail::SetAutoStopping(const bool& _autoStopping) { m_autoStopping = _autoStopping; m_autoStoppingHasBeenSet = true; } bool NotebookDetail::AutoStoppingHasBeenSet() const { return m_autoStoppingHasBeenSet; } vector<string> NotebookDetail::GetAdditionalCodeRepoIds() const { return m_additionalCodeRepoIds; } void NotebookDetail::SetAdditionalCodeRepoIds(const vector<string>& _additionalCodeRepoIds) { m_additionalCodeRepoIds = _additionalCodeRepoIds; m_additionalCodeRepoIdsHasBeenSet = true; } bool NotebookDetail::AdditionalCodeRepoIdsHasBeenSet() const { return m_additionalCodeRepoIdsHasBeenSet; } int64_t NotebookDetail::GetAutomaticStopTime() const { return m_automaticStopTime; } void NotebookDetail::SetAutomaticStopTime(const int64_t& _automaticStopTime) { m_automaticStopTime = _automaticStopTime; m_automaticStopTimeHasBeenSet = true; } bool NotebookDetail::AutomaticStopTimeHasBeenSet() const { return m_automaticStopTimeHasBeenSet; } ResourceConf NotebookDetail::GetResourceConf() const { return m_resourceConf; } void NotebookDetail::SetResourceConf(const ResourceConf& _resourceConf) { m_resourceConf = _resourceConf; m_resourceConfHasBeenSet = true; } bool NotebookDetail::ResourceConfHasBeenSet() const { return m_resourceConfHasBeenSet; } string NotebookDetail::GetDefaultCodeRepoId() const { return m_defaultCodeRepoId; } void NotebookDetail::SetDefaultCodeRepoId(const string& _defaultCodeRepoId) { m_defaultCodeRepoId = _defaultCodeRepoId; m_defaultCodeRepoIdHasBeenSet = true; } bool NotebookDetail::DefaultCodeRepoIdHasBeenSet() const { return m_defaultCodeRepoIdHasBeenSet; } string NotebookDetail::GetEndTime() const { return m_endTime; } void NotebookDetail::SetEndTime(const string& _endTime) { m_endTime = _endTime; m_endTimeHasBeenSet = true; } bool NotebookDetail::EndTimeHasBeenSet() const { return m_endTimeHasBeenSet; } bool NotebookDetail::GetLogEnable() const { return m_logEnable; } void NotebookDetail::SetLogEnable(const bool& _logEnable) { m_logEnable = _logEnable; m_logEnableHasBeenSet = true; } bool NotebookDetail::LogEnableHasBeenSet() const { return m_logEnableHasBeenSet; } LogConfig NotebookDetail::GetLogConfig() const { return m_logConfig; } void NotebookDetail::SetLogConfig(const LogConfig& _logConfig) { m_logConfig = _logConfig; m_logConfigHasBeenSet = true; } bool NotebookDetail::LogConfigHasBeenSet() const { return m_logConfigHasBeenSet; } string NotebookDetail::GetVpcId() const { return m_vpcId; } void NotebookDetail::SetVpcId(const string& _vpcId) { m_vpcId = _vpcId; m_vpcIdHasBeenSet = true; } bool NotebookDetail::VpcIdHasBeenSet() const { return m_vpcIdHasBeenSet; } string NotebookDetail::GetSubnetId() const { return m_subnetId; } void NotebookDetail::SetSubnetId(const string& _subnetId) { m_subnetId = _subnetId; m_subnetIdHasBeenSet = true; } bool NotebookDetail::SubnetIdHasBeenSet() const { return m_subnetIdHasBeenSet; } string NotebookDetail::GetStatus() const { return m_status; } void NotebookDetail::SetStatus(const string& _status) { m_status = _status; m_statusHasBeenSet = true; } bool NotebookDetail::StatusHasBeenSet() const { return m_statusHasBeenSet; } uint64_t NotebookDetail::GetRuntimeInSeconds() const { return m_runtimeInSeconds; } void NotebookDetail::SetRuntimeInSeconds(const uint64_t& _runtimeInSeconds) { m_runtimeInSeconds = _runtimeInSeconds; m_runtimeInSecondsHasBeenSet = true; } bool NotebookDetail::RuntimeInSecondsHasBeenSet() const { return m_runtimeInSecondsHasBeenSet; } string NotebookDetail::GetCreateTime() const { return m_createTime; } void NotebookDetail::SetCreateTime(const string& _createTime) { m_createTime = _createTime; m_createTimeHasBeenSet = true; } bool NotebookDetail::CreateTimeHasBeenSet() const { return m_createTimeHasBeenSet; } string NotebookDetail::GetStartTime() const { return m_startTime; } void NotebookDetail::SetStartTime(const string& _startTime) { m_startTime = _startTime; m_startTimeHasBeenSet = true; } bool NotebookDetail::StartTimeHasBeenSet() const { return m_startTimeHasBeenSet; } string NotebookDetail::GetChargeStatus() const { return m_chargeStatus; } void NotebookDetail::SetChargeStatus(const string& _chargeStatus) { m_chargeStatus = _chargeStatus; m_chargeStatusHasBeenSet = true; } bool NotebookDetail::ChargeStatusHasBeenSet() const { return m_chargeStatusHasBeenSet; } bool NotebookDetail::GetRootAccess() const { return m_rootAccess; } void NotebookDetail::SetRootAccess(const bool& _rootAccess) { m_rootAccess = _rootAccess; m_rootAccessHasBeenSet = true; } bool NotebookDetail::RootAccessHasBeenSet() const { return m_rootAccessHasBeenSet; } vector<string> NotebookDetail::GetBillingInfos() const { return m_billingInfos; } void NotebookDetail::SetBillingInfos(const vector<string>& _billingInfos) { m_billingInfos = _billingInfos; m_billingInfosHasBeenSet = true; } bool NotebookDetail::BillingInfosHasBeenSet() const { return m_billingInfosHasBeenSet; } uint64_t NotebookDetail::GetVolumeSizeInGB() const { return m_volumeSizeInGB; } void NotebookDetail::SetVolumeSizeInGB(const uint64_t& _volumeSizeInGB) { m_volumeSizeInGB = _volumeSizeInGB; m_volumeSizeInGBHasBeenSet = true; } bool NotebookDetail::VolumeSizeInGBHasBeenSet() const { return m_volumeSizeInGBHasBeenSet; } string NotebookDetail::GetFailureReason() const { return m_failureReason; } void NotebookDetail::SetFailureReason(const string& _failureReason) { m_failureReason = _failureReason; m_failureReasonHasBeenSet = true; } bool NotebookDetail::FailureReasonHasBeenSet() const { return m_failureReasonHasBeenSet; } string NotebookDetail::GetChargeType() const { return m_chargeType; } void NotebookDetail::SetChargeType(const string& _chargeType) { m_chargeType = _chargeType; m_chargeTypeHasBeenSet = true; } bool NotebookDetail::ChargeTypeHasBeenSet() const { return m_chargeTypeHasBeenSet; } string NotebookDetail::GetInstanceTypeAlias() const { return m_instanceTypeAlias; } void NotebookDetail::SetInstanceTypeAlias(const string& _instanceTypeAlias) { m_instanceTypeAlias = _instanceTypeAlias; m_instanceTypeAliasHasBeenSet = true; } bool NotebookDetail::InstanceTypeAliasHasBeenSet() const { return m_instanceTypeAliasHasBeenSet; } string NotebookDetail::GetResourceGroupName() const { return m_resourceGroupName; } void NotebookDetail::SetResourceGroupName(const string& _resourceGroupName) { m_resourceGroupName = _resourceGroupName; m_resourceGroupNameHasBeenSet = true; } bool NotebookDetail::ResourceGroupNameHasBeenSet() const { return m_resourceGroupNameHasBeenSet; } string NotebookDetail::GetVolumeSourceType() const { return m_volumeSourceType; } void NotebookDetail::SetVolumeSourceType(const string& _volumeSourceType) { m_volumeSourceType = _volumeSourceType; m_volumeSourceTypeHasBeenSet = true; } bool NotebookDetail::VolumeSourceTypeHasBeenSet() const { return m_volumeSourceTypeHasBeenSet; } CFSConfig NotebookDetail::GetVolumeSourceCFS() const { return m_volumeSourceCFS; } void NotebookDetail::SetVolumeSourceCFS(const CFSConfig& _volumeSourceCFS) { m_volumeSourceCFS = _volumeSourceCFS; m_volumeSourceCFSHasBeenSet = true; } bool NotebookDetail::VolumeSourceCFSHasBeenSet() const { return m_volumeSourceCFSHasBeenSet; } vector<DataConfig> NotebookDetail::GetDataConfigs() const { return m_dataConfigs; } void NotebookDetail::SetDataConfigs(const vector<DataConfig>& _dataConfigs) { m_dataConfigs = _dataConfigs; m_dataConfigsHasBeenSet = true; } bool NotebookDetail::DataConfigsHasBeenSet() const { return m_dataConfigsHasBeenSet; } string NotebookDetail::GetMessage() const { return m_message; } void NotebookDetail::SetMessage(const string& _message) { m_message = _message; m_messageHasBeenSet = true; } bool NotebookDetail::MessageHasBeenSet() const { return m_messageHasBeenSet; } string NotebookDetail::GetDataSource() const { return m_dataSource; } void NotebookDetail::SetDataSource(const string& _dataSource) { m_dataSource = _dataSource; m_dataSourceHasBeenSet = true; } bool NotebookDetail::DataSourceHasBeenSet() const { return m_dataSourceHasBeenSet; } ImageInfo NotebookDetail::GetImageInfo() const { return m_imageInfo; } void NotebookDetail::SetImageInfo(const ImageInfo& _imageInfo) { m_imageInfo = _imageInfo; m_imageInfoHasBeenSet = true; } bool NotebookDetail::ImageInfoHasBeenSet() const { return m_imageInfoHasBeenSet; } string NotebookDetail::GetImageType() const { return m_imageType; } void NotebookDetail::SetImageType(const string& _imageType) { m_imageType = _imageType; m_imageTypeHasBeenSet = true; } bool NotebookDetail::ImageTypeHasBeenSet() const { return m_imageTypeHasBeenSet; }
4e8527db68acc8dad7323c77bd3cb3fc940d4817
ab231081bfa1aba28afef57c754fea04656496e3
/editor/main.cpp
fb31a62131f265d63ed850a1414be03954d19a5a
[]
no_license
VaysseB/QVariantEditor
75e9c375931619c9e4780d680ac907442f642a79
f2c88b64b4f4fc2524ebfe090d21ff9be9852a48
refs/heads/master
2021-01-18T21:07:57.428416
2015-07-13T19:37:06
2015-07-13T19:37:06
35,686,557
0
0
null
null
null
null
UTF-8
C++
false
false
1,476
cpp
#include "mainwindow.h" #include <QApplication> #include <QDesktopWidget> #include <QIcon> #include <QTranslator> #include <QLibraryInfo> #include "project.h" int main(int argc, char *argv[]) { QApplication app(argc, argv); app.setApplicationName(PROJECT_NAME); app.setApplicationVersion(STR_VERSION); // traduction QString locale = QLocale::system().name(); QTranslator translatorQve; if (translatorQve.load(QString("qve_") + locale, app.applicationDirPath())) app.installTranslator(&translatorQve); QTranslator translatorQt; if (translatorQt.load(QString("qt_") + locale.section('_', 0, 0), QLibraryInfo::location(QLibraryInfo::TranslationsPath)) || translatorQt.load(QString("qt_") + locale.section('_', 0, 0), app.applicationDirPath())) app.installTranslator(&translatorQt); // icon theme (if empty) if (QIcon::themeName().isEmpty()) QIcon::setThemeName("QVariantEditorTheme"); // MainWindow w; w.show(); // centering mainwindow const QSize size = w.size(); const QRect screenRect = QApplication::desktop()->availableGeometry( QApplication::desktop()->primaryScreen()); w.move(QPoint(screenRect.left() + (screenRect.width() - size.width()) * 0.5, screenRect.top() + (screenRect.height() - size.height()) * 0.5)); return app.exec(); }
4dc79df11ac8ac9cc832657f0a2564e18fe9607c
d160bb839227b14bb25e6b1b70c8dffb8d270274
/MCMS/Main/Processes/ConfParty/ConfPartyLib/SIPTransInviteMrcInd.cpp
ad2092b20b1f0908009a3f49125bb1a042f85a08
[]
no_license
somesh-ballia/mcms
62a58baffee123a2af427b21fa7979beb1e39dd3
41aaa87d5f3b38bc186749861140fef464ddadd4
refs/heads/master
2020-12-02T22:04:46.442309
2017-07-03T06:02:21
2017-07-03T06:02:21
96,075,113
1
0
null
null
null
null
UTF-8
C++
false
false
23,710
cpp
//+========================================================================+ // SIPTransInviteMrcInd.h | // Copyright 2012 Polycom Israel Ltd. | // All Rights Reserved. | //-------------------------------------------------------------------------| // NOTE: This software contains valuable trade secrets and proprietary | // information of Polycom Technologies Ltd. and is protected by law. | // It may not be copied or distributed in any form or medium, disclosed | // to third parties, reverse engineered or used in any manner without | // prior written authorization from Polycom Technologies Ltd. | //-------------------------------------------------------------------------| // FILE: SIPTransInviteMrcInd.cpp | // SUBSYSTEM: MCMS | // PROGRAMMER: | //-------------------------------------------------------------------------| // Who | Date | Description | //-------------------------------------------------------------------------| // | | | //+========================================================================+ #include "Segment.h" #include "StateMachine.h" #include "Trace.h" #include "TaskApi.h" #include "PartyApi.h" #include "SIPCommon.h" #include "SipScm.h" #include "SipCall.h" #include "ConfApi.h" #include "SIPControl.h" #include "SIPParty.h" #include "IPParty.h" #include "SIPTransaction.h" #include "SIPTransInviteMrcInd.h" //////////////////////////////////////////////////////////////////////////// CSipTransInviteMrcInd::CSipTransInviteMrcInd(CTaskApp *pOwnerTask):CSipTransaction(pOwnerTask) { m_bIsOfferer = TRUE; m_bIsReInvite = FALSE; m_bIsCloseVideoChannels = FALSE; m_bIsCloseDataChannels = FALSE; m_bIsCloseBfcpChannels = FALSE; } //////////////////////////////////////////////////////////////////////////// CSipTransInviteMrcInd::~CSipTransInviteMrcInd() { } ///////////////////////////////////////////////////////////////////////////////////////// void CSipTransInviteMrcInd::InitPartyEstablishCallIdle() { if (!m_pTargetMode) { TRACEINTO << "No target mode found. must reject call. Name: " << m_pPartyConfName; SetDialState(kCapsDontMatch); EndTransaction(SIP_CAPS_DONT_MATCH); } TRACEINTO << "Name - " << m_pPartyConfName; if (!m_pSipCntl->IsBfcpCtrlCreated()) { TRACEINTO << "Content & BFCP is disabled"; m_pTargetMode->SetMediaOff(cmCapBfcp, cmCapReceiveAndTransmit); m_pTargetMode->SetMediaOff(cmCapVideo, cmCapReceiveAndTransmit, kRolePresentation); } // m_pTargetMode->SetMediaOff(cmCapVideo, cmCapReceiveAndTransmit, kRolePresentation); if (m_pTargetMode->IsMediaOn(cmCapBfcp, cmCapReceiveAndTransmit)) { m_pSipCntl->SetFloorParamsInLocalCaps(); m_pTargetMode->SetVideoBitRate(0, cmCapReceiveAndTransmit, kRolePresentation); } CSipCaps* pRemoteCaps = const_cast<CSipCaps*>(m_pSipCntl->GetLastRemoteCaps()); if (pRemoteCaps && pRemoteCaps->GetNumOfCapSets()) { SendOriginalRemoteCapsToParty(pRemoteCaps); } m_pSipCntl->RemoveUnsupportedSdesCapsForMrcCall(); } ///////////////////////////////////////////////////////////////////////////// void CSipTransInviteMrcInd::ContinueToCloseChannels() { m_state = sTRANS_CHANGECHANNELS; //FSN-613: Dynamic Content for SVC/Mix Conf BYTE IsCloseContentChannels = FALSE; if (m_bIsCloseBfcpChannels) IsCloseContentChannels =TRUE; CloseChannelsIfNeeded(m_bIsCloseVideoChannels, m_bIsCloseDataChannels, m_bIsCloseBfcpChannels, FALSE, IsCloseContentChannels); } ///////////////////////////////////////////////////////////////////// void CSipTransInviteMrcInd::OnPartyChannelsDisconnectedChangeChannels(CSegment* pParam) { TRACEINTO; m_state = sTRANS_RECOVERY; HandleChannelsDisconnectedStartRecovery(pParam); } ///////////////////////////////////////////////////////////////////// void CSipTransInviteMrcInd::OnPartyChannelsUpdatedRecovery(CSegment* pParam) { TRACEINTO; if (m_pSipCntl->GetIsNeedUpdateIceToNonIce()) { TRACEINTO <<"need to close ICE session"; m_pSipCntl->CloseIceSession(); m_pSipCntl->SetNeedUpdateIceToNonIce(FALSE); } HandleChannelsUpdatedDuringRecovery(pParam); } ///////////////////////////////////////////////////////////////////// void CSipTransInviteMrcInd::InternalRecoveryCompleted() { TRACEINTO; //open out channels switch (GetDialState()) { case kGuessSucceeded: case kNoRecoveryForVideo: { m_state = sTRANS_RMTCONNECTED; StartTimer(UPDATEBRIDGESTOUT, BRIDGES_TIME * SECOND); InformPartyRemoteConnect(); break; } default: DBGPASSERT(GetDialState()); } } ///////////////////////////////////////////////////////////////////////////////// void CSipTransInviteMrcInd::OnConfConnectCallRmtConnected(CSegment* pParam) { TRACEINTO << "Name - " << m_pPartyConfName; if (IsValidTimer(UPDATEBRIDGESTOUT)) DeleteTimer(UPDATEBRIDGESTOUT); m_state = sTRANS_OPENOUTCHANNELS; BYTE isAnsweringToNewCap = FALSE; // if(m_bNeedCloseIceChannels) if (m_pSipCntl->GetIsNeedUpdateIceToNonIce()) { OpenInAndOutChannelsIfNeeded (isAnsweringToNewCap); //if closed // m_bNeedCloseIceChannels = FALSE; m_pSipCntl->SetNeedUpdateIceToNonIce(FALSE); } else { OpenOutChannels(isAnsweringToNewCap); if (m_bNeedUpdateSrtpChannels/* For SRTP, Content channel is currently AVC so we need to close and reopen it as in AVC flow and not just update */) { CSipComMode* pComMode = new CSipComMode; pComMode->CopyMediaMode(*m_pTargetMode, cmCapVideo, cmCapReceive, kRolePresentation); pComMode->SetIsEncrypted(m_pTargetMode->GetIsEncrypted(), m_pTargetMode->GetIsDisconnectOnEncryptionFailure()); m_pSipCntl->OpenContentRecvChannelForSrtp(pComMode); POBJDELETE(pComMode); m_bNeedUpdateSrtpChannels = FALSE; } } } ///////////////////////////////////////////////////////////////////// void CSipTransInviteMrcInd::OnPartyChannelsConnectedOpenOut(CSegment* pParam) { PTRACE2(eLevelInfoNormal,"CSipTransInviteMrcInd::OnPartyChannelsConnectedOpenOut: Name ",m_pPartyConfName); HandleOutChannelsConnected(pParam); } ///////////////////////////////////////////////////////////////////////////// void CSipTransInviteMrcInd::OnConfBridgesConnectionTout(CSegment* pParam) { TRACEINTO; PASSERTMSG((DWORD)statIllegal,"CSipTransInviteMrcInd::OnConfBridgesConnectionTout"); EndTransaction(statIllegal); } ///////////////////////////////////////////////////////////////////////////// void CSipTransInviteMrcInd::OnUpdateBridgesTout(CSegment* pParam) { TRACEINTO; PASSERTMSG((DWORD)statIllegal,"CSipTransInviteMrcInd::OnUpdateBridgesTout"); EndTransaction(statIllegal); } ///////////////////////////////////////////////////////////////////////////////// void CSipTransInviteMrcInd::PartyConnectCall() { TRACEINTO << "Name - " << m_pPartyConfName; switch(GetDialState()) { case kGuessSucceeded: case kNoRecoveryForVideo: { SipInviteAckReqIfNeeded(); // if(IsNeedToSendRtcpVideoPreference()) // SendStartVideoPreferenceToParty(); //send flow control with new video rate // if ( kCp == m_pTargetMode->GetConfType() && m_vidRxRate != 0) // { // m_pSipCntl->SendInfoFlowControlReq(mainType, cmCapReceive, m_vidRxRate); // } EndTransaction(); break; } case kReInviteSent: case kNotInDialState: { PTRACE2INT(eLevelInfoNormal, "CSipTransInviteMrcWithSdpInd::PartyConnectCall: Do nothing on dial state Name ", GetDialState()); // there is nothing to do break; } default: { DBGPASSERT(GetDialState()); } } } ///////////////////////////////////////////////////////////////////////////////// // empty function. // implemented only in the derived class CSipTransInviteMrcWithSdpInd void CSipTransInviteMrcInd::SipInviteAckReqIfNeeded() { return; } ///////////////////////////////////////////////////////////////////////////////// void CSipTransInviteMrcInd::HandleBridgeConnectedInd(DWORD status) { TRACEINTO << "Name - " << m_pPartyConfName; if (status == STATUS_OK) { // its OK if both the bridges connected or its audio only call or there is no much in the video capability if((m_isAudioBridgeConnected && m_isVideoBridgeConnected /*&& m_isFeccBridgeConnected*/) || // hg and Shmuel - currently MRC does not support FECC (m_isAudioBridgeConnected && m_isVideoBridgeConnected && m_pTargetMode->IsMediaOff(cmCapData,cmCapReceiveAndTransmit)) || (m_isAudioBridgeConnected && GetIsVoice()) || (m_isAudioBridgeConnected && m_pTargetMode->IsMediaOff(cmCapVideo,cmCapReceiveAndTransmit))) { if (GetDialState() == kBeforeInvite) { if (IsValidTimer(OPENBRIDGESTOUT)) { DeleteTimer(OPENBRIDGESTOUT); TRACEINTO << "DeleteTimer(OPENBRIDGESTOUT)"; } m_state = sTRANS_CONNECTING; ContinueHandleBridgeConnectedInd(); } } else if (m_isAudioBridgeConnected) { TRACEINTO << "Is Voice Call? - " << ( GetIsVoice() ? "yes" : "no" ); } } else // (status != STATUS_OK) { // m_eDialState = kBadStatusAckArrived; DBGPASSERT(status); TRACEINTO << "Ack with bad status: " << status; EndTransaction(status); } } ///////////////////////////////////////////////////////////////////////////////////////// void CSipTransInviteMrcInd::OnPartyChannelsConnectedOpenIn(CSegment* pParam) { TRACEINTO << "Name - " << m_pPartyConfName; if (GetDialState() == kBeforeInvite) // channels in connected { InformChannelsConnectedOpenBridges(pParam); m_state = sTRANS_OPENBRIDGES; StartTimer(OPENBRIDGESTOUT, 10*SECOND); } else { TRACEINTO << "wrong dial state, Name: " << m_pPartyConfName; } } ///////////////////////////////////////////////////////////////////////////////////////// void CSipTransInviteMrcInd::ContinueOnPartyReceivedReinviteResponseOrAckConnecting() // in WithSdp receiving 'ReinviteResponse'; in NoSdp receiving 'Ack' { // pass the product ID to party control GetProductIdAndSendToConfLevel(); SendRemoteCapsReceivedToParty(); // Check that the incoming open channels are correct. That means the remote can transmit this mode to the MCU. // Therefore we have 3 options: GuessSucceeded (no change needed), Internal recovery (need to change only the RTP and codec/bridge setting) // and no recovery (this media should be close) CSipComMode* pBestMode = m_pSipCntl->FindBestModeToOpen((const CSipComMode&)*m_pTargetMode, FALSE); //Check encryption // DWORD isEncrypted = Encryp_Off; if(pBestMode) { pBestMode->Dump("1 : Best Mode",eLevelInfoNormal); DWORD isEncrypted = pBestMode->GetIsEncrypted(); BYTE bIsDisconnectOnEncFailure = pBestMode->GetIsDisconnectOnEncryptionFailure(); // BRIDGE-2510/2511 //-N.A-check IsDisconnectOnEncrypFail to see if nonEncrypted party can still connect // currently, Encryption is not supported in Cascade if ( (isEncrypted == Encryp_On) /*&& (CASCADE_MODE_NONE == m_pSipCntl->GetCascadeMode())*/ ) //--- patch for ignoring Encryption in Cascade { cmCapDataType mediaType; ERoleLabel eRole; for(int i = 0; i < MAX_SIP_MEDIA_TYPES; i++) { GetMediaDataTypeAndRole(globalMediaArr[i], mediaType, eRole); if (mediaType == cmCapBfcp) continue; if (pBestMode->IsMediaOn(mediaType,cmCapTransmit, eRole)) { CSdesCap *pSdesCap = NULL; pSdesCap = pBestMode->GetSipSdes(mediaType,cmCapReceive, eRole); if (!pSdesCap) { if( bIsDisconnectOnEncFailure == FALSE ) {// BRIDGE-2510/2511 -N.A- if so, remove SDES from RMX side and Set Encryption to OFF connect as Non-Encrypted Party TRACESTRFUNC(eLevelError) << "CSipTransInviteMrcInd::ContinueOnPartyReceivedReinviteResponseOrAckConnecting: set encryption to OFF. Name: " << m_pPartyConfName; pBestMode->RemoveSipSdes(mediaType,cmCapTransmit,eRole); pBestMode->SetEncryption(Encryp_Off, bIsDisconnectOnEncFailure); m_pTargetMode->SetEncryption(Encryp_Off, bIsDisconnectOnEncFailure); isEncrypted = Encryp_Off; m_bNeedUpdateSrtpChannels = TRUE; } else {//Disconnect Party POBJDELETE(pBestMode); DBGPASSERT(YES); TRACESTRFUNC(eLevelError) << "CSipTransInviteMrcInd::ContinueOnPartyReceivedReinviteResponseOrAckConnecting: SDES cap is incorrect or not matching. Media: " << globalMediaArr[i] << ", Name " << m_pPartyConfName; SetDialState(kNoRecovery); EndTransaction(SIP_CAPS_DONT_MATCH); return; } } else // pSdesCap { UpdateLocalCapsWithEncryptionParameters(pBestMode, mediaType , eRole); //BRIDGE-10820 } } } if ( isEncrypted == Encryp_On ) { SendUpdateDbEncryptionStatusToParty(YES); } } pBestMode->Dump("CSipTransInviteMrcInd::ContinueOnPartyReceivedReinviteResponseOrAckConnecting : Best Mode",eLevelInfoNormal); if(IsNoRecovery(pBestMode) ) { PTRACE2(eLevelError,"CSipTransInviteMrcInd::ContinueOnPartyReceivedReinviteResponseOrAckConnecting: Audio remote receive is not matching. Name ",m_pPartyConfName); SetDialState(kNotInDialState); } else { // Need to check if we should close channels (audio only media) // If we need to update incoming channels (we check UDP and RTP but for incoming channels - the only channels that are open in this stage - the only change possible is for RTP). // If we update RTP we should also update bridge. // Open outgoing bridge. // Open outgoing channel. // Set call as connected (or secondary). TRACEINTO << "Guess succeeded. Name - " << m_pPartyConfName; SetDialState(kGuessSucceeded); // this state indicates now that media can be establish, maybe after internal change. } m_bIsCloseVideoChannels = FALSE; if(IsNoRecoveryForVideo(pBestMode)) { if(GetDialState() == kGuessSucceeded) SetDialState(kNoRecoveryForVideo); m_bIsCloseVideoChannels = TRUE; const CSipCaps* pCurRemoteCaps = m_pSipCntl->GetLastRemoteCaps(); //Secondary if (pCurRemoteCaps->IsMedia(cmCapVideo)) m_bNeedReInviteForSecondary = TRUE; } m_bIsCloseDataChannels = FALSE; if(IsNoRecoveryForData(pBestMode)) { m_bIsCloseDataChannels = TRUE; } //FSN-613: Dynamic Content for SVC/Mix Conf m_bIsCloseBfcpChannels = FALSE; if(IsNoRecoveryForBfcp(pBestMode)) { m_bIsCloseBfcpChannels = TRUE; PTRACE2(eLevelError,"CSipTransInviteMrcInd::ContinueOnPartyReceivedReinviteResponseOrAckConnecting : need to close bfcp channels Name:",m_pPartyConfName); } if(isEncrypted == Encryp_On ) m_bNeedUpdateSrtpChannels = TRUE; // update media from best mode to target mode *((CIpComMode*)m_pTargetMode) = *((CIpComMode*)pBestMode); // added to synchronize SSRC streams, real solution is to implement update flow *((CIpComMode*)m_pCurrentMode) = *((CIpComMode*)pBestMode); //update pCall video streams with best mode m_pSipCntl->UpdateVideoInStreamsList(pBestMode->GetStreamsListForMediaMode(cmCapVideo, cmCapReceive, kRolePeople)) ; m_pTargetMode->Dump("CSipTransInviteMrcInd::ContinueOnPartyReceivedReinviteResponseOrAckConnecting : Best Mode",eLevelInfoNormal); POBJDELETE(pBestMode); } // end the function in one of two ways: disconnect the call if no recovery, or continue recovery flow (disconnect channels if needed) if(GetDialState() != kNotInDialState) { if (m_pSipCntl && m_pSipCntl->GetIsEnableICE()) { if (CProcessBase::GetProcess()->GetProductType() == eProductTypeSoftMCUMfw) { // VNGSWIBM-742 TRACEINTO << "Close channels if needed, before ICE stack close them"; m_state = sTRANS_CLOSE_CHANNELS_BEFORE_PROCESS_ANSWER; CloseChannelsIfNeeded(m_bIsCloseVideoChannels, m_bIsCloseDataChannels); } else { if (STATUS_OK == SendIceMgsReqAccordingToTargetModeAndCurrentMode(ICE_PROCESS_ANSWER_REQ)) { m_state = sTRANS_WAITFORICECANDIDATES; StartTimer(ICEGENERALTOUT, MAKE_ICE_CANDIDATES_TIMER); } else { TRACEINTO << "Send ICE_PROCESS_ANSWER_REQ returned error !"; m_bNeedReInviteForIce = TRUE; m_pSipCntl->SetIsEnableICE(FALSE); m_bNeedCloseIceChannels = TRUE; m_pSipCntl->SetNeedUpdateIceToNonIce(TRUE); // m_bNeedUpdateIceChannels = TRUE; ContinueToCloseChannels(); } } } else // ! m_pSipCntl->GetIsEnableICE() { ContinueToCloseChannels(); } } else // no recovery (DialState == kNotInDialState) { DBGPASSERT(1); PTRACE2(eLevelError,"CSipTransInviteMrcInd::ContinueOnPartyReceivedReinviteResponseOrAckConnecting: Audio remote receive is not matching. Name ",m_pPartyConfName); SetDialState(kNoRecovery); EndTransaction(SIP_CAPS_DONT_MATCH); return; } } ///////////////////////////////////////////////////////////////////////////// void CSipTransInviteMrcInd::OnIceReinviteContentArrivedFromIceStack(CSegment* pParam) { TRACEINTO; HandleReinviteforICE(pParam); } ///////////////////////////////////////////////////////////////////////////// void CSipTransInviteMrcInd::OnIceInviteModifyAnsArrivedFromIceStack(CSegment* pParam) { TRACEINTO; HandleReinviteforICE(pParam); } ///////////////////////////////////////////////////////////////////////////// void CSipTransInviteMrcInd::OnIceInviteProcessAnsArrivedFromIceStack(CSegment* pParam) { TRACEINTO; if (IsValidTimer (ICEGENERALTOUT)) DeleteTimer(ICEGENERALTOUT); DWORD status; *pParam >> status; if (status == STATUS_OK) StartTimer(ICECOMPLETETOUT, MAKE_ICE_CANDIDATES_TIMER); else { TRACEINTO << "Status FAIL!! - No need to wait for ReInvite_ind from Ice stuck"; //m_bNeedCloseIceChannels = TRUE; m_pSipCntl->SetNeedUpdateIceToNonIce(TRUE); ContinueToCloseChannels(); } } ///////////////////////////////////////////////////////////////////// void CSipTransInviteMrcInd::OnIceInviteReceiveMakeOfferInd(CSegment* pParam) { TRACEINTO << "Name: " << m_pPartyConfName; if (IsValidTimer (ICEOFFERTOUT)) DeleteTimer(ICEOFFERTOUT); WORD status = STATUS_OK; *pParam >> status; if (STATUS_OK != status) { if (m_IceMakeOfferAnswerCounter < 3) { m_IceMakeOfferAnswerCounter++; DWORD retryTimer = 0; CSysConfig* pSysConfig = CProcessBase::GetProcess()->GetSysConfig(); pSysConfig->GetDWORDDataByKey("ICE_RETRY_TIMER_IN_SECONDS", retryTimer); m_pSipCntl->SetIsEnableICE(TRUE); m_pSipCntl->CloseIceSession(); StartTimer(ICEPORTSRETRYTOUT, retryTimer*SECOND); TRACEINTO << "counter: " << m_IceMakeOfferAnswerCounter; } else { m_IceMakeOfferAnswerCounter = 0; PASSERTMSG((DWORD)statIllegal, "CSipTransInviteMrcInd::OnIceInviteReceiveMakeOfferInd - making ICE offer failed "); m_pSipCntl->SetIsEnableICE(FALSE); m_pSipCntl->CloseIceSession(); } } else { m_pSipCntl->MakeANewCall((CSipComMode*)m_pTargetMode, eTipNone, TRUE); m_state = sTRANS_OPENINCHANNELS; SetDialState(kBeforeInvite); } } ///////////////////////////////////////////////////////////////////////////// void CSipTransInviteMrcInd::OnICETimeout(CSegment* pParam) { TRACEINTO; PASSERTMSG (TRUE, "CSipTransInviteMrcInd::OnICETimeout"); if (eIceNotConnected != m_pSipCntl->GetIceConnectivityStatus()) { m_pSipCntl->SetIsEnableICE(FALSE); //m_bNeedCloseIceChannels = TRUE; m_pSipCntl->SetNeedUpdateIceToNonIce(TRUE); ContinueToCloseChannels(); } else EndTransaction(SIP_NO_ADDR_FOR_MEDIA); } ///////////////////////////////////////////////////////////////////// void CSipTransInviteMrcInd::OnICEOfferTimeout(CSegment* pParam) { TRACEINTO << "Name " << m_pPartyConfName; m_pSipCntl->SetIsEnableICE(FALSE); m_pSipCntl->CloseIceSession(); } ///////////////////////////////////////////////////////////////////// void CSipTransInviteMrcInd::OnICEReceiveCloseIceInd (CSegment* pParam) { TRACEINTO << "Name " << m_pPartyConfName; m_state = sTRANS_RECOVERY; CheckChangingInCurrentMode(); } ///////////////////////////////////////////////////////////////////// void CSipTransInviteMrcInd::OnICEReceiveCloseIceIndWaitForCandidates(CSegment* pParam) { TRACEINTO << "Name " << m_pPartyConfName; m_pSipCntl->MakeANewCall((CSipComMode*)m_pTargetMode, eTipNone, TRUE); m_state = sTRANS_OPENINCHANNELS; SetDialState(kBeforeInvite); } ////////////////////////////////////////////////////// void CSipTransInviteMrcInd::OnIcePortsRetryTout(CSegment* pParam) { TRACEINTO << " make offer. Name " << m_pPartyConfName; m_pSipCntl->SetIsEnableICE(TRUE); SendIceMgsReqAccordingToTargetMode(ICE_MAKE_OFFER_REQ); StartTimer(ICEOFFERTOUT, MAKE_ICE_CANDIDATES_TIMER); } /////////////////////////////////////////////////////////////////////////////////////// void CSipTransInviteMrcInd::IceConnectivityCheckComplete(CSegment* pParam) { TRACEINTO << "Name " << m_pPartyConfName; CSegment* CopyOfseg = new CSegment(*pParam); ICE_CHECK_COMPLETE_IND_S* pConnCheckStruct = (ICE_CHECK_COMPLETE_IND_S*) pParam->GetPtr(1); int status = pConnCheckStruct->status; TRACEINTO << "status: " << status; //In case of secondary - we first send Process answer to CM with A+V // and only after connectivity check we send Modify_req with A only - We don't need to wait to Re invite ind. if (STATUS_OK == status && m_bIsChangeInICEChannels) // if (m_bIsChangeInICEChannels) { m_bIsChangeInICEChannels = FALSE; SendIceMgsReqAccordingToTargetMode(ICE_MODIFY_SESSION_OFFER_REQ); } // else // Temp for ICE-SVC, currently we don't support ReInvite for SVC call so we continue with the flow. // { // PTRACE(eLevelInfoNormal, "ICE-SVC: CSipTransInviteMrcWithSdpInd::IceConnectivityCheckComplete : Currently we don't support ReInvite for SVC call. continue the flow without reinvite"); // ContinueToCloseChannels(); // } } ///////////////////////////////////////////////////////////////////////////// void CSipTransInviteMrcInd::HandleReinviteforICE(CSegment* pParam) { TRACEINTO; if (IsValidTimer (ICECOMPLETETOUT)) DeleteTimer(ICECOMPLETETOUT); //todo - Get the reinvite content DWORD status; *pParam >> status; TRACEINTO << "status: " << status << ", connectivity status: " << m_pSipCntl->GetIceConnectivityStatus() << ", is MOC: " << ( (m_pSipCntl->IsRemoteMicrosoft()) ? "yes" : "no" ); // Bridge-5263 - SVC call, We cannot drop ICE since we cannot send re-invite request to MFW - not imp. yet // Continue flow with ICE even if the call is local // BOOL preserve_ice_in_local_call_flag = GetSystemCfgFlagInt<BOOL>(CFG_KEY_SIP_PRESERVE_ICE_CHANNEL_IN_CASE_OF_LOCAL_MODE); // // if (!preserve_ice_in_local_call_flag) // { // if (status != STATUS_OK || (m_pSipCntl->GetIceConnectivityStatus() != eIceConnectedRemote && !m_pSipCntl->IsRemoteMicrosoft())) // { // m_pSipCntl->SetIsEnableICE(FALSE); // //m_bNeedCloseIceChannels = TRUE; // m_pSipCntl->SetNeedUpdateIceToNonIce(TRUE); // // FPTRACE (eLevelInfoNormal, "The call is local, ICE channel closed"); // } // // } else // { // if (status != STATUS_OK || (m_pSipCntl->GetIceConnectivityStatus() != eIceConnectedRemote && !m_pSipCntl->IsRemoteMicrosoft())) // FPTRACE (eLevelInfoNormal, "The call is local, ICE channel preserved due to configuration"); // } //PTRACE(eLevelInfoNormal, "ICE-SVC: CSipTransInviteMrcWithSdpInd::HandleReinviteforICE : Currently we don't support ReInvite for SVC call. continue the flow without reinvite"); //m_bNeedReInviteForIce = FALSE; TRACEINTO << "requesting Re-Invite"; m_bNeedReInviteForIce = TRUE; ContinueToCloseChannels(); }
765e8c699eeff191be9f4509632853baf2e38b73
0813e18eb6b6cd5de9898c33788b9ab7e93727c6
/codeforces/572/B.cc
9ae2c166a956ccd44bf410183a740debb64edae8
[ "MIT" ]
permissive
metaflow/contests
a769e97337363743a1ec89c292d27939781491d3
5e9ffcb72c3e7da54b5e0818b1afa59f5778ffa2
refs/heads/master
2021-07-13T00:09:23.470950
2021-06-28T10:54:47
2021-06-28T10:54:47
19,686,394
1
0
null
null
null
null
UTF-8
C++
false
false
1,194
cc
// time: 15:00 #include<bits/stdc++.h> using namespace std; using vi = vector<int>; using ii = pair<int,int>; using vii = vector<ii>; using vvi = vector<vi>; using ll = long long; using llu = unsigned long long; using vb = vector<bool>; using vvb = vector<vb>; using vd = vector<double>; using vvd = vector<vd>; using vll = vector<ll>; using vvll = vector<vll>; const int INF = numeric_limits<int>::max(); const double EPS = 1e-10; int main() { ios_base::sync_with_stdio(false); cin.tie(0); ll n, s; while (cin >> n >> s) { map<ll, ll, greater<ll>> buy, sell; for (ll i = 0; i < n; i++) { char d; ll p, q; cin >> d >> p >> q; if (d == 'B') { buy[p] += q; } else { sell[p] += q; } } ll i = 0; auto it = sell.begin(); if (s < sell.size()) { for (ll j = 0; j < sell.size() - s; j++) { it++; } } while (i < s && it != sell.end()) { cout << "S " << it->first << " " << it->second << endl; it++; i++; } it = buy.begin(); i = 0; while (i < s && it != buy.end()) { cout << "B " << it->first << " " << it->second << endl; it++; i++; } } }
c944d099d989cf3dd90fc93189e7f138ff88c953
dd3fd0211961c51ffcf4a0fc3c9c95b6ee407d50
/Source codes/BCproject.cpp
bc7dc79931fd7d100985e84073776e43c4589c93
[]
no_license
xmedyn00/Object-detection
e28772c0cc81cd12ae9d94255596ba661e3fa98c
c05853c01c3e26c46fc3d2af062e4d04a5592155
refs/heads/main
2023-06-03T04:30:15.809336
2021-06-17T10:21:26
2021-06-17T10:21:26
377,727,878
2
0
null
null
null
null
WINDOWS-1250
C++
false
false
21,670
cpp
#include "BCproject.h" BCproject::BCproject(QWidget *parent) : QMainWindow(parent) { ui.setupUi(this); ui.graphicsView->setScene(new QGraphicsScene(this)); ui.graphicsView->scene()->addItem(&pixmap); // scitavi nazvu trid ifstream ifs(classesFile.c_str()); while (getline(ifs, line)) classes.push_back(line); // Nastaveni site net.setPreferableBackend(DNN_BACKEND_CUDA); net.setPreferableTarget(DNN_TARGET_CUDA); //combobox config ui.comboBox->addItem("Choose video..."); ui.comboBox->addItem("test_video.mp4"); if (modelConfiguration == "yolov4-obj.cfg") { ui.label_18->setText("yolov4"); } else if (modelConfiguration == "yolov4-tiny-obj.cfg") { ui.label_18->setText("yolov4-tiny"); } ui.label_15->setText(CV_VERSION); } //Tlacitko pro otevreni videa void BCproject::on_LoadVideoBtn_clicked() { QString comboBoxValue = ui.comboBox->currentText(); if (comboBoxValue == "Choose video...") { //pokud kombox nastaven na "Choose video..." tak je moznost vybrat video na pocitaci dirOpen = QFileDialog::getOpenFileName(this, tr("Open File"), "/", tr("Video (*.mp4)")); } else { //jinak muzeme spustit video z komboboxu dirOpen = ui.comboBox->currentText(); } if (dirOpen.isEmpty()) { QMessageBox msgBox; msgBox.setText("The file was not selected!"); msgBox.exec(); } else { framecount_get = 0; //vynulovani frajmu PlayVideo(); //spousteni videa } } //pohyb slajderu void BCproject::on_slider_sliderMoved(int position) { cap.set(CAP_PROP_POS_FRAMES, position); } //Metoda pro spousteni videa a zpracovani kazdeho snimku void BCproject::PlayVideo() { if (streamType == 0) { //tlacitko choose video nastavi hodnotu promena streamType na 0 a tim povoli spousteni videa s pocitace cap.open(QString("%1").arg(dirOpen).toStdString()); } else if (streamType == 1) { //tlacitko real time nastavi hodnotu promene streamType na 1 a otevre video s pripojene kamery cap.open(0); } cap.set(CAP_PROP_POS_FRAMES, framecount_get); //video se otevre s cisla frajmu uvedeneho v promene framecount_get //nastaveni slajderu int contFrames = cap.get(CAP_PROP_FRAME_COUNT); ui.slider->setMinimum(0); ui.slider->setMaximum(contFrames); //overeni pripojeni kamery if (streamType == 1) { if (!cap.isOpened()) { QMessageBox msgBox; msgBox.setText("Camera is not connected!"); msgBox.exec(); } } int lastFrame = cap.get(CAP_PROP_FRAME_COUNT); while (1) { ui.slider->setSliderPosition(cap.get(CAP_PROP_POS_FRAMES)); cap >> frame; //ziskame snimek z videa if (lastFrame == cap.get(CAP_PROP_POS_FRAMES)) { on_StopBtn_clicked(); } //zastavit program pokud dojde ke koncí videa if (frame.empty()) { break; } //po nacteni snimku z videa nebo kamery on je preveden pres f-ci blobFromImage na objekt blob pro neuronovou sit. //Na vystupu teto f-ci dostame obraz velikosti (416, 416) blobFromImage(frame, blob, 1 / 255.0, Size(inpWidth, inpHeight), Scalar(0, 0, 0), true, false); //Nastavi blob na vstup do siti net.setInput(blob); // Spusti pruchod vpred pro vypocet vystupu vrstvy se jmenem objektu detekci vector<Mat> outs; net.forward(outs, getOutputsNames(net)); // odstranime ohranicujici ramecky s nizkou jistotou postprocess(frame, outs); // Doplnujici informace. vector<double> layersTimes; double freq = getTickFrequency() / 1000; double t = net.getPerfProfile(layersTimes) / freq; double fps = 1 / (t / 1000); ui.label_8->setText(QString("%1").arg(fps)); //ui.label_18->setText("sdasd"); // Zpracovani obrazu v rezimu ROI if (isSelectedRoiArea) { float alpha = 0.5; frame.copyTo(overlay); rectangle(frame, Rect(posXroi, posYroi, sizeWroi, sizeHroi), Scalar(100, 255, 100), -1); addWeighted(overlay, alpha, frame, 1 - alpha, 0, frame, 0); } // Vypis frajmu s bboxy Mat detectedFrame; frame.convertTo(detectedFrame, CV_8U); if (!frame.empty()) { //aby svravne zobrazit obrazek Mat na Qt QGraphicsView je potreba prevest Mat na QImage. //barevni prostor OpenCV je BGR a je potreba ho zmenit na RGB, potom QImage prevedeme na QPixmap //nakonec pridavame pixmap do QGraphicsScene QImage qimg(frame.data, frame.cols, frame.rows, frame.step, QImage::Format_RGB888); pixmap.setPixmap(QPixmap::fromImage(qimg.rgbSwapped())); // aby odrazek vzdy hodil k zobrzeni bez ohledu na velikost okna aplikace ui.graphicsView->fitInView(&pixmap, Qt::KeepAspectRatio); qApp->processEvents(); } } } //podminka zavreni aplikace void BCproject::closeEvent(QCloseEvent *event) { if (cap.isOpened()) { QMessageBox::warning(this, "Warning", "Please stop the video before closing the application!"); event->ignore(); } else { event->accept(); } } //tlacitka k ovladani prehravace //Play void BCproject::on_playBtn_clicked() { PlayVideo(); } //Stop void BCproject::on_StopBtn_clicked() { framecount_get = 0; cap.release(); } //Pause void BCproject::on_PauseBtn_clicked() { framecount_get = cap.get(CAP_PROP_POS_FRAMES); cap.release(); } //rezim vyberu videa void BCproject::on_chooseVideoBtn_clicked() { streamType = 0; ui.PauseBtn->setDisabled(0); ui.playBtn->setDisabled(0); ui.StopBtn->setDisabled(0); ui.comboBox->setDisabled(0); ui.LoadVideoBtn->setText("Open video"); ui.realTimeBtn->setStyleSheet("background:rgb(207, 207, 207)"); ui.chooseVideoBtn->setStyleSheet("background:rgba(100, 195, 35, 255)"); ui.comboBox->clear(); ui.comboBox->addItem("Choose video..."); ui.comboBox->addItem("test_video.mp4"); } //rezim Real time void BCproject::on_realTimeBtn_clicked() { //cap.release(); streamType = 1; ui.PauseBtn->setDisabled(1); ui.playBtn->setDisabled(1); ui.StopBtn->setDisabled(0); ui.comboBox->setDisabled(1); ui.LoadVideoBtn->setText("Start steaming"); ui.realTimeBtn->setStyleSheet("background:rgba(100, 195, 35, 255)"); ui.chooseVideoBtn->setStyleSheet("background:rgb(207, 207, 207)"); ui.comboBox->clear(); ui.comboBox->addItem("Streaming..."); } //tlacitka pro rizeni objektu detekce //auto void BCproject::on_BtnCar_clicked() { if (!detec_car) { detec_car = true; ui.BtnCar->setText("ON"); } else { detec_car = false; ui.BtnCar->setText("OFF"); } btnColorCheck(); } //clovek void BCproject::on_BtnPerson_clicked() { if (!detec_person) { detec_person = true; ui.BtnPerson->setText("ON"); } else { detec_person = false; ui.BtnPerson->setText("OFF"); } btnColorCheck(); } //kamion void BCproject::on_BtnTruck_clicked() { if (!detec_truck) { detec_truck = true; ui.BtnTruck->setText("ON"); } else { detec_truck = false; ui.BtnTruck->setText("OFF"); } btnColorCheck(); } //dodavka void BCproject::on_BtnVan_clicked() { if (!detec_van) { detec_van = true; ui.BtnVan->setText("ON"); } else { detec_van = false; ui.BtnVan->setText("OFF"); } btnColorCheck(); } //kolo void BCproject::on_BtnBicycle_clicked() { if (!detec_bicycle) { detec_bicycle = true; ui.BtnBicycle->setText("ON"); } else { detec_bicycle = false; ui.BtnBicycle->setText("OFF"); } btnColorCheck(); } //motorka void BCproject::on_BtnMotorbike_clicked() { if (!detec_motorbike) { detec_motorbike = true; ui.BtnMotorbike->setText("ON"); } else { detec_motorbike = false; ui.BtnMotorbike->setText("OFF"); } btnColorCheck(); } //autobus void BCproject::on_BtnBus_clicked() { if (!detec_bus) { detec_bus = true; ui.BtnBus->setText("ON"); } else { detec_bus = false; ui.BtnBus->setText("OFF"); } btnColorCheck(); } //detekovat vsechny objekty void BCproject::on_BtnDetect_clicked() { detec_motorbike = true; detec_bicycle = true; detec_van = true; detec_truck = true; detec_person = true; detec_car = true; detec_bus = true; btnColorCheck(); } //kontroluje barvu tlacitek void BCproject::btnColorCheck() { QString textBtnMotorbike = ui.BtnMotorbike->text(); QString textBtnBicycle = ui.BtnBicycle->text(); QString textBtnVan = ui.BtnVan->text(); QString textBtnTruck = ui.BtnTruck->text(); QString textBtnPerson = ui.BtnPerson->text(); QString textBtnCar = ui.BtnCar->text(); QString textBtnBus = ui.BtnBus->text(); if (textBtnMotorbike == "ON") { ui.BtnMotorbike->setStyleSheet("background:rgba(100, 195, 35, 255)"); } else { ui.BtnMotorbike->setStyleSheet("background:rgb(207, 207, 207)"); } if (textBtnBicycle == "ON") { ui.BtnBicycle->setStyleSheet("background:rgba(100, 195, 35, 255)"); } else { ui.BtnBicycle->setStyleSheet("background:rgb(207, 207, 207)"); } if (textBtnVan == "ON") { ui.BtnVan->setStyleSheet("background:rgba(100, 195, 35, 255)"); } else { ui.BtnVan->setStyleSheet("background:rgb(207, 207, 207)"); } if (textBtnTruck == "ON") { ui.BtnTruck->setStyleSheet("background:rgba(100, 195, 35, 255)"); } else { ui.BtnTruck->setStyleSheet("background:rgb(207, 207, 207)"); } if (textBtnPerson == "ON") { ui.BtnPerson->setStyleSheet("background:rgba(100, 195, 35, 255)"); } else { ui.BtnPerson->setStyleSheet("background:rgb(207, 207, 207)"); } if (textBtnCar == "ON") { ui.BtnCar->setStyleSheet("background:rgba(100, 195, 35, 255)"); } else { ui.BtnCar->setStyleSheet("background:rgb(207, 207, 207)"); } if (textBtnBus == "ON") { ui.BtnBus->setStyleSheet("background:rgba(100, 195, 35, 255)"); } else { ui.BtnBus->setStyleSheet("background:rgb(207, 207, 207)"); } if (detec_motorbike == true && detec_bicycle == true && detec_van == true && detec_truck == true && detec_person == true && detec_car == true && detec_bus == true) { ui.BtnDetect->setStyleSheet("background:rgba(100, 195, 35, 255)"); ui.BtnMotorbike->setText("ON"); ui.BtnMotorbike->setStyleSheet("background:rgba(100, 195, 35, 255)"); ui.BtnBicycle->setText("ON"); ui.BtnBicycle->setStyleSheet("background:rgba(100, 195, 35, 255)"); ui.BtnVan->setText("ON"); ui.BtnVan->setStyleSheet("background:rgba(100, 195, 35, 255)"); ui.BtnTruck->setText("ON"); ui.BtnTruck->setStyleSheet("background:rgba(100, 195, 35, 255)"); ui.BtnPerson->setText("ON"); ui.BtnPerson->setStyleSheet("background:rgba(100, 195, 35, 255)"); ui.BtnCar->setText("ON"); ui.BtnCar->setStyleSheet("background:rgba(100, 195, 35, 255)"); ui.BtnBus->setText("ON"); ui.BtnBus->setStyleSheet("background:rgba(100, 195, 35, 255)"); } else { ui.BtnDetect->setStyleSheet("background:rgb(207, 207, 207)"); } } // Tlacitka pro ovladani ROI //zapnout ROI void BCproject::on_BtnROI_clicked() { posXroi = frame.size().width / 2 - sizeWroi / 2; posYroi = frame.size().height / 2 - sizeWroi / 2; if (!isSelectedRoiArea) { isSelectedRoiArea = true; ui.BtnROI->setStyleSheet("background:rgba(100, 195, 35, 255)"); } else { isSelectedRoiArea = false; ui.BtnROI->setStyleSheet("background:rgb(207, 207, 207)"); } } //posunout ROI dolu void BCproject::on_BtnROIdown_pressed() { posYroi += 10; } //posunout ROI vpravo void BCproject::on_BtnROIright_pressed() { posXroi += 10; } //posunout ROI nahoru void BCproject::on_BtnROIup_pressed() { posYroi -= 10; } //posunout ROI vlevo void BCproject::on_BtnROIleft_pressed() { posXroi -= 10; } //zvetsit ROI oblast void BCproject::on_BtnROIzoomPlus_pressed() { sizeWroi += 10; sizeHroi += 10; posXroi -= 5; posYroi -= 5; } //zmensit ROI oblast void BCproject::on_BtnROIzoomMinus_pressed() { sizeWroi -= 10; sizeHroi -= 10; posXroi += 5; posYroi += 5; } //Odstrani ohranicujici ramecky s nizkou jistotou void BCproject::postprocess(Mat& frame, const vector<Mat>& outs) { vector<int> classIds; vector<float> confidences; vector<Rect> boxes; for (size_t i = 0; i < outs.size(); ++i) { float* data = (float*)outs[i].data; for (int j = 0; j < outs[i].rows; ++j, data += outs[i].cols) { Mat scores = outs[i].row(j).colRange(5, outs[i].cols); Point classIdPoint; double confidence; // Ziskame hodnotu a umisteni maximalniho skore minMaxLoc(scores, 0, &confidence, 0, &classIdPoint); if (confidence > confThreshold) { int centerX = (int)(data[0] * frame.cols); int centerY = (int)(data[1] * frame.rows); int width = (int)(data[2] * frame.cols); int height = (int)(data[3] * frame.rows); int left = centerX - width / 2; int top = centerY - height / 2; classIds.push_back(classIdPoint.x); confidences.push_back((float)confidence); boxes.push_back(Rect(left, top, width, height)); } } } //Provedeme potlaceni maxima(non maximum suppression) aby odstanit prekryvajici bloky s nizsimi duvernostmi vector<int> indices; NMSBoxes(boxes, confidences, confThreshold, nmsThreshold, indices); for (size_t i = 0; i < indices.size(); ++i) { int idx = indices[i]; Rect box = boxes[idx]; drawPred(classIds[idx], confidences[idx], box.x, box.y, box.x + box.width, box.y + box.height, frame); } } // Nakresli predpokladane ohranicovaci pole void BCproject::drawPred(int classId, float conf, int left, int top, int right, int bottom, Mat& frame) { //Ziska stitek s nazvem tridy a jeji duveryhodnost string label = format("%.2f", conf); if (!classes.empty()) { CV_Assert(classId < (int)classes.size()); label = classes[classId] + ":" + label; } //Zobrazi stitek v horni casti ohranicujiciho ramecku int baseLine; Size labelSize = getTextSize(label, FONT_HERSHEY_DUPLEX, 0.5, 1, &baseLine); top = max(top, labelSize.height); if (!isSelectedRoiArea) { if (detec_car) { if (classId == 0) { rectangle(frame, Point(left, top), Point(right, bottom), Scalar(255, 178, 50), 3); if (ui.checkBox_2->isChecked()) { frame.copyTo(overlay); rectangle(overlay, Point(left, top - round(1.5 * labelSize.height)), Point(left + round(1.5 * labelSize.width), top + baseLine), Scalar(100, 255, 100), -1); addWeighted(overlay, 0.5, frame, 1 - 0.5, 0, frame); putText(frame, label, Point(left, top), FONT_HERSHEY_DUPLEX, 0.75, Scalar(0, 0, 0), 1); } } } if (detec_person) { if (classId == 1) { rectangle(frame, Point(left, top), Point(right, bottom), Scalar(0, 0, 255), 3); if (ui.checkBox_2->isChecked()) { frame.copyTo(overlay); rectangle(overlay, Point(left, top - round(1.5 * labelSize.height)), Point(left + round(1.5 * labelSize.width), top + baseLine), Scalar(100, 255, 100), -1); addWeighted(overlay, 0.5, frame, 1 - 0.5, 0, frame); putText(frame, label, Point(left, top), FONT_HERSHEY_DUPLEX, 0.75, Scalar(0, 0, 0), 1); } } } if (detec_truck) { if (classId == 2) { rectangle(frame, Point(left, top), Point(right, bottom), Scalar(255, 0, 0), 3); if (ui.checkBox_2->isChecked()) { frame.copyTo(overlay); rectangle(overlay, Point(left, top - round(1.5 * labelSize.height)), Point(left + round(1.5 * labelSize.width), top + baseLine), Scalar(100, 255, 100), -1); addWeighted(overlay, 0.5, frame, 1 - 0.5, 0, frame); putText(frame, label, Point(left, top), FONT_HERSHEY_DUPLEX, 0.75, Scalar(0, 0, 0), 1); } } } if (detec_van) { if (classId == 3) { rectangle(frame, Point(left, top), Point(right, bottom), Scalar(0, 255, 0), 3); if (ui.checkBox_2->isChecked()) { frame.copyTo(overlay); rectangle(overlay, Point(left, top - round(1.5 * labelSize.height)), Point(left + round(1.5 * labelSize.width), top + baseLine), Scalar(100, 255, 100), -1); addWeighted(overlay, 0.5, frame, 1 - 0.5, 0, frame); putText(frame, label, Point(left, top), FONT_HERSHEY_DUPLEX, 0.75, Scalar(0, 0, 0), 1); } } } if (detec_bicycle) { if (classId == 4) { rectangle(frame, Point(left, top), Point(right, bottom), Scalar(0, 233, 255), 3); if (ui.checkBox_2->isChecked()) { frame.copyTo(overlay); rectangle(overlay, Point(left, top - round(1.5 * labelSize.height)), Point(left + round(1.5 * labelSize.width), top + baseLine), Scalar(100, 255, 100), -1); addWeighted(overlay, 0.5, frame, 1 - 0.5, 0, frame); putText(frame, label, Point(left, top), FONT_HERSHEY_DUPLEX, 0.75, Scalar(0, 0, 0), 1); } } } if (detec_motorbike) { if (classId == 5) { rectangle(frame, Point(left, top), Point(right, bottom), Scalar(255, 127, 0), 3); if (ui.checkBox_2->isChecked()) { frame.copyTo(overlay); rectangle(overlay, Point(left, top - round(1.5 * labelSize.height)), Point(left + round(1.5 * labelSize.width), top + baseLine), Scalar(100, 255, 100), -1); addWeighted(overlay, 0.5, frame, 1 - 0.5, 0, frame); putText(frame, label, Point(left, top), FONT_HERSHEY_DUPLEX, 0.75, Scalar(0, 0, 0), 1); } } } if (detec_bus) { if (classId == 6) { rectangle(frame, Point(left, top), Point(right, bottom), Scalar(97, 0, 255), 3); if (ui.checkBox_2->isChecked()) { frame.copyTo(overlay); rectangle(overlay, Point(left, top - round(1.5 * labelSize.height)), Point(left + round(1.5 * labelSize.width), top + baseLine), Scalar(100, 255, 100), -1); addWeighted(overlay, 0.5, frame, 1 - 0.5, 0, frame); putText(frame, label, Point(left, top), FONT_HERSHEY_DUPLEX, 0.75, Scalar(0, 0, 0), 1); } } } } if (isSelectedRoiArea) { if (right >= posXroi && left <= posXroi + sizeWroi && top >= posYroi && top <= posYroi + sizeHroi) { //right >= posXroi && left <= posXroi + sizeWroi && top >= posYroi && top <= posYroi + sizeHroi if (detec_car) { if (classId == 0) { rectangle(frame, Point(left, top), Point(right, bottom), Scalar(255, 178, 50), 3); if (ui.checkBox_2->isChecked()) { rectangle(frame, Point(left, top - round(1.5 * labelSize.height)), Point(left + round(1.5 * labelSize.width), top + baseLine), Scalar(255, 255, 255), FILLED); putText(frame, label, Point(left, top), FONT_HERSHEY_DUPLEX, 0.75, Scalar(0, 0, 0), 1); } } } if (detec_person) { if (classId == 1) { rectangle(frame, Point(left, top), Point(right, bottom), Scalar(0, 0, 255), 3); if (ui.checkBox_2->isChecked()) { rectangle(frame, Point(left, top - round(1.5 * labelSize.height)), Point(left + round(1.5 * labelSize.width), top + baseLine), Scalar(255, 255, 255), FILLED); putText(frame, label, Point(left, top), FONT_HERSHEY_DUPLEX, 0.75, Scalar(0, 0, 0), 1); } } } if (detec_truck) { if (classId == 2) { rectangle(frame, Point(left, top), Point(right, bottom), Scalar(255, 0, 0), 3); if (ui.checkBox_2->isChecked()) { rectangle(frame, Point(left, top - round(1.5 * labelSize.height)), Point(left + round(1.5 * labelSize.width), top + baseLine), Scalar(255, 255, 255), FILLED); putText(frame, label, Point(left, top), FONT_HERSHEY_DUPLEX, 0.75, Scalar(0, 0, 0), 1); } } } if (detec_van) { if (classId == 3) { rectangle(frame, Point(left, top), Point(right, bottom), Scalar(0, 255, 0), 3); if (ui.checkBox_2->isChecked()) { rectangle(frame, Point(left, top - round(1.5 * labelSize.height)), Point(left + round(1.5 * labelSize.width), top + baseLine), Scalar(255, 255, 255), FILLED); putText(frame, label, Point(left, top), FONT_HERSHEY_DUPLEX, 0.75, Scalar(0, 0, 0), 1); } } } if (detec_bicycle) { if (classId == 4) { rectangle(frame, Point(left, top), Point(right, bottom), Scalar(0, 233, 255), 3); if (ui.checkBox_2->isChecked()) { rectangle(frame, Point(left, top - round(1.5 * labelSize.height)), Point(left + round(1.5 * labelSize.width), top + baseLine), Scalar(255, 255, 255), FILLED); putText(frame, label, Point(left, top), FONT_HERSHEY_DUPLEX, 0.75, Scalar(0, 0, 0), 1); } } } if (detec_motorbike) { if (classId == 5) { rectangle(frame, Point(left, top), Point(right, bottom), Scalar(255, 127, 0), 3); if (ui.checkBox_2->isChecked()) { rectangle(frame, Point(left, top - round(1.5 * labelSize.height)), Point(left + round(1.5 * labelSize.width), top + baseLine), Scalar(255, 255, 255), FILLED); putText(frame, label, Point(left, top), FONT_HERSHEY_DUPLEX, 0.75, Scalar(0, 0, 0), 1); } } } if (detec_bus) { if (classId == 6) { rectangle(frame, Point(left, top), Point(right, bottom), Scalar(97, 0, 255), 3); if (ui.checkBox_2->isChecked()) { rectangle(frame, Point(left, top - round(1.5 * labelSize.height)), Point(left + round(1.5 * labelSize.width), top + baseLine), Scalar(255, 255, 255), FILLED); putText(frame, label, Point(left, top), FONT_HERSHEY_DUPLEX, 0.75, Scalar(0, 0, 0), 1); } } } } } } // Ziskam nazvy vystupnich vrstev vector<String> BCproject::getOutputsNames(const Net& net) { static vector<String> names; if (names.empty()) { // Ziskame indexy vystupnich vrstev, tj. vrstev s nepripojenymi vystupy vector<int> outLayers = net.getUnconnectedOutLayers(); //ziskame nazvy vsech vrstev v siti vector<String> layersNames = net.getLayerNames(); // Ziskame nazvy vystupnich vrstev v nazvech names.resize(outLayers.size()); for (size_t i = 0; i < outLayers.size(); ++i) names[i] = layersNames[outLayers[i] - 1]; } return names; }
0a6990277e5038063d7fd1813e3659d5ab57c765
ba181fa3354c6962d7b82b422cb605c0754cedd7
/toolchain/BMGTexTool/ImageWidget.h
0ac68acf126a94e439e4ef9bcb8e2840a347e61c
[ "MIT", "Zlib" ]
permissive
aismann/Bulllord-Engine
f8e2099c668b97083762d2527721e415341a1c5c
4b85f17f29365a56a5c6919b84762f35960ba98c
refs/heads/master
2020-03-28T01:10:34.484708
2018-08-31T22:50:42
2018-08-31T22:50:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,818
h
#ifndef IMAGEWINDOW_H #define IMAGEWINDOW_H #include <QtWidgets/QScrollArea> #include <QtGui/QPaintEvent> #include <QtWidgets/QWidget> #include <QtGui/QDragEnterEvent> #include <QtCore/QList> #include "Image.h" struct ImageArea { int x, y; int forcer; int rx, ry; QImage *image; QString name; QString fileName; int offsetx, offsety; ImageArea() { int x = y = rx = ry = 0; forcer = 0; setPos(0, 0); image = 0; offsetx = 0; offsety = 0; } void forceRR() { forcer = 1; } QString toAreaString() { int left, top, right, bottom; getArea(left, top, right, bottom); if(forcer) return QString("( %1, %2, %3, %4 )").arg(left).arg(top).arg(rx).arg(ry); else return QString("( %1, %2, %3, %4 )").arg(left).arg(top).arg(right).arg(bottom); } QString toCoordString() { int left, top, right, bottom; getArea(left, top, right, bottom); return QString("%1,%2,%3,%4").arg(left).arg(top).arg(right).arg(bottom); } void setPos(int x, int y) { this->x = x; this->y = y; } void setOffset(int x, int y) { this->offsetx = x; this->offsety = y; } int getOffsetX() { return offsetx; } int getOffsetY() { return offsety; } void getPos(int &x, int &y) { x = this->x; y = this->y; } void movePos(int ax, int ay) { x += ax; y += ay; if (x < 0) x = 0; if (y < 0) y = 0; } void getRightBottom(int &right, int &bottom) { assert(image != 0); if (image && !rx && !ry) { right = this->x + image->width(); bottom = this->y + image->height(); } else { right = rx; bottom = ry; } } void setArea(int left, int top, int right, int bottom) { //assert(image != 0); this->x = left; this->y = top; this->rx = right; this->ry = bottom; //bottom = this->y + image->height(); } void setSize(int right, int bottom) { //assert(image != 0); this->rx = right; this->ry = bottom; //bottom = this->y + image->height(); } void getArea(int &left, int &top, int &right, int &bottom) { //assert(image != 0); if (image && !rx && !ry) { left = this->x; top = this->y; right = this->x + image->width(); bottom = this->y + image->height(); } else { left = this->x; top = this->y; right = rx; bottom = ry; } } void getSize(int &width, int &height) { assert(image != 0); if (image && !rx && !ry) { width = image->width(); height = image->height(); } else { width = rx - x; height = ry - y; } } }; struct ImageAreaRef { ImageAreaRef() { imageArea = 0; } ImageAreaRef(ImageArea *data) { imageArea = data; } ImageArea *imageArea; }; Q_DECLARE_METATYPE(ImageAreaRef) class ImageWidget : public QScrollArea , public ImageOp { Q_OBJECT signals : void imageAreaChanged(ImageArea *image); void imageAdded(ImageArea *image); void imageSelected(ImageArea *image); void imageDeleted(ImageArea *image); void dataModified(bool m); public: ImageWidget(QWidget *parent = 0); virtual ~ImageWidget(); void setImage(Image *image,const QString filePath, int ofx, int ofy, std::vector<SpriteSheet>* ssv = NULL); Image *getImage() { return _image; } QString getImageFileName() { return _filePath; } void setImageFileName(QString name); bool IsBMG(); bool needSave(); bool changed(); void zoomIn(); void zoomOut(); void resetZoom(); void generatorMips(); void deleteAllMips(bool repaint = true); void lowerMips(); void higherMips(); void setSelectImage(ImageArea *image); void deleteImage(ImageArea *image); void deleteAllImage(); void setModefied2(QString modified); void setModefied(bool modified); void setBMG(const QString& path); void setChanged(bool falg = true); void moveImageToPoint(ImageArea *imageArea, int x, int y); bool moveImage(ImageArea *imageArea, int ax, int ay); QString getValidName(const QString &name); void addImage(QImage *image, const QString &imageName, int ofx, int ofy, std::vector<SpriteSheet>* ssv = NULL); void addImage(ImageArea *image); QList<ImageArea*> _imageAreaList; void ResetCanves(); protected: virtual void paintEvent(QPaintEvent *event); virtual void mousePressEvent(QMouseEvent *event); virtual void mouseReleaseEvent(QMouseEvent *event); protected: virtual void dragEnterEvent(QDragEnterEvent *event); virtual void dropEvent(QDropEvent *event); virtual void closeEvent(QCloseEvent *event); private slots: void updateWindowTitle(); void adjustWindowSize(); void setClientSize(); void getImageRect(int &width, int &height); void drawToDevice(QPaintDevice *device, bool select = true); QImage *combinToImage(); ImageArea * pickImage(int x, int y); private: ImageArea *_selectedImage; Image *_image; QString _filePath; bool _modified; bool _mousePressed; bool _MultiImage; bool _IsBMG; bool _BmgChanged; QWidget* _Parent; }; #endif //IMAGEWINDOW_H
d3aaabcbe0946681c447159d6d4ef89e8f752955
f0c402d3858f0643561886797578b1e64655b1b3
/base/inc/ReExecutionUnit.h
1224c603c5ca7272a8adb6ba83f91a8eb16a9ee9
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
Leo-Wang-JL/force-riscv
39ad2a72abd814df4b63879ce9825b6b06a9391a
deee6acaaee092eb90ac2538de122303334e5be3
refs/heads/master
2023-01-28T00:06:58.135651
2020-11-18T02:54:10
2020-11-18T02:54:10
271,873,013
0
0
NOASSERTION
2020-06-28T00:51:26
2020-06-12T19:15:26
C++
UTF-8
C++
false
false
3,107
h
// // Copyright (C) [2020] Futurewei Technologies, Inc. // // FORCE-RISCV is 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 // // THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR // FIT FOR A PARTICULAR PURPOSE. // See the License for the specific language governing permissions and // limitations under the License. // #ifndef Force_ReExecutionUnit_H #define Force_ReExecutionUnit_H #include <Defines.h> namespace Force { class ConstraintSet; /*! \class ReExecutionUnit \brief Handles re-execution related functionalities. */ class ReExecutionUnit { public: ReExecutionUnit(); //!< Constructor. COPY_CONSTRUCTOR_ABSENT(ReExecutionUnit); virtual ~ReExecutionUnit(); //!< Destructor. ASSIGNMENT_OPERATOR_ABSENT(ReExecutionUnit); void SetId(uint32 id) { mId = id; } //!< Set unit ID. uint32 Id() const { return mId; } //!< Return unit ID. void SetBeginAddress(uint64 beginAddr) { mBeginAddress = beginAddr; } //!< Set begin address. uint64 BeginAddress() const { return mBeginAddress; } //!< Return begin address. void SetEndAddress(uint64 endAddr) { mEndAddress = endAddr; } //!< Set end address uint64 EndAddress() const { return mEndAddress; } //!< Return end address. protected: uint32 mId; //!< Id of the unit. uint64 mBeginAddress; //!< Begin address. uint64 mEndAddress; //!< End address. ConstraintSet* mpVaRanges; //!< Virtual addresses of the loop body. ConstraintSet* mpPaRanges; //!< Physical addresses of the loop body. }; /*! \class Loop \brief Handles loop related functionalities. */ class Loop : public ReExecutionUnit { public: Loop() : ReExecutionUnit(), mReconvergeAddress(0), mPostLoopAddress(0) { } //!< Default constructor. void SetPostLoopAddress(uint64 addr) { mPostLoopAddress = addr; } //!< Set post loop address. void SetReconvergeAddress(uint64 addr) { mReconvergeAddress = addr; } //!< Set loop reconverge address. uint64 PostLoopAddress() const { return mPostLoopAddress; } //!< Return post loop address. uint64 ReconvergeAddress() const { return mReconvergeAddress; } //!< Return loop reconverge address. COPY_CONSTRUCTOR_ABSENT(Loop); SUBCLASS_DESTRUCTOR_DEFAULT(Loop); //!< Destructor. ASSIGNMENT_OPERATOR_ABSENT(Loop); protected: uint64 mReconvergeAddress; //!< Loop reconverge address. uint64 mPostLoopAddress; //!< Post loop address. }; /*! \class LinearBlock \brief Handles linear block related functionalities. */ class LinearBlock : public ReExecutionUnit { public: DEFAULT_CONSTRUCTOR_DEFAULT(LinearBlock); //!< Constructor. COPY_CONSTRUCTOR_ABSENT(LinearBlock); SUBCLASS_DESTRUCTOR_DEFAULT(LinearBlock); //!< Destructor. ASSIGNMENT_OPERATOR_ABSENT(LinearBlock); }; } #endif
dd3bb7f43aac3d51aced329d7496b871e0d232a0
786a89a4bd31e0a5953094c7880021cc98f78f98
/train/green/CF2017ac.cpp
b6a3edda501faf4ffc7316b812febce45625f4c7
[]
no_license
enjoy82/atcodersyozin
c12eb9cc04e61cedcdc13643b84e8c87c13ff4b1
c8a73577d1d75db2d5c22eab028f942f75f2fba7
refs/heads/master
2022-10-04T04:47:16.835712
2022-09-30T07:15:47
2022-09-30T07:15:47
243,669,940
0
0
null
null
null
null
UTF-8
C++
false
false
1,596
cpp
#include<bits/stdc++.h> typedef long long ll; typedef long double ld; using namespace std; using Pii = pair<int, int>; using Pll = pair<ll, ll>; #define REP(i, l, n) for(int i=(l), i##_len=(n); i<i##_len; ++i) #define ALL(x) (x).begin(),(x).end() #define pb push_back ll gcd(ll a,ll b){return b ? gcd(b,a%b) : a;} ll lcm(ll a,ll b){return a/gcd(a,b)*b;} template<class T> inline bool chmax(T &a, T b) { if(a < b) { a = b; return true; } return false; } template<class T> inline bool chmin(T &a, T b) { if(a > b) { a = b; return true; } return false; } char alpha[26] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}; int dx[4] = {-1, 1, 0, 0}; int dy[4] = {0, 0, 1, -1}; int main(){ int n, m; cin >> n >> m; vector<string> lis(n); REP(i, 0, n){cin >> lis[i];} vector<int> al(26, 0); REP(i, 0, n){ REP(l, 0, m){ al[(lis[i][l] - 'a')]++; } } int c4 = 0, c2 = 0, c1 = 0; c4 = (n - (n % 2)) / 2 * (m-(m%2)) / 2; c2 = (n % 2) * (m-(m%2)) / 2 + (m % 2) * (n-(n%2)) / 2; c1 = (n%2) * (m%2); int count4 = 0, count2 = 0; REP(i, 0, 26){ while(al[i] >=4 && c4 > count4){ al[i] -= 4; count4++; } } REP(i, 0, 26){ while(al[i] >=2 && c2 > count2){ al[i] -= 2; count2++; } } if(c4 == count4 && c2 == count2){ cout << "Yes" << endl; }else{ cout << "No" << endl; } }
4f7971e579679387457ca0303c9e73547a58109f
79ec46c617501b1cf879335cc80d28053e3b14d3
/BFRM/bfrmR2011_src/bfrmrawdata.cpp
a50fa039bf04fc30f917aa353452ccec83187e5c
[]
no_license
chuangao/BicMix
4307303e849f31ee1eb047735bffb38f7fbd4cb1
60dfbb8785ca1015f8db7b6dd8774f1c01426d12
refs/heads/master
2021-07-21T11:27:39.177178
2021-07-09T05:11:23
2021-07-09T05:11:23
108,202,906
1
1
null
null
null
null
UTF-8
C++
false
false
12,263
cpp
// bfrmrawdata.cpp: implementation of the BfrmRawData class. //Author: Quanli Wang [email protected] //Department of Statistical Science, Duke University ////////////////////////////////////////////////////////////////////// #include "tnt.h" using namespace TNT; #include "stdafx.h" #include "bfrmrawdata.h" ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// BfrmRawData::BfrmRawData() { mnBMask = 0; mnBCarlosMask = 0; mnYFactors = 0; mnControls = 0; mbHasXMask = false; } BfrmRawData::~BfrmRawData() { } //now extended to allow a strip //2 2 2 1 0 0 0 //2 2 2 2 1 0 0 //2 2 2 2 2 1 0 //2 2 2 2 2 2 1 //2 2 2 2 2 2 2 //2 2 2 2 2 2 2 int BfrmRawData::GetBMask(int i, int j, int design, int mode) { if (mode) { //variable selection mode if (i < mnYFactors) { return -1; //-1 means keep it unchanged } } if (mnBMask) { int jaddjust = j - design; if (i==jaddjust) { return 1; } else if (i > jaddjust) { //mask out block coresponding to control--phenotype interaction to zero //Mike 08/21/2005 if (mnControls > 0 && mnBMask == 2) { if (i < mnYFactors && j >= design - mnControls && j < design) { return 0; } } //End of Mike 08/21/2005 return 2; } else { //mnBMask == 2 if (mnBMask == 2) { if (i < mnYFactors && jaddjust >= mnYFactors) { return 2; } } } return 0; } return 2; } int BfrmRawData::GetBMaskAddjust(int j, int design) { int jaddjust = j - design; if (!mnBMask || jaddjust < 0) { jaddjust = 0;} if (mnBMask == 2) { if ( jaddjust >= mnYFactors) { jaddjust = jaddjust - mnYFactors; } } //mask out block coresponding to control--phenotype interaction to zero //Mike 08/21/2005 if (mnControls > 0 && mnBMask == 2) { if (j >= design - mnControls && j < design) { jaddjust = mnYFactors; } } //End of Mike 08/21/2005 return jaddjust; } bool BfrmRawData::InitialiseH(double* data, int nSampleSize, int design) { try { mH = Array2D<double>(nSampleSize, design); if (design <= 1) { mH = 1.0; } else { int index = 0; for (int j = 0; j < design; j++) { for (int i = 0; i < nSampleSize; i++) { mH[i][j] = data[index++]; } } } return true; } catch (...) { return false; } } bool BfrmRawData::InitialiseH(string FileName, int nSampleSize, int design, int control) { mnControls = control; if (design <= 1) { mH = Array2D<double>(nSampleSize, design); mH = 1.0; } else { return LoadData(FileName, mH, nSampleSize, design); } return true; } bool BfrmRawData::ReformatData(int nbinary, int nCategorical, int nSurvival, int nContinuous) { //if we have survival variables int i; mnExtraVariables = 0; for (i = nbinary + nCategorical; i < nbinary + nCategorical + nSurvival; i++) { for (int j = 0; j < mnSampleSize; j++) { if (mWeight[j] > 0 ) { if (mX[i][j] > 0) { mX[i][j] = log(mX[i][j]); } else { std::cout << "Survival time must be positive!" << endl; return false; } } } } //figure out how many extra categarical variables we will need if (nCategorical > 0) { int nExtraVariables = 0; int* nmax= new int[nCategorical]; for (i = nbinary; i < nbinary + nCategorical; i++) { nmax[i-nbinary] = 0; for (int j = 0; j < mnSampleSize; j++) { if (mX[i][j] > nmax[i-nbinary]) { nmax[i-nbinary] = (int)mX[i][j]; } } nExtraVariables += nmax[i-nbinary]; } nExtraVariables -= nCategorical; Array2D<double> newX = Array2D<double>(mnVariables + nExtraVariables, mnSampleSize); mCategorical = Array2D<double>(nCategorical, mnSampleSize); mCategoryIndex = Array2D<int>(nCategorical, 3); int nCount = 0; for (i = 0; i < nbinary; i++) { //binary variables for (int j = 0; j < mnSampleSize; j++) { newX[nCount][j] = mX[i][j]; } nCount++; } for (i = nbinary; i < nbinary + nCategorical; i++) { int nCurrentCV = i - nbinary; for (int j = 0; j < mnSampleSize; j++) { mCategorical[nCurrentCV][j] = mX[i][j]; for (int k = 0; k < nmax[nCurrentCV]; k++) { newX[nCount + k][j] = (((int)mX[i][j]) == (k)) ? 1 : 0; } } mCategoryIndex[nCurrentCV][0] = i; mCategoryIndex[nCurrentCV][1] = nCount; // [) nCount += nmax[nCurrentCV]; mCategoryIndex[nCurrentCV][2] = nCount; } //now all other variables for (i = nbinary + nCategorical; i < mnVariables; i++) { for (int j = 0; j < mnSampleSize; j++) { newX[nCount][j] = mX[i][j]; } nCount++; } mX = Array2D<double>(mnVariables + nExtraVariables, mnSampleSize); for (i = 0; i < mnVariables + nExtraVariables; i++) { for (int j = 0; j < mnSampleSize; j++) { mX[i][j] = newX[i][j]; } } mnVariables += nExtraVariables; mnExtraVariables = nExtraVariables; delete [] nmax; } mnVarBinary = nbinary; mnVarCategorical = nCategorical; mnVarSurvival = nSurvival; mnVarContinuous = nContinuous; mnYFactors = mnVarBinary + mnVarCategorical + mnExtraVariables + mnVarSurvival + mnVarContinuous; return true; } void BfrmRawData::ReformatYMask(Array2D<double>& RawYMask) { int i; int nCount = 0; mYMask = Array2D<double>(mnYFactors, mnSampleSize); for (i = 0; i < mnVarBinary; i++) { //binary variables for (int j = 0; j < mnSampleSize; j++) { mYMask[nCount][j] = RawYMask[i][j]; } nCount++; } for (i = mnVarBinary; i < mnVarBinary + mnVarCategorical; i++) { int nCurrentCV = i - mnVarBinary; int nVar = mCategoryIndex[nCurrentCV][2] - mCategoryIndex[nCurrentCV][1]; for (int j = 0; j < mnSampleSize; j++) { for (int k = 0; k < nVar; k++) { mYMask[nCount + k][j] = RawYMask[i][j]; } } nCount += nVar; } //now all other Y variables for (i = mnVarBinary + mnVarCategorical; i < mnVarBinary + mnVarCategorical + mnVarSurvival + mnVarContinuous; i++) { for (int j = 0; j < mnSampleSize; j++) { mYMask[nCount][j] = RawYMask[i][j]; } nCount++; } } bool BfrmRawData::SaveData(string FileName) { return BfrmData::SaveData(FileName,mX); } bool BfrmRawData::InitialiseWeight(string FileName, int nSampleSize) { if (FileName == "") { mWeight = Array1D<double>(nSampleSize); mWeight = 1.0; mnLeaveout = 0; } else { if (LoadData(FileName,mWeight,nSampleSize)) { mnLeaveout = 0; for (int i = 0; i < nSampleSize; i++) { if (mWeight[i] == 0) { mnLeaveout++; } } std::cout << "Number of samples used " << (nSampleSize - mnLeaveout) << endl; return true; } return false; } return true; } bool BfrmRawData::InitialiseWeight(double* data, int nSampleSize) { try { mWeight = Array1D<double>(nSampleSize); mnLeaveout = 0; for (int i = 0; i < nSampleSize; i++) { mWeight[i] = data[i]; if (mWeight[i] == 0) { mnLeaveout++; } } std::cout << "Number of samples used " << (nSampleSize - mnLeaveout) << endl; return true; } catch (...) { return false; } } bool BfrmRawData::InitialiseYMask(double* data) { //Only if Y exists if (mnYFactors > 0) { try { int i , j; mYMask = Array2D<double>(mnYFactors, mnSampleSize); if (data == NULL) { // no masks mYMask = 0; } else { if (!mnExtraVariables) { int index = 0; for (i = 0; i < mnYFactors; i++) { for (j = 0; j < mnSampleSize; j++) { mYMask[i][j] = data[index++]; } } } else { Array2D<double> RawYMask(mnYFactors - mnExtraVariables,mnSampleSize); int index = 0; for (i = 0; i < mnYFactors; i++) { for (j = 0; j < mnSampleSize; j++) { RawYMask[i][j] = data[index++]; } } ReformatYMask(RawYMask); } return true; } } catch (...) { return false; } } return true; } bool BfrmRawData::InitialiseXMask(string FileName) { if (FileName == "") { // no mask file mbHasXMask = false; return true; } else { mXMask = Array2D<double>(mnVariables - mnYFactors, mnSampleSize); mbHasXMask = LoadData(FileName, mXMask, mnVariables - mnYFactors, mnSampleSize); return mbHasXMask; } return true; } void BfrmRawData::InitiliseX() { if (mbHasXMask) { //fill the missings with mean values int i; //need to take missing values into consideration for ( i = mnYFactors; i < mnVariables; i++) { double sum =0; int nCount = 0; int j; for (j = 0; j < mnSampleSize; j++) { //if observed if ((mWeight[j] > 0) && (mXMask[i-mnYFactors][j] == 0)) { nCount ++ ; sum += mX[i][j]; } } double dmean = sum / nCount; for (j = 0; j < mnSampleSize; j++) { //if missing if ((mWeight[j] > 0) && (mXMask[i-mnYFactors][j] > 0)) { mX[i][j] = dmean; } } } } } bool BfrmRawData::InitialiseYMask(string FileName) { //Only if Y exists if (mnYFactors > 0) { mYMask = Array2D<double>(mnYFactors, mnSampleSize); if (FileName == "") { // no mask file mYMask = 0; } else { if (!mnExtraVariables) { return LoadData(FileName, mYMask, mnYFactors, mnSampleSize); } else { Array2D<double> RawYMask; if (LoadData(FileName, RawYMask, mnYFactors - mnExtraVariables, mnSampleSize)) { ReformatYMask(RawYMask); return true; } } return false; } } return true; } bool BfrmRawData::LoadDataXY(double *data, int rows, int columns, int nBinary, int nCategorical, int nSurvival, int nContinuous) { try { mnVariables = rows; mnSampleSize = columns; mX = Array2D<double>(rows,columns); int index = 0; for (int j = 0; j < columns; j++) { for (int i = 0; i < rows; i++) { mX[i][j] = data[index++]; } } //reformat survival and categorical data if necessary, mnVariables could be changed here return ReformatData(nBinary, nCategorical, nSurvival, nContinuous); } catch (...) { return false; } } bool BfrmRawData::LoadDataXY(string FileName, int nVariables, int nSampleSize, int nBinary, int nCategorical, int nSurvival, int nContinuous) { mnVariables = nVariables; mnSampleSize = nSampleSize; if (!LoadData(FileName,mX,nVariables,nSampleSize)) { return false; } //reformat survival and categorical data if necessary, mnVariables could be changed here return ReformatData(nBinary, nCategorical, nSurvival, nContinuous); } void BfrmRawData::SetBMasks(int nBMask, int nCarlosBMask) { mnBMask = nBMask; mnBCarlosMask = nCarlosBMask; } Array2D<double> BfrmRawData::RowMeanXY() { //calculate row means Array2D<double> Ones(mnSampleSize,1); try { for (int i = 0; i < mnSampleSize; i++) { Ones[0][i] = mWeight[i]; } } catch (...) { Ones = 1; mnLeaveout = 0; } Array2D<double> Mean = matmult(mX,Ones); Mean /= (double)(mnSampleSize-mnLeaveout); return Mean; } void BfrmRawData::SubtractSampleMeans() { int i; if (!mbHasXMask) { Array2D<double> Ones(mnSampleSize,1); for (i = 0; i < mnSampleSize; i++) { Ones[0][i] = mWeight[i]; } Array2D<double> Mean = matmult(mX,Ones); Mean /= (double)(mnSampleSize-mnLeaveout); mX -= matmult(Mean,transpose(Ones)); } else { //need to take missing values into consideration for ( i = 0; i < mnVariables; i++) { //for each variable including response variables double sum =0; int nCount = 0; int j; for (j = 0; j < mnSampleSize; j++) { if ((mWeight[j] > 0) && (i < mnYFactors || ((i >= mnYFactors) && mXMask[i-mnYFactors][j] == 0))) { nCount ++ ; sum += mX[i][j]; } } if (nCount <= 2) { std::cout << "At least two observed values are required for each variable" << endl; exit(1); } double dmean = sum / nCount; for (j = 0; j < mnSampleSize; j++) { if ((mWeight[j] > 0) && (i < mnYFactors || ((i >= mnYFactors) && mXMask[i-mnYFactors][j] == 0))) { mX[i][j] = mX[i][j] - dmean; } else { mX[i][j] = dmean; //does not matter here, would be overwritten anyway } } } } }
5a39fb8a74af7b77e585fdf0e06f8c9d80adde3d
d04827974bbfe5faa46a967af0b7e072ca9e1220
/sgxcdr/dealer/Enclave/crypto.cpp
2780d6e92adfe67cb91937da96b9e5db7b5276ab
[ "Apache-2.0" ]
permissive
krsna1729/c3po
b8640eeba51b10dd9873c15aefd952cfafc469c8
df54425693014cfc0cbe10be897364df00f8523e
refs/heads/master
2022-03-07T02:06:51.784244
2022-02-24T20:37:13
2022-02-24T20:37:13
172,896,481
0
0
Apache-2.0
2022-02-25T02:02:39
2019-02-27T10:42:59
C++
UTF-8
C++
false
false
8,546
cpp
#include "crypto.h" #include <mbedtls/net.h> #include <mbedtls/debug.h> #include "stdlib.h" #include <string.h> #include "ssl_conn_hdlr.h" //<TODO> this must be replaced after KMS integration uint8_t default_aad[] = { 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7 }; uint8_t default_ctr[16] = {0xb2, 0x4b, 0xf2, 0xf7, 0x7a, 0xc5, 0xec, 0x0c, 0x5e, 0x1f, 0x4d, 0xc1, 0xae, 0x46, 0x5e, 0x75}; static Crypto AESGCM(CRYPTO_TYPE_AES_GCM); static Crypto AESCTR(CRYPTO_TYPE_AES_CTR); void emit_debug(char* msg) { mbedtls_printf("%s\n", msg); } void emit_sizet(size_t s) { mbedtls_printf("%d\n", s); } Crypto::Crypto(int t = CRYPTO_TYPE_AES_GCM) { type = t; aad = NULL; aad_size = 0; ctr_num_bit_size = 32; } Crypto::~Crypto() { if (aad != NULL) { delete[] aad; aad = NULL; } } int Crypto::encrypt(char *in, size_t len, char *out, size_t *lenOut) { if (type == CRYPTO_TYPE_AES_GCM) { return encrypt_aesgcm(in, len, out, lenOut); } else if (type == CRYPTO_TYPE_AES_CTR) { return encrypt_aesctr(in, len, out); } else { return CRYPTO_TYPE_UNKNOWN; } } int Crypto::decrypt(char *in, size_t len, char *out, size_t *lenOut) { if (type == CRYPTO_TYPE_AES_GCM) { return decrypt_aesgcm(in, len, out, lenOut); } else if (type == CRYPTO_TYPE_AES_CTR) { return decrypt_aesctr(in, len, out); } else { return CRYPTO_TYPE_UNKNOWN; } } // ************************* AES-GCM APIs ********************************************************* int Crypto::encrypt_aesgcm(char *decMessageIn, size_t len, char *encMessageOut, size_t *lenOut) { uint8_t *origMessage = (uint8_t *) decMessageIn; uint8_t p_dst[BUFLEN] = { 0 }; *lenOut = len + SGX_AESGCM_MAC_SIZE + SGX_AESGCM_IV_SIZE; sgx_status_t status; // Generate the IV (nonce) sgx_read_rand(p_dst + SGX_AESGCM_MAC_SIZE, SGX_AESGCM_IV_SIZE); status = sgx_rijndael128GCM_encrypt(&aesgcm_key, origMessage, len, p_dst + SGX_AESGCM_MAC_SIZE + SGX_AESGCM_IV_SIZE, p_dst + SGX_AESGCM_MAC_SIZE, SGX_AESGCM_IV_SIZE, aad, aad_size, (sgx_aes_gcm_128bit_tag_t *) (p_dst)); if (status != SGX_SUCCESS) { if( status == SGX_ERROR_MAC_MISMATCH) { return -2; } return -1; } memcpy(encMessageOut, p_dst, *lenOut); return 0; } int Crypto::decrypt_aesgcm(char *encMessageIn, size_t len, char *decMessageOut, size_t *lenOut) { uint8_t *encMessage = (uint8_t *) encMessageIn; uint8_t p_dst[BUFLEN] = { 0 }; sgx_status_t status; *lenOut = len - SGX_AESGCM_MAC_SIZE - SGX_AESGCM_IV_SIZE; status = sgx_rijndael128GCM_decrypt(&aesgcm_key, encMessage + SGX_AESGCM_MAC_SIZE + SGX_AESGCM_IV_SIZE, *lenOut, p_dst, encMessage + SGX_AESGCM_MAC_SIZE, SGX_AESGCM_IV_SIZE, aad, aad_size, (sgx_aes_gcm_128bit_tag_t *) encMessage); if (status != SGX_SUCCESS) { if( status == SGX_ERROR_MAC_MISMATCH) { return -2; } return -1; } memcpy(decMessageOut, p_dst, *lenOut); return 0; } int Crypto::set_params_aesgcm(sgx_aes_gcm_128bit_key_t k, uint8_t* a = NULL, size_t s = 0) { memcpy(aesgcm_key, k, SGX_AESGCM_KEY_SIZE); if (a != NULL) { aad_size = s; if (aad == NULL) { aad = new uint8_t[aad_size]; } else { delete[] aad; aad = new uint8_t[aad_size]; } memcpy(aad, a, aad_size); } else { aad = NULL; aad_size = 0; } return 0; } // ************************* AES-GCM APIs ends here *********************************************** // ************************* AES-CTR APIs ******************************************************** int Crypto::encrypt_aesctr(char *plain_str, size_t src_len, char *enc_str) { const uint32_t ctr_num_bit_size = 32; uint8_t ctr[16] = {0xb2, 0x4b, 0xf2, 0xf7, 0x7a, 0xc5, 0xec, 0x0c, 0x5e, 0x1f, 0x4d, 0xc1, 0xae, 0x46, 0x5e, 0x75}; sgx_aes_ctr_128bit_key_t key; memset(key, 0, sizeof(key)); key[2] = 'z'; if (sgx_aes_ctr_encrypt((const sgx_aes_ctr_128bit_key_t*) key, (uint8_t *) plain_str, src_len, ctr, ctr_num_bit_size, (uint8_t *)enc_str) != SGX_SUCCESS) { return -1; } return 0; } int Crypto::decrypt_aesctr(char *enc_str, size_t src_len, char *plain_str) { const uint32_t ctr_num_bit_size = 32; uint8_t ctr[16] = {0xb2, 0x4b, 0xf2, 0xf7, 0x7a, 0xc5, 0xec, 0x0c, 0x5e, 0x1f, 0x4d, 0xc1, 0xae, 0x46, 0x5e, 0x75}; sgx_aes_ctr_128bit_key_t key; memset(key, 0, sizeof(key)); key[2] = 'z'; if (sgx_aes_ctr_decrypt((const sgx_aes_ctr_128bit_key_t*) key, (uint8_t *) enc_str, src_len, ctr, ctr_num_bit_size, (uint8_t *)plain_str) != SGX_SUCCESS) { return -1; } return 0; } int Crypto::set_params_aesctr(sgx_aes_ctr_128bit_key_t k, uint8_t *c) { //set key memcpy(aesctr_key, k, 16); // set counter if (c == NULL) { memcpy(ctr, default_ctr, 16); } else { memcpy(ctr, c, 16); } ctr_num_bit_size = 32; return 0; } // ************************* AES-CTR APIs ends here *********************************************** #if 0 // ******************************* Testing ******************************************************** class Test { public: size_t max; char *str; size_t str_len; size_t test_size; Test() { max = 1024; str = NULL; test_size = 25; str_len = 0; } ~Test() { if (str != NULL) { free(str); str = NULL; } } size_t random_length(); void random_string(); void alloc(size_t); void test_aesgcm(Crypto &); void test_aesctr(Crypto &); }; void Test::alloc(size_t len) { // free previous allocation, if any if (str != NULL) { free(str); } // allocate new buffer of size "len" str = (char*) malloc(len + 1); memset(str, 0, len + 1); str_len = len; } size_t Test::random_length() { // generate random message length not more than "max" // if random length is zero, then make it 25 size_t length; sgx_read_rand((unsigned char*) &length, 8); length = length % max; if (length <= 0) length = 25; return length; } void Test::random_string() { size_t len = random_length(); alloc(len); // create random string of size "length" sgx_read_rand((unsigned char*) str, len); str[len] = '\0'; } void Test::test_aesgcm(Crypto &AESGCM) { for (int i = 0; i < test_size; i++) { random_string(); int ret; size_t encMessageLen = (SGX_AESGCM_MAC_SIZE + SGX_AESGCM_IV_SIZE + str_len); char *encMessage = (char *) malloc((encMessageLen + 1) * sizeof(char)); ret = AESGCM.encrypt(str, str_len, encMessage, &encMessageLen); encMessage[encMessageLen] = '\0'; if (ret != 0) { emit_debug("Test failed!"); } // The decrypted message will contain the same message as the original one. size_t decMessageLen = str_len; char *decMessage = (char *) malloc((decMessageLen + 1) * sizeof(char)); ret = AESGCM.decrypt(encMessage, encMessageLen, decMessage, &decMessageLen); decMessage[decMessageLen] = '\0'; if (ret != 0) { emit_debug("Test failed!"); } if (strncmp(str, decMessage, str_len) == 0) { emit_debug("Test successful!"); } else { emit_debug("Test failed!"); } //clean up free(encMessage); encMessage = NULL; free(decMessage); decMessage = NULL; free(str); str = NULL; } } void Test::test_aesctr(Crypto &AESCTR) { for (int i = 0; i < test_size; i++) { random_string(); int ret; size_t lenOut; char *encMessage = (char *) malloc((str_len + 1) * sizeof(char)); ret = AESCTR.encrypt(str, str_len, encMessage, &lenOut); encMessage[str_len] = '\0'; if (ret != 0) { emit_debug("Test failed!"); } // The decrypted message will contain the same message as the original one. size_t decMessageLen = str_len; char *decMessage = (char *) malloc((decMessageLen + 1) * sizeof(char)); ret = AESCTR.decrypt(encMessage, str_len, decMessage, &decMessageLen); decMessage[decMessageLen] = '\0'; if (ret != 0) { emit_debug("Test failed!"); } if (strncmp(str, decMessage, str_len) == 0) { emit_debug("Test successful!"); } else { emit_debug("Test failed!"); } //clean up free(encMessage); encMessage = NULL; free(decMessage); decMessage = NULL; free(str); str = NULL; } } void test_crypto(int size) { Test t1; t1.test_size = size; emit_debug("testing GCM mode"); // test aes-gcm mode Crypto aesgcm(CRYPTO_TYPE_AES_GCM); aesgcm.set_params_aesgcm(default_key_gcm, default_aad, sizeof(default_aad)); t1.test_aesgcm(aesgcm); Test t2; t2.test_size = size; emit_debug("testing CTR mode"); // test aes-ctr mode Crypto aesctr(CRYPTO_TYPE_AES_CTR); aesgcm.set_params_aesctr(default_key_ctr, default_ctr); t2.test_aesctr(aesctr); } // ******************************* Testing ends here ********************************************** #endif
963801e695a10410a3d1220cd18ed351d5c0a25f
2523d516ce49af7f082685b8a34c7dd8e99a40b1
/Day 20/Binary Search.cpp
fb049889c1ba692733a455968ca47e07fcdfe572
[]
no_license
jtomar24/100-days-of-code
3b3ee0f5421a7dc9b1ceb606b05fffc4feb3c1ac
3f6843507dc635d272aae52ca825ed090cf51f85
refs/heads/main
2023-07-08T12:11:19.332444
2021-08-15T16:26:17
2021-08-15T16:26:17
372,228,583
2
1
null
null
null
null
UTF-8
C++
false
false
209
cpp
class Solution{ public: int binarysearch(int arr[], int n, int k){ int s=0, e=n-1, mid; while(s<=e) { mid=(s+e)/2; if(arr[mid]==k) return mid; else if(k < arr[mid]) e=mid-1; else s=mid+1; } return -1; } };
ebd09d247f18e617117e4b56dcdaf72f040b75ba
9f9660f318732124b8a5154e6670e1cfc372acc4
/Case_save/Case20/Case/case3/1100/alphat
4b2efbfdec9b43874b9415003aa63fd2fe8348c5
[]
no_license
mamitsu2/aircond5
9a6857f4190caec15823cb3f975cdddb7cfec80b
20a6408fb10c3ba7081923b61e44454a8f09e2be
refs/heads/master
2020-04-10T22:41:47.782141
2019-09-02T03:42:37
2019-09-02T03:42:37
161,329,638
0
0
null
null
null
null
UTF-8
C++
false
false
9,406
/*--------------------------------*- C++ -*----------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Version: 6 \\/ M anipulation | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volScalarField; location "1100"; object alphat; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [1 -1 -1 0 0 0 0]; internalField nonuniform List<scalar> 459 ( 0.00125388 0.00137107 0.00139675 0.00146392 0.00152613 0.00158436 0.00164147 0.0016972 0.00173647 0.0017529 0.0017406 0.00169598 0.00161882 0.00151559 0.00140229 0.000550629 0.000673219 0.000757157 0.00075226 0.000726254 0.000692183 0.000649531 0.000607286 0.000568932 0.00053486 0.000504672 0.000477834 0.000453956 0.000432505 0.000412717 0.000393599 0.000373693 0.000359435 0.000327325 0.00170703 0.00417513 0.00399779 0.00465361 0.0052984 0.00594314 0.00651183 0.00694031 0.00732756 0.00764206 0.0078399 0.00787133 0.00766053 0.00701696 0.00524966 0.00143004 0.000841137 0.000595394 0.00124892 0.00172331 0.00206109 0.00223858 0.00222863 0.00179255 0.00154662 0.00137044 0.00123512 0.00112751 0.00103997 0.000964587 0.000894389 0.000826338 0.000765861 0.000713293 0.000835125 0.000427443 0.00208349 0.00570241 0.00496188 0.00622125 0.00685104 0.00731927 0.00768362 0.00797494 0.00829041 0.00861877 0.00892113 0.00914269 0.00922264 0.00907104 0.00844911 0.00651411 0.00142291 0.0011876 0.00170496 0.00218149 0.00260333 0.00288609 0.00280263 0.000929838 0.000821153 0.000733843 0.000663391 0.000605989 0.00055872 0.000519488 0.000486957 0.000460572 0.000496254 0.000573702 0.000938447 0.000494196 0.00244428 0.0072862 0.00497816 0.0065849 0.0071379 0.00732853 0.00745447 0.00760699 0.00785982 0.00819668 0.008577 0.00893259 0.00920033 0.00930926 0.00917601 0.00850884 0.00622582 0.00170242 0.00211025 0.00272104 0.00330565 0.00376243 0.00403506 0.0037719 0.00104902 0.000954949 0.000887583 0.000836278 0.000792778 0.000752912 0.00071468 0.000674593 0.000628131 0.00058924 0.000602265 0.00107097 0.000545991 0.00281184 0.00931895 0.00547402 0.00634302 0.00707414 0.00712703 0.007072 0.0071568 0.00738051 0.00772287 0.00814895 0.00856501 0.00888349 0.00903417 0.00899244 0.00870963 0.00799033 0.00660884 0.00613263 0.00597079 0.00590924 0.00586624 0.00579377 0.00556279 0.0046947 0.00427846 0.00403811 0.00385416 0.00366067 0.00338063 0.00299982 0.00253505 0.00201692 0.001494 0.00110127 0.00110169 0.000732601 0.000672493 0.000814213 0.000913904 0.00320129 0.0115316 0.00753343 0.00632265 0.00687401 0.00712476 0.00697175 0.00704038 0.0072088 0.00751488 0.00794436 0.00839959 0.00874945 0.00889324 0.00880837 0.00854985 0.00820641 0.00784866 0.00764366 0.00748753 0.00731089 0.00711217 0.00689385 0.0066265 0.00623741 0.00589224 0.00558766 0.00529563 0.00499701 0.0046706 0.00425661 0.00373953 0.00311953 0.00243229 0.00182344 0.001361 0.00102392 0.000868921 0.00123815 0.000953536 0.00355514 0.0130762 0.0105485 0.00815327 0.00771626 0.00761834 0.00736072 0.00719969 0.0072548 0.00755348 0.00802922 0.0085365 0.00890444 0.00901455 0.00885596 0.00854247 0.00827226 0.00817606 0.00817759 0.00809135 0.00786898 0.00755406 0.00718502 0.00678049 0.00635645 0.00596287 0.00560084 0.00526141 0.00494492 0.00465917 0.00440464 0.00405956 0.00357405 0.00297933 0.00240597 0.00189118 0.00151276 0.0013922 0.00141871 0.0010847 0.00362127 0.0116188 0.0103311 0.00954682 0.00884407 0.00803376 0.00740491 0.00716016 0.0073221 0.0078024 0.00843632 0.00901431 0.00934142 0.00932595 0.00901593 0.00860659 0.00835842 0.0083485 0.00834171 0.00807866 0.00763396 0.00709487 0.0065295 0.00599314 0.00552205 0.00512382 0.00478348 0.00449307 0.00425673 0.00408454 0.00398639 0.00393519 0.00369436 0.00330829 0.00296544 0.00278085 0.00287101 0.00330032 0.00406369 0.00169164 0.00352146 0.00417892 0.00464172 0.0047578 0.00485896 0.00513526 0.00568831 0.00652638 0.00755073 0.00858325 0.00943314 0.00992132 0.00993129 0.00952308 0.00891526 0.00849628 0.00825184 0.00803426 0.00768094 0.00713357 0.0064724 0.00579627 0.00518532 0.00467893 0.0042757 0.00395151 0.00368185 0.00345212 0.00325358 0.00307791 0.00291631 0.0027682 0.00265166 0.00256554 0.00253053 0.00253858 0.00252352 0.00242442 0.00226855 0.00159113 0.00175947 0.00360697 0.00586156 0.00773165 0.00918417 0.0102862 0.0109756 0.0112411 0.0111252 0.0106191 0.00982965 0.00885302 0.00802388 0.00750325 0.00707651 0.00656083 0.00594203 0.00529072 0.00467808 0.00415024 0.00373192 0.00340781 0.00315275 0.00294724 0.00278045 0.00264762 0.00254719 0.00247898 0.0024457 0.00244526 0.00246127 0.00248909 0.00252001 0.00252694 0.0024658 0.00232217 0.0021053 0.00132468 0.00235251 0.00604527 0.00899775 0.0101159 0.0106732 0.0108404 0.0105893 0.00999259 0.0091719 0.00824597 0.00736977 0.00658821 0.00595517 0.00541404 0.00487182 0.00434475 0.00388343 0.00351239 0.00322776 0.00301167 0.00283687 0.00268868 0.0025606 0.00245571 0.00237732 0.00232519 0.00229835 0.00229517 0.00232175 0.00237491 0.00245068 0.00254052 0.00262599 0.00268501 0.00266357 0.00269479 0.00273568 0.00135035 0.00208694 0.00221188 0.0023 0.00246251 0.00237607 0.00227667 0.00221211 0.00212141 0.00199189 0.00183137 0.00165098 0.00146351 0.00128158 0.00112552 0.00100763 0.000923889 0.00086464 0.000822094 0.000791445 0.000769878 0.0007556 0.00074751 0.000744882 0.000747892 0.000757044 0.000772036 0.00079265 0.000819297 0.000852632 0.000893551 0.000941002 0.000995048 0.00105626 0.00112515 0.00120115 0.00129145 0.00132046 0.00128663 0.00120923 0.001127 ) ; boundaryField { floor { type compressible::alphatWallFunction; Prt 0.85; value nonuniform List<scalar> 29 ( 0.000197812 7.69566e-05 9.52688e-05 0.00010757 0.000106857 0.000103061 9.80635e-05 9.17647e-05 8.5476e-05 7.972e-05 7.45662e-05 6.99656e-05 6.58467e-05 6.21572e-05 5.88219e-05 5.57265e-05 5.27177e-05 4.95648e-05 4.72931e-05 4.21336e-05 4.2133e-05 5.80321e-05 6.83615e-05 7.62547e-05 0.00019781 7.69557e-05 8.36958e-05 0.000168457 0.000238024 ) ; } ceiling { type compressible::alphatWallFunction; Prt 0.85; value nonuniform List<scalar> 43 ( 0.000288324 0.00030447 0.000315802 0.0003367 0.00032572 0.000313003 0.00030471 0.000293005 0.00027619 0.000255177 0.000231319 0.000206215 0.000181505 0.000159989 0.000143508 0.000131666 0.000123211 0.000117097 0.00011267 0.000109542 0.000107466 0.000106287 0.000105904 0.000106343 0.000107676 0.000109856 0.000112845 0.000116695 0.000121491 0.000127347 0.000134099 0.00014174 0.000150337 0.000159942 0.000170462 0.000182863 0.000186825 0.000182204 0.000171577 0.000160203 0.000469213 0.000549178 0.000322362 ) ; } sWall { type compressible::alphatWallFunction; Prt 0.85; value uniform 0.000287115; } nWall { type compressible::alphatWallFunction; Prt 0.85; value nonuniform List<scalar> 6(0.000129928 0.000135549 0.000153975 0.000187076 0.000190571 0.000159881); } sideWalls { type empty; } glass1 { type compressible::alphatWallFunction; Prt 0.85; value nonuniform List<scalar> 9(0.000173295 0.000233545 0.000282376 0.000328371 0.000374556 0.000422851 0.00046625 0.000474442 0.000462497); } glass2 { type compressible::alphatWallFunction; Prt 0.85; value nonuniform List<scalar> 2(0.000235042 0.000221779); } sun { type compressible::alphatWallFunction; Prt 0.85; value nonuniform List<scalar> 14 ( 0.0001776 0.000193582 0.000197065 0.000206146 0.000214514 0.000222313 0.00022993 0.000237335 0.000242537 0.000244709 0.000243083 0.000237171 0.000226908 0.000213095 ) ; } heatsource1 { type compressible::alphatWallFunction; Prt 0.85; value nonuniform List<scalar> 3(9.52654e-05 0.000115945 0.000130231); } heatsource2 { type compressible::alphatWallFunction; Prt 0.85; value nonuniform List<scalar> 4(0.000201688 0.000119823 0.000119821 0.000200721); } Table_master { type compressible::alphatWallFunction; Prt 0.85; value nonuniform List<scalar> 9(0.000132493 0.000116943 0.000104274 9.3918e-05 8.53813e-05 7.82766e-05 7.23232e-05 6.73439e-05 6.32745e-05); } Table_slave { type compressible::alphatWallFunction; Prt 0.85; value nonuniform List<scalar> 9(0.000149305 0.000136058 0.000126477 0.000119124 0.000112847 0.000107058 0.000101472 9.55755e-05 8.86875e-05); } inlet { type fixedValue; value uniform 1.94e-05; } outlet { type zeroGradient; } } // ************************************************************************* //
e48877cfccd1c798e4596fb7d8e7ffc33acf1fd4
38d26a6f0352729d63f8eaab275f9a5bd7450a2e
/8VC Venture Cup 2016 - Elimination Round/A/main.cpp
bb49266bd0d925d352523ac315224495a8be0f69
[]
no_license
Shadek07/codeforces
4a7c5443a9751041d067b84f04fe166f8222bc15
39e5504238467ee55702f1f8ebe22760cf724df5
refs/heads/master
2022-07-15T22:28:51.869195
2016-12-19T10:33:50
2016-12-19T10:33:50
265,459,527
1
0
null
null
null
null
UTF-8
C++
false
false
2,462
cpp
#pragma comment(linker,"/STACK:16777216") #pragma warning ( disable: 4786) #include <bits/stdc++.h> using namespace std; #define max(x,y) ((x)>(y)?(x):(y)) #define min(x,y) ((x)<(y)?(x):(y)) #define forl(i,a,b) for ( i = a; i < b; i++) #define fore(i,a,b) for ( i = a; i <= b; i++) #define forrev(i,a,b) for ( i = a; i >= b; i--) #define MID(a, b) (a + ((b - a) >> 1)) #define pb push_back typedef long long LL; #define in(a,b,c) ((a) <= (b) && (b) <= (c)) #define ms(a,b) memset((a),(b),sizeof(a)) #define all(v) (v).begin(),(v).end() #define pb push_back #define ull unsigned long long int typedef vector<int> vi; typedef vector<string> vs; typedef pair<int,int> pii; typedef vector<pii> vpii; string to_string(long long x) { stringstream ss; ss << x; return ss.str(); } long long to_int(const string &s) { stringstream ss; ss << s; long long x; ss >> x; return x; } #define MAX 205 #define INF 9999999 int main(void) { //freopen("1.txt", "r", stdin); //freopen("2.txt", "w", stdout); char in[MAX]; int pref[MAX][4]; //d,u,l,r int n,i,j,k; while(cin >> n){ getchar(); gets(in); ms(pref,0); forl(i,0,n){ if(in[i] == 'D'){ pref[i+1][1] = pref[i][1]; pref[i+1][2] = pref[i][2]; pref[i+1][3] = pref[i][3]; pref[i+1][0] = pref[i][0] + 1; }else if(in[i] == 'U'){ pref[i+1][0] = pref[i][0]; pref[i+1][2] = pref[i][2]; pref[i+1][3] = pref[i][3]; pref[i+1][1] = pref[i][1] + 1; } else if(in[i] == 'L'){ pref[i+1][0] = pref[i][0]; pref[i+1][1] = pref[i][1]; pref[i+1][3] = pref[i][3]; pref[i+1][2] = pref[i][2] + 1; } else if(in[i] == 'R'){ pref[i+1][0] = pref[i][0]; pref[i+1][1] = pref[i][1]; pref[i+1][2] = pref[i][2]; pref[i+1][3] = pref[i][3] + 1; } } int cnt=0; forl(i,0,n){ forl(j,i+1,n){ bool ok=true; int a = (pref[j+1][0] - pref[i][0]) - (pref[j+1][1] - pref[i][1]); int b = (pref[j+1][2] - pref[i][2]) - (pref[j+1][3] - pref[i][3]); if(a == 0 && b ==0) cnt++; } } cout << cnt << endl; } return 0; }
f954fee22dd1cd6cbf24e1c017a7ddeeab24e598
19d71dcbb85aff2f5de031f65fd0dd412d5fe06e
/include/AST/expression/realtion_expr.h
4c9ed729876e5a78c673299b3aaf0da2a0f7ed1b
[ "MIT" ]
permissive
przestaw/vecc_SimpleLanguage
1daefb546199615e8e521fdc8ab5613be9d209fc
a48bb8c0e53cc5f256c926cdb28cf39b107d66ee
refs/heads/master
2022-10-04T02:21:53.870701
2020-06-04T09:28:52
2020-06-04T09:28:52
246,838,921
0
0
null
null
null
null
UTF-8
C++
false
false
1,490
h
// // Created by przemek on 20.03.2020. // #ifndef VECC_LANG_ADDITIVE_EXPR_H #define VECC_LANG_ADDITIVE_EXPR_H #include <AST/expression/expression.h> #include <AST/general/variable.h> #include <memory> namespace vecc::ast { /** * Class describing Relational Expression */ class RelationExpr : public Expression { public: /** * Type of operation */ enum class OperatorType { Equal, //!< == NotEqual, //!< != Greater, //!< > GreaterOrEqual, //!< >= Less, //!< < LessOrEqual, //!< <= }; /** * Constructor * @param lVal left side of relation * @param type OperatorType * @param rVal right side of relation * @param position Position of relation used to inform about errors */ RelationExpr(std::unique_ptr<Expression> lVal, const OperatorType &type, std::unique_ptr<Expression> rVal, const Position &position = Position()); /** * Calculate value of Expression * @return Expression value */ [[nodiscard]] Variable calculate() const override; /** * Returns simplified AST representation * @return simplified AST */ [[nodiscard]] std::string toString() const override; private: OperatorType type_; std::unique_ptr<Expression> lVal_; Position pos_; std::unique_ptr<Expression> rVal_; }; } // namespace vecc::ast #endif // VECC_LANG_ADDITIVE_EXPR_H
ce58d36b503a66d89c64f2117cce6df92f1173e4
f9bc0403229a9bfa8e865eb405594b7a0831a20b
/C++/LuoGu1164.cpp
f2a98cda39d2dca9e0e87b5927cec2eb8a0b3146
[]
no_license
firstfan119/first_fan-s-code-on-luogu
06251c519d9be54a972ec7da56a4dd95aa803c08
3e15f939a1db9a949d86f48590508ab59031f15d
refs/heads/master
2020-08-27T05:24:50.576917
2019-10-24T09:15:24
2019-10-24T09:15:24
217,255,672
0
0
null
null
null
null
GB18030
C++
false
false
583
cpp
#include <bits/stdc++.h> using namespace std; int type,lim; int val[110]; int dp[110][10010]; //前i道菜当中恰好花j元的方案数 void input() { scanf("%d%d",&type,&lim); for(int i=1;i<=type;i++) { scanf("%d",&val[i]); } } int main() { input(); for(int i=1;i<=type;i++) { for(int j=1;j<=lim;j++) { if(j==val[i]) { dp[i][j]=dp[i-1][j]+1; } else if(j>val[i]) { dp[i][j]=dp[i-1][j]+dp[i-1][j-val[i]]; } else if(j<val[i]) { dp[i][j]=dp[i-1][j]; } } } cout<<dp[type][lim]; return 0; }
cddff203d6ad4df0bc286a5a8a50aca693ff05e6
aa701cd580bb209e958897b885b76988671ccc86
/450-Questions-List/Array/problem16.cpp
609e9f6809ae683159398595b13aee78deeb74fa
[]
no_license
rahulMishra05/DSA-Problems
b0b51e720e8e7fd5278fe77376d6e5e390754639
8cbc6cf05b279f9c9b125e7dffb01e9adf359d35
refs/heads/main
2023-08-14T21:47:56.097005
2021-09-30T10:28:32
2021-09-30T10:28:32
361,634,452
0
0
null
null
null
null
UTF-8
C++
false
false
327
cpp
// Question => Count Inversion #include<iostream> using namespace std; int main(){ int n = 4; int arr[] = {8,4,2,1}; long count = 0; for(int i=0; i<n; i++){ for(int j = i+1; i<n; j++){ if(arr[i] > arr[j]){ count++; } } } cout<<count<<endl; }
3455d47f242f2666f2a994e435f469c90c4ee3f7
17230d981c03ec6e2dbd1fe3a9ab57d8d6199daf
/src/PlayingState.cc
ac52acac11f00d8af38340799953118662e268a3
[]
no_license
danielrugutt/pacman-game
7f7938da255d4d590695d4311456982c9cb1bead
91dccd53e078bfd1519f59226389f36d5e85c8d1
refs/heads/master
2023-05-25T04:56:54.954205
2021-06-09T18:40:26
2021-06-09T18:40:26
374,218,996
0
0
null
null
null
null
UTF-8
C++
false
false
10,833
cc
#include "PlayingState.hpp" #include <SFML/Graphics.hpp> #include "Resources.hpp" #include "PacMan.hpp" #include "Directions.hpp" #include "Ghost.hpp" #include "Player.hpp" #include "Engine.hpp" #include <cmath> #include <random> #include <cstdlib> #include <assert.h> #include <iostream> using namespace sf; void PlayingState::init() { console = new Console("PlayingState"); labyrinth = new Labyrinth(); pacman = new PacMan(); blinky = new Ghost(13, 14, 3, 4); pinky = new Ghost(13, 17, 23, 4); inky = new Ghost(11, 17, 26, 32); clyde = new Ghost(15, 17, 1, 32); blinky->teleport(13, 14); console->writeLine("Finish initializing playing state"); console->writeLine("Init done"); waitTime = 0; // Open a textbox to input name this->paused = false; Window window; std::string name; window.setKeyRepeatEnabled(false); while (window.isOpen()) { window.display(); Event event; while (window.pollEvent(event)) { switch (event.type) { case (Event::Closed): window.close(); break; case (Event::TextEntered): if (event.text.unicode >= 33 && event.text.unicode <= 126) { assert(name.size() <= 3/*, "Enter only 3 characters"*/); name += (char)event.text.unicode; } else if (event.text.unicode == 8) { name = name.substr(0, name.length() - 1); } } } } } void PlayingState::loop() { if (pacmanCanMove() && !pacman->isDead()) { pacman->move(); } else { pacman->stop(); } if (labyrinth->isIntersection(pacman->getTileX(), pacman->getTileY())) { pacman->stop(); } labyrinth->removeDot(pacman, blinky, pinky, inky, clyde); if (!pacman->getDirections().empty()) { if (!blinky->isScattering()) { blinky->setDestination(pacman->getTileX(), pacman->getTileY()); } if (!pinky->isScattering()) { switch (pacman->getDirections().front()) { case Direction::Up: pinky->setDestination(pacman->getTileX(), pacman->getTileY() - 4); break; case Direction::Down: pinky->setDestination(pacman->getTileX(), pacman->getTileY() + 4); break; case Direction::Left: pinky->setDestination(pacman->getTileX() - 4, pacman->getTileY()); break; case Direction::Right: pinky->setDestination(pacman->getTileX() + 4, pacman->getTileY()); break; } } if(!inky->isScattering()) { inky->setDestination(pacman->getTileX() + (blinky->getTileX() - pacman->getTileX()), pacman->getTileY() + (blinky->getTileY() - pacman->getTileY())); } if (!clyde->isScattering()) { if (sqrt(pow((clyde->getTileX() - (pacman->getTileX())), 2) + pow((clyde->getTileY() - (pacman->getTileY())), 2)) < 9) { clyde->setDestination(pacman->getTileX(), pacman->getTileY()); } else { clyde->setDestination(1, 32); } } } handleGhostMovement(blinky); handleGhostMovement(pinky); handleGhostMovement(inky); handleGhostMovement(clyde); //teleports ghosts depending on how many dots the pacman has ate if(pacman->getDotsEaten() == 5) pinky->teleport(13, 14); if (pacman->getDotsEaten() == 50) inky->teleport(13, 14); if (pacman->getDotsEaten() == 100) clyde->teleport(13, 14); teleportTunnels(pacman); teleportTunnels(blinky); teleportTunnels(pinky); teleportTunnels(inky); teleportTunnels(clyde); handleGhostFrightening(blinky); handleGhostFrightening(pinky); handleGhostFrightening(inky); handleGhostFrightening(clyde); if (pacman->getDotsEaten() == 240) { //end of round blinky->teleport(-2, -2); pinky->teleport(-2, -2); inky->teleport(-2, -2); clyde->teleport(-2, -2); waitTime++; } if (pacman->isDead()) { waitTime++; } if (waitTime == 200) { if (pacman->isDead()) { if (blinky->isOutOfCage()) blinky->teleport(13, 14); if (pinky->isOutOfCage()) pinky->teleport(13, 14); if (inky->isOutOfCage()) inky->teleport(13, 14); if (clyde->isOutOfCage()) clyde->teleport(13, 14); pacman->teleport(13, 26); pacman->setDead(false); int lives = pacman->getLives(); lives--; pacman->setLives(lives); waitTime = 0; } else { PlayingState::init(); waitTime = 0; } } if (pacman->getLives() == 0) { console->writeLine("Game over :("); Engine::scoreboard(pacman->getDotsEaten()); pacman->setLives(3); pacman->setDead(false); PlayingState::init(); waitTime = 0; } } int PlayingState::getPacManPoints() { return pacman->getDotsEaten(); } // void PlayingState::SaveData(std::string& name, int& score) { // Player player; // player.name = name; // player.score = score; // } void PlayingState::render(RenderWindow* window) { Sprite pacmanSprite; Sprite blinkySprite; Sprite pinkySprite; Sprite inkySprite; Sprite clydeSprite; if (pacman->getDirections().empty()) { pacmanSprite = *Resources::get(Resources::PacMan, false, Direction::Unset); } else { pacmanSprite = *Resources::get(Resources::PacMan, true, pacman->getDirections().front()); } if (pacman->isDead()) { pacmanSprite = *Resources::get(Resources::DeadPacMan, true, Direction::Unset); } if (!blinky->isFrightened()) { blinkySprite = *Resources::get(Resources::Blinky, blinky->isOutOfCage(), blinky->getDirection()); } else { blinkySprite = *Resources::get(Resources::FrightenedGhost, blinky->isOutOfCage(), blinky->getDirection()); } if (!pinky->isFrightened()) { pinkySprite = *Resources::get(Resources::Pinky, pinky->isOutOfCage(), pinky->getDirection()); } else { pinkySprite = *Resources::get(Resources::FrightenedGhost, pinky->isOutOfCage(), pinky->getDirection()); } if (!inky->isFrightened()) { inkySprite = *Resources::get(Resources::Inky, inky->isOutOfCage(), inky->getDirection()); } else { inkySprite = *Resources::get(Resources::FrightenedGhost, inky->isOutOfCage(), inky->getDirection()); } if(!clyde->isFrightened()) { clydeSprite = *Resources::get(Resources::Clyde, clyde->isOutOfCage(), clyde->getDirection()); } else { clydeSprite = *Resources::get(Resources::FrightenedGhost, clyde->isOutOfCage(), clyde->getDirection()); } pacmanSprite.setPosition(pacman->getScreenPosX(), pacman->getScreenPosY()); blinkySprite.setPosition(blinky->getScreenPosX(), blinky->getScreenPosY()); pinkySprite.setPosition(pinky->getScreenPosX(), pinky->getScreenPosY()); inkySprite.setPosition(inky->getScreenPosX(), inky->getScreenPosY()); clydeSprite.setPosition(clyde->getScreenPosX(), clyde->getScreenPosY()); for (int i = 0; i < Labyrinth::SizeX; i++) { for (int j = 0; j < Labyrinth::SizeY; j++) { Resources::LabyrinthPieces[labyrinth->getTileCode(i, j)]->setPosition(i * 16.0f, j * 16.0f); window->draw(*Resources::LabyrinthPieces[labyrinth->getTileCode(i, j)]); } } window->draw(pacmanSprite); window->draw(blinkySprite); window->draw(pinkySprite); window->draw(inkySprite); window->draw(clydeSprite); } void PlayingState::keyPressed(int code) { switch (code) { case Keyboard::Up: pacman->queueDirection(Direction::Up); break; case Keyboard::Down: pacman->queueDirection(Direction::Down); break; case Keyboard::Left: pacman->queueDirection(Direction::Left); break; case Keyboard::Right: pacman->queueDirection(Direction::Right); break; // case Keyboard::P: // if (!paused) { // PlayingState::ghostCanMove(); // PlayingState::pacmanCanMove(); // break; // } // !PlayingState::ghostCanMove(); // !PlayingState::pacmanCanMove(); // paused = true; } } void PlayingState::keyReleased(int code) { } bool PlayingState::pacmanCanMove() { if (!pacman->getDirections().empty()) { switch (pacman->getDirections().front()) { case Direction::Up: return !labyrinth->tileBlocksEntity(pacman->getTileX(), pacman->getTileY() - 1); break; case Direction::Down: return !labyrinth->tileBlocksEntity(pacman->getTileX(), pacman->getTileY() + 1); break; case Direction::Left: return !labyrinth->tileBlocksEntity(pacman->getTileX() - 1, pacman->getTileY()); break; case Direction::Right: return !labyrinth->tileBlocksEntity(pacman->getTileX() + 1, pacman->getTileY()); break; } } return true; } void PlayingState::handleGhostMovement(Ghost* ghost) { if (ghost->isScattering()) { if (ghost->getTileX() == ghost->getDestX() && ghost->getTileY() == ghost->getDestY()) { ghost->setScattering(false); } } if (labyrinth->isIntersection(ghost->getTileX(), ghost->getTileY())) { if (ghost->shouldTakeDecision()) { float dirRight = calculateDistance(ghost, 1, 0); float dirLeft = calculateDistance(ghost, -1, 0); float dirUp = calculateDistance(ghost, 0, -1); float dirDown = calculateDistance(ghost, 0, 1); if (dirRight < dirLeft && dirRight < dirUp && dirRight < dirDown) { ghost->setDirection(Direction::Right); } else if (dirLeft < dirRight && dirLeft < dirUp && dirLeft < dirDown) { ghost->setDirection(Direction::Left); } else if (dirUp < dirLeft && dirUp < dirRight && dirUp < dirDown) { ghost->setDirection(Direction::Up); } else if (dirDown < dirLeft && dirDown < dirUp && dirDown < dirRight) { ghost->setDirection(Direction::Down); } } ghost->setTakeDecision(false); } else { ghost->setTakeDecision(true); } if (ghostCanMove(ghost) && ghost->isOutOfCage()) { ghost->move(); } else { ghost->setTakeDecision(true); } } bool PlayingState::ghostCanMove(Ghost* ghost) { switch (ghost->getDirection()) { case Direction::Up: return !labyrinth->tileBlocksEntity(ghost->getTileX(), ghost->getTileY() - 1); break; case Direction::Down: return !labyrinth->tileBlocksEntity(ghost->getTileX(), ghost->getTileY() + 1); break; case Direction::Left: return !labyrinth->tileBlocksEntity(ghost->getTileX() - 1, ghost->getTileY()); break; case Direction::Right: return !labyrinth->tileBlocksEntity(ghost->getTileX() + 1, ghost->getTileY()); break; default: return false; } } float PlayingState::calculateDistance(Ghost* ghost, int addX, int addY) { float distance = 1000000.0f; if (!labyrinth->tileBlocksEntity(ghost->getTileX() + addX, ghost->getTileY() + addY)) { distance = (float) sqrt(pow((ghost->getDestX() - (ghost->getTileX() + addX)), 2) + pow((ghost->getDestY() - (ghost->getTileY() + addY)), 2)); } return distance; } void PlayingState::teleportTunnels(Entity* entity) { if (entity->getTileX() == 0 && entity->getTileY() == 17) { entity->teleport(26, 17); } else if (entity->getTileX() == 27 && entity->getTileY() == 17) { entity->teleport(1, 17); } } void PlayingState::handleGhostFrightening(Ghost* ghost) { if (pacman->getTileX() == ghost->getTileX() && pacman->getTileY() == ghost->getTileY()) { if (ghost->isFrightened()) { ghost->teleport(13, 14); ghost->setFrightened(false); } else { pacman->setDead(true); blinky->teleport(-2, -2); pinky->teleport(-2, -2); inky->teleport(-2, -2); clyde->teleport(-2, -2); } } }
2121d803a10bd977f8b34ed773c8155788cfaf0a
f3495224144e61c612a0c01449a0dba05fc4c4a3
/usingLib/exampleA/lib/advancelib.cpp
43a5f9c49830bb461407eeaf40e7fab3e31e0567
[]
no_license
dangvanuy/CLibrary
434287cf2dd1d4b4a717ce94a0865e3619a1110c
b26ffea2a7a92dda7c7b66f66b65fa8b85b3bcf4
refs/heads/master
2020-05-17T18:07:15.190055
2014-12-04T02:25:52
2014-12-04T02:25:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
140
cpp
#include <stdio.h> #include "advancelib.h" #include "basiclib.h" void libAdvance_funA() { libBasic_funA(); printf("libBasic_funA\n"); }
73031aa6963d47fcd7442676ad8922001a186a99
b0b31c7b0bfdc82202e032891eb84f24980173db
/EmployeeLibrary/Manager.h
cdf5f7aa64d448b26075baf02b198ad40d1e3553
[]
no_license
samueldmaus/employee-timesheet-project
87fa28d301ca474ba93ae41fb2ad410c419e506a
988c056e37055ce424281e383818c179e2f23053
refs/heads/main
2023-04-05T10:57:56.279689
2021-04-09T23:49:35
2021-04-09T23:49:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
702
h
#ifndef MANAGER_H #define MANAGER_H #include "Department.h" #include "Employee.h" class Manager : public Employee { public: Manager(unsigned int id, std::string name, std::string email, std::string password); Manager& operator=(Manager&& rhs) noexcept; Manager(Manager&& src) noexcept; std::shared_ptr<Department> getDepartment(const std::string& department); void addEmployee(unsigned int id, const std::string& name, const std::string& email, const std::string& password, const std::string& name_of_department) const; void createDepartment(std::string name); void addDepartment(Department& department); private: std::vector<std::shared_ptr<Department>> departments_; }; #endif
1f8d249fffbe69767551f063884237416972ed58
771559e4fb2c36d3eb272cad1d79236a8c47c891
/primer/3.36.cpp
f78c2f31d94033c94a898a5f6930a4660164333a
[]
no_license
shanewa/coding
9ce4ce90969cc92131c552c5d6e0a79eb993f83d
7021b8f0e3c43dc687e01aeac488ee877b2f1f54
refs/heads/main
2023-03-27T04:50:00.935091
2021-03-24T14:30:18
2021-03-24T14:30:18
350,664,617
0
0
null
null
null
null
UTF-8
C++
false
false
282
cpp
#include <iostream> #include <vector> using namespace std; int main() { vector<int> test1 = {1, 2, 3, 4}; vector<int> test2 = {1, 2, 3, 4}; if (test1 == test2) { cout << "=" << endl; } else { cout << "!=" << endl; } return 0; }
5154e826c421a49bc46eacca3caf10a69f3b0ab9
37eeaf9713eeaa9b345c8d0f35dfcee45bf4a4dc
/libcaf_core/src/sync_request_bouncer.cpp
6cb47825d405865371e3c8f85700a56b61842469
[ "BSL-1.0" ]
permissive
Boubou818/actor-framework
377a18fccbb83cfb317d39e5842d4a33a5190ce3
da90ef78b26da5d225f039072e616da415c48494
refs/heads/master
2020-04-27T07:46:42.948823
2019-03-05T19:17:33
2019-03-05T19:17:33
174,147,348
1
0
NOASSERTION
2019-03-06T13:08:56
2019-03-06T13:08:55
null
UTF-8
C++
false
false
2,331
cpp
/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright 2011-2018 Dominik Charousset * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #include "caf/sec.hpp" #include "caf/atom.hpp" #include "caf/actor.hpp" #include "caf/config.hpp" #include "caf/actor_cast.hpp" #include "caf/message_id.hpp" #include "caf/exit_reason.hpp" #include "caf/mailbox_element.hpp" #include "caf/system_messages.hpp" #include "caf/detail/sync_request_bouncer.hpp" namespace caf { namespace detail { sync_request_bouncer::sync_request_bouncer(error r) : rsn(std::move(r)) { // nop } void sync_request_bouncer::operator()(const strong_actor_ptr& sender, const message_id& mid) const { if (sender && mid.is_request()) sender->enqueue(nullptr, mid.response_id(), make_message(make_error(sec::request_receiver_down)), // TODO: this breaks out of the execution unit nullptr); } void sync_request_bouncer::operator()(const mailbox_element& e) const { (*this)(e.sender, e.mid); } } // namespace detail } // namespace caf
94a2b3d7c087cdf393e4b7892fd86696bd392ee6
7353a670a04d55068dc9eb4436d06f834e145efe
/libs/future/hpp/future_.hpp
4d0f6224eca03c3cb4d931a63bf864badc92c7e0
[]
no_license
shinobu-x/cpp
a53b25d6c81dbafad59bb9b288f630153ccb0021
0969ba4d3214555617743ddff30847770fd11e96
refs/heads/master
2021-01-22T06:28:29.011183
2018-09-15T10:42:06
2018-09-15T10:42:06
92,556,004
1
0
null
null
null
null
UTF-8
C++
false
false
93
hpp
#ifndef FUTURE_HPP_ #define FUTURE_HPP_ #include "../impl/future_.ipp" #endif // FUTURE_HPP_
a5a903d9fdbb4c3c80def762412adf818995b432
4c1d515719425db127ba5285b5be4f03af10d5a1
/UVa-Judge/UVa_00624.cpp
06d5ffdb1317dd4411c2369b250ae5545f0f78f6
[]
no_license
matheusmtta/Competitive-Programming
26e51741332aed223b9231da33749940f5a1b977
e254b80090cc75bc213aad0a7957875842e90f1a
refs/heads/master
2023-04-28T18:08:51.417470
2023-04-24T21:09:00
2023-04-24T21:09:00
223,605,672
7
0
null
null
null
null
UTF-8
C++
false
false
1,361
cpp
#include <bits/stdc++.h> using namespace std; #define MOD 1000000007 #define INF (int)0x3f3f3f3f #define LINF (long long)0x3f3f3f3f3f3f3f3fll #define MP make_pair #define PB push_back typedef long int int32; typedef unsigned long int uint32; typedef long long int int64; typedef unsigned long long int uint64; const int MAXN = 1000; const int MAXW = 1000; int memo[MAXN][MAXN]; vector <int> g; vector <int> r; int limit; int k; int dp(int idx, int capacity){ if (capacity < 0) return -INF; if (idx == k) return 0; int &q = memo[idx][capacity]; if (q != -1) return q; return q = max(dp(idx+1, capacity), g[idx] + dp(idx+1, capacity-g[idx])); } void recover(int idx, int capacity){ if (idx == k) return; int pick = g[idx] + dp(idx+1, capacity-g[idx]); int left = dp(idx+1, capacity); if (pick >= left){ r.push_back(idx); recover(idx+1, capacity-g[idx]); } else recover(idx+1, capacity); } int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); int n; while (cin >> limit){ cin >> k; for (int i = 0; i < MAXN; i++) for (int j = 0; j < MAXW; j++) memo[i][j] = -1; for (int i = 0; i < k; i++){ int x; cin >> x; g.push_back(x); } int ans = dp(0, limit); recover(0, limit); for (auto i : r) cout << g[i] << " "; cout << "sum:" << ans << endl; r.clear(); g.clear(); } return 0; }
309761ebaee5cd6465eafbc1dd1a3595d6912429
d18527a3a328c8b412cc62a62c6e520f0efd34b7
/utility/yaml_importer/src/yaml-cpp/noncopyable.h
05f0e544491a2ab00514dd22b4d483f95016be41
[]
no_license
hinike/ds_cinder
113934aad679ccfdcf09bc6269e4f68f2d6bb33d
1fbbc87ca8a49fd5c83b3e300b1ab4ae0953ed6e
refs/heads/master
2020-03-19T16:14:25.129849
2018-01-03T06:08:42
2018-01-03T06:11:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
640
h
#ifndef NONCOPYABLE_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #define NONCOPYABLE_H_62B23520_7C8E_11DE_8A39_0800200C9A66 #if defined(_MSC_VER) || (defined(__GNUC__) && (__GNUC__ == 3 && __GNUC_MINOR__ >= 4) || (__GNUC__ >= 4)) // GCC supports "pragma once" correctly since 3.4 #pragma once #endif #include "yaml-cpp/dll.h" namespace YAML { // this is basically boost::noncopyable class YAML_CPP_API noncopyable { protected: noncopyable() {} ~noncopyable() {} private: noncopyable(const noncopyable&); const noncopyable& operator = (const noncopyable&); }; } #endif // NONCOPYABLE_H_62B23520_7C8E_11DE_8A39_0800200C9A66
0c4095978c7f1450a722a38481bd39f8a095ae87
f0b80d4b8453282dab4dac2187b44284f8295af7
/yandex/2014/r2/a.cpp
2bbf147df39bdab6cb5c653d99c3267d62306103
[]
no_license
caiwaifung/algo
c63a5d2ab4c5de78e791482badfc4873d5cb0018
07e5b2ab62d11061d582c76edafdd649861b940b
refs/heads/master
2021-01-23T11:48:37.805450
2018-06-02T20:24:42
2018-06-02T20:24:42
35,368,287
3
1
null
null
null
null
UTF-8
C++
false
false
1,148
cpp
#include <cstdlib> #include <cstring> #include <cstdio> #include <cmath> #include <algorithm> #include <iostream> #include <vector> #include <string> #include <map> #include <set> using namespace std; #define forint(i, a, b) for(int i=int(a); i<=int(b); ++i) #define forintdown(i, a, b) for(int i=int(a); i>=int(b); --i) #define forn(i, n) forint(i, 0, (n)-1) #define forndown(i, n) forintdown(i, (n)-1, 0) #define fillchar(a, x) memset(a, x, sizeof(a)) #define fi first #define se second #define PB push_back #define MP make_pair typedef long long LL; typedef pair<double,double> PDD; typedef pair<int,int> PII; typedef pair<LL,LL> PLL; typedef vector<int> VI; typedef vector<LL> VL; typedef vector<PII> VPI; typedef vector<PLL> VPL; int c[100010]; int n, k; int main() : scanf("%d%d", &n,&k); forint(i, 1, n) scanf("%d", &c[i]); LL ans=0; if(k%2==0) { forint(i, 1, n) { int t=c[i]+1-k; if(t>=0) ans+=t/k+1; } } else { int cnt=0; forint(i, 1, n) { int t=c[i]+1-(k+1); int v=(t>=0?(t/k+1):0); t=c[i]+1-k; int v2=(t>=0?(t/k+1):0); ans+=v; if(v2>v) ++cnt; } if(cnt>0) ++ans; } cout<<ans<<endl; return 0; }
534dbd95b899fcaddf348c9eb17f70fa12dbadcc
519bd681952ad8d74da425221df9ff059932133b
/Cpp/551_StudentAttendanceRecordI.cpp
d64b3e73788dfb9b27dbeb6f761c8e63bce9913f
[]
no_license
Icay12/LeetCode
d4efe859a259a52e60f335c064632681afc4c22a
c4e872e1ce2624e5fd8dd3b923a96311fc596986
refs/heads/master
2021-01-10T22:43:06.455090
2018-09-19T05:48:13
2018-09-19T05:48:13
70,383,956
0
0
null
null
null
null
UTF-8
C++
false
false
458
cpp
class Solution { public: bool checkRecord(string s) { int A = 0; //number of 'A' int L = 0; //status of 'L' for(char c : s) { if(c == 'A') { A++; } if(c == 'L') { L++; } else { L = 0; } if(A >= 2 || L >= 3) return false; } return true; } };
cfebd6431bd6b7c5c6c0cd50e087c46e90f068f9
66dfe5eaf4ffefb691adf99de821c4acf8edf71e
/main.cpp
9342ad47df86a9f8cb3938a7f935352fb2df91d2
[]
no_license
CaiNot/RemoveDuplicates
ef184dfcf9a12ed959deffbe1f9d554a4b757e49
8c088ba43de4df6614285dd87c0e6d85498250c4
refs/heads/master
2020-03-29T09:16:15.860643
2018-09-21T10:40:21
2018-09-21T10:40:21
149,749,647
0
0
null
null
null
null
UTF-8
C++
false
false
826
cpp
#include <iostream> #include <vector> using namespace std; class Solution { public: int removeDuplicates(vector<int> &nums) { if (nums.size() < 2) return nums.size(); int lastNum = nums[0], len = nums.size(), pos = 1; for (int i = 1; i < len; i++) { if (lastNum != nums[i]) { lastNum = nums[i]; nums[pos] = lastNum; pos++; } } return pos; } void show(vector<int> &nums) { for (int i = 0; i < nums.size(); i++) { cout << nums[i] << ","; } cout << endl; } }; int main() { std::cout << "Hello, World!" << std::endl; vector<int> nums = {1,1,2}; Solution s; cout << s.removeDuplicates(nums) << endl; s.show(nums); return 0; }
0457c7069f58bd311ec93fe563799a78d93b8bbd
972b2a2f64bfa227755b680fa5fc4116be0df71f
/RayTracer/PointLight.h
09ba8c08f73307a7c623f9990c16d0cd456a80d6
[]
no_license
Developer-The-Great/CPURaycaster
e7362507635e95c2f7dac46e13a0b9a49f1db741
97c55005153123735d853866ed50f42074abb7de
refs/heads/master
2022-11-10T20:06:14.932497
2019-06-26T16:22:46
2019-06-26T16:22:46
275,394,709
0
0
null
null
null
null
UTF-8
C++
false
false
145
h
#pragma once #include "Light.h" class PointLight :public Light { public: PointLight(vec3 positionToSet, vec3 colorToSet); ~PointLight(); };
7e73ea8e86e401b1a73f8957a62b610155bbee73
598a187ec063715361592b56d583a62e55db6810
/examples/huzzah-dht22-mqtt/huzzah-dht22-mqtt.ino
ae587699ac209c6ceaf0f0c2d56e0446d48c7c47
[ "MIT" ]
permissive
cloud-of-things/cot-c-mqtt-mqttsn-arduino-sdk
2e0764ee58ed7b8a471f4455e646b14ba51a78e3
dd4f912b556c71406605f978d7b8211cacf79401
refs/heads/master
2020-07-24T20:19:46.048311
2019-09-26T13:55:31
2019-09-26T13:55:31
208,035,987
2
3
MIT
2020-01-14T09:54:50
2019-09-12T11:32:33
C++
WINDOWS-1252
C++
false
false
2,894
ino
/** * @description Simple Demo for CoT Library using MQTT * @copyright (C) 2017-2018 Deutsche Telekom AG- all rights reserved. * @licence MIT licence */ /** This project demonstrates how simple it is to build a DTCoT application This example also shows that DTCoT does not depend on device type, network and protocol libraies, and can be easily extended by adding more devices and underlaying protocols (as soon as the cloud starts supporting them). Application description: In this demo a real temperature measurement from DHT22 sensor is sent to the cloud via the ESP8266 WiFi module. This sketch has the following library dependencies: - <Adafruit MQTT Library> v0.20.1 - <ESP8266WiFi> v1.0 - <Time> v1.5 - <DHT sensor library (Default)> v1.3.0 */ #include "dt-arduino-iot-agent.h" #include "cot_sdk/DTCotSdkMqtt.h" #include "cot_sdk/DTCoTDevice.h" #include "devices/DTCoTDeviceHUZZAH_WIFI.h" #include "DHT.h" /************************* WiFi Access Point *********************************/ #define SECRET_WIFI_SSID "...your local Wifi network's SSID..." #define SECRET_WIFI_PASSWORD "...your local Wifi network's password..." /*************************** Sketch Code ************************************/ using namespace DTCoT; #define DHTPIN D2 // what digital pin the DHT22 is conected to (D2 = 4) #define DHTTYPE DHT22 // there are multiple kinds of DHT sensors float tempThreshold = 27; // Alarm threshold, °C /* Setup the Cloud access and the device to communicate to cloud */ CoTDevice cotDevice; DHT dht(DHTPIN, DHTTYPE); void setup() { delay(100); Serial.begin(115200); delay(100); DT_DEBUG_PRINTLN_INFO("\nSetup..."); /* Setup the Cloud access and the device to communicate to cloud. */ CoTConfigDeviceHuzzahWifi* boardConfig = new CoTConfigDeviceHuzzahWifi(SECRET_WIFI_SSID, SECRET_WIFI_PASSWORD); CoTDeviceHuzzahWifi* board = new CoTDeviceHuzzahWifi(*boardConfig); CotSdkMqtt* cotSDK = new CotSdkMqtt(*board); //initialize the device while(!cotDevice.setup(cotSDK)); delay(0); DT_DEBUG_PRINTLN_INFO("Setup... done."); } void loop() { float temp = dht.readTemperature(); // Read temperature as Celsius (the default) // Check if any reads failed and exit early (to try again). if (isnan(temp)) { DT_INFO_PRINTLN("### Failed to read temperature from DHT22 sensor!"); return; } DT_DEBUG_PRINTLN("Send measurement: %f", tempC); cotDevice.sendMeasurement("ty", "Room1", "Temperature", "C", temp, now()); if (temp > tempThreshold) { DT_DEBUG_PRINTLN("### temp: %f greater than threshold: %f => send Alarm!", temp, tempThreshold); cotDevice.sendAlarm("Temperature threshold exceeded!", "temperature_alarm", AlarmSeverity::MAJOR, AlarmStatus::ACTIVE); } DT_DEBUG_PRINTLN_INFO("Loop... done."); delay(10000); //[ms] }
e2efa7938c4f3ae18e8e35aad08ecc5f979958e1
88d8e885fbd686d4ef35d444b80701cff6f43740
/AtCoderBeginnerContest/061/a.cpp
733bc39a9df9f472e4fdb79d48a55ca975f820fa
[]
no_license
morishitamakoto0330/AtCoder
f18cf0804322775cbb5ee3ac958a8b5f129161c1
2c389f2809ec16cff4128dbbd985e3de94ad7309
refs/heads/master
2020-07-19T19:26:01.497595
2019-10-21T06:13:39
2019-10-21T06:13:39
206,501,162
0
0
null
null
null
null
UTF-8
C++
false
false
237
cpp
#include <iostream> #include <string> using namespace std; int main(void) { int A, B, C; string ans; cin >> A >> B >> C; ans = "No"; if (A <= C && C <= B) { ans = "Yes"; } cout << ans << endl; return 0; }
ee7c93b52ec9ad4f66045ca41217bc26002e2c3a
898aba0ba23c7bfb1af1c0857ad56c814a6d32ba
/EclipseCppProjects/PTTRN_State/main.cpp
dff7a42b6bc6035ed03d701bced142bab2c314a9
[]
no_license
andrewbolster/cppqubmarch2013
735d4bdefc4e2413969a5bb7a3480969549281fe
cb033fc22f5262daba9f542062d2d0ac40b38f4a
refs/heads/master
2016-09-05T19:03:32.343921
2013-03-22T13:41:27
2013-03-22T13:41:27
8,875,864
0
2
null
null
null
null
UTF-8
C++
false
false
4,087
cpp
#include<iostream> #define OVERTIME_RATE 50 #define STANDARD_HOURS 30 using namespace std; class EmployeeStatus; //We cannot have a simple hierarchy of employee classes // as client code frequently needs to change the status of // an employee and should not be burdened with calling // copy constructors class Employee { //The state classes will modify our data friend class PermanentStatus; friend class TemporaryStatus; public: Employee(bool isPermanent,double monthlySalary); ~Employee(); void changeToPermanent(); void changeToTemporary(); double calculateNetSalary(int hoursWorked); private: void changeStatus(EmployeeStatus *newStatus); private: //The state object contains the behaviour appropriate // to the employees current status EmployeeStatus* currentStatus; double monthlySalary; int pensionContributions; double travelAllowance; }; //This is the base of the state classes // We use both variants of the state pattern here // the methods 'beginNewStatus' and 'endCurrentStatus' // change the members of the employee object whilst the // query method 'isEligableForOvertime' helps the employee // object calculate its salary class EmployeeStatus { public: EmployeeStatus(Employee& e); virtual void beginNewStatus() = 0; virtual void endCurrentStatus() = 0; virtual bool isEligableForOvertime() = 0; protected: Employee& employee; }; class PermanentStatus : public EmployeeStatus { public: PermanentStatus(Employee& e); void beginNewStatus(); void endCurrentStatus(); bool isEligableForOvertime(); }; class TemporaryStatus : public EmployeeStatus { public: TemporaryStatus(Employee& e); void beginNewStatus(); void endCurrentStatus(); bool isEligableForOvertime(); }; Employee::Employee(bool isPermanent,double monthlySalary) : currentStatus(0) { if(isPermanent) { currentStatus = new PermanentStatus(*this); } else { currentStatus = new TemporaryStatus(*this); } this->monthlySalary = monthlySalary; currentStatus->beginNewStatus(); }; Employee::~Employee() { currentStatus->endCurrentStatus(); delete currentStatus; } void Employee::changeToPermanent() { changeStatus(new PermanentStatus(*this)); } void Employee::changeToTemporary() { changeStatus(new TemporaryStatus(*this)); } void Employee::changeStatus(EmployeeStatus *newStatus) { currentStatus->endCurrentStatus(); delete currentStatus; currentStatus = newStatus; currentStatus->beginNewStatus(); } double Employee::calculateNetSalary(int hoursWorked) { double netSalary = monthlySalary; netSalary -= ((monthlySalary * pensionContributions)/100); netSalary += travelAllowance; if(currentStatus->isEligableForOvertime() && hoursWorked > STANDARD_HOURS) { netSalary += (hoursWorked - STANDARD_HOURS) * OVERTIME_RATE; } return netSalary; } EmployeeStatus::EmployeeStatus(Employee& e) : employee(e) {} TemporaryStatus::TemporaryStatus(Employee& e) : EmployeeStatus(e) {} //Set the members of Employee to appropariate values // for a temporary worker. These are 'magic numbers' where // in reality we would be performing calculations void TemporaryStatus::beginNewStatus() { employee.pensionContributions = 0; employee.travelAllowance = 75; } void TemporaryStatus::endCurrentStatus() {} bool TemporaryStatus::isEligableForOvertime() { return true; } PermanentStatus::PermanentStatus(Employee& e) : EmployeeStatus(e) {} //Set the members of Employee to appropariate values // for a temporary worker. These are 'magic numbers' where // in reality we would be performing calculations void PermanentStatus::beginNewStatus() { employee.pensionContributions = 20; employee.travelAllowance = 0; } void PermanentStatus::endCurrentStatus() {} bool PermanentStatus::isEligableForOvertime() { return false; } int main() { Employee dave(false,50000); //dave works a month as a temp cout << "As a temporary dave earned " << dave.calculateNetSalary(40) << endl; //dave becomes full time staff dave.changeToPermanent(); //dave works a month as permanent staff cout << "As full time dave earned " << dave.calculateNetSalary(50) << endl; }
[ "bolster@localhost.(none)" ]
bolster@localhost.(none)
0c35ffb3c56fcdff8c8b2a31777c934c3f7aeab3
c02e6a950d0bf2ee8c875c70ad707df8b074bb8e
/build/Android/Debug/bimcast/app/src/main/include/Fuse.Animations.RangeAdapterHelpers.h
6aa6123a0a76dc2b498abfb2656e3c65906e44b9
[]
no_license
BIMCast/bimcast-landing-ui
38c51ad5f997348f8c97051386552509ff4e3faf
a9c7ff963d32d625dfb0237a8a5d1933c7009516
refs/heads/master
2021-05-03T10:51:50.705052
2016-10-04T12:18:22
2016-10-04T12:18:22
69,959,209
0
0
null
null
null
null
UTF-8
C++
false
false
716
h
// This file was generated based on C:\ProgramData\Uno\Packages\Fuse.Animations\0.35.12\$.uno. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Uno.h> namespace g{namespace Fuse{namespace Animations{struct RangeAdapterHelpers;}}} namespace g{namespace Uno{namespace UX{struct Selector;}}} namespace g{ namespace Fuse{ namespace Animations{ // internal static class RangeAdapterHelpers :2484 // { uClassType* RangeAdapterHelpers_typeof(); struct RangeAdapterHelpers : uObject { static ::g::Uno::UX::Selector _valueName_; static ::g::Uno::UX::Selector& _valueName() { return RangeAdapterHelpers_typeof()->Init(), _valueName_; } }; // } }}} // ::g::Fuse::Animations
d0ac1096f25e4f60733ff841e2872a4f09f5dca2
6da6f9e02a1e913063a839c4c402a1ff1c7a9ebd
/src/01/01_hello/mywidget.h
c6bc09d099583b0d17dd97a4f58b2ef48b86f17d
[]
no_license
nizhangdemei/Qt_code
6347e36b92b4cd8b7c62e3fedbc212da5ba04da1
9a743465a6ffdee5f10cdd911b21777f8c877912
refs/heads/master
2020-12-10T23:30:01.386610
2020-01-16T01:33:58
2020-01-16T01:33:58
233,740,803
0
0
null
null
null
null
UTF-8
C++
false
false
327
h
#ifndef MYWIDGET_H #define MYWIDGET_H #include <QWidget> namespace Ui { class MyWidget; } class MyWidget : public QWidget { Q_OBJECT public: explicit MyWidget(QWidget *parent = nullptr); ~MyWidget(); private slots: void on_pushButton_clicked(); private: Ui::MyWidget *ui; }; #endif // MYWIDGET_H
cb2aa6dad92838f56ac17693b8f0f17f3dd13d78
2960105217a0e135259e15f220da121e089b4a74
/HackerRank/Python/Introduction/Python Division.cpp
3680fb447078b0a92924e6bc6cb4ee3eaeb1497a
[]
no_license
iCoder0020/Competitive-Coding
7bf23122774128e1cdacf7c5a82ab65c41699dcd
a4fc60ec119e588dd69e2c040bd1aa7564c53e6a
refs/heads/master
2021-08-26T08:56:51.066001
2021-08-15T05:24:07
2021-08-15T05:24:07
142,176,794
0
0
null
null
null
null
UTF-8
C++
false
false
127
cpp
#ID: f20170069 #PROG: Python: Division #LANG: Python A=(float)(input()) B=(float)(input()) print((int)(A/B)) print(A/B)
b5c27e7ad310f932da32771e5befc90b41e16a95
32815cd1de61cfa78fd025486ba74249c08b009a
/college_life/codeforces/problemset/579a.cpp
306ee12f7a9cbe8637d502af59e8f42c00e2633b
[]
no_license
krshubham/compete
c09d4662eaee9f24df72059d67058e7564a4bc10
d16b0f820fa50f8a7f686a7f93cab7f9914a3f9d
refs/heads/master
2020-12-25T09:09:10.484045
2020-10-31T07:46:39
2020-10-31T07:46:39
60,250,510
2
1
null
2020-10-31T07:46:40
2016-06-02T09:25:15
C++
UTF-8
C++
false
false
1,174
cpp
#include <bits/stdc++.h> using namespace std; #define bye return 0 #define pb push_back #define mp make_pair #define mod(n) (n) % 1000000007 #define e_val 2.718281828 #define stp(a,b) a.push(b) #define all(a) a.begin(),a.end() #define PI 3.1415926535897932384626433832795 #define rep(i,n) for( int i = 0; i < n; i++ ) #define rrep(i,n) for(int i = n - 1 ; i >= 0 ; i--) #define crep(i,a,b) for( int i = a; i <= b; i++ ) #define endl '\n' #define fi first #define se second #define sz(x) ((int)x.size()) #define sqr(x) ((x)*(x)) typedef long long int lli; typedef long long ll; typedef unsigned long long int ulli; typedef unsigned long long ull; typedef pair<lli,lli> plli; typedef vector<lli> vlli; typedef map<string,lli> mslli; typedef map<lli,lli> mlli; typedef vector<pair<lli,lli> > vplli; inline bool isPrime(lli n){ if (n <= 1) { return false; } if (n <= 3) { return true; } if (n%2 == 0 || n%3 == 0) { return false; } for (int i=5; i*i<=n; i=i+6){ if (n%i == 0 || n%(i+2) == 0){ return false; } } return true; } int main(){ ios_base::sync_with_stdio(0); lli t,n,a,b,c,d,e,f,x,y; cin>>n; cout<<__builtin_popcount(n)<<endl; bye; }
62592568606fc3e595487d902787c2e395cb2191
2ffd0b4369fbd8d42b65e1891151410b5227f2ef
/1_LSQw/lsq_Dropout.h
56f5c9130a3f5bb55323af78f3e9729b7d27a27c
[]
no_license
coocoky/Alignment_Projects
771afc5d34fb70ca73ff9b9daca9e123ad30afce
4b2f2ecf832d96ea7026fd3d57afc79ec3e47122
refs/heads/master
2021-01-22T15:50:36.019528
2016-07-11T00:11:21
2016-07-11T00:11:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
546
h
#pragma once /* --------------------------------------------------------------- */ /* Types --------------------------------------------------------- */ /* --------------------------------------------------------------- */ class Dropout { public: long rmax, read, pnts, kill, cutd; private: void Add( const Dropout& rhs ) { rmax += rhs.rmax; read += rhs.read; pnts += rhs.pnts; kill += rhs.kill; cutd += rhs.cutd; }; void GatherCounts(); public: Dropout() : rmax(0), read(0), pnts(0), kill(0), cutd(0) {}; void Scan(); };
730674a420886be307d8ec24c36fddb872409c32
6ee200c9dba87a5d622c2bd525b50680e92b8dab
/Autumn/Core/Math/Color.cpp
6b83316c5db8b27ee784ff290e860641955750b9
[]
no_license
Ishoa/bizon
4dbcbbe94d1b380f213115251e1caac5e3139f4d
d7820563ab6831d19e973a9ded259d9649e20e27
refs/heads/master
2016-09-05T11:44:00.831438
2010-03-10T23:14:22
2010-03-10T23:14:22
32,632,823
0
0
null
null
null
null
UTF-8
C++
false
false
1,221
cpp
#include "stdafx.h" #include "Color.h" Color::Color() : m_cColor(0.0f, 0.0f, 0.0f, 1.0f) { } Color::Color(float _fRed, float _fGreen, float _fBlue) : m_cColor( _fRed, _fGreen, _fBlue, 1.0f) { } Color::Color(float _fRed, float _fGreen, float _fBlue, float _fAlpha) : m_cColor( _fRed, _fGreen, _fBlue, _fAlpha) { } Color::Color(const Color & c) : m_cColor( c.m_cColor ) { } Color::~Color() { } void Color::Set(float _fRed, float _fGreen, float _fBlue, float _fAlpha) { m_cColor.r = _fRed; m_cColor.g = _fGreen; m_cColor.b = _fBlue; m_cColor.a = _fAlpha; } Color operator + (const Color & _c1, const Color & _c2) { Color cRes; cRes.m_cColor = _c1.m_cColor + _c2.m_cColor; return cRes; } Color operator - (const Color & _c1, const Color & _c2) { Color cRes; cRes.m_cColor = _c1.m_cColor - _c2.m_cColor; return cRes; } Color operator * (const Color & _c1, const Color & _c2) { return Color(_c1.m_cColor.r * _c2.m_cColor.r, _c1.m_cColor.g * _c2.m_cColor.g, _c1.m_cColor.b * _c2.m_cColor.b, _c1.m_cColor.a * _c2.m_cColor.a); } Color operator * (const Color & _c, const float & _f) { Color cRes; cRes.m_cColor = _c.m_cColor * _f; return cRes; }
[ "edouard.roge@ab19582e-f48f-11de-8f43-4547254af6c6" ]
edouard.roge@ab19582e-f48f-11de-8f43-4547254af6c6
9d75d768e5a1c7a40f168664f278a1f4cb058383
127d9b35aaf4751666072fe7c850bdb562b85a36
/2.基本语言/23vector类型简介和定义初始化.cpp
044b79b11d3cfb8ce491271e6d62ee1cd9994318
[ "Apache-2.0" ]
permissive
xuesongzh/cpp-basis
9a3778ac4aa0e91a1174b69be758ce6c45e97e7a
2be3c5349edfa9a8f5937ba7eae013769c27449d
refs/heads/main
2023-02-17T09:22:12.805346
2021-01-16T03:26:34
2021-01-16T03:26:34
314,296,869
0
0
null
null
null
null
GB18030
C++
false
false
3,092
cpp
#include <cstdlib> #include <iostream> #include <string> #include <vector> using namespace std; //一个类模板的例子 template <typename T> void mySwap(T& a, T& b) { T tem; tem = a; a = b; b = tem; return; } struct Student { int number; string name; }; int main(void) { vector<int> v1; //定义一个vector对象,名字叫v1,存储int类型的数据 //<>是类模板中的内容,vector本身就是一个类模板,<int>就是一个类模板的实例化过程,需要告诉类型信息。 //像上面的一个简单类模板,可以实例化如下 int a = 3; int b = 5; mySwap<int>(a, b); cout << "a=" << a << "\t" << "b=" << b << endl; //可以存放自定义的数据类型 vector<Student> stuList; //存放结构体Student类型的容器 vector<vector<string>> str_str; //vector中的每一个元素都是一个存放string类型的vector vector<int*> v2; // 存放int*类型 //vector<int&>v3; //引用是一个别名,不是一个对象所以不能存放在vector容器中 //1.空vector vector<string> myStr; //创建一个空的存储string类型的vector对象,不包含任何元素 myStr.push_back("abcd"); myStr.push_back("123"); //2.进行元素拷贝的初始化方式 vector<string> myStr2(myStr); //把myStr元素拷贝到myStr2 vector<string> myStr3 = myStr; //每一个容器都有自己的内存空间,是拷贝复制出来的 //3.c++11中的列表初始化方式{} vector<string> myStr4 = {"aaaa", "bbbb", "ccccc"}; //4.创建指定数量的元素,有元素数量概念的东西,一般使用() vector<int> Number1(15, 0); // 包含15个元素,每个元素的值是0 vector<string> Mystr05(12, "AAAAA"); //如果不给初值,那么系统会设置初值 vector<int> Nubmer2(20); //0 vector<string> myStr06(12); //="" //5.其他初始化方式()表示元素数量 {}元素内容 --但是不是绝对的 vector<int> Nubmer03(10); //集合中有10个元素,每个元素的值由系统给定。 vector<int> Number04{10}; //集合中有一个元素10. vector<string> myStr07{"hello"}; //一个元素,是hello字符串 vector<string> myStr08{10}; //这里的10是int类型,与字符串类型不匹配,系统自动解释为10个元素,每个元素为空'' vector<string> myStr09{10, "AAAA"}; //10个元素,每个元素都是AAAA vector<int> Number05(10, 1); // 10个元素,每个元素值为1 vector<int> Number06{10, 1}; // 2个元素,10,1等同于初始化列表 //总结:要想通过{}初始化列表的方式进行初始化,那么<>里面的类型必须和后面的匹配 system("pause"); return 0; } /* * (1)vector类型简介:是标准库中的一种类型,集合或者动态数组,我们可以把若干个相同类型的对象放入其中。 *vector能把其他对象装进来,所以也被称为容器。 * *(2)定义和初始化vector对象 * */
03803536c4eb176675195fe4787090dd782db121
9f30e0ec74baf09b5f6db359edfd54f3ff26fc06
/server/ScenesServer/zObject.h
d03b5ba44ab97b68fec4e01b2761eebfe33d4ec2
[]
no_license
Georgiana-Unity/unitygame
186b23c4e69784f7bd5b3b86ecefe5e5eea6edd1
a478b1a22c57e40276fc8eb1fe136e19be5401b9
refs/heads/master
2020-08-01T18:33:05.665066
2017-10-02T15:56:37
2017-10-02T15:56:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
28,442
h
#ifndef _zObject_h_ #define _zObject_h_ #include "zDatabase.h" #include "SaveObject.h" #include "ObjectManager.h" #include "zTime.h" #include "zSceneEntry.h" struct zObject:zEntry { friend class GlobalObjectIndex; public: t_Object data; zObjectB *base; //only for RebuildObject::make,it's ugly,but .....sigh WORD* _p1[5]; WORD* _p2[18]; static zObject *create(zObjectB *objbase,DWORD num=1,BYTE level = 0); static void destroy(zObject*& ob); static void logger(QWORD createid,DWORD objid,char *objname,DWORD num,DWORD change,DWORD type,DWORD srcid,char *srcname,DWORD dstid,char *dstname,const char *action,zObjectB *base,BYTE kind,BYTE upgrade); static DWORD RepairMoney2RepairGold(DWORD dwObjectRepair); static zObject *create(zObject *objsrc); static zObject *load(const SaveObject *o); bool getSaveData(SaveObject *save) const ; int foundSocket(); bool canMail(); void checkBind(); //zCountryMaterialB* canContribute(); // 是否能被捐献 DWORD getMaterialKind(); // 获得原料类别: 0,普通物资,1,丝线,2,矿石,3,矿产,4,木材,5,皮毛,6,草药 const stObjectLocation &reserve() const; void restore(const stObjectLocation &loc); union { struct { DWORD createtime; DWORD dwCreateThisID; }; QWORD createid; }; // */ private: friend class Package; friend class Packages; friend class MainPack; friend class zSceneObject; //friend class luabind::detail::delete_s<zObject>; zObject(); ~zObject(); bool free() const; void free(bool flag); void fill(t_Object& d); void generateThisID(); bool inserted; //[Shx Add 检查该物品是否套装组成] void MakeSuit(zObjectB *objbase); void FillSuit(); void FillSuitPPT(int nIndex); public: bool fullMobileObject(t_Object_mobile &data); }; struct zSceneObject:public zSceneEntry { static zSceneObject *create(zObject *obj,const zRTime &ct) { if (obj==NULL) return NULL; zSceneObject *ret=new zSceneObject(obj,ct); return ret; } /** * \brief 检查地上物品是否过期 * 过期的地上物品会消失掉 * \param ct 当前时间 * \return 是否过期 */ bool checkOverdue(const zRTime &ct) const { return ct >= this->ct; } bool checkProtectOverdue(const zRTime &ct) { if (ownerID == 0) { return false; } if (ct > protectTime) { protectTime = 0; ownerID = 0; return true; } return false; } void setOwner(DWORD dwID,int protime=10) { if (dwID) { ownerID = dwID; zRTime ctv; protectTime = ctv; this->protectTime.addDelay(protime * 1000); } } void setOverDueTime(zRTime &ct_1) { ct = ct_1; } DWORD getOwner() { return ownerID; } ~zSceneObject() { if (o) o->free(); zObject::destroy(o); } void clear() { o=NULL; } zObject *getObject() { return o; } // sky 重新设置保护时间 void setprotectTime( int i ) { protectTime.addDelay( i * 1000 ); } // sky 强行删除物品保护 bool DelProtectOverdue() { if( ownerID == 0) return false; protectTime = 0; ownerID = 0; return true; } private: DWORD ownerID; zRTime protectTime; zObject *o; zRTime ct; zSceneObject(zObject *obj,const zRTime &ct):zSceneEntry(SceneEntry_Object),ct(ct) { this->ct.addDelay(600 * 1000); o=obj; ownerID=0; id = obj->data.qwThisID; tempid = obj->base->id; strncpy(name, obj->data.strName, MAX_NAMESIZE); } }; #define DECLARE(prop,type) type get_##prop() const {return prop;} #define RESET(prop) prop = 0; class Equips { public: Equips() { reset(); } void reset() { RESET(maxhp) // 最大生命值 RESET(maxmp) // 最大法术值 RESET(maxsp) // 最大体力值 RESET(pdamage) // 最小攻击力 RESET(maxpdamage) // 最大攻击力 RESET(mdamage) // 最小法术攻击力 RESET(maxmdamage) // 最大法术攻击力 RESET(appendminpet) // 宠物增强最小值 RESET(appendmaxpet) // 宠物增强最大值 RESET(pdefence) // 物防 RESET(mdefence) // 魔防 RESET(damagebonus) // 伤害加成 RESET(damage) // 增加伤害值x% RESET(akspeed) // 攻击速度 RESET(mvspeed) // 移动速度 RESET(atrating) // 命中率 RESET(akdodge) // 躲避率 RESET(str) // 力量 RESET(inte) // 智力 RESET(dex) // 敏捷 RESET(spi) // 精神 RESET(con) // 体质 RESET(hpr) // 生命值恢复 RESET(mpr) // 法术值恢复 RESET(spr) // 体力值恢复 RESET(holy) //神圣一击 RESET(bang) //重击率 RESET(pdam) // 增加物理攻击力 RESET(pdef) // 增加物理防御力 RESET(mdam) // 增加魔法攻击力 RESET(mdef) // 增加魔法防御力 RESET(poisondef) //抗毒增加 RESET(lulldef) //抗麻痹增加 RESET(reeldef) //抗眩晕增加 RESET(evildef) //抗噬魔增加 RESET(bitedef) //抗噬力增加 RESET(chaosdef) //抗混乱增加 RESET(colddef) //抗冰冻增加 RESET(petrifydef) //抗石化增加 RESET(blinddef) //抗失明增加 RESET(stabledef) //抗定身增加 RESET(slowdef) //抗减速增加 RESET(luredef) //抗诱惑增加 RESET(poison) //中毒增加 RESET(lull) //麻痹增加 RESET(reel) //眩晕增加 RESET(evil) //噬魔增加 RESET(bite) //噬力增加 RESET(chaos) //混乱增加 RESET(cold) //冰冻增加 RESET(petrify) //石化增加 RESET(blind) //失明增加 RESET(stable) //定身增加 RESET(slow) //减速增加 RESET(lure) //诱惑增加 RESET(hpleech.odds) RESET(hpleech.effect) RESET(mpleech.odds) //x%吸收生命值y RESET(mpleech.effect) //x%吸收法术值y RESET(hptomp) //转换生命值为法术值x% RESET(dhpp) //物理伤害减少x% RESET(dmpp) //法术伤害值减少x% RESET(incgold) //增加金钱掉落x% RESET(doublexp) //x%双倍经验 RESET(mf) //增加掉宝率x% //五行套装相关属性 RESET(dpdam) //物理伤害减少%x RESET(dmdam) //法术伤害减少%x RESET(bdam) //增加伤害x% RESET(rdam) //伤害反射%x RESET(ignoredef) //%x忽视目标防御 // RESET(aftype) //aftype = FIVE_NONE; RESET(afpoint) // RESET(dftype) //dftype = FIVE_NONE; RESET(dfpoint) RESET(maxhprate) RESET(maxmprate) RESET(Freedom.str_Attribute) RESET(Freedom.inte_Attribute) RESET(Freedom.dex_Attribute) RESET(Freedom.spi_Attribute) RESET(Freedom.con_Attribute) skill.clear(); skills.clear(); //gempop.clear(); } DECLARE(maxhp,WORD) // 最大生命值 DECLARE(maxmp,WORD) // 最大法术值 DECLARE(maxsp,WORD) // 最大体力值 DECLARE(pdamage,WORD) // 最小攻击力 DECLARE(maxpdamage,WORD) // 最大攻击力 DECLARE(mdamage,WORD) // 最小法术攻击力 DECLARE(maxmdamage,WORD) // 最大法术攻击力 DECLARE(appendminpet,WORD) // 最小宠物增强 DECLARE(appendmaxpet,WORD) // 最大宠物增强 DECLARE(pdefence,WORD) // 物防 DECLARE(mdefence,WORD) // 魔防 DECLARE(damagebonus,BYTE) // 伤害加成 DECLARE(damage,BYTE) // 增加伤害值x% DECLARE(akspeed,WORD) // 攻击速度 DECLARE(mvspeed,WORD) // 移动速度 DECLARE(atrating,WORD) // 命中率 DECLARE(akdodge,WORD) // 躲避率 DECLARE(str,WORD) // 力量 DECLARE(inte,WORD) // 智力 DECLARE(dex,WORD) // 敏捷 DECLARE(spi,WORD) // 精神 DECLARE(con,WORD) // 体质 DECLARE(hpr,WORD) // 生命值恢复 DECLARE(mpr,WORD) // 法术值恢复 DECLARE(spr,WORD) // 体力值恢复 DECLARE(holy,WORD) //神圣一击 DECLARE(bang,WORD) //重击率 DECLARE(pdam,WORD) // 增加物理攻击力 DECLARE(pdef,WORD) // 增加物理防御力 DECLARE(mdam,WORD) // 增加魔法攻击力 DECLARE(mdef,WORD) // 增加魔法防御力 DECLARE(poisondef,WORD) //抗毒增加 DECLARE(lulldef,WORD) //抗麻痹增加 DECLARE(reeldef,WORD) //抗眩晕增加 DECLARE(evildef,WORD) //抗噬魔增加 DECLARE(bitedef,WORD) //抗噬力增加 DECLARE(chaosdef,WORD) //抗混乱增加 DECLARE(colddef,WORD) //抗冰冻增加 DECLARE(petrifydef,WORD) //抗石化增加 DECLARE(blinddef,WORD) //抗失明增加 DECLARE(stabledef,WORD) //抗定身增加 DECLARE(slowdef,WORD) //抗减速增加 DECLARE(luredef,WORD) //抗诱惑增加 DECLARE(poison,WORD) //中毒增加 DECLARE(lull,WORD) //麻痹增加 DECLARE(reel,WORD) //眩晕增加 DECLARE(evil,WORD) //噬魔增加 DECLARE(bite,WORD) //噬力增加 DECLARE(chaos,WORD) //混乱增加 DECLARE(cold,WORD) //冰冻增加 DECLARE(petrify,WORD) //石化增加 DECLARE(blind,WORD) //失明增加 DECLARE(stable,WORD) //定身增加 DECLARE(slow,WORD) //减速增加 DECLARE(lure,WORD) //诱惑增加 DECLARE(hptomp,BYTE) //转换生命值为法术值x% DECLARE(dhpp,BYTE) //物理伤害减少x% DECLARE(dmpp,BYTE) //法术伤害值减少x% DECLARE(incgold,BYTE) //增加金钱掉落x% DECLARE(doublexp,BYTE) //x%双倍经验 DECLARE(mf,BYTE) //增加掉宝率x% //五行套装相关属性 DECLARE(dpdam,BYTE) //物理伤害减少%x DECLARE(dmdam,BYTE) //法术伤害减少%x DECLARE(bdam,BYTE) //增加伤害x% DECLARE(rdam,BYTE) //伤害反射%x DECLARE(ignoredef,BYTE) //%x忽视目标防御 DECLARE(maxhprate,BYTE) //按百分比增加最大hp DECLARE(maxmprate,BYTE) //按百分比增加最大mp //sky 新增自由加点的属性 WORD get_Freedom_str() const { return Freedom.str_Attribute;} WORD get_Freedom_inte() const { return Freedom.inte_Attribute;} WORD get_Freedom_dex() const { return Freedom.dex_Attribute;} WORD get_Freedom_spi() const { return Freedom.spi_Attribute;} WORD get_Freedom_con() const { return Freedom.con_Attribute;} BYTE get_hpleech_odds() const {return hpleech.odds;} WORD get_hpleech_effect() const {return hpleech.effect;} //x%吸收生命值y BYTE get_mpleech_odds() const {return mpleech.odds;} WORD get_mpleech_effect() const {return mpleech.effect;} //x%吸收法术值y #if 0 /** * \brief sky 获取宝石属性 * \return 攻击五行类型 */ WORD get_gem_str() const //获取宝石的力量 { WORD str; const_iterator1 it; for(it = gempop.begin(); it!=gempop.end(); it++) { if( it->GemID != INVALID_HOLE ) str += it->gem_str; } return str; } WORD get_gem_inte() const //获取宝石的智力 { WORD inte; const_iterator1 it; for(it = gempop.begin(); it!=gempop.end(); it++) { if( it->GemID != INVALID_HOLE ) inte += it->gem_inte; } return inte; } WORD get_gem_dex() const //获取宝石的敏捷 { WORD dex; const_iterator1 it; for(it = gempop.begin(); it!=gempop.end(); it++) { if( it->GemID != INVALID_HOLE ) dex += it->gem_dex; } return dex; } WORD get_gem_spi() const //获取宝石的精神 { WORD spi; const_iterator1 it; for(it = gempop.begin(); it!=gempop.end(); it++) { if( it->GemID != INVALID_HOLE ) spi += it->gem_spi; } return spi; } WORD get_gem_con() const //获取宝石的耐力 { WORD con; const_iterator1 it; for(it = gempop.begin(); it!=gempop.end(); it++) { if( it->GemID != INVALID_HOLE ) con += it->gem_con; } return con; } WORD gem_atk; //物理攻击力 WORD gem_mkt; WORD get_gem_def() const //获取宝石的物理防御 { WORD def; const_iterator1 it; for(it = gempop.begin(); it!=gempop.end(); it++) { if( it->GemID != INVALID_HOLE ) def += it->gem_def; } return def; } WORD get_gem_mdef() const //获取宝石的魔法防御 { WORD mdef; const_iterator1 it; for(it = gempop.begin(); it!=gempop.end(); it++) { if( it->GemID != INVALID_HOLE ) mdef += it->gem_mdef; } return mdef; } WORD get_gem_dhpp() const //获取宝石的物理免伤 { WORD dhpp; const_iterator1 it; for(it = gempop.begin(); it!=gempop.end(); it++) { if( it->GemID != INVALID_HOLE ) dhpp += it->gem_dhpp; } return dhpp; } WORD get_gem_dmpp() const //获取宝石的魔法免伤 { WORD dmpp; const_iterator1 it; for(it = gempop.begin(); it!=gempop.end(); it++) { if( it->GemID != INVALID_HOLE ) dmpp += it->gem_dmpp; } return dmpp; } WORD get_gem_atk() const //获取宝石的物理攻击力 { WORD atk; const_iterator1 it; for(it = gempop.begin(); it!=gempop.end(); it++) { if( it->GemID != INVALID_HOLE ) atk += it->gem_atk; } return atk; } WORD get_gem_mtk() const //获取宝石的魔法攻击力 { WORD mtk; const_iterator1 it; for(it = gempop.begin(); it!=gempop.end(); it++) { if( it->GemID != INVALID_HOLE ) mtk += it->gem_mkt; } return mtk; } #endif /** * \brief 获取攻击五行 * \return 攻击五行类型 */ DWORD getAttFive() const {return aftype;} /** * \brief 获取攻击五行点数 * \return 五行点数 */ DWORD getAttFivePoint() const {return afpoint;} /** * \brief 获取防御五行 * \return 防御五行类型 */ DWORD getDefFive() const {return dftype;} /** * \brief 获取防御五行点数 * \return 五行点数 */ DWORD getDefFivePoint() const {return dfpoint;} /** * \brief 获取装备对单个技能的加成 * * \param id: 技能id * \return 加成等级 */ DWORD getMaxSkill(WORD id) const { const_iterator it = skill.find(id); if (it != skill.end()) { return it->second; } return 0; } /** * \brief 获取装备对某系技能的加成 * * \param id: 技能系别 * \return 加成等级 */ DWORD getMaxSkills(WORD id) const { const_iterator it = skills.find(id); if (it != skills.end()) { return it->second; } return 0; } private: friend class EquipPack; DWORD maxhp; // 最大生命值 DWORD maxmp; // 最大法术值 DWORD maxsp; // 最大体力值 DWORD pdamage; // 最小攻击力 DWORD maxpdamage; // 最大攻击力 DWORD mdamage; // 最小法术攻击力 DWORD maxmdamage; // 最大法术攻击力 WORD appendminpet; // 给宠召唤兽能力增强最小值 WORD appendmaxpet; // 给宠召唤兽能力增强最大值 WORD pdefence; // 物防 WORD mdefence; // 魔防 BYTE damagebonus; // 伤害加成 BYTE damage; // 增加伤害值x% WORD akspeed; // 攻击速度 WORD mvspeed; // 移动速度 WORD atrating; // 命中率 WORD akdodge; // 躲避率 WORD str; // 力量 WORD inte; // 智力 WORD dex; // 敏捷 WORD spi; // 精神 WORD con; // 体质 // WORD fivetype; // 五行属性 // WORD fivepoint; // 五行属性 WORD hpr; // 生命值恢复 WORD mpr; // 法术值恢复 WORD spr; // 体力值恢复 WORD holy; //神圣一击 WORD bang; //重击率 WORD pdam; // 增加物理攻击力 WORD pdef; // 增加物理防御力 WORD mdam; // 增加魔法攻击力 WORD mdef; // 增加魔法防御力 WORD poisondef; //抗毒增加 WORD lulldef; //抗麻痹增加 WORD reeldef; //抗眩晕增加 WORD evildef; //抗噬魔增加 WORD bitedef; //抗噬力增加 WORD chaosdef; //抗混乱增加 WORD colddef; //抗冰冻增加 WORD petrifydef; //抗石化增加 WORD blinddef; //抗失明增加 WORD stabledef; //抗定身增加 WORD slowdef; //抗减速增加 WORD luredef; //抗诱惑增加 WORD poison; //中毒增加 WORD lull; //麻痹增加 WORD reel; //眩晕增加 WORD evil; //噬魔增加 WORD bite; //噬力增加 WORD chaos; //混乱增加 WORD cold; //冰冻增加 WORD petrify; //石化增加 WORD blind; //失明增加 WORD stable; //定身增加 WORD slow; //减速增加 WORD lure; //诱惑增加 struct leech { BYTE odds; //x WORD effect; //y }; leech hpleech; //x%吸收生命值y leech mpleech; //x%吸收法术值y BYTE hptomp; //转换生命值为法术值x% BYTE dhpp; //物理伤害减少x% BYTE dmpp; //法术伤害值减少x% BYTE incgold; //增加金钱掉落x% BYTE doublexp; //x%双倍经验 BYTE mf; //增加掉宝率x% union { BYTE _five_props[5]; struct { //五行套装相关属性 BYTE dpdam; //物理伤害减少%x BYTE dmdam; //法术伤害减少%x BYTE bdam; //增加伤害x% BYTE rdam; //伤害反射%x BYTE ignoredef; //%x忽视目标防御 }; }; WORD aftype; WORD afpoint; WORD dftype; WORD dfpoint; typedef std::map<WORD,WORD> SKILL; typedef SKILL::const_iterator const_iterator; SKILL skill; //单个技能加成 SKILL skills; //全系技能加成 BYTE maxhprate; //按百分比增加最大hp BYTE maxmprate; //按百分比增加最大mp struct Freedom_Attribute { WORD str_Attribute; // 力量已经加过的自由点 WORD inte_Attribute; // 智力已经加过的自由点 WORD dex_Attribute; // 敏捷已经加过的自由点 WORD spi_Attribute; // 精神已经加过的自由点 WORD con_Attribute; // 体质已经加过的自由点 } Freedom; #if 0 //sky 新增宝石属性结构 typedef std::vector<GemPop> GEMPOP; typedef GEMPOP::const_iterator const_iterator1; GEMPOP gempop; #endif }; struct PackageCallback { virtual bool exec(zObject * o)=0; virtual ~PackageCallback(){}; }; class Package:private zNoncopyable { protected: zObject** container; virtual bool add(zObject *object,bool find); virtual bool remove(zObject *object); virtual bool checkAdd(SceneUser *pUser,zObject *object,WORD x,WORD y); public: Package(WORD type,DWORD id,WORD w,WORD h); virtual ~Package(); virtual bool getObjectByZone(zObject **ret,WORD x,WORD y); virtual bool getObjectByID(zObject **ret,DWORD id); virtual void execEvery(PackageCallback &callback); virtual WORD space() const; virtual WORD size() const; virtual WORD getObjectNum() const; virtual WORD getObjectNumByBaseID(DWORD) const; WORD type() const; DWORD id() const; void setSpace(WORD); private: friend class Packages; virtual void removeAll(); bool find_space(WORD &x,WORD &y) const; virtual int position(WORD x,WORD y) const; virtual WORD width() const { return _width; } virtual WORD height() const { return _height; } public: virtual bool sort(SceneUser* pUser, DWORD flag=0); virtual DWORD typeWeight(WORD type); virtual bool needSwap(zObject* ob1, zObject* ob2); virtual bool swap(WORD index1, WORD index2); WORD _type; DWORD _id; WORD _width; WORD _height; WORD _space; WORD _size; }; #if 0 class MultiPack:public Package { protected: WORD width; WORD height; std::vector<std::vector<zObject *> >grid; std::set<zObject *> allset; public: MultiPack(WORD type,DWORD id,WORD width,WORD height); virtual ~MultiPack(); virtual bool add(zObject *object,bool find); virtual void remove(zObject *object); virtual void removeAll(); virtual bool checkAdd(SceneUser *pUser,zObject *object,WORD x,WORD y); virtual bool getObjectByZone(zObject **ret,WORD x,WORD y,WORD width,WORD height); virtual void execEvery(PackageCallback &callback); virtual bool findSpace(WORD owidth,WORD oheight,WORD &x,WORD &y); std::set<zObject *> &getAllset() { return allset; } WORD get_width() const { return width; } WORD get_height() const { return height; } }; #endif class ObjectPack : public Package { public: ObjectPack(zObject* ob,int type = Cmd::OBJECTCELLTYPE_PACKAGE,bool consume = true); ~ObjectPack(); bool empty() const { return space() == size(); } zObject* object() { return _ob; } void consume_dur_by(SceneUser* user,const zRTime& current); bool can_input() { if (!_ob || _ob->data.dur == 0) { return false; } return true; } private: bool checkAdd(SceneUser *pUser,zObject *object,WORD x,WORD y); //bool add(zObject *object,bool find); zObject* _ob; bool _cosume_by_time; Timer _one_min; }; class EquipPack : public Package { public: enum EQUIPNO{ BODY, HEAD, HANDL, HANDR, BELT, NECKLACE,//5 RINGL, RINGR, BANGL, BANGR, BOOTS,//10 OTHERS, OTHERS1, OTHERS2, OTHERS3, OTHERS4, //15 }; enum PACKNO{ R_PACK, L_PACK, R_MAKE, L_MAKE, }; EquipPack(SceneUser* user); ~EquipPack(); DWORD doubleexp_obj; DWORD doubleexp_obj_time; DWORD family_obj_times; DWORD family_obj_time; DWORD tong_obj_times; DWORD tong_obj_time; DWORD king_obj_times; DWORD king_obj_time; const Equips &getEquips() const; ObjectPack* pack(PACKNO no) const; zObject* equip(EQUIPNO no) const; bool getObjectByZone(zObject **ret,WORD x,WORD y); zObject *getObjectByEquipNo(EQUIPNO no); zObject *getObjectByEquipPos(DWORD no); bool costAttackDur(SceneUser *pThis); bool costDefenceDur(SceneUser *pThis); bool costAttackDurByPet(SceneUser *pThis); bool costDefenceDurByPet(SceneUser *pThis); void restituteDurability(SceneUser *pThis,const zRTime &ct); void updateDurability(SceneUser *pThis,DWORD value); DWORD fullAllEquiped(char *buf); bool needRecalc; int effectCount; bool skillReduceObject(SceneUser* pThis,DWORD kind,WORD num); bool skillCheckReduceObject(SceneUser* pThis,DWORD id,WORD num); bool canChangeColor(); void calcAll(); int reduceDur(SceneUser *pThis,DWORD which,DWORD type,DWORD num,bool needFresh=true,bool needCal=true); bool isTonic(); void obtain_exp(SceneUser* user,DWORD exp,bool force = false); //装备包裹是否为空 bool isEmpty(); private: bool add(zObject *object,bool find); bool remove(zObject *object); bool checkAdd(SceneUser *pUser,zObject *object,WORD x,WORD y); //sky 检测物品的装备职业是否符合当前玩家的职业 */ bool IsJobEquip(DWORD useJob, DWORD EquipType); virtual int position(WORD x,WORD y) const; bool reduceDur(SceneUser *pThis,DWORD which); inline void freshDurability(SceneUser *pThis,zObject *o); inline void freshUserData(SceneUser *pThis); bool process_extra_add(zObject* ob); bool process_extra_remove(zObject* ob); bool process_extra_get(zObject** ob,WORD x,WORD y); SceneUser* owner; ObjectPack** packs; Equips equips; const static int _poses[60]; }; #define MAX_TAB_NUM 5 #define MIN_TAB_NUM 2 class MainPack:public Package { public: enum { //sky 设置包袱的格子有效区域 WIDTH = 5, HEIGHT = 8, }; MainPack(); ~MainPack(); BYTE TabNum; //sky 玩家可以使用的包裹页数 bool getObjectByZone(zObject **ret,WORD x,WORD y); zObject * getGold(); DWORD getGoldNum(); bool skillReduceObject(SceneUser* pThis,DWORD kind,DWORD num); private: bool add(zObject *object,bool find); bool remove(zObject *object); bool checkAdd(SceneUser *pUser,zObject *object,WORD x,WORD y); zObject *gold; }; class StorePack : public Package { public: enum { W = 7, H = 6, }; BYTE days; StorePack(); ~StorePack(); void goldstore(SceneUser *pThis,bool notify=true); int load(BYTE* dest); int save(BYTE* dest); void notify(SceneUser* user); private: bool checkAdd(SceneUser* pUser,zObject* object,WORD x,WORD y); }; class PetPack : public Package { public: static const BYTE W = 8; static const BYTE H = 10; PetPack(); ~PetPack(); WORD size() const;//返回最大可用数 void setAvailable(WORD);//设置最大可用数 bool isEmpty() const; private: WORD available;//可用的总数 bool checkAdd(SceneUser* pUser,zObject* object,WORD x,WORD y); }; template<typename T> class Type2Type { public: typedef T BASE; }; class Packages { private: SceneUser *owner; Package** getPackage(int packs); public: enum { MAIN_PACK = 1, LEFT_PACK = 2, RIGHT_PACK = 4, EQUIP_PACK = 8, STORE_PACK = 16, LM_PACK = 32, RM_PACK = 64, PET_PACK = 128, }; UserObjectM uom; MainPack main; EquipPack equip; StorePack store; PetPack petPack; Packages(SceneUser* user); ~Packages(); void addMoney(DWORD num,const char *disc,const char *note = NULL,bool notify = true); void addGold(DWORD num,const char *disc,const char *note = NULL,bool notify = true,bool pack=false); void addTicket(DWORD num,const char *disc,const char *note = NULL,bool notify = true); bool checkMoney(DWORD need); bool checkTicket(DWORD need); bool checkGold(DWORD need); bool removeMoney(DWORD num,const char *disc); bool removeGold(DWORD num,const char *disc,bool need=true); bool removeTicket(DWORD num,const char *disc); bool moveObject(SceneUser *pUser,zObject*& srcObj,stObjectLocation &dst); bool moveObjectToScene(zObject *o,const zPos &pos,DWORD overdue_msecs=0,const unsigned long dwID=0); bool removeObject(zObject*& srcObj,bool notify = true,bool del = true); bool addObject(zObject *srcObj,bool needFind,int packs = 0); Package* getPackage(DWORD type,DWORD id); SceneUser *getOwner() { return owner; } template<typename T> void execEvery(Package* pack,T t) { typename T::BASE cb(this); pack->execEvery(cb); } template<typename T,typename P1> void execEvery(Package* pack,T t,P1 p1) { typename T::BASE cb(this,p1); pack->execEvery(cb); } zObject *getGold(); DWORD getGoldNum(); }; #define AUTO_PACK Packages::MAIN_PACK |Packages::LEFT_PACK| Packages::RIGHT_PACK struct Combination : public PackageCallback { public: Combination(SceneUser* user,zObject* get) : _user(user),_get(get),_num(0) { } virtual bool exec(zObject* o); int num() const { return _num; } private: SceneUser* _user; zObject* _get; int _num; }; struct ClearPack : public PackageCallback { public: ClearPack(const Packages* ps) : _ps(ps) { } virtual bool exec(zObject* p); private: const Packages* _ps; }; struct DropFromPack : public PackageCallback { public: struct Param { Package* pack; int drop_num; zPos pos; Param(Package* p,int d,const zPos& s) : pack(p),drop_num(d),pos(s) { } }; DropFromPack(const Packages* ps,const Param& p) ; virtual bool exec(zObject* ob); private: const Packages* _ps; Param _p; int _begin; int _pos; }; #endif
861b818ad11d9a502d4a661239d698980f924dda
1c8e5a1fc7f9dfee4969194c1bd77918eea73095
/Source/AllProjects/CIDLib/CIDLib_Size.hpp
124b3703dd377a705bff679901eb98dd0d2f5d9c
[]
no_license
naushad-rahman/CIDLib
bcb579a6f9517d23d25ad17a152cc99b7508330e
577c343d33d01e0f064d76dfc0b3433d1686f488
refs/heads/master
2020-04-28T01:08:35.084154
2019-03-10T02:03:20
2019-03-10T02:03:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,619
hpp
// // FILE NAME: CIDLib_Size.hpp // // AUTHOR: Dean Roddey // // CREATED: 09/10/1996 // // COPYRIGHT: $_CIDLib_CopyRight_$ // // $_CIDLib_CopyRight2_$ // // DESCRIPTION: // // This is the header for the CIDLib_Size.Cpp file, which implements the // TSize class. This class represents a positive extent in a 2D cardinal // coordinate space. // // CAVEATS/GOTCHAS: // // LOG: // // $_CIDLib_Log_$ // #pragma once #pragma CIDLIB_PACK(CIDLIBPACK) // --------------------------------------------------------------------------- // CLASS: TSize // PREFIX: sz // --------------------------------------------------------------------------- class CIDLIBEXP TSize : public TObject, public MStreamable, public MDuplicable, public MFormattable { public : // ------------------------------------------------------------------- // Constructors and Destructor // ------------------------------------------------------------------- TSize() = default; TSize ( const tCIDLib::THostSize& szToCopy ); TSize ( const tCIDLib::TRawSize& szToCopy ); TSize(const tCIDLib::TCard4 c4X, const tCIDLib::TCard4 c4Y) : m_c4CX(c4X) , m_c4CY(c4Y) { } explicit TSize(const tCIDLib::TCard4 c4Both) : m_c4CX(c4Both) , m_c4CY(c4Both) { } TSize(const TSize& szSrc) = default; // ------------------------------------------------------------------- // Public operators // ------------------------------------------------------------------- operator const tCIDLib::THostSize&() const; TSize& operator=(const TSize&) = default; tCIDLib::TVoid operator= ( const tCIDLib::TRawSize& szSrc ); tCIDLib::TVoid operator+= ( const TSize& szToAdd ); friend TSize CIDLIBEXP operator+ ( const TSize& sz1 , const TSize& sz2 ); tCIDLib::TVoid operator-= ( const TSize& szToSub ); friend TSize CIDLIBEXP operator- ( const TSize& sz1 , const TSize& sz2 ); constexpr tCIDLib::TBoolean operator==(const TSize& szToTest) const { return (m_c4CX == szToTest.m_c4CX) && (m_c4CY == szToTest.m_c4CY); } constexpr tCIDLib::TBoolean operator!=(const TSize& szToTest) const { return !operator==(szToTest); } tCIDLib::TVoid operator|= ( const TSize& szToOR ); friend TSize CIDLIBEXP operator| ( const TSize& szOR1 , const TSize& szOR2 ); tCIDLib::TVoid operator&= ( const TSize& szToAND ); friend TSize CIDLIBEXP operator& ( const TSize& szAND1 , const TSize& szAND2 ); // ------------------------------------------------------------------- // Public, non-virtual methods // ------------------------------------------------------------------- tCIDLib::TVoid Adjust ( const tCIDLib::TInt4 i4XOfs , const tCIDLib::TInt4 i4YOfs ); tCIDLib::TVoid Adjust ( const tCIDLib::TInt4 i4Ofs ); tCIDLib::TVoid AdjustCX ( const tCIDLib::TInt4 i4Ofs ); tCIDLib::TVoid AdjustCY ( const tCIDLib::TInt4 i4Ofs ); tCIDLib::TBoolean bAllZero() const { return (!m_c4CX && !m_c4CY); } tCIDLib::TBoolean bEitherLargerThan ( const TSize& szThan ) const; tCIDLib::TBoolean bEitherZero() const { return (!m_c4CX || !m_c4CY); } tCIDLib::TBoolean bParseFromText ( const TString& strText , const tCIDLib::ERadices eRadix = tCIDLib::ERadices::Auto , const tCIDLib::TCh chSepChar = L',' ); tCIDLib::TCard4 c4Packed() const; constexpr tCIDLib::TCard4 c4Height() const { return m_c4CY; } tCIDLib::TCard4 c4Height(const tCIDLib::TCard4 c4New) { m_c4CY = c4New; return m_c4CY; } constexpr tCIDLib::TCard4 c4SquareUnits() const { return m_c4CX * m_c4CY; } constexpr tCIDLib::TCard4 c4Width() const { return m_c4CX; } tCIDLib::TCard4 c4Width(const tCIDLib::TCard4 c4New) { m_c4CX = c4New; return m_c4CX; } constexpr tCIDLib::TCard4 c4X() const { return m_c4CX; } tCIDLib::TCard4 c4X(tCIDLib::TCard4 c4XNew) { m_c4CX = c4XNew; return m_c4CX; } constexpr tCIDLib::TCard4 c4Y() const { return m_c4CY; } tCIDLib::TCard4 c4Y(tCIDLib::TCard4 c4YNew) { m_c4CY = c4YNew; return m_c4CY; } tCIDLib::TVoid Exchange() { tCIDLib::TCard4 i4Tmp = m_c4CX; m_c4CX = m_c4CY; m_c4CY = i4Tmp; } tCIDLib::TVoid FormatToText ( TString& strToFill , const tCIDLib::ERadices eRadix = tCIDLib::ERadices::Auto , const tCIDLib::TCh chSepChar = L',' , const tCIDLib::TBoolean bAppend = kCIDLib::False ) const; tCIDLib::TVoid ParseFromText ( const TString& strText , const tCIDLib::ERadices eRadix = tCIDLib::ERadices::Auto , const tCIDLib::TCh chSepChar = L',' ); tCIDLib::TVoid Scale ( const tCIDLib::TFloat8& f8HScale , const tCIDLib::TFloat8& f8VScale ); tCIDLib::TVoid Scale ( const tCIDLib::TFloat8& f8Scale ); tCIDLib::TVoid ScaleAR ( const TSize& szTarArea ); tCIDLib::TVoid ScaleToWidthAR ( const tCIDLib::TCard4 c4NewWidth ); tCIDLib::TVoid ScaleToHeightAR ( const tCIDLib::TCard4 c4NewHeight ); tCIDLib::TVoid Set(const tCIDLib::TCard4 c4CXNew, const tCIDLib::TCard4 c4CYNew) { m_c4CX = c4CXNew; m_c4CY = c4CYNew; } tCIDLib::TVoid SetFromPacked ( const tCIDLib::TCard4 c4ToSet ); tCIDLib::TVoid TakeLarger ( const TSize& szOther ); tCIDLib::TVoid TakeSmaller ( const TSize& szOther ); tCIDLib::TVoid ToHostPt ( tCIDLib::THostPoint& ptToFill ) const; tCIDLib::TVoid ToRawSize ( tCIDLib::TRawSize& szToFill ) const; tCIDLib::TVoid ToHostSize ( tCIDLib::THostSize& szToFill ) const; tCIDLib::TVoid Zero() { m_c4CX = 0; m_c4CY = 0; } protected : // ------------------------------------------------------------------- // Protected, inherited methods // ------------------------------------------------------------------- tCIDLib::TVoid FormatTo ( TTextOutStream& strmToWriteTo ) const override; tCIDLib::TVoid StreamFrom ( TBinInStream& strmToReadFrom ) override; tCIDLib::TVoid StreamTo ( TBinOutStream& strmToWriteTo ) const override; private : // ------------------------------------------------------------------- // Private data members // // m_c4CX // m_c4CY // These are the extents in the x and y axes. // ------------------------------------------------------------------- tCIDLib::TCard4 m_c4CX = 0; tCIDLib::TCard4 m_c4CY = 0; // ------------------------------------------------------------------- // Do any needed magic macros // ------------------------------------------------------------------- RTTIDefs(TSize,TObject) DefPolyDup(TSize) NulObject(TSize) }; #pragma CIDLIB_POPPACK // --------------------------------------------------------------------------- // Alias TSize to another name, TQ1Point. Since a cartesian point in the // 1st quadrant has basically the same functionality, we use this class for // both. It has methods to look at the values either way, i.e. as a size or // as a point value. // --------------------------------------------------------------------------- using TQ1Point = TSize;
9e162b95f52519d22eed99882d08553b55e272c7
493be61134c0d3c3aada182224bb69b88e702606
/bunGLM/main.cpp
88e0379ccd7e56ca25febac6bc28496b9f7dd0c6
[]
no_license
bunguang/bunOpenGL
9bbc26f935c756dee38b43b24d9453248d7dfba3
10b76fe7a42c307bc3969536f5cc4a6c3aefd2f7
refs/heads/master
2020-03-26T18:17:30.063758
2018-11-10T13:16:38
2018-11-10T13:16:38
145,206,026
0
0
null
null
null
null
UTF-8
C++
false
false
6,475
cpp
// // Created by bunguang on 2018/8/16. // #include <glad/glad.h> #include <GLFW/glfw3.h> #include <iostream> #include <cmath> #include "Shader.h" #include "../stb_image.h" #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> using namespace std; void framebuffer_size_callback(GLFWwindow* window, int width, int height); void processInput(GLFWwindow *window); // settings const unsigned int SCR_WIDTH = 800; const unsigned int SCR_HEIGHT = 600; void framebuffer_size_callback(GLFWwindow *window, int width, int height) { glViewport(0, 0, width, height); } void processInput(GLFWwindow *window) { if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) glfwSetWindowShouldClose(window, true); } int main() { // 初始化和配置GLFW glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // 实例化窗口对象 GLFWwindow *window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "BunOpenGL", NULL, NULL); if (window == NULL) { std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); // 用GLAD来管理openGL函数指针 // 在调用任何openGL函数之前,应该先要初始化GLAD if (!gladLoadGLLoader((GLADloadproc) glfwGetProcAddress)) { std::cout << "Failed to initialize GLAD" << std::endl; return -1; } // 设定openGL输出的图像范围,视口大小(和窗口大小不是一个东西) glViewport(0, 0, 800, 600); // 视口大小随着窗口大小改变而改变 glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); // 编译着色器 Shader bunShader("shader.vs", "shader.fs"); float vertices[] = { // ---- 位置 ---- ---- 颜色 ---- - 纹理坐标 - 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, // 右上 0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, // 右下 -0.5f, -0.5f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, // 左下 -0.5f, 0.5f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f // 左上 }; unsigned int indices[] = { // 注意索引从0开始! 0, 1, 3, // 第一个三角形 1, 2, 3 // 第二个三角形 }; // 生成顶点缓冲对象 unsigned int VBO, VAO, EBO; glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); glGenBuffers(1, &EBO); glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW); // 设置顶点属性指针 // 位置属性 glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void *) 0); glEnableVertexAttribArray(0); // 颜色属性 glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void *) (3 * sizeof(float))); glEnableVertexAttribArray(1); // 纹理属性 glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(6 * sizeof(float))); glEnableVertexAttribArray(2); // 设置材质 unsigned int texture0, texture1; glGenTextures(1, &texture0); glGenTextures(1, &texture1); glBindTexture(GL_TEXTURE_2D, texture0); // 为当前绑定的纹理对象设置环绕、过滤方式 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // 加载并生成纹理 int width, height, nrChannels; stbi_set_flip_vertically_on_load(true); unsigned char *data = stbi_load("wall.jpg", &width, &height, &nrChannels, 0); if (data) { glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); } else { std::cout << "Failed to load texture" << std::endl; } stbi_image_free(data); glBindTexture(GL_TEXTURE_2D, texture1); // 为当前绑定的纹理对象设置环绕、过滤方式 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // 加载并生成纹理 // stbi_set_flip_vertically_on_load(true); data = stbi_load("awesomeface.png", &width, &height, &nrChannels, 0); if (data) { glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); } else { std::cout << "Failed to load texture" << std::endl; } stbi_image_free(data); bunShader.use(); bunShader.setInt("texture0", 0); bunShader.setInt("texture1", 1); // 主渲染循环逻辑 while (!glfwWindowShouldClose(window)) { // 检测按钮输入 processInput(window); // 渲染指令 // 覆盖上一帧的渲染结果 glClearColor(0.2f, 0.3f, 0.3f, 1.0f); // 状态设置函数 glClear(GL_COLOR_BUFFER_BIT); // 状态使用函数 // 真正起作用的渲染指令 glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture0); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, texture1); glm::mat4 trans; // trans = glm::translate(trans, glm::vec3(0.5f, -0.5f, 0.0f)); trans = glm::rotate(trans, (float)glfwGetTime(), glm::vec3(0.0f, 0.0f, 1.0f)); unsigned int transformLoc = glGetUniformLocation(bunShader.ID, "transform"); glUniformMatrix4fv(transformLoc, 1, GL_FALSE, glm::value_ptr(trans)); bunShader.use(); glBindVertexArray(VAO); glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0); // 检查并调用事件,交换缓冲 glfwSwapBuffers(window); glfwPollEvents(); } // 界面关闭,清空资源 glDeleteVertexArrays(1, &VAO); glDeleteBuffers(1, &VBO); glfwTerminate(); return 0; }
33b24871ecfdd816bca4494f790eebdb34c6bae4
52f62927bb096e6cbc01bd6e5625a119fb35c1c5
/avt/VisWindow/Tools/avtPointToolInterface.h
55398fa8ad9e10c8b2562ba307540ad80c0eecda
[]
no_license
HarinarayanKrishnan/VisIt27RC_Trunk
f42f82d1cb2492f6df1c2f5bb05bbb598fce99c3
16cdd647ac0ad5abfd66b252d31c8b833142145a
refs/heads/master
2020-06-03T07:13:46.229264
2014-02-26T18:13:38
2014-02-26T18:13:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,976
h
/***************************************************************************** * * Copyright (c) 2000 - 2013, Lawrence Livermore National Security, LLC * Produced at the Lawrence Livermore National Laboratory * LLNL-CODE-442911 * All rights reserved. * * This file is part of VisIt. For details, see https://visit.llnl.gov/. The * full copyright notice is contained in the file COPYRIGHT located at the root * of the VisIt distribution or at http://www.llnl.gov/visit/copyright.html. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the disclaimer below. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the disclaimer (as noted below) in the * documentation and/or other materials provided with the distribution. * - Neither the name of the LLNS/LLNL nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL LAWRENCE LIVERMORE NATIONAL SECURITY, * LLC, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. * *****************************************************************************/ #ifndef VISIT_POINT_TOOL_INTERFACE_H #define VISIT_POINT_TOOL_INTERFACE_H #include <viswindow_exports.h> #include <avtToolInterface.h> // **************************************************************************** // Class: avtPointToolInterface // // Purpose: // This class contains the information passed to users of the point tool. // // Notes: // // Programmer: Akira Haddox // Creation: Mon Jun 9 09:37:49 PDT 2003 // // Modifications: // // **************************************************************************** class VISWINDOW_API avtPointToolInterface : public avtToolInterface { public: avtPointToolInterface(const VisWindow *v); virtual ~avtPointToolInterface(); void SetPoint(double, double, double); const double *GetPoint() const; }; #endif
[ "brugger@18c085ea-50e0-402c-830e-de6fd14e8384" ]
brugger@18c085ea-50e0-402c-830e-de6fd14e8384
067ba40e5c846d93fb5c4d4a74d59333df99027e
ad8271700e52ec93bc62a6fa3ee52ef080e320f2
/CatalystRichPresence/CatalystSDK/PamAIStateHeliAttackData.h
21f42c993f1f50e11dc2d6d6b77c87443ce08cb2
[]
no_license
RubberDuckShobe/CatalystRPC
6b0cd4482d514a8be3b992b55ec143273b3ada7b
92d0e2723e600d03c33f9f027c3980d0f087c6bf
refs/heads/master
2022-07-29T20:50:50.640653
2021-03-25T06:21:35
2021-03-25T06:21:35
351,097,185
2
0
null
null
null
null
UTF-8
C++
false
false
456
h
// // Generated with FrostbiteGen by Chod // File: SDK\PamAIStateHeliAttackData.h // Created: Wed Mar 10 19:05:13 2021 // #ifndef FBGEN_PamAIStateHeliAttackData_H #define FBGEN_PamAIStateHeliAttackData_H #include "PamAIStateBaseData.h" class PamAIStateHeliAttackData : public PamAIStateBaseData // size = 0x28 { public: static void* GetTypeInfo() { return (void*)0x000000014286D810; } }; // size = 0x28 #endif // FBGEN_PamAIStateHeliAttackData_H
d6515aab8765dbb1179f385b22ddc9fa105b4065
f5d87ed79a91f17cdf2aee7bea7c15f5b5258c05
/cuts/iccm/arch/tron/deployment/Tron_Container_Strategy.cpp
ec4b1f8638a66087227e1c88d3c87cc8f50762a5
[]
no_license
SEDS/CUTS
a4449214a894e2b47bdea42090fa6cfc56befac8
0ad462fadcd3adefd91735aef6d87952022db2b7
refs/heads/master
2020-04-06T06:57:35.710601
2016-08-16T19:37:34
2016-08-16T19:37:34
25,653,522
0
3
null
null
null
null
UTF-8
C++
false
false
1,640
cpp
// -*- C++ -*- // $Id$ #include "Tron_Container_Strategy.h" #if !defined (__CUTS_INLINE__) #include "Tron_Container_Strategy.inl" #endif #include "Tron_Container.h" #include "../servant/Tron_Servant.h" #include "TestAdapter_i.h" namespace iCCM { // // install_servant // void Tron_Container_Strategy:: install_servant (::PortableServer::Servant servant) { Tron_Servant * tron_servant = dynamic_cast <Tron_Servant *> (servant); if (0 == tron_servant) return; // Set the servant's reporter. This will allow the servant to // register all its input/output ports with the reporter and // TRON/UPPAAL. tron_servant->init (this->container_.inst_handler ()->get_reporter (), this->container_.inst_handler ()->get_consumer_map ()); } // // configure_servant // void Tron_Container_Strategy:: configure_servant (::PortableServer::Servant servant, const ::Components::ConfigValues & values) { // NOTE: The servant can be casted to an Tron_Servant // by using 'dynamic_cast <Tron_Servant *> (servant)'. // Also, the ConfigValues passed into this method are the same // configuration values attached to a component instance. for (size_t i = 0; i < values.length (); ++ i) { // const char * param = 0; // config[i].name >>= param; ACE_ERROR ((LM_DEBUG, ACE_TEXT ("%T (%t) - %M - found param: %s\n"), values[i]->name ())); } } // // remove_servant // void Tron_Container_Strategy:: remove_servant (::PortableServer::Servant servant) { // NOTE: The servant can be casted to an Tron_Servant // by using 'dynamic_cast <Tron_Servant *> (servant)'. } }
b99d7bcc108ceecbe359cce9e47bb885e416488a
05a929c43b2327661c3a874fd54e50b7cf1f961b
/src/ArbreAbstrait.h
a453965d76ce7e0f9e2d7748c4f21d2eceab9aff
[]
no_license
LucaDeslot/ProjetInterpreteur
429bfd9474cf242e8b287887b25483b9a72b2562
454663e0f41bdbfa2c03bdc2078998095c4ec4e0
refs/heads/master
2021-07-25T14:19:00.757444
2017-11-07T21:58:17
2017-11-07T21:58:17
106,405,918
0
0
null
null
null
null
UTF-8
C++
false
false
6,711
h
#ifndef ARBREABSTRAIT_H #define ARBREABSTRAIT_H // Contient toutes les déclarations de classes nécessaires // pour représenter l'arbre abstrait #include <vector> #include <iostream> #include <iomanip> #include "Symbole.h" #include "Exceptions.h" using namespace std; //////////////////////////////////////////////////////////////////////////////// class Noeud { // Classe abstraite dont dériveront toutes les classes servant à représenter l'arbre abstrait // Remarque : la classe ne contient aucun constructeur public: virtual int executer() =0; // Méthode pure (non implémentée) qui rend la classe abstraite virtual void traduitCpp(unsigned int ind, ostream& out = cout) = 0; virtual void ajoute(Noeud* instruction) { throw OperationInterditeException(); } virtual ~Noeud() { } // Présence d'un destructeur virtuel conseillée dans les classes abstraites }; //////////////////////////////////////////////////////////////////////////////// class NoeudSeqInst: public Noeud { // Classe pour représenter un noeud "sequence d'instruction" // qui a autant de fils que d'instructions dans la séquence public: NoeudSeqInst(); // Construit une séquence d'instruction vide ~NoeudSeqInst() { } // A cause du destructeur virtuel de la classe Noeud int executer() override; // Exécute chaque instruction de la séquence void traduitCpp(unsigned int ind, ostream& out = cout) override; void ajoute(Noeud* instruction) override; // Ajoute une instruction à la séquence private: vector<Noeud *> m_instructions; // pour stocker les instructions de la séquenceArbreAbstrait }; //////////////////////////////////////////////////////////////////////////////// class NoeudAffectation: public Noeud { // Classe pour représenter un noeud "affectation" // composé de 2 fils : la variable et l'expression qu'on lui affecte public: NoeudAffectation(Noeud* variable, Noeud* expression); // construit une affectation ~NoeudAffectation() { } // A cause du destructeur virtuel de la classe Noeud int executer() override; // Exécute (évalue) l'expression et affecte sa valeur à la variable void traduitCpp(unsigned int ind, ostream& out = cout) override; private: Noeud* m_variable; Noeud* m_expression; }; //////////////////////////////////////////////////////////////////////////////// class NoeudOperateurBinaire: public Noeud { // Classe pour représenter un noeud "opération binaire" composé d'un opérateur // et de 2 fils : l'opérande gauche et l'opérande droit public: NoeudOperateurBinaire(Symbole operateur, Noeud* operandeGauche, Noeud* operandeDroit); // Construit une opération binaire : operandeGauche operateur OperandeDroit ~NoeudOperateurBinaire() { } // A cause du destructeur virtuel de la classe Noeud int executer() override; // Exécute (évalue) l'opération binaire) void traduitCpp(unsigned int ind, ostream& out = cout) override; private: Symbole m_operateur; Noeud* m_operandeGauche; Noeud* m_operandeDroit; }; //////////////////////////////////////////////////////////////////////////////// class NoeudInstSi: public Noeud { // Classe pour représenter un noeud "instruction si" // et ses 2 fils : la condition du si et la séquence d'instruction associée public: NoeudInstSi() = default; NoeudInstSi(Noeud* condition, Noeud* sequence); // Construit une "instruction si" avec sa condition et sa séquence d'instruction ~NoeudInstSi() { } // A cause du destructeur virtuel de la classe Noeud void ajoute(Noeud* instruction) override; int executer() override; // Exécute l'instruction si : si condition vraie on exécute la séquence void traduitCpp(unsigned int ind, ostream& out = cout) override; private: /** * all conditions of if/elseif : match with the seqInstructions * @note conditions.at(i) match with seqInstructions.at(i) * @details if the size of seqInstructions is bigger by 1 than the conditions size the last seqInstruction is for else */ vector<Noeud*> conditions; /** \ref conditions * all conditions of if/elseif : match with the conditions * @note conditions.at(i) match with seqInstructions.at(i) * @details if the size of seqInstructions is bigger by 1 than the conditions size the last seqInstruction is for else */ vector<Noeud*> seqIntructions; }; //////////////////////////////////////////////////////////////////////////////// class NoeudInstTantQue: public Noeud { public: NoeudInstTantQue(Noeud* condition, Noeud* seqInst); ~NoeudInstTantQue() { } virtual int executer() override; virtual void traduitCpp(unsigned int ind, ostream& out = cout) override; protected: Noeud* condition; Noeud* seqInst; }; //////////////////////////////////////////////////////////////////////////////// class NoeudInstRepeter: public NoeudInstTantQue { public: NoeudInstRepeter(Noeud* seqInst, Noeud* condition); ~NoeudInstRepeter() { } int executer() override; void traduitCpp(unsigned int ind, ostream& out = cout) override; private: }; //////////////////////////////////////////////////////////////////////////////// class NoeudInstPour: public NoeudInstTantQue { public: NoeudInstPour(Noeud* condition, Noeud* seqInst, Noeud* affect1 = nullptr, Noeud* affect2 = nullptr); ~NoeudInstPour() { } int executer() override; void traduitCpp(unsigned int ind, ostream& out = cout) override; private: Noeud* affect1; Noeud* affect2; }; //////////////////////////////////////////////////////////////////////////////// class NoeudInstEcrire: public Noeud { public: NoeudInstEcrire(Noeud* exp); ~NoeudInstEcrire() { } int executer() override; void traduitCpp(unsigned int ind, ostream& out = cout) override; void ajoute(Noeud* instruction) override; private: vector<Noeud*> exps; }; //////////////////////////////////////////////////////////////////////////////// class NoeudInstLire: public Noeud { public: NoeudInstLire(Noeud* var); ~NoeudInstLire() { } int executer() override; void traduitCpp(unsigned int ind, ostream& out = cout) override; void ajoute(Noeud* var) override; private: vector<Noeud*> vars; }; //////////////////////////////////////////////////////////////////////////////// class NoeudInstSelon : public NoeudInstSi { // on pourrait redefinir le traduitCpp pour faire un case et pas un if }; #endif /* ARBREABSTRAIT_H */
262b708b5755478eff0e384100b343d915a3bf25
15bd7227959f8fd37d4293f44a3d99d5b5172510
/LeetCode/1342/Solution.cpp
a55da044927c6aba035fd5b4bf57d6854c859800
[]
no_license
dskym/Algorithm
a9d589ec47a472a157fb4843010c77a09315e262
6b215fdf88ba02370b75c8565867cdc401c40fa1
refs/heads/master
2023-05-10T22:04:44.567097
2023-05-09T13:12:41
2023-05-09T13:12:41
148,602,397
0
0
null
null
null
null
UTF-8
C++
false
false
286
cpp
class Solution { public: int numberOfSteps (int num) { int count = 0; while(num != 0) { if(num % 2 == 0) num /=2; else num -= 1; count++; } return count; } };